hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
02ab7ba80486283467fd4a75f2e7c5f9a4e0bbbd
671
cpp
C++
solutions/931.cpp
tdakhran/leetcode
ed680059661faae32857eaa791ca29c1d9c16120
[ "MIT" ]
null
null
null
solutions/931.cpp
tdakhran/leetcode
ed680059661faae32857eaa791ca29c1d9c16120
[ "MIT" ]
null
null
null
solutions/931.cpp
tdakhran/leetcode
ed680059661faae32857eaa791ca29c1d9c16120
[ "MIT" ]
null
null
null
#include <algorithm> #include <vector> class Solution { public: int minFallingPathSum(std::vector<std::vector<int>>& matrix) { size_t n = matrix.size(); for (size_t row = 1; row < n; ++row) { matrix[row][0] += std::min(matrix[row - 1][0], matrix[row - 1][1]); for (size_t col = 1; col + 1 < n; ++col) { matrix[row][col] += std::min(std::min(matrix[row - 1][col - 1], matrix[row - 1][col]), matrix[row - 1][col + 1]); } matrix[row][n - 1] += std::min(matrix[row - 1][n - 1], matrix[row - 1][n - 2]); } return *std::min_element(begin(matrix.back()), end(matrix.back())); } };
31.952381
78
0.514158
[ "vector" ]
02ad0bf7a50aa7699f039d03c47cadbfc3bcb8ed
38,264
cpp
C++
physx/source/physxextensions/src/ExtD6Joint.cpp
Guillaume0477/PhysX_ME
69c35c405d39df9b112567750e92542b235bdba7
[ "Unlicense" ]
13
2020-01-08T00:55:42.000Z
2022-01-21T06:15:08.000Z
physx/source/physxextensions/src/ExtD6Joint.cpp
Guillaume0477/PhysX_ME
69c35c405d39df9b112567750e92542b235bdba7
[ "Unlicense" ]
8
2020-01-13T07:10:57.000Z
2021-05-14T20:55:17.000Z
physx/source/physxextensions/src/ExtD6Joint.cpp
Guillaume0477/PhysX_ME
69c35c405d39df9b112567750e92542b235bdba7
[ "Unlicense" ]
5
2020-05-05T08:37:01.000Z
2021-03-16T20:46:44.000Z
// // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2019 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "common/PxRenderBuffer.h" #include "PxPhysics.h" #include "ExtD6Joint.h" #include "ExtConstraintHelper.h" #include "CmConeLimitHelper.h" using namespace physx; using namespace Ext; using namespace shdfnd; PxD6Joint* physx::PxD6JointCreate(PxPhysics& physics, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1) { PX_CHECK_AND_RETURN_NULL(localFrame0.isSane(), "PxD6JointCreate: local frame 0 is not a valid transform"); PX_CHECK_AND_RETURN_NULL(localFrame1.isSane(), "PxD6JointCreate: local frame 1 is not a valid transform"); PX_CHECK_AND_RETURN_NULL(actor0 != actor1, "PxD6JointCreate: actors must be different"); PX_CHECK_AND_RETURN_NULL((actor0 && actor0->is<PxRigidBody>()) || (actor1 && actor1->is<PxRigidBody>()), "PxD6JointCreate: at least one actor must be dynamic"); D6Joint* j; PX_NEW_SERIALIZED(j, D6Joint)(physics.getTolerancesScale(), actor0, localFrame0, actor1, localFrame1); if(j->attach(physics, actor0, actor1)) return j; PX_DELETE(j); return NULL; } D6Joint::D6Joint(const PxTolerancesScale& scale, PxRigidActor* actor0, const PxTransform& localFrame0, PxRigidActor* actor1, const PxTransform& localFrame1) : D6JointT(PxJointConcreteType::eD6, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE, actor0, localFrame0, actor1, localFrame1, sizeof(D6JointData), "D6JointData"), mRecomputeMotion (true) { D6JointData* data = static_cast<D6JointData*>(mData); for(PxU32 i=0;i<6;i++) data->motion[i] = PxD6Motion::eLOCKED; data->twistLimit = PxJointAngularLimitPair(-PxPi/2, PxPi/2); data->swingLimit = PxJointLimitCone(PxPi/2, PxPi/2); data->pyramidSwingLimit = PxJointLimitPyramid(-PxPi/2, PxPi/2, -PxPi/2, PxPi/2); data->distanceLimit = PxJointLinearLimit(scale, PX_MAX_F32); data->distanceMinDist = 1e-6f*scale.length; data->linearLimitX = PxJointLinearLimitPair(scale); data->linearLimitY = PxJointLinearLimitPair(scale); data->linearLimitZ = PxJointLinearLimitPair(scale); for(PxU32 i=0;i<PxD6Drive::eCOUNT;i++) data->drive[i] = PxD6JointDrive(); data->drivePosition = PxTransform(PxIdentity); data->driveLinearVelocity = PxVec3(0.0f); data->driveAngularVelocity = PxVec3(0.0f); data->projectionLinearTolerance = 1e10f; data->projectionAngularTolerance = PxPi; data->mUseDistanceLimit = false; data->mUseNewLinearLimits = false; data->mUseConeLimit = false; data->mUsePyramidLimits = false; } PxD6Motion::Enum D6Joint::getMotion(PxD6Axis::Enum index) const { return data().motion[index]; } void D6Joint::setMotion(PxD6Axis::Enum index, PxD6Motion::Enum t) { data().motion[index] = t; mRecomputeMotion = true; markDirty(); } PxReal D6Joint::getTwistAngle() const { return getTwistAngle_Internal(); } PxReal D6Joint::getSwingYAngle() const { return getSwingYAngle_Internal(); } PxReal D6Joint::getSwingZAngle() const { return getSwingZAngle_Internal(); } PxD6JointDrive D6Joint::getDrive(PxD6Drive::Enum index) const { return data().drive[index]; } void D6Joint::setDrive(PxD6Drive::Enum index, const PxD6JointDrive& d) { PX_CHECK_AND_RETURN(d.isValid(), "PxD6Joint::setDrive: drive is invalid"); data().drive[index] = d; mRecomputeMotion = true; markDirty(); } void D6Joint::setDistanceLimit(const PxJointLinearLimit& l) { PX_CHECK_AND_RETURN(l.isValid(), "PxD6Joint::setDistanceLimit: limit invalid"); data().distanceLimit = l; data().mUseDistanceLimit = true; markDirty(); } PxJointLinearLimit D6Joint::getDistanceLimit() const { return data().distanceLimit; } void D6Joint::setLinearLimit(PxD6Axis::Enum axis, const PxJointLinearLimitPair& limit) { PX_CHECK_AND_RETURN(axis>=PxD6Axis::eX && axis<=PxD6Axis::eZ, "PxD6Joint::setLinearLimit: invalid axis value"); PX_CHECK_AND_RETURN(limit.isValid(), "PxD6Joint::setLinearLimit: limit invalid"); D6JointData& d = data(); if(axis==PxD6Axis::eX) d.linearLimitX = limit; else if(axis==PxD6Axis::eY) d.linearLimitY = limit; else if(axis==PxD6Axis::eZ) d.linearLimitZ = limit; else return; d.mUseNewLinearLimits = true; markDirty(); } PxJointLinearLimitPair D6Joint::getLinearLimit(PxD6Axis::Enum axis) const { PX_CHECK_AND_RETURN_VAL(axis>=PxD6Axis::eX && axis<=PxD6Axis::eZ, "PxD6Joint::getLinearLimit: invalid axis value", PxJointLinearLimitPair(PxTolerancesScale(), 0.0f, 0.0f)); const D6JointData& d = data(); if(axis==PxD6Axis::eX) return d.linearLimitX; else if(axis==PxD6Axis::eY) return d.linearLimitY; else if(axis==PxD6Axis::eZ) return d.linearLimitZ; return PxJointLinearLimitPair(PxTolerancesScale(), 0.0f, 0.0f); } PxJointAngularLimitPair D6Joint::getTwistLimit() const { return data().twistLimit; } void D6Joint::setTwistLimit(const PxJointAngularLimitPair& l) { PX_CHECK_AND_RETURN(l.isValid(), "PxD6Joint::setTwistLimit: limit invalid"); // PT: the tangent version is not compatible with the double-cover feature, since the potential limit extent in that case is 4*PI. // i.e. we'd potentially take the tangent of something equal to PI/2. So the tangent stuff makes the limits less accurate, and it // also reduces the available angular range for the joint. All that for questionable performance gains. PX_CHECK_AND_RETURN(l.lower>-PxTwoPi && l.upper<PxTwoPi , "PxD6Joint::twist limit must be strictly between -2*PI and 2*PI"); data().twistLimit = l; markDirty(); } PxJointLimitPyramid D6Joint::getPyramidSwingLimit() const { return data().pyramidSwingLimit; } void D6Joint::setPyramidSwingLimit(const PxJointLimitPyramid& l) { PX_CHECK_AND_RETURN(l.isValid(), "PxD6Joint::setPyramidSwingLimit: limit invalid"); data().pyramidSwingLimit = l; data().mUsePyramidLimits = true; markDirty(); } PxJointLimitCone D6Joint::getSwingLimit() const { return data().swingLimit; } void D6Joint::setSwingLimit(const PxJointLimitCone& l) { PX_CHECK_AND_RETURN(l.isValid(), "PxD6Joint::setSwingLimit: limit invalid"); data().swingLimit = l; data().mUseConeLimit = true; markDirty(); } PxTransform D6Joint::getDrivePosition() const { return data().drivePosition; } void D6Joint::setDrivePosition(const PxTransform& pose, bool autowake) { PX_CHECK_AND_RETURN(pose.isSane(), "PxD6Joint::setDrivePosition: pose invalid"); data().drivePosition = pose.getNormalized(); if(autowake) wakeUpActors(); markDirty(); } void D6Joint::getDriveVelocity(PxVec3& linear, PxVec3& angular) const { linear = data().driveLinearVelocity; angular = data().driveAngularVelocity; } void D6Joint::setDriveVelocity(const PxVec3& linear, const PxVec3& angular, bool autowake) { PX_CHECK_AND_RETURN(linear.isFinite() && angular.isFinite(), "PxD6Joint::setDriveVelocity: velocity invalid"); data().driveLinearVelocity = linear; data().driveAngularVelocity = angular; if(autowake) wakeUpActors(); markDirty(); } void D6Joint::setProjectionAngularTolerance(PxReal tolerance) { PX_CHECK_AND_RETURN(PxIsFinite(tolerance) && tolerance >=0 && tolerance <= PxPi, "PxD6Joint::setProjectionAngularTolerance: tolerance invalid"); data().projectionAngularTolerance = tolerance; markDirty(); } PxReal D6Joint::getProjectionAngularTolerance() const { return data().projectionAngularTolerance; } void D6Joint::setProjectionLinearTolerance(PxReal tolerance) { PX_CHECK_AND_RETURN(PxIsFinite(tolerance) && tolerance >=0, "PxD6Joint::setProjectionLinearTolerance: invalid parameter"); data().projectionLinearTolerance = tolerance; markDirty(); } PxReal D6Joint::getProjectionLinearTolerance() const { return data().projectionLinearTolerance; } void* D6Joint::prepareData() { D6JointData& d = data(); if(mRecomputeMotion) { mRecomputeMotion = false; d.driving = 0; d.limited = 0; d.locked = 0; for(PxU32 i=0;i<PxD6Axis::eCOUNT;i++) { if(d.motion[i] == PxD6Motion::eLIMITED) d.limited |= 1<<i; else if(d.motion[i] == PxD6Motion::eLOCKED) d.locked |= 1<<i; } // a linear direction isn't driven if it's locked if(active(PxD6Drive::eX) && d.motion[PxD6Axis::eX]!=PxD6Motion::eLOCKED) d.driving |= 1<< PxD6Drive::eX; if(active(PxD6Drive::eY) && d.motion[PxD6Axis::eY]!=PxD6Motion::eLOCKED) d.driving |= 1<< PxD6Drive::eY; if(active(PxD6Drive::eZ) && d.motion[PxD6Axis::eZ]!=PxD6Motion::eLOCKED) d.driving |= 1<< PxD6Drive::eZ; // SLERP drive requires all angular dofs unlocked, and inhibits swing/twist const bool swing1Locked = d.motion[PxD6Axis::eSWING1] == PxD6Motion::eLOCKED; const bool swing2Locked = d.motion[PxD6Axis::eSWING2] == PxD6Motion::eLOCKED; const bool twistLocked = d.motion[PxD6Axis::eTWIST] == PxD6Motion::eLOCKED; if(active(PxD6Drive::eSLERP) && !swing1Locked && !swing2Locked && !twistLocked) d.driving |= 1<<PxD6Drive::eSLERP; else { if(active(PxD6Drive::eTWIST) && !twistLocked) d.driving |= 1<<PxD6Drive::eTWIST; if(active(PxD6Drive::eSWING) && (!swing1Locked || !swing2Locked)) d.driving |= 1<< PxD6Drive::eSWING; } } this->D6JointT::prepareData(); return mData; } bool D6Joint::attach(PxPhysics &physics, PxRigidActor* actor0, PxRigidActor* actor1) { mPxConstraint = physics.createConstraint(actor0, actor1, *this, sShaders, sizeof(D6JointData)); return mPxConstraint!=NULL; } void D6Joint::exportExtraData(PxSerializationContext& stream) { if(mData) { stream.alignData(PX_SERIAL_ALIGN); stream.writeData(mData, sizeof(D6JointData)); } stream.writeName(mName); } void D6Joint::importExtraData(PxDeserializationContext& context) { if(mData) mData = context.readExtraData<D6JointData, PX_SERIAL_ALIGN>(); context.readName(mName); } void D6Joint::resolveReferences(PxDeserializationContext& context) { setPxConstraint(resolveConstraintPtr(context, getPxConstraint(), getConnector(), sShaders)); } D6Joint* D6Joint::createObject(PxU8*& address, PxDeserializationContext& context) { D6Joint* obj = new (address) D6Joint(PxBaseFlag::eIS_RELEASABLE); address += sizeof(D6Joint); obj->importExtraData(context); obj->resolveReferences(context); return obj; } // global function to share the joint shaders with API capture const PxConstraintShaderTable* Ext::GetD6JointShaderTable() { return &D6Joint::getConstraintShaderTable(); } //~PX_SERIALIZATION // Notes: /* This used to be in the linear drive model: if(motion[PxD6Axis::eX+i] == PxD6Motion::eLIMITED) { if(data.driveLinearVelocity[i] < 0.0f && cB2cA.p[i] < -mLimits[PxD6Limit::eLINEAR].mValue || data.driveLinearVelocity[i] > 0.0f && cB2cA.p[i] > mLimits[PxD6Limit::eLINEAR].mValue) continue; } it doesn't seem like a good idea though, because it turns off drive altogether, despite the fact that positional drive might pull us back in towards the limit. Might be better to make the drive unilateral so it can only pull us in from the limit This used to be in angular locked: // Angular locked //TODO fix this properly. if(PxAbs(cB2cA.q.x) < 0.0001f) cB2cA.q.x = 0; if(PxAbs(cB2cA.q.y) < 0.0001f) cB2cA.q.y = 0; if(PxAbs(cB2cA.q.z) < 0.0001f) cB2cA.q.z = 0; if(PxAbs(cB2cA.q.w) < 0.0001f) cB2cA.q.w = 0; */ static PxQuat truncate(const PxQuat& qIn, PxReal minCosHalfTol, bool& truncated) { const PxQuat q = qIn.w >= 0.0f ? qIn : -qIn; truncated = q.w < minCosHalfTol; if(!truncated) return q; const PxVec3 v = q.getImaginaryPart().getNormalized() * PxSqrt(1.0f - minCosHalfTol * minCosHalfTol); return PxQuat(v.x, v.y, v.z, minCosHalfTol); } // we decompose the quaternion as q1 * q2, where q1 is a rotation orthogonal to the unit axis, and q2 a rotation around it. // (so for example if 'axis' is the twist axis, this is separateSwingTwist). static PxQuat project(const PxQuat& q, const PxVec3& axis, PxReal cosHalfTol, bool& truncated) { const PxReal a = q.getImaginaryPart().dot(axis); const PxQuat q2 = PxAbs(a) >= 1e-6f ? PxQuat(a*axis.x, a*axis.y, a*axis.z, q.w).getNormalized() : PxQuat(PxIdentity); const PxQuat q1 = q * q2.getConjugate(); PX_ASSERT(PxAbs(q1.getImaginaryPart().dot(q2.getImaginaryPart())) < 1e-6f); return truncate(q1, cosHalfTol, truncated) * q2; } // Here's how the angular part works: // * if no DOFs are locked, there's nothing to do. // * if all DOFs are locked, we just truncate the rotation // * if two DOFs are locked // * we decompose the rotation into swing * twist, where twist is a rotation around the free DOF and swing is a rotation around an axis orthogonal to the free DOF // * then we truncate swing // The case of one locked DOF is currently unimplemented, but one option would be: // * if one DOF is locked (the tricky case), we define the 'free' axis as follows (as the velocity solver prep function does) // TWIST: cB[0] // SWING1: cB[0].cross(cA[2]) // SWING2: cB[0].cross(cA[1]) // then, as above, we decompose into swing * free, and truncate the free rotation //export this in the physx namespace so we can unit test it namespace physx { PxQuat angularProject(PxU32 lockedDofs, const PxQuat& q, PxReal cosHalfTol, bool& truncated) { PX_ASSERT(lockedDofs <= 7); truncated = false; switch(lockedDofs) { case 0: return q; case 1: return q; // currently unimplemented case 2: return q; // currently unimplemented case 3: return project(q, PxVec3(0.0f, 0.0f, 1.0f), cosHalfTol, truncated); case 4: return q; // currently unimplemented case 5: return project(q, PxVec3(0.0f, 1.0f, 0.0f), cosHalfTol, truncated); case 6: return project(q, PxVec3(1.0f, 0.0f, 0.0f), cosHalfTol, truncated); case 7: return truncate(q, cosHalfTol, truncated); default: return PxQuat(PxIdentity); } } } static void D6JointProject(const void* constantBlock, PxTransform& bodyAToWorld, PxTransform& bodyBToWorld, bool projectToA) { const D6JointData& data = *reinterpret_cast<const D6JointData*>(constantBlock); PxTransform cA2w, cB2w, cB2cA, projected; joint::computeDerived(data, bodyAToWorld, bodyBToWorld, cA2w, cB2w, cB2cA, false); const PxVec3 v(data.locked & 1 ? cB2cA.p.x : 0.0f, data.locked & 2 ? cB2cA.p.y : 0.0f, data.locked & 4 ? cB2cA.p.z : 0.0f); bool linearTrunc, angularTrunc = false; projected.p = joint::truncateLinear(v, data.projectionLinearTolerance, linearTrunc) + (cB2cA.p - v); projected.q = angularProject(data.locked >> 3, cB2cA.q, PxCos(data.projectionAngularTolerance / 2), angularTrunc); if(linearTrunc || angularTrunc) joint::projectTransforms(bodyAToWorld, bodyBToWorld, cA2w, cB2w, projected, data, projectToA); } static PX_FORCE_INLINE PxReal computePhi(const PxQuat& q) { PxQuat twist = q; twist.normalize(); PxReal angle = twist.getAngle(); if(twist.x<0.0f) angle = -angle; return angle; } static void visualizeAngularLimit(PxConstraintVisualizer& viz, const D6JointData& data, const PxTransform& t, float swingYZ, float swingW, float swingLimitYZ) { bool active = PxAbs(computeSwingAngle(swingYZ, swingW)) > swingLimitYZ - data.swingLimit.contactDistance; viz.visualizeAngularLimit(t, -swingLimitYZ, swingLimitYZ, active); } static void visualizeDoubleCone(PxConstraintVisualizer& viz, const D6JointData& data, const PxTransform& t, float sin, float swingLimitYZ) { const PxReal angle = PxAsin(sin); const PxReal pad = data.swingLimit.contactDistance; const PxReal low = -swingLimitYZ; const PxReal high = swingLimitYZ; const bool active = isLimitActive(data.swingLimit, pad, angle, low, high); viz.visualizeDoubleCone(t, swingLimitYZ, active); } // PT: TODO: refactor with spherical joint code static void visualizeCone(PxConstraintVisualizer& viz, const D6JointData& data, const PxQuat& swing, const PxTransform& cA2w) { const PxVec3 swingAngle(0.0f, computeSwingAngle(swing.y, swing.w), computeSwingAngle(swing.z, swing.w)); const PxReal pad = data.swingLimit.isSoft() ? 0.0f : data.swingLimit.contactDistance; Cm::ConeLimitHelperTanLess coneHelper(data.swingLimit.yAngle, data.swingLimit.zAngle, pad); viz.visualizeLimitCone(cA2w, PxTan(data.swingLimit.zAngle / 4), PxTan(data.swingLimit.yAngle / 4), !coneHelper.contains(swingAngle)); } static PX_FORCE_INLINE bool isLinearLimitActive(const PxJointLinearLimitPair& limit, float ordinate) { const PxReal pad = limit.isSoft() ? 0.0f : limit.contactDistance; return (ordinate < limit.lower + pad) || (ordinate > limit.upper - pad); } static void visualizeLine(PxConstraintVisualizer& viz, const PxVec3& origin, const PxVec3& axis, const PxJointLinearLimitPair& limit, float ordinate) { const bool active = isLinearLimitActive(limit, ordinate); const PxVec3 p0 = origin + axis * limit.lower; const PxVec3 p1 = origin + axis * limit.upper; viz.visualizeLine(p0, p1, active ? 0xff0000u : 0xffffffu); } static void visualizeQuad(PxConstraintVisualizer& viz, const PxVec3& origin, const PxVec3& axis0, const PxJointLinearLimitPair& limit0, float ordinate0, const PxVec3& axis1, const PxJointLinearLimitPair& limit1, float ordinate1) { const bool active0 = isLinearLimitActive(limit0, ordinate0); const bool active1 = isLinearLimitActive(limit1, ordinate1); const PxU32 color = (active0 || active1) ? 0xff0000u : 0xffffffu; const PxVec3 l0 = axis0 * limit0.lower; const PxVec3 u0 = axis0 * limit0.upper; const PxVec3 l1 = axis1 * limit1.lower; const PxVec3 u1 = axis1 * limit1.upper; const PxVec3 p0 = origin + l0 + l1; const PxVec3 p1 = origin + u0 + l1; const PxVec3 p2 = origin + u0 + u1; const PxVec3 p3 = origin + l0 + u1; viz.visualizeLine(p0, p1, color); viz.visualizeLine(p1, p2, color); viz.visualizeLine(p2, p3, color); viz.visualizeLine(p3, p0, color); } static void visualizeBox(PxConstraintVisualizer& viz, const PxVec3& origin, const PxVec3& axis0, const PxJointLinearLimitPair& limit0, float ordinate0, const PxVec3& axis1, const PxJointLinearLimitPair& limit1, float ordinate1, const PxVec3& axis2, const PxJointLinearLimitPair& limit2, float ordinate2) { const bool active0 = isLinearLimitActive(limit0, ordinate0); const bool active1 = isLinearLimitActive(limit1, ordinate1); const bool active2 = isLinearLimitActive(limit2, ordinate2); const PxU32 color = (active0 || active1 || active2) ? 0xff0000u : 0xffffffu; const PxVec3 l0 = axis0 * limit0.lower; const PxVec3 u0 = axis0 * limit0.upper; const PxVec3 l1 = axis1 * limit1.lower; const PxVec3 u1 = axis1 * limit1.upper; const PxVec3 l2 = axis2 * limit2.lower; const PxVec3 u2 = axis2 * limit2.upper; const PxVec3 p0 = origin + l0 + l1 + l2; const PxVec3 p1 = origin + u0 + l1 + l2; const PxVec3 p2 = origin + u0 + u1 + l2; const PxVec3 p3 = origin + l0 + u1 + l2; const PxVec3 p0b = origin + l0 + l1 + u2; const PxVec3 p1b = origin + u0 + l1 + u2; const PxVec3 p2b = origin + u0 + u1 + u2; const PxVec3 p3b = origin + l0 + u1 + u2; viz.visualizeLine(p0, p1, color); viz.visualizeLine(p1, p2, color); viz.visualizeLine(p2, p3, color); viz.visualizeLine(p3, p0, color); viz.visualizeLine(p0b, p1b, color); viz.visualizeLine(p1b, p2b, color); viz.visualizeLine(p2b, p3b, color); viz.visualizeLine(p3b, p0b, color); viz.visualizeLine(p0, p0b, color); viz.visualizeLine(p1, p1b, color); viz.visualizeLine(p2, p2b, color); viz.visualizeLine(p3, p3b, color); } static float computeLimitedDistance(const D6JointData& data, const PxTransform& cB2cA, const PxMat33& cA2w_m, PxVec3& _limitDir) { PxVec3 limitDir(0.0f); for(PxU32 i = 0; i<3; i++) { if(data.limited & (1 << (PxD6Axis::eX + i))) limitDir += cA2w_m[i] * cB2cA.p[i]; } _limitDir = limitDir; return limitDir.magnitude(); } void _setRotY(PxMat33& m, PxReal angle) { m = PxMat33(PxIdentity); const PxReal cos = cosf(angle); const PxReal sin = sinf(angle); m[0][0] = m[2][2] = cos; m[0][2] = -sin; m[2][0] = sin; } void _setRotZ(PxMat33& m, PxReal angle) { m = PxMat33(PxIdentity); const PxReal cos = cosf(angle); const PxReal sin = sinf(angle); m[0][0] = m[1][1] = cos; m[0][1] = sin; m[1][0] = -sin; } PxQuat _getRotYQuat(float angle) { PxMat33 m; _setRotY(m, angle); return PxQuat(m); } PxQuat _getRotZQuat(float angle) { PxMat33 m; _setRotZ(m, angle); return PxQuat(m); } void _setRotX(PxMat33& m, PxReal angle) { m = PxMat33(PxIdentity); const PxReal cos = cosf(angle); const PxReal sin = sinf(angle); m[1][1] = m[2][2] = cos; m[1][2] = sin; m[2][1] = -sin; } PxQuat _getRotXQuat(float angle) { PxMat33 m; _setRotX(m, angle); return PxQuat(m); } static void drawPyramid(PxConstraintVisualizer& viz, const D6JointData& data, const PxTransform& cA2w, const PxQuat& swing, bool useY, bool useZ) { struct Local { static void drawArc(PxConstraintVisualizer& _viz, const PxTransform& _cA2w, float ymin, float ymax, float zmin, float zmax, PxU32 color) { // PT: we use 32 segments for the cone case, so that's 32/4 segments per arc in the pyramid case const PxU32 nb = 32/4; PxVec3 prev(0.0f); for(PxU32 i=0;i<nb;i++) { const float coeff = float(i)/float(nb-1); const float y = coeff*ymax + (1.0f-coeff)*ymin; const float z = coeff*zmax + (1.0f-coeff)*zmin; const float r = 1.0f; PxMat33 my; _setRotZ(my, z); PxMat33 mz; _setRotY(mz, y); const PxVec3 p0 = (my*mz).transform(PxVec3(r, 0.0f, 0.0f)); const PxVec3 p0w = _cA2w.transform(p0); _viz.visualizeLine(_cA2w.p, p0w, color); if(i) _viz.visualizeLine(prev, p0w, color); prev = p0w; } } }; const PxJointLimitPyramid& l = data.pyramidSwingLimit; const bool activeY = useY ? isLimitActive(l, l.contactDistance, computeSwingAngle(swing.y, swing.w), l.yAngleMin, l.yAngleMax) : false; const bool activeZ = useZ ? isLimitActive(l, l.contactDistance, computeSwingAngle(swing.z, swing.w), l.zAngleMin, l.zAngleMax) : false; const PxU32 color = (activeY||activeZ) ? PxDebugColor::eARGB_RED : PxDebugColor::eARGB_GREY; Local::drawArc(viz, cA2w, l.yAngleMin, l.yAngleMin, l.zAngleMin, l.zAngleMax, color); Local::drawArc(viz, cA2w, l.yAngleMax, l.yAngleMax, l.zAngleMin, l.zAngleMax, color); Local::drawArc(viz, cA2w, l.yAngleMin, l.yAngleMax, l.zAngleMin, l.zAngleMin, color); Local::drawArc(viz, cA2w, l.yAngleMin, l.yAngleMax, l.zAngleMax, l.zAngleMax, color); } static void D6JointVisualize(PxConstraintVisualizer& viz, const void* constantBlock, const PxTransform& body0Transform, const PxTransform& body1Transform, PxU32 flags) { const PxU32 SWING1_FLAG = 1<<PxD6Axis::eSWING1, SWING2_FLAG = 1<<PxD6Axis::eSWING2, TWIST_FLAG = 1<<PxD6Axis::eTWIST; const PxU32 ANGULAR_MASK = SWING1_FLAG | SWING2_FLAG | TWIST_FLAG; const PxU32 LINEAR_MASK = 1<<PxD6Axis::eX | 1<<PxD6Axis::eY | 1<<PxD6Axis::eZ; PX_UNUSED(ANGULAR_MASK); PX_UNUSED(LINEAR_MASK); const D6JointData& data = *reinterpret_cast<const D6JointData*>(constantBlock); PxTransform cA2w, cB2w; joint::computeJointFrames(cA2w, cB2w, data, body0Transform, body1Transform); if(flags & PxConstraintVisualizationFlag::eLOCAL_FRAMES) viz.visualizeJointFrames(cA2w, cB2w); if(flags & PxConstraintVisualizationFlag::eLIMITS) { // PT: it is a mistake to use the neighborhood operator since it // prevents us from using the quat's double-cover feature. // if(cA2w.q.dot(cB2w.q)<0.0f) // cB2w.q = -cB2w.q; const PxTransform cB2cA = cA2w.transformInv(cB2w); const PxMat33 cA2w_m(cA2w.q), cB2w_m(cB2w.q); if(data.mUseNewLinearLimits) { switch(data.limited) { case 1<<PxD6Axis::eX: visualizeLine(viz, cA2w.p, cA2w_m.column0, data.linearLimitX, cB2cA.p.x); break; case 1<<PxD6Axis::eY: visualizeLine(viz, cA2w.p, cA2w_m.column1, data.linearLimitY, cB2cA.p.y); break; case 1<<PxD6Axis::eZ: visualizeLine(viz, cA2w.p, cA2w_m.column2, data.linearLimitZ, cB2cA.p.z); break; case 1<<PxD6Axis::eX|1<<PxD6Axis::eY: visualizeQuad(viz, cA2w.p, cA2w_m.column0, data.linearLimitX, cB2cA.p.x, cA2w_m.column1, data.linearLimitY, cB2cA.p.y); break; case 1<<PxD6Axis::eX|1<<PxD6Axis::eZ: visualizeQuad(viz, cA2w.p, cA2w_m.column0, data.linearLimitX, cB2cA.p.x, cA2w_m.column2, data.linearLimitZ, cB2cA.p.z); break; case 1<<PxD6Axis::eY|1<<PxD6Axis::eZ: visualizeQuad(viz, cA2w.p, cA2w_m.column1, data.linearLimitY, cB2cA.p.y, cA2w_m.column2, data.linearLimitZ, cB2cA.p.z); break; case 1<<PxD6Axis::eX|1<<PxD6Axis::eY|1<<PxD6Axis::eZ: visualizeBox(viz, cA2w.p, cA2w_m.column0, data.linearLimitX, cB2cA.p.x, cA2w_m.column1, data.linearLimitY, cB2cA.p.y, cA2w_m.column2, data.linearLimitZ, cB2cA.p.z); break; } } if(data.mUseDistanceLimit) // PT: old linear/distance limit { PxVec3 limitDir; const float distance = computeLimitedDistance(data, cB2cA, cA2w_m, limitDir); // visualise only if some of the axis is limited if(distance > data.distanceMinDist) { PxU32 color = 0x00ff00; if(distance>data.distanceLimit.value) color = 0xff0000; viz.visualizeLine(cA2w.p, cB2w.p, color); } } PxQuat swing, twist; Ps::separateSwingTwist(cB2cA.q, swing, twist); const PxVec3& bX = cB2w_m.column0; const PxVec3& aY = cA2w_m.column1; const PxVec3& aZ = cA2w_m.column2; if(data.limited&TWIST_FLAG) { const PxReal angle = computePhi(twist); const PxReal pad = data.twistLimit.contactDistance; const PxReal low = data.twistLimit.lower; const PxReal high = data.twistLimit.upper; const bool active = isLimitActive(data.twistLimit, pad, angle, low, high); viz.visualizeAngularLimit(cA2w, data.twistLimit.lower, data.twistLimit.upper, active); } const bool swing1Limited = (data.limited & SWING1_FLAG)!=0, swing2Limited = (data.limited & SWING2_FLAG)!=0; if(swing1Limited && swing2Limited) { if(data.mUseConeLimit) visualizeCone(viz, data, swing, cA2w); if(data.mUsePyramidLimits) drawPyramid(viz, data, cA2w, swing, true, true); } else if(swing1Limited ^ swing2Limited) { const PxTransform yToX(PxVec3(0.0f), PxQuat(-PxPi/2.0f, PxVec3(0.0f, 0.0f, 1.0f))); const PxTransform zToX(PxVec3(0.0f), PxQuat(PxPi/2.0f, PxVec3(0.0f, 1.0f, 0.0f))); if(swing1Limited) { if(data.locked & SWING2_FLAG) { if(data.mUsePyramidLimits) drawPyramid(viz, data, cA2w, swing, true, false); else visualizeAngularLimit(viz, data, cA2w * yToX, swing.y, swing.w, data.swingLimit.yAngle); // PT: swing Y limited, swing Z locked } else if(!data.mUsePyramidLimits) visualizeDoubleCone(viz, data, cA2w * zToX, aZ.dot(bX), data.swingLimit.yAngle); // PT: swing Y limited, swing Z free } else { if(data.locked & SWING1_FLAG) { if(data.mUsePyramidLimits) drawPyramid(viz, data, cA2w, swing, false, true); else visualizeAngularLimit(viz, data, cA2w * zToX, swing.z, swing.w, data.swingLimit.zAngle); // PT: swing Z limited, swing Y locked } else if(!data.mUsePyramidLimits) visualizeDoubleCone(viz, data, cA2w * yToX, aY.dot(bX), data.swingLimit.zAngle); // PT: swing Z limited, swing Y free } } } } static PX_FORCE_INLINE void setupSingleSwingLimit(joint::ConstraintHelper& ch, const D6JointData& data, const PxVec3& axis, float swingYZ, float swingW, float swingLimitYZ) { ch.anglePair(computeSwingAngle(swingYZ, swingW), -swingLimitYZ, swingLimitYZ, data.swingLimit.contactDistance, axis, data.swingLimit); } static PX_FORCE_INLINE void setupDualConeSwingLimits(joint::ConstraintHelper& ch, const D6JointData& data, const PxVec3& axis, float sin, float swingLimitYZ) { ch.anglePair(PxAsin(sin), -swingLimitYZ, swingLimitYZ, data.swingLimit.contactDistance, axis.getNormalized(), data.swingLimit); } // PT: TODO: refactor with spherical joint code static void setupConeSwingLimits(joint::ConstraintHelper& ch, const D6JointData& data, const PxQuat& swing, const PxTransform& cA2w) { PxVec3 axis; PxReal error; const PxReal pad = data.swingLimit.isSoft() ? 0.0f : data.swingLimit.contactDistance; const Cm::ConeLimitHelperTanLess coneHelper(data.swingLimit.yAngle, data.swingLimit.zAngle, pad); bool active = coneHelper.getLimit(swing, axis, error); if(active) ch.angularLimit(cA2w.rotate(axis), error, data.swingLimit); } static void setupPyramidSwingLimits(joint::ConstraintHelper& ch, const D6JointData& data, const PxQuat& swing, const PxTransform& cA2w, bool useY, bool useZ) { const PxQuat q = cA2w.q * swing; const PxJointLimitPyramid& l = data.pyramidSwingLimit; if(useY) ch.anglePair(computeSwingAngle(swing.y, swing.w), l.yAngleMin, l.yAngleMax, l.contactDistance, q.getBasisVector1(), l); if(useZ) ch.anglePair(computeSwingAngle(swing.z, swing.w), l.zAngleMin, l.zAngleMax, l.contactDistance, q.getBasisVector2(), l); } static void setupLinearLimit(joint::ConstraintHelper& ch, const PxJointLinearLimitPair& limit, const float origin, const PxVec3& axis) { ch.linearLimit(axis, origin, limit.upper, limit); ch.linearLimit(-axis, -origin, -limit.lower, limit); } static PxU32 D6JointSolverPrep(Px1DConstraint* constraints, PxVec3& body0WorldOffset, PxU32 /*maxConstraints*/, PxConstraintInvMassScale& invMassScale, const void* constantBlock, const PxTransform& bA2w, const PxTransform& bB2w, bool useExtendedLimits, PxVec3& cA2wOut, PxVec3& cB2wOut) { const D6JointData& data = *reinterpret_cast<const D6JointData*>(constantBlock); PxTransform cA2w, cB2w; joint::ConstraintHelper ch(constraints, invMassScale, cA2w, cB2w, body0WorldOffset, data, bA2w, bB2w); const PxU32 SWING1_FLAG = 1<<PxD6Axis::eSWING1; const PxU32 SWING2_FLAG = 1<<PxD6Axis::eSWING2; const PxU32 TWIST_FLAG = 1<<PxD6Axis::eTWIST; const PxU32 ANGULAR_MASK = SWING1_FLAG | SWING2_FLAG | TWIST_FLAG; const PxU32 LINEAR_MASK = 1<<PxD6Axis::eX | 1<<PxD6Axis::eY | 1<<PxD6Axis::eZ; const PxD6JointDrive* drives = data.drive; PxU32 locked = data.locked; const PxU32 limited = data.limited; const PxU32 driving = data.driving; // PT: it is a mistake to use the neighborhood operator since it // prevents us from using the quat's double-cover feature. if(!useExtendedLimits && cA2w.q.dot(cB2w.q)<0.0f) // minimum dist quat (equiv to flipping cB2bB.q, which we don't use anywhere) cB2w.q = -cB2w.q; const PxTransform cB2cA = cA2w.transformInv(cB2w); PX_ASSERT(data.c2b[0].isValid()); PX_ASSERT(data.c2b[1].isValid()); PX_ASSERT(cA2w.isValid()); PX_ASSERT(cB2w.isValid()); PX_ASSERT(cB2cA.isValid()); const PxMat33 cA2w_m(cA2w.q); const PxMat33 cB2w_m(cB2w.q); // handy for swing computation const PxVec3& bX = cB2w_m.column0; const PxVec3& aY = cA2w_m.column1; const PxVec3& aZ = cA2w_m.column2; if(driving & ((1<<PxD6Drive::eX)|(1<<PxD6Drive::eY)|(1<<PxD6Drive::eZ))) { // TODO: make drive unilateral if we are outside the limit const PxVec3 posErr = data.drivePosition.p - cB2cA.p; for(PxU32 i=0; i<3; i++) { // -driveVelocity because velTarget is child (body1) - parent (body0) and Jacobian is 1 for body0 and -1 for parent if(driving & (1<<(PxD6Drive::eX+i))) ch.linear(cA2w_m[i], -data.driveLinearVelocity[i], posErr[i], drives[PxD6Drive::eX+i]); } } if(driving & ((1<<PxD6Drive::eSLERP)|(1<<PxD6Drive::eSWING)|(1<<PxD6Drive::eTWIST))) { const PxQuat d2cA_q = cB2cA.q.dot(data.drivePosition.q)>0.0f ? data.drivePosition.q : -data.drivePosition.q; const PxVec3& v = data.driveAngularVelocity; const PxQuat delta = d2cA_q.getConjugate() * cB2cA.q; if(driving & (1<<PxD6Drive::eSLERP)) { const PxVec3 velTarget = -cA2w.rotate(data.driveAngularVelocity); PxVec3 axis[3] = { PxVec3(1.0f, 0.0f, 0.0f), PxVec3(0.0f, 1.0f, 0.0f), PxVec3(0.0f, 0.0f, 1.0f) }; if(drives[PxD6Drive::eSLERP].stiffness!=0.0f) joint::computeJacobianAxes(axis, cA2w.q * d2cA_q, cB2w.q); // converges faster if there is only velocity drive for(PxU32 i=0; i<3; i++) ch.angular(axis[i], axis[i].dot(velTarget), -delta.getImaginaryPart()[i], drives[PxD6Drive::eSLERP], PxConstraintSolveHint::eSLERP_SPRING); } else { if(driving & (1<<PxD6Drive::eTWIST)) ch.angular(bX, v.x, -2.0f * delta.x, drives[PxD6Drive::eTWIST]); if(driving & (1<<PxD6Drive::eSWING)) { const PxVec3 err = delta.rotate(PxVec3(1.0f, 0.0f, 0.0f)); if(!(locked & SWING1_FLAG)) ch.angular(cB2w_m[1], v.y, err.z, drives[PxD6Drive::eSWING]); if(!(locked & SWING2_FLAG)) ch.angular(cB2w_m[2], v.z, -err.y, drives[PxD6Drive::eSWING]); } } } if(limited & ANGULAR_MASK) { PxQuat swing, twist; Ps::separateSwingTwist(cB2cA.q, swing, twist); // swing limits: if just one is limited: if the other is free, we support // (-pi/2, +pi/2) limit, using tan of the half-angle as the error measure parameter. // If the other is locked, we support (-pi, +pi) limits using the tan of the quarter-angle // Notation: th == Ps::tanHalf, tq = tanQuarter if(limited & SWING1_FLAG && limited & SWING2_FLAG) { if(data.mUseConeLimit) setupConeSwingLimits(ch, data, swing, cA2w); // PT: no else here by design, we want to allow creating both the cone & the pyramid at the same time, // which can be useful to make the cone more robust against large velocities. if(data.mUsePyramidLimits) setupPyramidSwingLimits(ch, data, swing, cA2w, true, true); } else { if(limited & SWING1_FLAG) { if(locked & SWING2_FLAG) { if(data.mUsePyramidLimits) setupPyramidSwingLimits(ch, data, swing, cA2w, true, false); else setupSingleSwingLimit(ch, data, aY, swing.y, swing.w, data.swingLimit.yAngle); // PT: swing Y limited, swing Z locked } else { if(!data.mUsePyramidLimits) setupDualConeSwingLimits(ch, data, aZ.cross(bX), -aZ.dot(bX), data.swingLimit.yAngle); // PT: swing Y limited, swing Z free else Ps::getFoundation().error(PxErrorCode::eINVALID_OPERATION, __FILE__, __LINE__, "D6JointSolverPrep: invalid joint setup. Double pyramid mode not supported."); } } if(limited & SWING2_FLAG) { if(locked & SWING1_FLAG) { if(data.mUsePyramidLimits) setupPyramidSwingLimits(ch, data, swing, cA2w, false, true); else setupSingleSwingLimit(ch, data, aZ, swing.z, swing.w, data.swingLimit.zAngle); // PT: swing Z limited, swing Y locked } else if(!data.mUsePyramidLimits) setupDualConeSwingLimits(ch, data, -aY.cross(bX), aY.dot(bX), data.swingLimit.zAngle); // PT: swing Z limited, swing Y free else Ps::getFoundation().error(PxErrorCode::eINVALID_OPERATION, __FILE__, __LINE__, "D6JointSolverPrep: invalid joint setup. Double pyramid mode not supported."); } } if(limited & TWIST_FLAG) { ch.anglePair(computePhi(twist), data.twistLimit.lower, data.twistLimit.upper, data.twistLimit.contactDistance, cB2w_m.column0, data.twistLimit); } } if(limited & LINEAR_MASK) { if(data.mUseDistanceLimit) // PT: old linear/distance limit { PxVec3 limitDir; const float distance = computeLimitedDistance(data, cB2cA, cA2w_m, limitDir); if(distance > data.distanceMinDist) ch.linearLimit(limitDir * (1.0f/distance), distance, data.distanceLimit.value, data.distanceLimit); } if(data.mUseNewLinearLimits) // PT: new asymmetric linear limits { const PxVec3& bOriginInA = cB2cA.p; // PT: TODO: we check that the DOFs are not "locked" to be consistent with the prismatic joint, but it // doesn't look like this case is possible, since it would be caught by the "isValid" check when setting // the limits. And in fact the "distance" linear limit above doesn't do this check. if((limited & (1<<PxD6Axis::eX)) && data.linearLimitX.lower <= data.linearLimitX.upper) setupLinearLimit(ch, data.linearLimitX, bOriginInA.x, cA2w_m.column0); if((limited & (1<<PxD6Axis::eY)) && data.linearLimitY.lower <= data.linearLimitY.upper) setupLinearLimit(ch, data.linearLimitY, bOriginInA.y, cA2w_m.column1); if((limited & (1<<PxD6Axis::eZ)) && data.linearLimitZ.lower <= data.linearLimitZ.upper) setupLinearLimit(ch, data.linearLimitZ, bOriginInA.z, cA2w_m.column2); } } // we handle specially the case of just one swing dof locked const PxU32 angularLocked = locked & ANGULAR_MASK; if(angularLocked == SWING1_FLAG) { ch.angularHard(bX.cross(aZ), -bX.dot(aZ)); locked &= ~SWING1_FLAG; } else if(angularLocked == SWING2_FLAG) { locked &= ~SWING2_FLAG; ch.angularHard(bX.cross(aY), -bX.dot(aY)); } PxVec3 ra, rb; ch.prepareLockedAxes(cA2w.q, cB2w.q, cB2cA.p, locked&7, locked>>3, ra, rb); cA2wOut = ra + bA2w.p; cB2wOut = rb + bB2w.p; /*cA2wOut = cA2w.p; cB2wOut = cB2w.p;*/ // PT: TODO: check the number cannot be too high now return ch.getCount(); } PxConstraintShaderTable Ext::D6Joint::sShaders = { D6JointSolverPrep, D6JointProject, D6JointVisualize, /*PxConstraintFlag::Enum(0)*/PxConstraintFlag::eGPU_COMPATIBLE };
35.169118
173
0.722611
[ "model", "transform" ]
02b2f4dcc44252845ce97a4817386f3625c7cd80
7,956
hpp
C++
include/watchdog.hpp
946336/Watchdog
4c8a12ba288bc89022071a034344906ce6beedf8
[ "MIT" ]
1
2019-01-10T02:55:57.000Z
2019-01-10T02:55:57.000Z
include/watchdog.hpp
946336/Watchdog
4c8a12ba288bc89022071a034344906ce6beedf8
[ "MIT" ]
null
null
null
include/watchdog.hpp
946336/Watchdog
4c8a12ba288bc89022071a034344906ce6beedf8
[ "MIT" ]
1
2019-01-10T02:40:08.000Z
2019-01-10T02:40:08.000Z
#ifndef WATCHDOG_H #define WATCHDOG_H #include <errno.h> #include <unistd.h> #include <sys/types.h> // inotify #include <sys/inotify.h> #if WATCHDOG_DEBUG #include <cstdio> #endif #include <functional> #include <utility> #include <algorithm> #include <vector> #include <map> #include <set> #include <flags.hpp> #include <exceptions.hpp> #include <helpers.hpp> #include <watchdog_common.hpp> #include <storage_policies.hpp> // If you want to override the defaults, this will allow you to do so by // defining these names before you include this header. #ifndef WATCHDOG_MAX_EVENTS // Maximum number of events the buffer can hold at once #define WATCHDOG_MAX_EVENTS 1024 #endif #ifndef WATCHDOG_MAX_LEN_NAME // Maximum length of paths to watch #define WATCHDOG_MAX_LEN_NAME 255 #endif #ifndef WATCHDOG_DEBUG #define WATCHDOG_DEBUG false #endif #if WATCHDOG_DEBUG #include <cstdio> #endif namespace Watch { // For more information, see `man inotify` using Event = inotify_event; // Callbacks attached to Events are fired and given the Event as an // argument. using Callback = std::function<void(Event*, std::string path)>; // Do you want to watch directories recursively? enum Recurse { Normally, Recursively }; // max_events and max_len_name used to determine internal buffer length // For more information, see man or info pages for inotify template < Recurse RECURSE, FlagBearer Default_Flags = Flags::Add, class Container = Small, std::size_t MAX_EVENTS = WATCHDOG_MAX_EVENTS, std::size_t MAX_LEN_NAME = WATCHDOG_MAX_LEN_NAME > class Sentry { public: // Don't allow assignment or copying Sentry(const Sentry &src) = delete; Sentry& operator=(const Sentry &src) = delete; // Path is required, but the ignore list is optional Sentry(const std::string &path, const std::set<std::string> ignore = {}) : paths_(1, path), ignored_(ignore) { if (WATCHDOG_DEBUG) { fprintf(stderr, "[DEBUG]: Setting up to watch %s %s\n", path.c_str(), (RECURSE == Normally) ? "normally" : "recursively"); } fd = inotify_init(); if (fd < 0) { throw Exception("Failed to initiate watch"); } if (RECURSE == Watch::Recursively) { for (const auto &path_ : enumerateSubdirectories(path)) { if (ignored_.find(path_) == ignored_.end()) { paths_.push_back(path_); } else if (WATCHDOG_DEBUG) { fprintf(stderr, "[DEBUG]: Ignoring %s\n", path_.c_str()); } } } if (WATCHDOG_DEBUG) { for (const auto &path : paths_) { fprintf(stderr, "[DEBUG]: Watching %s\n", path.c_str()); } } } ~Sentry() { if (WATCHDOG_DEBUG) { fprintf(stderr, "[DEBUG]: Cleaning up watches for %s\n", paths_[0].c_str()); } for (const auto wd : wds.backing()) { inotify_rm_watch(fd, wd.first); } close(fd); } void add_callback(Callback cb, FlagBearer flags) { if (WATCHDOG_DEBUG) { fprintf(stderr, "[DEBUG]: Registering callback for %s\n", paths_[0].c_str()); } Container wds_; // Attempt to add all watches. While _this_ is in left in a // relatively consistent state if an exception is thrown, you // probably have other problems when that happens. for (const auto path : paths_) { int wd = inotify_add_watch(fd, path.c_str(), flags | Default_Flags); if (wd < 0) { throw Exception("Failed to add watch to " + path); } wds_.add(wd, path); } _callbacks.push_back(std::make_pair(flags, cb)); wds.append(wds_); } void listen() { if (WATCHDOG_DEBUG) { fprintf(stderr, "[DEBUG]: Forever listening for " "changes to %s\n", paths_[0].c_str()); } #if WATCHDOG_DEBUG while (true) listen_(1); #else while (true) listen_(10000); #endif } private: void listen_(std::size_t howManyTimes) { if (WATCHDOG_DEBUG) { fprintf(stderr, "[DEBUG]: Listening for changes to %s\n", paths_[0].c_str()); } Event *ev = nullptr; int length = 0; for (std::size_t event_count = 0; event_count < howManyTimes; ++event_count) { length = read(fd, buffer, buffer_length); if (length < 0) { throw Exception("Failed to read events"); } if (WATCHDOG_DEBUG) { fprintf(stderr, "[DEBUG]: Read %d bytes of " "events\n", length); } // Process each event's callback int i = 0; for (; i < length; i += sizeof(Event) + ev->len) { // Technically unsafe, I know ev = (Event*) &buffer[i]; dispatch(ev); } } } void dispatch(Event *ev) { // Call each callback that matches for (auto cbp : _callbacks) { if (WATCHDOG_DEBUG) { fprintf(stderr, "[DEBUG]: Mask: 0x%lx " "Event Flags: 0x%x\n", cbp.first, ev->mask); } // Ignore when mask doesn't match if ((cbp.first & ev->mask) == 0) continue; // Ignore Ignored events if (ev->mask & Reply::Ignored) { if (WATCHDOG_DEBUG) { fprintf(stderr, "[DEBUG]: From %s -> ignored\n", ev->name); } continue; } // Explode when the queue does if (ev->mask & Reply::Overflow) { throw Exception("Inotify queue overflowed"); } cbp.second(ev, wds.find(ev->wd)); } } std::vector< std::pair<FlagBearer, Callback> > _callbacks; std::vector< std::string > paths_; // Hmm... std::set< std::string > ignored_; // buffer_length is nonstatic char buffer[ MAX_EVENTS * ( sizeof(Event) + MAX_LEN_NAME ) ]; std::size_t buffer_length = MAX_EVENTS * ( sizeof(Event) + MAX_LEN_NAME ); int fd; // File descriptor Container wds; }; using Dog = Sentry<Watch::Normally>; using Pen = Sentry<Watch::Recursively>; } // namespace Watch #endif
31.078125
80
0.460156
[ "vector" ]
02b4aaaf6f4c85696593440a004b33752f4876aa
33,700
cpp
C++
gui/ctrl/look/button.cpp
r3dl3g/guipp
3d3179be3022935b46b59f1b988a029abeabfcbf
[ "MIT" ]
null
null
null
gui/ctrl/look/button.cpp
r3dl3g/guipp
3d3179be3022935b46b59f1b988a029abeabfcbf
[ "MIT" ]
null
null
null
gui/ctrl/look/button.cpp
r3dl3g/guipp
3d3179be3022935b46b59f1b988a029abeabfcbf
[ "MIT" ]
null
null
null
/** * @copyright (c) 2016-2021 Ing. Buero Rothfuss * Riedlinger Str. 8 * 70327 Stuttgart * Germany * http://www.rothfuss-web.de * * @author <a href="mailto:armin@rothfuss-web.de">Armin Rothfuss</a> * * Project gui++ lib * * @brief various button looks * * @license MIT license. See accompanying file LICENSE. */ // -------------------------------------------------------------------------- // // Common includes // #include <cmath> // -------------------------------------------------------------------------- // // Library includes // #include <gui/draw/drawers.h> #include <gui/draw/frames.h> #include <gui/draw/pen.h> #include <gui/draw/brush.h> #include <gui/draw/font.h> #include <gui/draw/graphics.h> #include <gui/ctrl/look/button.h> #include <gui/io/pnm.h> namespace gui { namespace image_data { # include <gui/ctrl/look/res/button_frame.h> # include <gui/ctrl/look/res/button_pressed_frame.h> # include <gui/ctrl/look/res/button_rot_frame.h> # include <gui/ctrl/look/res/button_pressed_rot_frame.h> # include <gui/ctrl/look/res/simple_frame.h> # include <gui/ctrl/look/res/metal_check_off.h> # include <gui/ctrl/look/res/metal_check_on.h> # include <gui/ctrl/look/res/metal_check_disabled.h> # include <gui/ctrl/look/res/metal_check_disabled_on.h> # include <gui/ctrl/look/res/metal_radio_off.h> # include <gui/ctrl/look/res/metal_radio_on.h> # include <gui/ctrl/look/res/metal_radio_disabled.h> # include <gui/ctrl/look/res/metal_radio_disabled_on.h> # include <gui/ctrl/look/res/osx_checkbox_off.h> # include <gui/ctrl/look/res/osx_checkbox_on.h> # include <gui/ctrl/look/res/osx_checkbox_disabled_off.h> # include <gui/ctrl/look/res/osx_checkbox_disabled_on.h> # include <gui/ctrl/look/res/osx_radio_off.h> # include <gui/ctrl/look/res/osx_radio_on.h> # include <gui/ctrl/look/res/osx_radio_disabled_off.h> # include <gui/ctrl/look/res/osx_radio_disabled_on.h> # include <gui/ctrl/look/res/osx_frame.h> # include <gui/ctrl/look/res/osx_frame_disabled.h> # include <gui/ctrl/look/res/osx_frame_default.h> # include <gui/ctrl/look/res/osx_frame_pressed.h> } // namespace image_data namespace detail { template<typename T, size_t N> inline std::string make_string (T(&t)[N]) { return std::string((const char*)t, N); } draw::graymap build_gray_image (const std::string& data) { draw::graymap bmp; std::istringstream in(data); io::load_pnm(in, bmp); return bmp; } draw::rgbmap build_rgb_image (const std::string& data) { draw::rgbmap bmp; std::istringstream in(data); io::load_pnm(in, bmp); return bmp; } draw::graymap build_button_frame_image (bool pressed, bool rot) { return build_gray_image(pressed ? (rot ? make_string(image_data::button_pressed_rot_frame_bytes) : make_string(image_data::button_pressed_frame_bytes)) : (rot ? make_string(image_data::button_rot_frame_bytes) : make_string(image_data::button_frame_bytes))); } draw::graymap build_simple_frame_image () { return build_gray_image(make_string(image_data::simple_frame_bytes)); } template<bool rot, bool pressed> const draw::graymap& get_button_frame () { static draw::graymap image(detail::build_button_frame_image(pressed, rot)); return image; } const draw::graymap& get_simple_frame () { static draw::graymap image(detail::build_simple_frame_image()); return image; } template<alignment_t A> const draw::graymap& get_tab_frame (bool pressed); template<> const draw::graymap& get_tab_frame<alignment_t::top> (bool pressed) { static draw::graymap image(get_button_frame<false, false>().sub(1, 0, 7, 24)); static draw::graymap image_pressed(get_button_frame<false, true>().sub(1, 0, 7, 24)); return pressed ? image_pressed : image; } template<> const draw::graymap& get_tab_frame<alignment_t::bottom> (bool pressed) { static draw::graymap image(get_button_frame<false, true>().sub(1, 4, 7, 24)); static draw::graymap image_pressed(get_button_frame<false, false>().sub(1, 4, 7, 24)); return pressed ? image_pressed : image; } template<> const draw::graymap& get_tab_frame<alignment_t::left> (bool pressed) { static draw::graymap image(get_button_frame<true, false>().sub(0, 1, 24, 7)); static draw::graymap image_pressed(get_button_frame<true, true>().sub(0, 1, 24, 7)); return pressed ? image_pressed : image; } template<> const draw::graymap& get_tab_frame<alignment_t::right> (bool pressed) { static draw::graymap image(get_button_frame<true, true>().sub(4, 1, 24, 7)); static draw::graymap image_pressed(get_button_frame<true, false>().sub(4, 1, 24, 7)); return pressed ? image_pressed : image; } template<typename T> T upscale (const T& img) { if (core::global::get_scale_factor() != 1.0) { T up(img.native_size() * core::global::get_scale_factor()); up.stretch_from(img); return up; } return img; } template<typename T> T downscale (const T& img) { if (core::global::get_scale_factor() != 2.0) { T up(img.native_size() * (core::global::get_scale_factor() / 2.0)); up.stretch_from(img); return up; } return img; } template<typename T> draw::masked_bitmap make_masked (const T& img) { auto mask = img.get_mask({0x01}); return draw::masked_bitmap(img, std::move(mask)); } const draw::masked_bitmap& get_osx_checkbox (bool active, bool disabled) { static draw::masked_bitmap off = make_masked(upscale(build_gray_image(make_string(image_data::osx_checkbox_off)).convert<pixel_format_t::RGB>())); static draw::masked_bitmap on = make_masked(upscale(build_rgb_image(make_string(image_data::osx_checkbox_on)))); static draw::masked_bitmap dis_off = make_masked(upscale(build_gray_image(make_string(image_data::osx_checkbox_disabled_off)).convert<pixel_format_t::RGB>())); static draw::masked_bitmap dis_on = make_masked(upscale(build_gray_image(make_string(image_data::osx_checkbox_disabled_on)).convert<pixel_format_t::RGB>())); return disabled ? (active ? dis_on : dis_off) : (active ? on : off); } const draw::masked_bitmap& get_osx_radio (bool active, bool disabled) { static draw::masked_bitmap off = make_masked(upscale(build_gray_image(make_string(image_data::osx_radio_off)).convert<pixel_format_t::RGB>())); static draw::masked_bitmap on = make_masked(upscale(build_rgb_image(make_string(image_data::osx_radio_on)))); static draw::masked_bitmap dis_off = make_masked(upscale(build_gray_image(make_string(image_data::osx_radio_disabled_off)).convert<pixel_format_t::RGB>())); static draw::masked_bitmap dis_on = make_masked(upscale(build_gray_image(make_string(image_data::osx_radio_disabled_on)).convert<pixel_format_t::RGB>())); return disabled ? (active ? dis_on : dis_off) : (active ? on : off); } const draw::masked_bitmap& get_metal_checkbox (bool active, bool disabled) { static draw::masked_bitmap off = make_masked(downscale(build_gray_image(make_string(image_data::metal_check_off)))); static draw::masked_bitmap on = make_masked(downscale(build_gray_image(make_string(image_data::metal_check_on)))); static draw::masked_bitmap dis_off = make_masked(downscale(build_gray_image(make_string(image_data::metal_check_disabled)))); static draw::masked_bitmap dis_on = make_masked(downscale(build_gray_image(make_string(image_data::metal_check_disabled_on)))); return disabled ? (active ? dis_on : dis_off) : (active ? on : off); } const draw::masked_bitmap& get_metal_radio (bool active, bool disabled) { static draw::masked_bitmap off = make_masked(downscale(build_gray_image(make_string(image_data::metal_radio_off)))); static draw::masked_bitmap on = make_masked(downscale(build_gray_image(make_string(image_data::metal_radio_on)))); static draw::masked_bitmap dis_off = make_masked(downscale(build_gray_image(make_string(image_data::metal_radio_disabled)))); static draw::masked_bitmap dis_on = make_masked(downscale(build_gray_image(make_string(image_data::metal_radio_disabled_on)))); return disabled ? (active ? dis_on : dis_off) : (active ? on : off); } } // namespace detail // -------------------------------------------------------------------------- namespace look { namespace osx { const draw::rgbmap& get_frame () { static draw::rgbmap img = detail::build_gray_image(detail::make_string(image_data::osx_frame)).convert<pixel_format_t::RGB>(); return img; } const draw::rgbmap& get_disabled_frame () { static draw::rgbmap img = detail::build_gray_image(detail::make_string(image_data::osx_frame_disabled)).convert<pixel_format_t::RGB>(); return img; } const draw::rgbmap& get_focused_frame () { static draw::rgbmap img = detail::build_rgb_image(detail::make_string(image_data::osx_frame_default)); return img; } const draw::rgbmap& get_pressed_frame () { static draw::rgbmap img = detail::build_rgb_image(detail::make_string(image_data::osx_frame_pressed)); return img; } } // namespace osx #ifndef GUIPP_BUILD_FOR_MOBILE const gui::draw::pen::size_type dot_line_width = 1; const draw::pen::Style dot_line_style = draw::pen::Style::dot; #endif // GUIPP_BUILD_FOR_MOBILE // -------------------------------------------------------------------------- template<> void button_frame_t<look_and_feel_t::w95> (draw::graphics& graph, const core::rectangle& r, const core::button_state::is& st) { core::rectangle area = r; graph.fill(draw::rectangle(area), st.enabled() && st.hilited() ? color::buttonHighLightColor() : color::buttonColor()); if (st.enabled() && st.focused()) { graph.frame(draw::rectangle(area), color::black); area.shrink({1, 1}); } draw::frame::deep_relief(graph, area, st.pushed()); #ifndef GUIPP_BUILD_FOR_MOBILE if (st.enabled() && st.focused() && !st.pushed()) { area = r.shrinked({6, 6}); graph.frame(draw::rectangle(area), draw::pen(color::light_gray, dot_line_width, dot_line_style)); } #endif // GUIPP_BUILD_FOR_MOBILE } namespace win10 { os::color get_button_color (const core::button_state::is& st) { if (!st.enabled()) { return color::rgb_gray<204>::value; } else if (st.pushed()) { return color::rgb<204, 228, 247>::value; } else if (st.hilited() || st.focused()) { return color::rgb<229, 241, 251>::value; } else { return color::rgb_gray<225>::value; } } os::color get_button_frame_color (const core::button_state::is& st) { if (!st.enabled()) { return color::rgb_gray<191>::value; } else if (st.pushed()) { return color::rgb<0, 84, 153>::value; } else if (st.hilited() || st.focused()) { return color::rgb<0, 120, 215>::value; } else { return color::rgb_gray<173>::value; } } } // -------------------------------------------------------------------------- os::color get_flat_button_background (const core::button_state::is& st, os::color bg) { if (st.enabled()) { if (st.pushed()) { return color::darker(bg, 0.25); } else if (st.hilited()) { return color::lighter(bg, 0.25); } } return bg; } os::color get_flat_button_foreground (const core::button_state::is& st, os::color fg, os::color bg) { if (st.enabled()) { if (st.pushed()) { const os::color b2 = color::invert(bg); const os::color f2 = color::invert(fg); const int i1 = color::compare_weight(bg, b2); const int i2 = color::compare_weight(bg, f2); if (std::abs(i1) > std::abs(i2)) { return b2; } else { return f2; } } return fg; } else { return color::darker(fg); } } // -------------------------------------------------------------------------- template<> void button_frame_t<look_and_feel_t::w10> (draw::graphics& graph, const core::rectangle& r, const core::button_state::is& st) { graph.draw(draw::rectangle(r), win10::get_button_color(st), win10::get_button_frame_color(st)); } // -------------------------------------------------------------------------- template<> void button_frame_t<look_and_feel_t::metal> (draw::graphics& graph, const core::rectangle& r, const core::button_state::is& st) { if (st.enabled() && st.hilited()) { graph.copy(draw::frame_image(r, detail::get_button_frame<false, false>().brightness(1.025F), 4), r.top_left()); } else { graph.copy(draw::frame_image(r, detail::get_button_frame<false, false>(), 4), r.top_left()); } if (st.pushed()) { draw::frame::sunken_relief(graph, r.shrinked(core::size::two)); } if (st.enabled() && st.focused() && !st.pushed()) { core::rectangle area = r; area.shrink({2, 2}); graph.frame(draw::rectangle(area), draw::pen(color::very_light_blue, 2, draw::pen::Style::solid)); } } // -------------------------------------------------------------------------- template<> void button_frame_t<look_and_feel_t::osx> (draw::graphics& graph, const core::rectangle& r, const core::button_state::is& st) { if (!st.enabled()) { graph.copy(draw::frame_image(r, osx::get_disabled_frame(), 4), r.top_left()); } else if (st.pushed() && st.hilited()) { graph.copy(draw::frame_image(r, osx::get_pressed_frame(), 4), r.top_left()); } else if (st.focused()) { graph.copy(draw::frame_image(r, osx::get_focused_frame(), 4), r.top_left()); } else { graph.copy(draw::frame_image(r, osx::get_frame(), 4), r.top_left()); } } void button_frame (draw::graphics& graph, const core::rectangle& r, const core::button_state::is& st, os::color, os::color) { button_frame_t<system_look_and_feel>(graph, r, st); } // -------------------------------------------------------------------------- void button_text (draw::graphics& g, const core::rectangle& r, const std::string& text, const core::button_state::is& st, os::color fg, os::color) { os::color f = st.enabled() ? fg : color::disabledTextColor(); g.text(draw::text_box(text, r, text_origin_t::center), draw::font::system(), f); } // -------------------------------------------------------------------------- void simple_frame (draw::graphics& graph, const core::rectangle& r, bool hilite, uint32_t horizontal, uint32_t vertical) { graph.copy(draw::frame_image(r, hilite ? detail::get_simple_frame().brightness(1.025F) : detail::get_simple_frame(), horizontal, vertical), r.top_left()); } void simple_frame (draw::graphics& g, const core::rectangle& r, const core::button_state::is& st, os::color, os::color) { simple_frame(g, r, st.hilited()); } // -------------------------------------------------------------------------- void flat_button_frame (draw::graphics& g, const core::rectangle& r, const core::button_state::is& st, os::color fg, os::color bg) { os::color b = get_flat_button_background(st, bg); g.fill(draw::rectangle(r), b); #ifndef GUIPP_BUILD_FOR_MOBILE if (st.enabled() && st.focused()) { g.frame(draw::rectangle(r), draw::pen(get_flat_button_foreground(st, fg, b), dot_line_width, dot_line_style)); } #endif // GUIPP_BUILD_FOR_MOBILE } void flat_button_text (draw::graphics& g, const core::rectangle& r, const std::string& text, const core::button_state::is& st, os::color fg, os::color bg) { os::color f = get_flat_button_foreground(st, fg, get_flat_button_background(st, bg)); g.text(draw::text_box(text, r, text_origin_t::center), draw::font::system(), f); } // -------------------------------------------------------------------------- void flat_button (draw::graphics& g, const core::rectangle& r, const std::string& text, const core::button_state::is& st, os::color fg, os::color bg) { flat_button_frame(g, r, st, fg, bg); flat_button_text(g, r, text, st, fg, bg); } // -------------------------------------------------------------------------- void push_button (draw::graphics& g, const core::rectangle& r, const std::string& text, const core::button_state::is& st, os::color fg, os::color bg) { button_frame(g, r, st, fg, bg); button_text(g, r, text, st, fg, bg); } // -------------------------------------------------------------------------- template<> void tab_button<look_and_feel_t::metal> (draw::graphics& g, const core::rectangle& r, const core::button_state::is& st, os::color fg, alignment_t a) { if (st.checked()) { switch (a) { case alignment_t::top: g.copy(draw::frame_image(r, detail::get_tab_frame<alignment_t::top>(true), 3, 3, 3, 0), r.top_left()); break; case alignment_t::bottom: g.copy(draw::frame_image(r, detail::get_tab_frame<alignment_t::bottom>(true), 3, 0, 3, 3), r.top_left()); break; case alignment_t::left: g.copy(draw::frame_image(r, detail::get_tab_frame<alignment_t::left>(true), 3, 3, 0, 3), r.top_left()); break; case alignment_t::right: g.copy(draw::frame_image(r, detail::get_tab_frame<alignment_t::right>(true), 0, 3, 3, 3), r.top_left()); break; default: break; } } else if (st.enabled()) { if (st.hilited()) { switch (a) { case alignment_t::top: g.copy(draw::frame_image(r, detail::get_tab_frame<alignment_t::top>(false).brightness(1.025F), 3, 3, 3, 0), r.top_left()); break; case alignment_t::bottom: g.copy(draw::frame_image(r, detail::get_tab_frame<alignment_t::bottom>(false).brightness(1.025F), 3, 0, 3, 3), r.top_left()); break; case alignment_t::left: g.copy(draw::frame_image(r, detail::get_tab_frame<alignment_t::left>(false).brightness(1.025F), 3, 3, 0, 3), r.top_left()); break; case alignment_t::right: g.copy(draw::frame_image(r, detail::get_tab_frame<alignment_t::right>(false).brightness(1.025F), 0, 3, 3, 3), r.top_left()); break; default: break; } } else { switch (a) { case alignment_t::top: g.copy(draw::frame_image(r, detail::get_tab_frame<alignment_t::top>(false), 3, 3, 3, 0), r.top_left()); break; case alignment_t::bottom: g.copy(draw::frame_image(r, detail::get_tab_frame<alignment_t::bottom>(false), 3, 0, 3, 3), r.top_left()); break; case alignment_t::left: g.copy(draw::frame_image(r, detail::get_tab_frame<alignment_t::left>(false), 3, 3, 0, 3), r.top_left()); break; case alignment_t::right: g.copy(draw::frame_image(r, detail::get_tab_frame<alignment_t::right>(false), 0, 3, 3, 3), r.top_left()); break; default: break; } } } else { switch (a) { case alignment_t::top: g.copy(draw::frame_image(r, detail::get_tab_frame<alignment_t::top>(false).brightness(0.75F), 3, 3, 3, 0), r.top_left()); break; case alignment_t::bottom: g.copy(draw::frame_image(r, detail::get_tab_frame<alignment_t::bottom>(false).brightness(0.75F), 3, 0, 3, 3), r.top_left()); break; case alignment_t::left: g.copy(draw::frame_image(r, detail::get_tab_frame<alignment_t::left>(false).brightness(0.75F), 3, 3, 0, 3), r.top_left()); break; case alignment_t::right: g.copy(draw::frame_image(r, detail::get_tab_frame<alignment_t::right>(false).brightness(0.75F), 0, 3, 3, 3), r.top_left()); break; default: break; } } } void tab_button_text (draw::graphics& g, const core::rectangle& r, const std::string& text, const core::button_state::is& st, os::color fg, os::color bg) { g.text(draw::text_box(text, r.shrinked({4, 4}), text_origin_t::center), draw::font::system(), fg); } // -------------------------------------------------------------------------- void switch_button (draw::graphics& graph, const core::rectangle& rect, const core::button_state::is& st, os::color fg, os::color bg) { animated_switch_button(graph, rect, st, fg, bg); } void switch_button_text (draw::graphics& graph, const core::rectangle& rect, const std::string& text, const core::button_state::is& st, os::color fg, os::color bg) { os::color text_col = st.enabled() ? color::windowTextColor() : color::disabledTextColor(); graph.text(draw::text_box(text, rect + core::point(rect.height() * 2 + 10, 0), text_origin_t::vcenter_left), draw::font::system(), text_col); } // -------------------------------------------------------------------------- void animated_switch_button (draw::graphics& graph, const core::rectangle& rect, const core::button_state::is& st, os::color fg, os::color bg, float animation_step) { bool enabled = st.enabled(); core::size::type height = rect.height(); core::size::type width = height * 2; core::size::type edge = height / 2; graph.fill(draw::rectangle(rect), bg); float step = st.checked() ? animation_step : 1.0F - animation_step; core::rectangle switch_rect{rect.top_left(), core::size(width, height)}; os::color thumb_col = enabled && st.hilited() ? color::lighter(bg) : bg; os::color fill_col = color::merge(fg, color::very_light_gray, 1.0F - step); core::rectangle thumb = {core::point{rect.x() + height * step, rect.y()}, core::size(height)}; graph.draw(draw::round_rectangle(switch_rect, core::size(edge)), fill_col, color::medium_gray); auto center = thumb.center(); graph.draw(draw::pie(center, edge, 0, 360), thumb_col, color::medium_gray); graph.frame(draw::pie(center, edge - 1, 40, 250), color::white); graph.frame(draw::pie(center, edge - 1, 250, 40), color::medium_gray); graph.fill(draw::pie(center, edge - 2, 0, 360), thumb_col); } // -------------------------------------------------------------------------- template<> os::color get_button_foreground<look_and_feel_t::metal> (const core::button_state::is& st, os::color fg, os::color bg) { return st.enabled() ? fg : color::disabledTextColor(); } template<> os::color get_button_foreground<look_and_feel_t::w95> (const core::button_state::is& st, os::color fg, os::color bg) { return st.enabled() ? fg : color::disabledTextColor(); } template<> os::color get_button_foreground<look_and_feel_t::w10> (const core::button_state::is& st, os::color fg, os::color bg) { if (!st.enabled()) { return color::rgb_gray<204>::value; } else if (st.focused() || st.pushed()) { return color::rgb<0, 120, 215>::value; } else { return color::black; } } template<> os::color get_button_foreground<look_and_feel_t::osx> (const core::button_state::is& st, os::color fg, os::color bg) { return st.enabled() ? fg : color::disabledTextColor(); } // -------------------------------------------------------------------------- void check_button_text (draw::graphics& graph, const core::rectangle& rec, const std::string& text, const core::button_state::is& st, os::color fg, os::color) { using namespace draw; core::rectangle area = rec.dx(20); graph.text(text_box(text, area, text_origin_t::vcenter_left), font::system(), fg); #ifndef GUIPP_BUILD_FOR_MOBILE if (st.focused()) { graph.text(bounding_box(text, area, text_origin_t::vcenter_left), font::system(), color::black); area.grow({3, 3}); graph.frame(draw::rectangle(area), pen(color::black, dot_line_width, dot_line_style)); } #endif // GUIPP_BUILD_FOR_MOBILE } // -------------------------------------------------------------------------- template<> void radio_button_frame<look_and_feel_t::w95> (draw::graphics& graph, const core::rectangle& area, const core::button_state::is& st, os::color fg, os::color bg) { using namespace draw; graph.fill(draw::rectangle(area), bg); core::point::type y = area.y() + area.size().height() / 2; core::rectangle r(core::point(area.x() + 1, y - 5), core::size(10, 10)); graph.draw(ellipse(r), st.pushed() ? color::very_light_gray : bg, fg); if (st.checked()) { r.shrink(core::size(2, 2)); graph.fill(ellipse(r), st.pushed() ? color::dark_gray : fg); } } // -------------------------------------------------------------------------- template<> void radio_button_frame<look_and_feel_t::w10> (draw::graphics& graph, const core::rectangle& area, const core::button_state::is& st, os::color fg, os::color bg) { using namespace draw; graph.fill(rectangle(area), bg); core::point::type y = area.center_y(); core::rectangle r(core::point(area.x() + 1, y - 6), core::size(12, 12)); graph.frame(ellipse(r), fg); if (st.checked()) { r.shrink(core::size(3, 3)); graph.fill(ellipse(r), fg); } } // -------------------------------------------------------------------------- template<> void radio_button_frame<look_and_feel_t::metal> (draw::graphics& graph, const core::rectangle& area, const core::button_state::is& st, os::color fg, os::color bg) { using namespace draw; const auto& img = detail::get_metal_radio(st.checked(), !st.enabled()); graph.fill(draw::image<decltype(img)>(img, area, text_origin_t::vcenter_left), bg); } // -------------------------------------------------------------------------- template<> void radio_button_frame<look_and_feel_t::osx> (draw::graphics& graph, const core::rectangle& area, const core::button_state::is& st, os::color fg, os::color bg) { using namespace draw; const auto& img = detail::get_osx_radio(st.checked(), !st.enabled()); graph.fill(draw::image<decltype(img)>(img, area, text_origin_t::vcenter_left), bg); } // -------------------------------------------------------------------------- void radio_button (draw::graphics& graph, const core::rectangle& rec, const std::string& text, const core::button_state::is& st, os::color fg, os::color bg) { fg = get_button_foreground<>(st, fg, bg); radio_button_frame<>(graph, rec, st, fg, bg); check_button_text(graph, rec, text, st, fg, bg); } // -------------------------------------------------------------------------- template<> void check_box_frame<look_and_feel_t::w95> (draw::graphics& graph, const core::rectangle& area, const core::button_state::is& st, os::color fg, os::color bg) { using namespace draw; graph.fill(draw::rectangle(area), bg); core::point::type y = area.y() + area.height() / 2; core::rectangle r(core::point(area.x() + 1, y - 5), core::size(10, 10)); graph.draw(rectangle(r), st.pushed() ? color::very_light_gray : bg, fg); if (st.checked()) { r.shrink(core::size(2, 2)); graph.fill(rectangle(r), st.pushed() ? color::dark_gray : fg); } } // -------------------------------------------------------------------------- template<> void check_box_frame<look_and_feel_t::w10> (draw::graphics& graph, const core::rectangle& area, const core::button_state::is& st, os::color fg, os::color bg) { using namespace draw; graph.fill(rectangle(area), bg); core::point::type y = area.center_y(); core::rectangle r(core::point(area.x() + 1, y - 6), core::size(12, 12)); graph.frame(rectangle(r), fg); if (st.checked()) { graph.frame(polyline({{r.x() + 1, y}, {r.x() + 4, y + 3}, {r.x() + 10, y - 3}}), pen(fg, 2)); } } // -------------------------------------------------------------------------- template<> void check_box_frame<look_and_feel_t::metal> (draw::graphics& graph, const core::rectangle& area, const core::button_state::is& st, os::color fg, os::color bg) { const auto& img = detail::get_metal_checkbox(st.checked(), !st.enabled()); graph.copy(draw::image<decltype(img)>(img, area, text_origin_t::vcenter_left), area.top_left()); } // -------------------------------------------------------------------------- template<> void check_box_frame<look_and_feel_t::osx> (draw::graphics& graph, const core::rectangle& area, const core::button_state::is& st, os::color fg, os::color bg) { const auto& img = detail::get_osx_checkbox(st.checked(), !st.enabled()); graph.copy(draw::image<decltype(img)>(img, area, text_origin_t::vcenter_left), area.top_left()); } // -------------------------------------------------------------------------- void check_box (draw::graphics& graph, const core::rectangle& rec, const std::string& text, const core::button_state::is& st, os::color fg, os::color bg) { fg = get_button_foreground<>(st, fg, bg); check_box_frame<>(graph, rec, st, fg, bg); check_button_text(graph, rec, text, st, fg, bg); } } // look } // gui
44.57672
170
0.524332
[ "solid" ]
02ba520260d1463c86113a957f1a319532cdfc41
2,008
hpp
C++
cpp/DataLoader.hpp
MPieter/hero_radar_odometry
107c1a07b22784fec54c22e5f8bb03251cc9f786
[ "BSD-3-Clause" ]
56
2021-06-01T11:58:22.000Z
2022-03-30T13:20:40.000Z
cpp/DataLoader.hpp
MPieter/hero_radar_odometry
107c1a07b22784fec54c22e5f8bb03251cc9f786
[ "BSD-3-Clause" ]
3
2021-06-13T15:23:13.000Z
2021-09-09T23:02:58.000Z
cpp/DataLoader.hpp
MPieter/hero_radar_odometry
107c1a07b22784fec54c22e5f8bb03251cc9f786
[ "BSD-3-Clause" ]
12
2021-06-05T00:07:28.000Z
2022-03-04T04:58:56.000Z
#pragma once #include <vector> #include <string> #include <boost/python.hpp> #include <boost/python/numpy.hpp> namespace p = boost::python; namespace np = boost::python::numpy; #define CTS350 0 #define CIR204 1 class DataLoader { public: DataLoader(const double radar_resolution_, const double cart_resolution_, const uint cart_pixel_width_, const uint navtech_version_) : radar_resolution(radar_resolution_), cart_resolution(cart_resolution_), cart_pixel_width(cart_pixel_width_), navtech_version(navtech_version_) { if (navtech_version == CIR204) { range_bins = 3360; } min_range = uint(2.35 / radar_resolution); } // timestamps: N x 1 , azimuths: N x 1, fft_data: N x R need to be sized correctly by the python user. void load_radar(const std::string path, np::ndarray& timestamps, np::ndarray& azimuths, np::ndarray& fft_data); // azimuths: N x 1, fft_data: N x R, cart: W x W need to be sized correctly by the python user. void polar_to_cartesian(const np::ndarray& azimuths, const np::ndarray& fft_data, np::ndarray& cart); private: double radar_resolution = 0.0432; double cart_resolution = 0.2160; uint cart_pixel_width = 640; uint navtech_version = 0; // 0: CTS350, 1: CIR204 uint range_bins = 3768; uint num_azimuths = 400; uint min_range = 54; bool interpolate_crossover = true; }; class releaseGIL{ public: inline releaseGIL(){ save_state = PyEval_SaveThread(); } inline ~releaseGIL(){ PyEval_RestoreThread(save_state); save_state = NULL; } private: PyThreadState *save_state; }; // boost wrapper BOOST_PYTHON_MODULE(DataLoader) { PyEval_InitThreads(); Py_Initialize(); np::initialize(); p::class_<DataLoader>("DataLoader", p::init<const double, const double, const uint, const uint>()) .def("load_radar", &DataLoader::load_radar) .def("polar_to_cartesian", &DataLoader::polar_to_cartesian); }
30.892308
115
0.688745
[ "vector" ]
02bb3b886fee0a1b3bfa00de252bbf58a024ac85
59,981
cxx
C++
com/ole32/com/moniker2/classmon.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
com/ole32/com/moniker2/classmon.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
com/ole32/com/moniker2/classmon.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+--------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1996. // // File: classmon.cxx // // Contents: Implementation of CClassMoniker // // Classes: CClassMoniker // // Functions: CreateClassMoniker // // History: 22-Feb-96 ShannonC Created // 25-Feb-97 ShannonC Use AsyncGetClassBits. // //---------------------------------------------------------------------------- #include <ole2int.h> #include <classmon.hxx> #include <dllhost.hxx> #include <cfactory.hxx> #include "mnk.h" #ifndef OLETRACEIN #define OLETRACEIN(x) #endif #ifndef OLETRACEOUT #define OLETRACEOUT(x) #endif // This needs to be in a public header if it's still used. // Comes from private\inet\urlmon\download\cdl.h #define CD_FLAGS_NEED_CLASSFACTORY 0x4 HMODULE hUrlMon = 0; ASYNCGETCLASSBITS *pfnAsyncGetClassBits = PrivAsyncGetClassBits; REGISTERBINDSTATUSCALLBACK *pfnRegisterBindStatusCallback = PrivRegisterBindStatusCallback; REVOKEBINDSTATUSCALLBACK *pfnRevokeBindStatusCallback = PrivRevokeBindStatusCallback; #define REG_BSCB_HOLDER OLESTR("_BSCB_Holder_") //+--------------------------------------------------------------------------- // // Function: CreateClassMoniker // // Synopsis: Creates a class moniker for the specified CLSID. // // Arguments: [rclsid] - Supplies the CLSID of the class. // [ppmk] - Returns interface pointer of the new moniker. // // Returns: S_OK // E_INVALIDARG // E_OUTOFMEMORY // //---------------------------------------------------------------------------- STDAPI CreateClassMoniker( REFCLSID rclsid, IMoniker **ppmk) { HRESULT hr; CLSID clsid; IMoniker *pmk; __try { OLETRACEIN((API_CreateClassMoniker, PARAMFMT("rclsid= %I, ppmk= %p"), &rclsid, ppmk)); //Validate parameters. *ppmk = NULL; clsid = rclsid; pmk = new CClassMoniker(clsid); if (pmk != NULL) { *ppmk = pmk; hr = S_OK; CALLHOOKOBJECTCREATE(hr, CLSID_ClassMoniker, IID_IMoniker, (IUnknown **)ppmk); } else { hr = E_OUTOFMEMORY; } } __except(EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } OLETRACEOUT((API_CreateFileMoniker, hr)); return hr; } //+--------------------------------------------------------------------------- // // Method: CClassMoniker::CClassMoniker // // Synopsis: Constructor for class moniker. // // Arguments: rclsid - Supplies the CLSID of the class. // //---------------------------------------------------------------------------- CClassMoniker::CClassMoniker(REFCLSID rclsid) : _cRefs(1), _pExtra(NULL), _pszCodeBase(NULL), _dwFileVersionMS(0), _dwFileVersionLS(0) { mnkDebugOut((DEB_ITRACE, "CClassMoniker::CClassMoniker(%x,%I)\n", this, &rclsid)); _data.clsid = rclsid; _data.cbExtra = 0; } //+--------------------------------------------------------------------------- // // Method: CClassMoniker::~CClassMoniker // // Synopsis: Constructor for class moniker. // // Arguments: rclsid - Supplies the CLSID of the class. // //---------------------------------------------------------------------------- CClassMoniker::~CClassMoniker() { mnkDebugOut((DEB_ITRACE, "CClassMoniker::~CClassMoniker(%x)\n", this)); if(_pExtra != NULL) { PrivMemFree(_pExtra); } } //+--------------------------------------------------------------------------- // // Method: CClassMoniker::SetParameters // // Synopsis: Set the parameters on the class moniker // // Arguments: pszName - Name of the parameter. // pszValue - Value of the parameter. // //---------------------------------------------------------------------------- HRESULT CClassMoniker::SetParameters( LPCWSTR pszParameters) { HRESULT hr = S_OK; //Free the old data. if(_pExtra != NULL) { PrivMemFree(_pExtra); _pExtra = NULL; } if(pszParameters != NULL) { _data.cbExtra = lstrlenW(pszParameters) * sizeof(WCHAR) + sizeof(WCHAR); //Allocate memory for the extra bytes. _pExtra = PrivMemAlloc(_data.cbExtra); if(_pExtra != 0) { memcpy(_pExtra, pszParameters, _data.cbExtra); hr = S_OK; } else { hr = E_OUTOFMEMORY; } } return hr; } //+--------------------------------------------------------------------------- // // Method: CClassMoniker::QueryInterface // // Synopsis: Gets a pointer to the specified interface. The class // moniker supports the IMarshal, IMoniker, IPersistStream, // IPersist, IROTData, and IUnknown interfaces. The class // moniker also supports CLSID_ClassMoniker so that the // IsEqual method can directly access the data members. // // Arguments: [iid] -- the requested interface // [ppv] -- where to put the interface pointer // // Returns: S_OK // E_INVALIDARG // E_NOINTERFACE // // Notes: Bad parameters will raise an exception. The exception // handler catches exceptions and returns E_INVALIDARG. // //---------------------------------------------------------------------------- STDMETHODIMP CClassMoniker::QueryInterface( REFIID riid, void **ppv) { HRESULT hr; __try { mnkDebugOut((DEB_ITRACE, "CClassMoniker::QueryInterface(%x,%I,%x)\n", this, &riid, ppv)); //Parameter validation. *ppv = NULL; if (IsEqualIID(riid, IID_IMarshal)) { AddRef(); *ppv = (IMarshal *) this; hr = S_OK; } else if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IMoniker) || IsEqualIID(riid, IID_IPersistStream) || IsEqualIID(riid, IID_IPersist)) { AddRef(); *ppv = (IMoniker *) this; hr = S_OK; } else if (IsEqualIID(riid, IID_IROTData)) { AddRef(); *ppv = (IROTData *) this; hr = S_OK; } else if (IsEqualIID(riid, CLSID_ClassMoniker)) { AddRef(); *ppv = (CClassMoniker *) this; hr = S_OK; } else { hr = E_NOINTERFACE; } } __except(EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } return hr; } //+--------------------------------------------------------------------------- // // Method: CClassMoniker::AddRef // // Synopsis: Increment the reference count. // // Arguments: void // // Returns: ULONG -- the new reference count // // Notes: Use InterlockedIncrement to make it multi-thread safe. // //---------------------------------------------------------------------------- STDMETHODIMP_(ULONG) CClassMoniker::AddRef(void) { mnkDebugOut((DEB_ITRACE, "CClassMoniker::AddRef(%x)\n", this)); InterlockedIncrement(&_cRefs); return _cRefs; } //+--------------------------------------------------------------------------- // // Method: CClassMoniker::Release // // Synopsis: Decrement the reference count. // // Arguments: void // // Returns: ULONG -- the remaining reference count // // Notes: Use InterlockedDecrement to make it multi-thread safe. // We use a local variable so that we don't access // a data member after decrementing the reference count. // //---------------------------------------------------------------------------- STDMETHODIMP_(ULONG) CClassMoniker::Release(void) { ULONG count = _cRefs - 1; mnkDebugOut((DEB_ITRACE, "CClassMoniker::Release(%x)\n", this)); if(0 == InterlockedDecrement(&_cRefs)) { delete this; count = 0; } return count; } //+--------------------------------------------------------------------------- // // Method: CClassMoniker::GetClassID // // Synopsis: Gets the class ID of the object. // //---------------------------------------------------------------------------- STDMETHODIMP CClassMoniker::GetClassID( CLSID *pClassID) { HRESULT hr; mnkDebugOut((DEB_ITRACE, "CClassMoniker::GetClassID(%x,%x)\n", this, pClassID)); __try { *pClassID = CLSID_ClassMoniker; hr = S_OK; } __except(EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } return hr; } //+--------------------------------------------------------------------------- // // Method: CClassMoniker::IsDirty // // Synopsis: Checks the object for changes since it was last saved. // //---------------------------------------------------------------------------- STDMETHODIMP CClassMoniker::IsDirty() { mnkDebugOut((DEB_ITRACE, "CClassMoniker::IsDirty(%x)\n", this)); return S_FALSE; } //+--------------------------------------------------------------------------- // // Method: CClassMoniker::Load // // Synopsis: Loads a class moniker from a stream // //---------------------------------------------------------------------------- STDMETHODIMP CClassMoniker::Load( IStream *pStream) { HRESULT hr; ULONG cbRead; mnkDebugOut((DEB_ITRACE, "CClassMoniker::Load(%x,%x)\n", this, pStream)); __try { hr = pStream->Read(&_data, sizeof(_data), &cbRead); if(SUCCEEDED(hr)) { if(sizeof(_data) == cbRead) { if(_data.cbExtra != 0) { //Free the old buffer if necessary. if(_pExtra != NULL) { PrivMemFree(_pExtra); } //Allocate buffer and read the extra bytes. _pExtra = PrivMemAlloc(_data.cbExtra); if(_pExtra != NULL) { hr = pStream->Read(_pExtra, _data.cbExtra, &cbRead); if(SUCCEEDED(hr)) { if(cbRead == _data.cbExtra) hr = S_OK; else hr = STG_E_READFAULT; } } else { hr = E_OUTOFMEMORY; } } else { hr = S_OK; } } else { hr = STG_E_READFAULT; } } } __except(EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } return hr; } //+--------------------------------------------------------------------------- // // Method: CClassMoniker::Save // // Synopsis: Save the class moniker to a stream // //---------------------------------------------------------------------------- STDMETHODIMP CClassMoniker::Save( IStream *pStream, BOOL fClearDirty) { HRESULT hr; mnkDebugOut((DEB_ITRACE, "CClassMoniker::Save(%x,%x,%x)\n", this, pStream, fClearDirty)); __try { hr = pStream->Write(&_data, sizeof(_data), NULL); if(SUCCEEDED(hr) && _pExtra != NULL && _data.cbExtra > 0) { //Write the extra bytes. hr = pStream->Write(_pExtra, _data.cbExtra, NULL); } } __except(EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } return hr; } //+--------------------------------------------------------------------------- // // Method: CClassMoniker::GetSizeMax // // Synopsis: Get the maximum size required to serialize this moniker // //---------------------------------------------------------------------------- STDMETHODIMP CClassMoniker::GetSizeMax( ULARGE_INTEGER * pcbSize) { HRESULT hr; mnkDebugOut((DEB_ITRACE, "CClassMoniker::GetSizeMax(%x,%x)\n", this, pcbSize)); __try { ULISet32(*pcbSize, sizeof(_data) + _data.cbExtra); hr = S_OK; } __except(EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } return hr; } //+--------------------------------------------------------------------------- // // Method: CClassMoniker::BindToObject // // Synopsis: Bind to the object named by this moniker. // // Notes: If pmkToLeft is zero, then the class moniker calls // AsyncGetClassBits to get the class object. // // If pmkToLeft is non-zero, then the class moniker binds to the // IClassActivator interface and then calls // IClassActivator::GetClassObject. // //---------------------------------------------------------------------------- STDMETHODIMP CClassMoniker::BindToObject ( IBindCtx *pbc, IMoniker *pmkToLeft, REFIID riid, void ** ppv) { HRESULT hr; BIND_OPTS2 bindOpts; __try { mnkDebugOut((DEB_ITRACE, "CClassMoniker::BindToObject(%x,%x,%x,%I,%x)\n", this, pbc, pmkToLeft, &riid, ppv)); //Validate parameters *ppv = NULL; bindOpts.cbStruct = sizeof(bindOpts); hr = pbc->GetBindOptions(&bindOpts); if(SUCCEEDED(hr)) { if(bindOpts.cbStruct < sizeof(BIND_OPTS2)) { //Initialize the new BIND_OPTS2 fields bindOpts.dwTrackFlags = 0; bindOpts.locale = GetThreadLocale(); bindOpts.pServerInfo = 0; bindOpts.dwClassContext = CLSCTX_SERVER; } if(NULL == pmkToLeft) { if(!bindOpts.pServerInfo) { IUrlMon *pUrlMon = NULL; hr = ApartmentDllGetClassObject(CLSID_UrlMonWrapper, IID_IUrlMon, (void **) &pUrlMon); if(SUCCEEDED(hr) && pUrlMon) { hr = pUrlMon->AsyncGetClassBits(_data.clsid, NULL, NULL, _dwFileVersionMS, _dwFileVersionLS, _pszCodeBase, pbc, bindOpts.dwClassContext, riid, CD_FLAGS_NEED_CLASSFACTORY); } if(pUrlMon) pUrlMon->Release(); } if(SUCCEEDED(hr) && (hr != MK_S_ASYNCHRONOUS)) { hr = CoGetClassObject(_data.clsid, bindOpts.dwClassContext | CLSCTX_NO_CODE_DOWNLOAD, bindOpts.pServerInfo, riid, ppv); } } else { IClassActivator *pActivate; hr = pmkToLeft->BindToObject(pbc, NULL, IID_IClassActivator, (void **) &pActivate); if(SUCCEEDED(hr)) { hr = pActivate->GetClassObject(_data.clsid, bindOpts.dwClassContext, bindOpts.locale, riid, ppv); pActivate->Release(); } } } } __except(EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } return hr; } //+--------------------------------------------------------------------------- // // Method: CClassMoniker::BindToStorage // // Synopsis: Bind to the storage for the object named by the moniker. // //---------------------------------------------------------------------------- STDMETHODIMP CClassMoniker::BindToStorage( IBindCtx *pbc, IMoniker *pmkToLeft, REFIID riid, void ** ppv) { HRESULT hr; mnkDebugOut((DEB_ITRACE, "CClassMoniker::BindToStorage(%x,%x,%x,%I,%x)\n", this, pbc, pmkToLeft, &riid, ppv)); hr = BindToObject(pbc, pmkToLeft, riid, ppv); return hr; } //+--------------------------------------------------------------------------- // // Method: CClassMoniker::Reduce // // Synopsis: Reduce the moniker. // //---------------------------------------------------------------------------- STDMETHODIMP CClassMoniker::Reduce( IBindCtx * pbc, DWORD dwReduceHowFar, IMoniker ** ppmkToLeft, IMoniker ** ppmkReduced) { HRESULT hr; mnkDebugOut((DEB_ITRACE, "CClassMoniker::Reduce(%x,%x,%x,%x,%x)\n", this, pbc, dwReduceHowFar, ppmkToLeft, ppmkReduced)); __try { //Validate parameters. *ppmkReduced = NULL; AddRef(); *ppmkReduced = (IMoniker *) this; hr = MK_S_REDUCED_TO_SELF; } __except(EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } return hr; } //+--------------------------------------------------------------------------- // // Method: CClassMoniker::ComposeWith // // Synopsis: Compose another moniker onto the end of this moniker. // //---------------------------------------------------------------------------- STDMETHODIMP CClassMoniker::ComposeWith( IMoniker * pmkRight, BOOL fOnlyIfNotGeneric, IMoniker **ppmkComposite) { HRESULT hr; IMoniker *pmk; mnkDebugOut((DEB_ITRACE, "CClassMoniker::ComposeWith(%x,%x,%x,%x)\n", this, pmkRight, fOnlyIfNotGeneric, ppmkComposite)); __try { //Validate parameters. *ppmkComposite = NULL; //Check for an anti-moniker hr = pmkRight->QueryInterface(CLSID_AntiMoniker, (void **)&pmk); if(FAILED(hr)) { //pmkRight is not an anti-moniker. if (!fOnlyIfNotGeneric) { hr = CreateGenericComposite(this, pmkRight, ppmkComposite); } else { hr = MK_E_NEEDGENERIC; } } else { //pmkRight is an anti-moniker. pmk->Release(); hr = S_OK; } } __except(EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } return hr; } //+--------------------------------------------------------------------------- // // Method: CClassMoniker::Enum // // Synopsis: Enumerate the components of this moniker. // //---------------------------------------------------------------------------- STDMETHODIMP CClassMoniker::Enum( BOOL fForward, IEnumMoniker ** ppenumMoniker) { HRESULT hr; mnkDebugOut((DEB_ITRACE, "CClassMoniker::Enum(%x,%x,%x)\n", this, fForward, ppenumMoniker)); __try { *ppenumMoniker = NULL; hr = S_OK; } __except(EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } return hr; } //+--------------------------------------------------------------------------- // // Method: CClassMoniker::IsEqual // // Synopsis: Compares with another moniker. // //---------------------------------------------------------------------------- STDMETHODIMP CClassMoniker::IsEqual( IMoniker *pmkOther) { HRESULT hr; CClassMoniker *pClassMoniker; mnkDebugOut((DEB_ITRACE, "CClassMoniker::IsEqual(%x,%x)\n", this, pmkOther)); __try { hr = pmkOther->QueryInterface(CLSID_ClassMoniker, (void **) &pClassMoniker); if(SUCCEEDED(hr)) { if(IsEqualCLSID(_data.clsid, pClassMoniker->_data.clsid)) { hr = S_OK; } else { hr = S_FALSE; } pClassMoniker->Release(); } else { hr = S_FALSE; } } __except(EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } return hr; } //+--------------------------------------------------------------------------- // // Method: CClassMoniker::Hash // // Synopsis: Compute a hash value // //---------------------------------------------------------------------------- STDMETHODIMP CClassMoniker::Hash( DWORD * pdwHash) { HRESULT hr; mnkDebugOut((DEB_ITRACE, "CClassMoniker::Hash(%x,%x)\n", this, pdwHash)); __try { *pdwHash = _data.clsid.Data1; hr = S_OK; } __except(EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } return hr; } //+--------------------------------------------------------------------------- // // Method: CClassMoniker::IsRunning // // Synopsis: Determines if the object identified by this moniker is // running. Since we can't search the class table to determine // if the object is running, we just return E_NOTIMPL. // //---------------------------------------------------------------------------- STDMETHODIMP CClassMoniker::IsRunning( IBindCtx * pbc, IMoniker * pmkToLeft, IMoniker * pmkNewlyRunning) { mnkDebugOut((DEB_ITRACE, "CClassMoniker::IsRunning(%x,%x,%x,%x)\n", this, pbc, pmkToLeft, pmkNewlyRunning)); return E_NOTIMPL; } //+--------------------------------------------------------------------------- // // Method: CClassMoniker::GetTimeOfLastChange // // Synopsis: Returns the time when the object identified by this moniker // was changed. // //---------------------------------------------------------------------------- STDMETHODIMP CClassMoniker::GetTimeOfLastChange ( IBindCtx * pbc, IMoniker * pmkToLeft, FILETIME * pFileTime) { mnkDebugOut((DEB_ITRACE, "CClassMoniker::GetTimeOfLastChange(%x,%x,%x,%x)\n", this, pbc, pmkToLeft, pFileTime)); return MK_E_UNAVAILABLE; } //+--------------------------------------------------------------------------- // // Method: CClassMoniker::Inverse // // Synopsis: Returns the inverse of this moniker. // //---------------------------------------------------------------------------- STDMETHODIMP CClassMoniker::Inverse( IMoniker ** ppmk) { mnkDebugOut((DEB_ITRACE, "CClassMoniker::Inverse(%x,%x)\n", this, ppmk)); return CreateAntiMoniker(ppmk); } //+--------------------------------------------------------------------------- // // Method: CClassMoniker::CommonPrefixWith // // Synopsis: Returns the common prefix shared by this moniker and the // other moniker. // //---------------------------------------------------------------------------- STDMETHODIMP CClassMoniker::CommonPrefixWith( IMoniker * pmkOther, IMoniker ** ppmkPrefix) { HRESULT hr; CClassMoniker *pClassMoniker; mnkDebugOut((DEB_ITRACE, "CClassMoniker::CommonPrefixWith(%x,%x,%x)\n", this, pmkOther, ppmkPrefix)); __try { //Validate parameters. *ppmkPrefix = NULL; hr = pmkOther->QueryInterface(CLSID_ClassMoniker, (void **) &pClassMoniker); if(SUCCEEDED(hr)) { if(IsEqualCLSID(_data.clsid, pClassMoniker->_data.clsid)) { AddRef(); *ppmkPrefix = (IMoniker *) this; hr = MK_S_US; } else { hr = MK_E_NOPREFIX; } pClassMoniker->Release(); } else { hr = MonikerCommonPrefixWith(this, pmkOther, ppmkPrefix); } } __except(EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } return hr; } //+--------------------------------------------------------------------------- // // Method: CClassMoniker::RelativePathTo // // Synopsis: Returns the relative path between this moniker and the // other moniker. // //---------------------------------------------------------------------------- STDMETHODIMP CClassMoniker::RelativePathTo( IMoniker * pmkOther, IMoniker ** ppmkRelPath) { HRESULT hr; mnkDebugOut((DEB_ITRACE, "CClassMoniker::RelativePathTo(%x,%x,%x)\n", this, pmkOther, ppmkRelPath)); __try { *ppmkRelPath = NULL; hr = MonikerRelativePathTo(this, pmkOther, ppmkRelPath, TRUE); } __except(EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } return hr; } //+--------------------------------------------------------------------------- // // Method: CClassMoniker::GetDisplayName // // Synopsis: Get the display name of this moniker. // // Notes: Call ProgIDFromClassID to get the ProgID // Append a ':' to the end of the string. // If no ProgID is available, then use // clsid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx;parameters: // //---------------------------------------------------------------------------- STDMETHODIMP CClassMoniker::GetDisplayName( IBindCtx * pbc, IMoniker * pmkToLeft, LPWSTR * lplpszDisplayName) { HRESULT hr = E_FAIL; LPWSTR pszDisplayName; mnkDebugOut((DEB_ITRACE, "CClassMoniker::GetDisplayName(%x,%x,%x,%x)\n", this, pbc, pmkToLeft, lplpszDisplayName)); __try { LPWSTR pszPrefix; WCHAR szClassID[37]; LPWSTR pszParameters = (LPWSTR) _pExtra; if((lstrlenW(pszParameters) * sizeof(WCHAR)) > _data.cbExtra) return E_INVALIDARG; //Validate parameters. *lplpszDisplayName = NULL; //Create a display name from the class ID. //Get the class ID string. wStringFromUUID(_data.clsid, szClassID); //Get the prefix hr = ProgIDFromCLSID(CLSID_ClassMoniker, &pszPrefix); if(SUCCEEDED(hr)) { ULONG cName; cName = lstrlenW(pszPrefix) + 1 + lstrlenW(szClassID); if(pszParameters != NULL) { cName += lstrlenW(pszParameters); } cName += 2; pszDisplayName = (LPWSTR) CoTaskMemAlloc(cName * sizeof(wchar_t)); if(pszDisplayName != NULL) { lstrcpyW(pszDisplayName, pszPrefix); lstrcatW(pszDisplayName, L":"); lstrcatW(pszDisplayName, szClassID); if(pszParameters != NULL) { lstrcatW(pszDisplayName, pszParameters); } lstrcatW(pszDisplayName, L":"); *lplpszDisplayName = pszDisplayName; hr = S_OK; } else { hr = E_OUTOFMEMORY; } CoTaskMemFree(pszPrefix); } } __except(EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } return hr; } //+--------------------------------------------------------------------------- // // Method: CClassMoniker::ParseDisplayName // // Synopsis: Parse the display name. // // Algorithm: Call BindToObject to get an IParseDisplayName on the class // object. Call IParseDisplayName::ParseDisplayName on the // class object. // //---------------------------------------------------------------------------- STDMETHODIMP CClassMoniker::ParseDisplayName ( IBindCtx * pbc, IMoniker * pmkToLeft, LPWSTR lpszDisplayName, ULONG * pchEaten, IMoniker ** ppmkOut) { HRESULT hr; IParseDisplayName *pPDN; mnkDebugOut((DEB_ITRACE, "CClassMoniker::ParseDisplayName(%x,%x,%x,%ws,%x,%x)\n", this, pbc, pmkToLeft, lpszDisplayName, pchEaten, ppmkOut)); __try { //Validate parameters *ppmkOut = NULL; *pchEaten = 0; hr = BindToObject(pbc, pmkToLeft, IID_IParseDisplayName, (void **) &pPDN); if(SUCCEEDED(hr)) { //Register the object with the bind context. hr = pbc->RegisterObjectBound(pPDN); if(SUCCEEDED(hr)) { //Parse the display name. hr = pPDN->ParseDisplayName(pbc, lpszDisplayName, pchEaten, ppmkOut); } pPDN->Release(); } } __except(EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } return hr; } //+--------------------------------------------------------------------------- // // Method: CClassMoniker::IsSystemMoniker // // Synopsis: Determines if this is one of the system supplied monikers. // //---------------------------------------------------------------------------- STDMETHODIMP CClassMoniker::IsSystemMoniker( DWORD * pdwType) { HRESULT hr; mnkDebugOut((DEB_ITRACE, "CClassMoniker::IsSystemMoniker(%x,%x)\n", this, pdwType)); __try { *pdwType = MKSYS_CLASSMONIKER; hr = S_OK; } __except(EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } return hr; } //+--------------------------------------------------------------------------- // // Method: CClassMoniker::GetComparisonData // // Synopsis: Get comparison data for registration in the ROT // //---------------------------------------------------------------------------- STDMETHODIMP CClassMoniker::GetComparisonData( byte * pbData, ULONG cbMax, DWORD *pcbData) { HRESULT hr; mnkDebugOut((DEB_ITRACE, "CClassMoniker::GetComparisonData(%x,%x,%x,%x)\n", this, pbData, cbMax, pcbData)); __try { *pcbData = 0; if(cbMax >= sizeof(CLSID_ClassMoniker) + sizeof(_data.clsid)) { memcpy(pbData, &CLSID_ClassMoniker, sizeof(CLSID_ClassMoniker)); pbData += sizeof(CLSID); memcpy(pbData, &_data.clsid, sizeof(_data.clsid)); *pcbData = sizeof(CLSID_ClassMoniker) + sizeof(_data.clsid); hr = S_OK; } else { hr = E_OUTOFMEMORY; } } __except(EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } return hr; } //+--------------------------------------------------------------------------- // // Method: CClassMoniker::GetUnmarshalClass // // Synopsis: Get the class ID. // //---------------------------------------------------------------------------- STDMETHODIMP CClassMoniker::GetUnmarshalClass( REFIID riid, LPVOID pv, DWORD dwDestContext, LPVOID pvDestContext, DWORD mshlflags, CLSID * pClassID) { mnkDebugOut((DEB_ITRACE, "CClassMoniker::GetUnmarshalClass(%x,%I,%x,%x,%x,%x,%x)\n", this, &riid, pv, dwDestContext, pvDestContext, mshlflags, pClassID)); return GetClassID(pClassID); } //+--------------------------------------------------------------------------- // // Method: CClassMoniker::GetMarshalSizeMax // // Synopsis: Get maximum size of marshalled moniker. // //---------------------------------------------------------------------------- STDMETHODIMP CClassMoniker::GetMarshalSizeMax( REFIID riid, LPVOID pv, DWORD dwDestContext, LPVOID pvDestContext, DWORD mshlflags, DWORD *pSize) { HRESULT hr; mnkDebugOut((DEB_ITRACE, "CClassMoniker::GetMarshalSizeMax(%x,%I,%x,%x,%x,%x,%x)\n", this, &riid, pv, dwDestContext, pvDestContext, mshlflags, pSize)); __try { *pSize = sizeof(_data) + _data.cbExtra; hr = S_OK; } __except(EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } return hr; } //+--------------------------------------------------------------------------- // // Method: CClassMoniker::MarshalInterface // // Synopsis: Marshal moniker into a stream. // //---------------------------------------------------------------------------- STDMETHODIMP CClassMoniker::MarshalInterface( IStream * pStream, REFIID riid, void * pv, DWORD dwDestContext, LPVOID pvDestContext, DWORD mshlflags) { mnkDebugOut((DEB_ITRACE, "CClassMoniker::MarshalInterface(%x,%x,%I,%x,%x,%x,%x)\n", this, pStream, &riid, pv, dwDestContext, pvDestContext, mshlflags)); return Save(pStream, FALSE); } //+--------------------------------------------------------------------------- // // Method: CClassMoniker::UnmarshalInterface // // Synopsis: Unmarshal moniker from a stream. // //---------------------------------------------------------------------------- STDMETHODIMP CClassMoniker::UnmarshalInterface( IStream * pStream, REFIID riid, void ** ppv) { HRESULT hr; mnkDebugOut((DEB_ITRACE, "CClassMoniker::UnmarshalInterface(%x,%x,%I,%x)\n", this, pStream, &riid, ppv)); __try { //Validate parameters. *ppv = NULL; hr = Load(pStream); if(SUCCEEDED(hr)) { hr = QueryInterface(riid, ppv); } } __except(EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } return hr; } //+--------------------------------------------------------------------------- // // Method: CClassMoniker::ReleaseMarshalData // // Synopsis: Release a marshalled class moniker. // Just seek to the end of the marshalled class moniker. // //---------------------------------------------------------------------------- STDMETHODIMP CClassMoniker::ReleaseMarshalData( IStream * pStream) { HRESULT hr; LARGE_INTEGER liSize; mnkDebugOut((DEB_ITRACE, "CClassMoniker::ReleaseMarshalData(%x,%x)\n", this, pStream)); hr = GetSizeMax((ULARGE_INTEGER *) &liSize); if(SUCCEEDED(hr)) { hr = pStream->Seek(liSize, STREAM_SEEK_CUR, NULL); } return hr; } //+--------------------------------------------------------------------------- // // Method: CClassMoniker::DisconnectObject // // Synopsis: Disconnect the object. // //---------------------------------------------------------------------------- STDMETHODIMP CClassMoniker::DisconnectObject( DWORD dwReserved) { mnkDebugOut((DEB_ITRACE, "CClassMoniker::DisconnectObject(%x,%x)\n", this, dwReserved)); return S_OK; } //+------------------------------------------------------------------------- // // Member: CUrlMonWrapper::QueryInterface // // Synopsis: The UrlMon wrapper supports IUnknown and IUrlMon. // // Arguments: [iid] -- the requested interface // [ppvObj] -- where to put the interface pointer // // Returns: S_OK // E_INVALIDARG // E_NOINTERFACE // // Notes: Bad parameters will raise an exception. The exception // handler catches exceptions and returns E_INVALIDARG. // //-------------------------------------------------------------------------- STDMETHODIMP CUrlMonWrapper::QueryInterface (REFIID iid, void ** ppv) { HRESULT hr; __try { mnkDebugOut((DEB_TRACE, "CUrlMonWrapper::QueryInterface(%x,%I,%x)\n", this, &iid, ppv)); if(IsEqualIID(iid,IID_IUnknown) || IsEqualIID(iid,IID_IUrlMon)) { AddRef(); *ppv = (IUrlMon *) this; hr = S_OK; } else { *ppv = NULL; hr = E_NOINTERFACE; } } __except(EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } return hr; } //+------------------------------------------------------------------------- // // Member: CUrlMonWrapper::CUrlMonWrapper // // Synopsis: Constructor for CUrlMonWrapper. // // Arguments: void // // Returns: void // // //-------------------------------------------------------------------------- CUrlMonWrapper::CUrlMonWrapper() : _cRef(1) { mnkDebugOut((DEB_TRACE, "CUrlMonWrapper::CUrlMonWrapper\n")); } //+------------------------------------------------------------------------- // // Member: CUrlMonWrapper::AddRef // // Synopsis: Increment the reference count. // // Arguments: void // // Returns: ULONG -- the new reference count // // //-------------------------------------------------------------------------- STDMETHODIMP_(ULONG) CUrlMonWrapper::AddRef(void) { mnkDebugOut((DEB_TRACE, "CUrlMonWrapper::AddRef(%x)\n", this)); InterlockedIncrement(&_cRef); return _cRef; } //+------------------------------------------------------------------------- // // Member: CUrlMonWrapper::Release // // Synopsis: Decrements the reference count. // // Arguments: void // // Returns: ULONG -- the remaining reference count // //-------------------------------------------------------------------------- STDMETHODIMP_(ULONG) CUrlMonWrapper::Release(void) { ULONG count = _cRef - 1; mnkDebugOut((DEB_TRACE, "CUrlMonWrapper::Release(%x)\n", this)); if(0 == InterlockedDecrement(&_cRef)) { delete this; count = 0; } return count; } //+------------------------------------------------------------------------- // // Member: CUrlMonWrapper::AsyncGetClassBits // // Synopsis: This wrapper function supports both synchronous and // asynchronous operation. In synchronous mode, this // function waits in a modal loop for completion of the // operation. In asynchronous mode, the client supplies // an IBindStatusCallback. The function returns // immediately with MK_S_ASYNCHRONOUS. When the operation // completes, the client is notified via // IBindStatusCallback::OnCompletion. // // Returns: S_OK // //-------------------------------------------------------------------------- STDMETHODIMP CUrlMonWrapper::AsyncGetClassBits( REFCLSID rclsid, LPCWSTR pszMimeType, LPCWSTR pszFileExt, DWORD dwFileVersionMS, DWORD dwFileVersionLS, LPCWSTR pszCodeBase, IBindCtx *pBindCtx, DWORD dwClassContext, REFIID riid, DWORD flags) { HRESULT hr; mnkDebugOut((DEB_TRACE, "CUrlMonWrapper::AsyncGetClassBits(%I, %s)\n", rclsid, pszCodeBase)); __try { if(pBindCtx != NULL) { IUnknown *punk; //Check if an IBindStatusCallback is registered. hr = pBindCtx->GetObjectParam(REG_BSCB_HOLDER, &punk); if(SUCCEEDED(hr)) { //Asynchronous call with IBindStatusCallback. hr = (*pfnAsyncGetClassBits)(rclsid, pszMimeType, pszFileExt, dwFileVersionMS, dwFileVersionLS, pszCodeBase, pBindCtx, dwClassContext, NULL, riid, flags); punk->Release(); } else { //Synchronous call with bind context. CBindStatusCallback *pCallback = new CBindStatusCallback(hr); if(pCallback != NULL) { if(SUCCEEDED(hr)) { IBindStatusCallback * pibsc; // this will give us the progress UI hr = CreateStdProgressIndicator(NULL, NULL, pCallback, &pibsc); if(SUCCEEDED(hr)) { hr = (*pfnRegisterBindStatusCallback)(pBindCtx, pibsc, 0, 0); if(SUCCEEDED(hr)) { hr = (*pfnAsyncGetClassBits)(rclsid, pszMimeType, pszFileExt, dwFileVersionMS, dwFileVersionLS, pszCodeBase, pBindCtx, dwClassContext, NULL, riid, flags); //Wait for completion of the operation. if(hr == MK_S_ASYNCHRONOUS) { hr = pCallback->Wait(0,30000); } (*pfnRevokeBindStatusCallback)(pBindCtx, pCallback); } pibsc->Release(); } } pCallback->Release(); } else { hr = E_OUTOFMEMORY; } } } else { //Synchronous call without bind context. //Create a bind context and make recursive call. IBindCtx *pbc; hr = CreateBindCtx(0, &pbc); if(SUCCEEDED(hr)) { hr = AsyncGetClassBits(rclsid, pszMimeType, pszFileExt, dwFileVersionMS, dwFileVersionLS, pszCodeBase, pbc, dwClassContext, riid, flags); pbc->Release(); } } } __except(EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } return hr; } //+------------------------------------------------------------------- // // Function: PrivAsyncGetClassBits // // Synopsis: Loads urlmon.dll and calls AsyncGetClassBits // // Returns: S_OK, ERROR_MOD_NOT_FOUND // //-------------------------------------------------------------------- STDAPI PrivAsyncGetClassBits( REFCLSID rclsid, // CLSID LPCWSTR szTYPE, LPCWSTR szExt, DWORD dwFileVersionMS, // CODE=http://foo#Version=a,b,c,d DWORD dwFileVersionLS, // MAKEDWORD(c,b) of above LPCWSTR szURL, // CODE= in INSERT tag IBindCtx *pbc, // bind ctx DWORD dwClsContext, // CLSCTX flags LPVOID pvReserved, // Must be NULL REFIID riid, // Usually IID_IClassFactory DWORD flags) { HRESULT hr = E_FAIL; if(!hUrlMon) { hUrlMon = LoadLibraryA("urlmon.dll"); } if(hUrlMon != 0) { void *pfn = GetProcAddress(hUrlMon, "AsyncGetClassBits"); if(pfn != NULL) { pfnAsyncGetClassBits = (ASYNCGETCLASSBITS *) pfn; hr = (*pfnAsyncGetClassBits)(rclsid, szTYPE, szExt, dwFileVersionMS, dwFileVersionLS, szURL, pbc, dwClsContext, pvReserved, riid, flags); } else { hr = HRESULT_FROM_WIN32(GetLastError()); } } else { hr = HRESULT_FROM_WIN32(GetLastError()); } return hr; } //+------------------------------------------------------------------- // // Function: PrivRegisterBindStatusCallback // // Synopsis: Loads urlmon.dll and calls RegisterBindStatusCallback // // Returns: S_OK, ERROR_MOD_NOT_FOUND // //-------------------------------------------------------------------- STDAPI PrivRegisterBindStatusCallback( LPBC pBC, IBindStatusCallback *pBSCb, IBindStatusCallback** ppBSCBPrev, DWORD dwReserved) { HRESULT hr = E_FAIL; if(!hUrlMon) { hUrlMon = LoadLibraryA("urlmon.dll"); } if(hUrlMon != 0) { void *pfn = GetProcAddress(hUrlMon, "RegisterBindStatusCallback"); if(pfn != NULL) { pfnRegisterBindStatusCallback = (REGISTERBINDSTATUSCALLBACK *) pfn; hr = (*pfnRegisterBindStatusCallback)(pBC, pBSCb, ppBSCBPrev, dwReserved); } else { hr = HRESULT_FROM_WIN32(GetLastError()); } } else { hr = HRESULT_FROM_WIN32(GetLastError()); } return hr; } //+------------------------------------------------------------------- // // Function: PrivRevokeBindStatusCallback // // Synopsis: Loads urlmon.dll and calls RevokeBindStatusCallback. // // Returns: S_OK, ERROR_MOD_NOT_FOUND // //-------------------------------------------------------------------- STDAPI PrivRevokeBindStatusCallback( LPBC pBC, IBindStatusCallback *pBSCb) { HRESULT hr = E_FAIL; if(!hUrlMon) { hUrlMon = LoadLibraryA("urlmon.dll"); } if(hUrlMon != 0) { void *pfn = GetProcAddress(hUrlMon, "RevokeBindStatusCallback"); if(pfn != NULL) { pfnRevokeBindStatusCallback = (REVOKEBINDSTATUSCALLBACK *) pfn; hr = (*pfnRevokeBindStatusCallback)(pBC, pBSCb); } else { hr = HRESULT_FROM_WIN32(GetLastError()); } } else { hr = HRESULT_FROM_WIN32(GetLastError()); } return hr; } // =========================================================================== // CBindStatusCallback Implementation // =========================================================================== //+--------------------------------------------------------------------------- // // Method: CBindStatusCallback::CBindStatusCallback // // Synopsis: Creates a bind status callback object. // //---------------------------------------------------------------------------- CBindStatusCallback::CBindStatusCallback(HRESULT &hr) : _cRef(1), _hr(MK_S_ASYNCHRONOUS) { _hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); if(_hEvent != NULL) { hr = S_OK; } else { hr = HRESULT_FROM_WIN32(GetLastError()); } } //+--------------------------------------------------------------------------- // // Method: CBindStatusCallback::~CBindStatusCallback // // Synopsis: Destructor for CBindStatusCallback object. // //---------------------------------------------------------------------------- CBindStatusCallback::~CBindStatusCallback() { if(_hEvent != NULL) { CloseHandle(_hEvent); } } //+--------------------------------------------------------------------------- // // Method: CBindStatusCallback::QueryInterface // // Synopsis: Gets an interface pointer to the bind status callback object. // //---------------------------------------------------------------------------- STDMETHODIMP CBindStatusCallback::QueryInterface(REFIID riid, void** ppv) { HRESULT hr = S_OK; *ppv = NULL; if(IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IBindStatusCallback)) { AddRef(); *ppv = (IBindStatusCallback *) this; } else if(IsEqualIID(riid, IID_ISynchronize)) { AddRef(); *ppv = (ISynchronize *) this; } else { hr = E_NOINTERFACE; } return hr; } //+--------------------------------------------------------------------------- // // Method: CBindStatusCallback::AddRef // // Synopsis: Increments the reference count. // //---------------------------------------------------------------------------- STDMETHODIMP_(ULONG) CBindStatusCallback::AddRef() { InterlockedIncrement((long *) &_cRef); return _cRef; } //+--------------------------------------------------------------------------- // // Method: CBindStatusCallback::Release // // Synopsis: Decrements the reference count. // //---------------------------------------------------------------------------- STDMETHODIMP_(ULONG) CBindStatusCallback::Release() { LONG count = _cRef - 1; if(0 == InterlockedDecrement((long *) &_cRef)) { delete this; count = 0; } return count; } // --------------------------------------------------------------------------- // %%Function: CBindStatusCallback::OnStartBinding // --------------------------------------------------------------------------- STDMETHODIMP CBindStatusCallback::OnStartBinding(DWORD grfBSCOption, IBinding* pbinding) { ComDebOut((DEB_ACTIVATE,"CBindStatusCallback::OnStartBinding\n")); return(NOERROR); } // --------------------------------------------------------------------------- // %%Function: CBindStatusCallback::GetPriority // --------------------------------------------------------------------------- STDMETHODIMP CBindStatusCallback::GetPriority(LONG* pnPriority) { ComDebOut((DEB_ACTIVATE, "CBindStatusCallback::GetPriority\n")); return(NOERROR); } // --------------------------------------------------------------------------- // %%Function: CBindStatusCallback::OnLowResource // --------------------------------------------------------------------------- STDMETHODIMP CBindStatusCallback::OnLowResource(DWORD dwReserved) { ComDebOut((DEB_ACTIVATE, "CBindStatusCallback::OnLowResource\n")); return(NOERROR); } // --------------------------------------------------------------------------- // %%Function: CBindStatusCallback::OnStopBinding // --------------------------------------------------------------------------- STDMETHODIMP CBindStatusCallback::OnStopBinding(HRESULT hrStatus, LPCWSTR pszError) { ComDebOut((DEB_ACTIVATE, "CBindStatusCallback::OnStopBinding hrStatus:%x\n", hrStatus)); _hr = hrStatus; Signal(); return(NOERROR); } // --------------------------------------------------------------------------- // %%Function: CBindStatusCallback::GetBindInfo // --------------------------------------------------------------------------- STDMETHODIMP CBindStatusCallback::GetBindInfo(DWORD* pgrfBINDF, BINDINFO* pbindInfo) { ComDebOut((DEB_ACTIVATE, "CBindStatusCallback::GetBindInfo\n")); return (NOERROR); } // --------------------------------------------------------------------------- // %%Function: CBindStatusCallback::OnDataAvailable // This function is called whenever data starts arriving. When the file download is // complete then the BSCF_LASTDATANOTIFICATION comes and you can get the local cached // File Name. // --------------------------------------------------------------------------- STDMETHODIMP CBindStatusCallback::OnDataAvailable( DWORD grfBSCF, DWORD dwSize, FORMATETC* pfmtetc, STGMEDIUM* pstgmed) { ComDebOut((DEB_ACTIVATE, "CBindStatusCallback::OnDataAvailable\n")); return(NOERROR); } // --------------------------------------------------------------------------- // %%Function: CBindStatusCallback::OnObjectAvailable // --------------------------------------------------------------------------- STDMETHODIMP CBindStatusCallback::OnObjectAvailable(REFIID riid, IUnknown* punk) { ComDebOut((DEB_ACTIVATE, "CBindStatusCallback::OnObjectAvailable\n")); return(NOERROR); } // --------------------------------------------------------------------------- // %%Function: CBindStatusCallback::OnProgress // --------------------------------------------------------------------------- STDMETHODIMP CBindStatusCallback::OnProgress ( ULONG ulProgress, ULONG ulProgressMax, ULONG ulStatusCode, LPCWSTR pwzStatusText ) { ComDebOut((DEB_ACTIVATE, "CBindStatusCallback::OnProgress %d of %d\n", ulProgress, (ulProgress > ulProgressMax) ? ulProgress : ulProgressMax)); #if DBG==1 if(pwzStatusText != NULL) { int cb = lstrlenW(pwzStatusText) * 2 + 1; char *psz = (char *) alloca(cb); if(psz != NULL) { WideCharToMultiByte(CP_ACP, 0, pwzStatusText,-1, psz, cb, 0,0); ComDebOut((DEB_ACTIVATE, "%s\n", psz)); } } #endif return(NOERROR); } //+--------------------------------------------------------------------------- // // Method: CBindStatusCallback::Wait // // Synopsis: Waits in a message loop for completion of an operation. // The message loop dispatches the timer messages required // by the urlmon state machine. // //---------------------------------------------------------------------------- STDMETHODIMP CBindStatusCallback::Wait(DWORD dwFlags, DWORD dwMilliseconds) { HRESULT hr; DWORD dwWakeReason = WAIT_OBJECT_0 + 1; MSG msg; while(WAIT_OBJECT_0 + 1 == dwWakeReason) { //Process the incoming Windows messages. while(SSPeekMessage(&msg, NULL, 0, 0, PM_REMOVE) != 0) { TranslateMessage(&msg); SSDispatchMessage(&msg); } dwWakeReason = MsgWaitForMultipleObjects(1, &_hEvent, FALSE, dwMilliseconds, QS_ALLINPUT); } switch(dwWakeReason) { case WAIT_OBJECT_0: hr = _hr; break; case WAIT_TIMEOUT: hr = RPC_E_TIMEOUT; break; case 0xFFFFFFFF: hr = HRESULT_FROM_WIN32(GetLastError()); break; default: hr = E_FAIL; break; } return hr; } //+--------------------------------------------------------------------------- // // Method: CBindStatusCallback::Signal // // Synopsis: Signal the event. // //---------------------------------------------------------------------------- STDMETHODIMP CBindStatusCallback::Signal() { HRESULT hr = S_OK; if(!SetEvent(_hEvent)) { hr = HRESULT_FROM_WIN32(GetLastError()); } return hr; } //+--------------------------------------------------------------------------- // // Method: CBindStatusCallback::Reset // // Synopsis: Reset the event. // //---------------------------------------------------------------------------- STDMETHODIMP CBindStatusCallback::Reset() { HRESULT hr = S_OK; if(!ResetEvent(_hEvent)) { hr = HRESULT_FROM_WIN32(GetLastError()); } return hr; }
28.279585
93
0.415882
[ "object" ]
02bd91e05eea28b21e374ad82143217bf0bfbbad
1,490
hpp
C++
include/nbla/utils/im2col.hpp
kodavatimahendra/nnabla
72009f670af075f17ffca9c809b07d48cca30bd9
[ "Apache-2.0" ]
1
2021-04-08T00:33:23.000Z
2021-04-08T00:33:23.000Z
include/nbla/utils/im2col.hpp
kodavatimahendra/nnabla
72009f670af075f17ffca9c809b07d48cca30bd9
[ "Apache-2.0" ]
null
null
null
include/nbla/utils/im2col.hpp
kodavatimahendra/nnabla
72009f670af075f17ffca9c809b07d48cca30bd9
[ "Apache-2.0" ]
1
2020-08-19T08:32:51.000Z
2020-08-19T08:32:51.000Z
// Copyright (c) 2017 Sony Corporation. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef __NBLA_UTILS_IM2COL_HPP__ #define __NBLA_UTILS_IM2COL_HPP__ namespace nbla { template <typename T> void im2col(const T *img, const int c_i, const int *shape, const int *k, const int *p, const int *s, const int *d, T *col); template <typename T> void im2col_nd(const T *img, const int c, const int spatial_dims, const int *spatial_shape, const int *kernel, const int *pad, const int *stride, const int *dilation, T *col); template <typename T> void col2im(const T *col, const int c_i, const int *shape, const int *k, const int *p, const int *s, const int *d, T *img); template <typename T> void col2im_nd(const T *col, const int c, const int spatial_dims, const int *spatial_shape, const int *kernel, const int *pad, const int *stride, const int *dilation, T *img); } #endif
39.210526
75
0.696644
[ "shape" ]
02bfb1ba2102fd4698cddc66cc82160a371bbb54
2,422
cpp
C++
rs/test/throw_test.cpp
dymk/rs
b75ab0df5f235ac12ec4da825e6bd6e1fa9e7493
[ "Apache-2.0" ]
19
2017-05-15T08:20:00.000Z
2021-12-03T05:58:32.000Z
rs/test/throw_test.cpp
dymk/rs
b75ab0df5f235ac12ec4da825e6bd6e1fa9e7493
[ "Apache-2.0" ]
null
null
null
rs/test/throw_test.cpp
dymk/rs
b75ab0df5f235ac12ec4da825e6bd6e1fa9e7493
[ "Apache-2.0" ]
3
2018-01-16T18:07:30.000Z
2021-06-30T07:33:44.000Z
// Copyright 2017 Per Grön. 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 <catch.hpp> #include <rs/throw.h> #include <rs/subscriber.h> namespace shk { TEST_CASE("Throw") { auto error = std::make_exception_ptr(std::runtime_error("test")); SECTION("construct") { auto stream = Throw(error); static_assert( IsPublisher<decltype(stream)>, "Throw stream should be a publisher"); } SECTION("subscribe") { auto stream = Throw(error); std::exception_ptr received_error; { auto subscription = stream.Subscribe(MakeSubscriber( [](int next) { CHECK(!"should not happen"); }, [&received_error](std::exception_ptr &&error) { received_error = error; }, [] { CHECK(!"should not happen"); })); CHECK(received_error); received_error = std::exception_ptr(); subscription.Request(ElementCount(0)); subscription.Request(ElementCount(1)); subscription.Request(ElementCount::Unbounded()); CHECK(!received_error); } // Destroy subscription CHECK(!received_error); } SECTION("create with exception object rather than exception_ptr") { auto stream = Throw(std::runtime_error("test")); std::exception_ptr received_error; { auto subscription = stream.Subscribe(MakeSubscriber( [](int next) { CHECK(!"should not happen"); }, [&received_error](std::exception_ptr &&error) { received_error = error; }, [] { CHECK(!"should not happen"); })); CHECK(received_error); received_error = std::exception_ptr(); subscription.Request(ElementCount(0)); subscription.Request(ElementCount(1)); subscription.Request(ElementCount::Unbounded()); CHECK(!received_error); } // Destroy subscription CHECK(!received_error); } } } // namespace shk
30.275
75
0.657308
[ "object" ]
02bfb7232a4d14aef62061aea615357c3f3713db
6,972
cpp
C++
cheat/RenderManager.cpp
aequabit/ayyware-web
de06d0c95ffc926caee654fa6d98c83fe3670534
[ "MIT" ]
8
2017-06-07T09:55:37.000Z
2019-01-15T18:59:06.000Z
cheat/RenderManager.cpp
aequabit/ayyware-web
de06d0c95ffc926caee654fa6d98c83fe3670534
[ "MIT" ]
null
null
null
cheat/RenderManager.cpp
aequabit/ayyware-web
de06d0c95ffc926caee654fa6d98c83fe3670534
[ "MIT" ]
2
2017-06-08T22:23:08.000Z
2019-12-25T00:13:05.000Z
#pragma once #include "RenderManager.h" #define _CRT_SECURE_NO_WARNINGS // Font Instances namespace Render { // Text functions namespace Fonts { DWORD Default; DWORD Menu; DWORD MenuBold; DWORD ayyware; DWORD ESP; }; }; // We don't use these anywhere else, no reason for them to be // available anywhere else enum EFontFlags { FONTFLAG_NONE, FONTFLAG_ITALIC = 0x001, FONTFLAG_UNDERLINE = 0x002, FONTFLAG_STRIKEOUT = 0x004, FONTFLAG_SYMBOL = 0x008, FONTFLAG_ANTIALIAS = 0x010, FONTFLAG_GAUSSIANBLUR = 0x020, FONTFLAG_ROTARY = 0x040, FONTFLAG_DROPSHADOW = 0x080, FONTFLAG_ADDITIVE = 0x100, FONTFLAG_OUTLINE = 0x200, FONTFLAG_CUSTOM = 0x400, FONTFLAG_BITMAP = 0x800, }; // Initialises the rendering system, setting up fonts etc void Render::Initialise() { Fonts::Default = 0x1D; // MainMenu Font from vgui_spew_fonts Fonts::Menu = Interfaces::Surface->FontCreate(); Fonts::MenuBold = Interfaces::Surface->FontCreate(); Fonts::ESP = Interfaces::Surface->FontCreate(); Fonts::ayyware = Interfaces::Surface->FontCreate(); Interfaces::Surface->SetFontGlyphSet(Fonts::Menu, "DINPro-Regular", 14, 500, 0, 0, FONTFLAG_ANTIALIAS); Interfaces::Surface->SetFontGlyphSet(Fonts::MenuBold, "DINPro-Regular", 14, 900, 0, 0, FONTFLAG_ANTIALIAS); Interfaces::Surface->SetFontGlyphSet(Fonts::ESP, "DINPro-Regular", 14, 500, 0, 0, FONTFLAG_ANTIALIAS | FONTFLAG_DROPSHADOW); Interfaces::Surface->SetFontGlyphSet(Fonts::ayyware, "DINPro-Regular", 112, 500, 0, 0, FONTFLAG_ANTIALIAS); } RECT Render::GetViewport() { RECT Viewport = { 0, 0, 0, 0 }; int w, h; Interfaces::Engine->GetScreenSize(w, h); Viewport.right = w; Viewport.bottom = h; return Viewport; } void Render::Clear(int x, int y, int w, int h, Color color) { Interfaces::Surface->DrawSetColor(color); Interfaces::Surface->DrawFilledRect(x, y, x + w, y + h); } void Render::Outline(int x, int y, int w, int h, Color color) { Interfaces::Surface->DrawSetColor(color); Interfaces::Surface->DrawOutlinedRect(x, y, x + w, y + h); } void Render::Line(int x, int y, int x2, int y2, Color color) { Interfaces::Surface->DrawSetColor(color); Interfaces::Surface->DrawLine(x, y, x2, y2); } void Render::PolyLine(int *x, int *y, int count, Color color) { Interfaces::Surface->DrawSetColor(color); Interfaces::Surface->DrawPolyLine(x, y, count); } bool Render::WorldToScreen(Vector &in, Vector &out) { const matrix3x4& worldToScreen = Interfaces::Engine->WorldToScreenMatrix(); //Grab the world to screen matrix from CEngineClient::WorldToScreenMatrix float w = worldToScreen[3][0] * in[0] + worldToScreen[3][1] * in[1] + worldToScreen[3][2] * in[2] + worldToScreen[3][3]; //Calculate the angle in compareson to the player's camera. out.z = 0; //Screen doesn't have a 3rd dimension. if (w > 0.001) //If the object is within view. { RECT ScreenSize = GetViewport(); float fl1DBw = 1 / w; //Divide 1 by the angle. out.x = (ScreenSize.right / 2) + (0.5f * ((worldToScreen[0][0] * in[0] + worldToScreen[0][1] * in[1] + worldToScreen[0][2] * in[2] + worldToScreen[0][3]) * fl1DBw) * ScreenSize.right + 0.5f); //Get the X dimension and push it in to the Vector. out.y = (ScreenSize.bottom / 2) - (0.5f * ((worldToScreen[1][0] * in[0] + worldToScreen[1][1] * in[1] + worldToScreen[1][2] * in[2] + worldToScreen[1][3]) * fl1DBw) * ScreenSize.bottom + 0.5f); //Get the Y dimension and push it in to the Vector. return true; } return false; } void Render::Text(int x, int y, Color color, DWORD font, const char* text) { size_t origsize = strlen(text) + 1; const size_t newsize = 100; size_t convertedChars = 0; wchar_t wcstring[newsize]; mbstowcs_s(&convertedChars, wcstring, origsize, text, _TRUNCATE); Interfaces::Surface->DrawSetTextFont(font); Interfaces::Surface->DrawSetTextColor(color); Interfaces::Surface->DrawSetTextPos(x, y); Interfaces::Surface->DrawPrintText(wcstring, wcslen(wcstring)); return; } void Render::Text(int x, int y, Color color, DWORD font, const wchar_t* text) { Interfaces::Surface->DrawSetTextFont(font); Interfaces::Surface->DrawSetTextColor(color); Interfaces::Surface->DrawSetTextPos(x, y); Interfaces::Surface->DrawPrintText(text, wcslen(text)); } void Render::Textf(int x, int y, Color color, DWORD font, const char* fmt, ...) { if (!fmt) return; //if the passed string is null return if (strlen(fmt) < 2) return; //Set up va_list and buffer to hold the params va_list va_alist; char logBuf[256] = { 0 }; //Do sprintf with the parameters va_start(va_alist, fmt); _vsnprintf_s(logBuf + strlen(logBuf), 256 - strlen(logBuf), sizeof(logBuf) - strlen(logBuf), fmt, va_alist); va_end(va_alist); Text(x, y, color, font, logBuf); } RECT Render::GetTextSize(DWORD font, const char* text) { size_t origsize = strlen(text) + 1; const size_t newsize = 100; size_t convertedChars = 0; wchar_t wcstring[newsize]; mbstowcs_s(&convertedChars, wcstring, origsize, text, _TRUNCATE); RECT rect; int x, y; Interfaces::Surface->GetTextSize(font, wcstring, x, y); rect.left = x; rect.bottom = y; rect.right = x; return rect; } void Render::GradientV(int x, int y, int w, int h, Color c1, Color c2) { Clear(x, y, w, h, c1); BYTE first = c2.r(); BYTE second = c2.g(); BYTE third = c2.b(); for (int i = 0; i < h; i++) { float fi = i, fh = h; float a = fi / fh; DWORD ia = a * 255; Clear(x, y + i, w, 1, Color(first, second, third, ia)); } } void Render::GradientH(int x, int y, int w, int h, Color c1, Color c2) { Clear(x, y, w, h, c1); BYTE first = c2.r(); BYTE second = c2.g(); BYTE third = c2.b(); for (int i = 0; i < w; i++) { float fi = i, fw = w; float a = fi / fw; DWORD ia = a * 255; Clear(x + i, y, 1, h, Color(first, second, third, ia)); } } void Render::Polygon(int count, Vertex_t* Vertexs, Color color) { static int Texture = Interfaces::Surface->CreateNewTextureID(true); //need to make a texture with procedural true unsigned char buffer[4] = { 255, 255, 255, 255 };//{ color.r(), color.g(), color.b(), color.a() }; Interfaces::Surface->DrawSetTextureRGBA(Texture, buffer, 1, 1); //Texture, char array of texture, width, height Interfaces::Surface->DrawSetColor(color); // keep this full color and opacity use the RGBA @top to set values. Interfaces::Surface->DrawSetTexture(Texture); // bind texture Interfaces::Surface->DrawTexturedPolygon(count, Vertexs); } void Render::PolygonOutline(int count, Vertex_t* Vertexs, Color color, Color colorLine) { static int x[128]; static int y[128]; Render::Polygon(count, Vertexs, color); for (int i = 0; i < count; i++) { x[i] = Vertexs[i].m_Position.x; y[i] = Vertexs[i].m_Position.y; } Render::PolyLine(x, y, count, colorLine); } void Render::PolyLine(int count, Vertex_t* Vertexs, Color colorLine) { static int x[128]; static int y[128]; for (int i = 0; i < count; i++) { x[i] = Vertexs[i].m_Position.x; y[i] = Vertexs[i].m_Position.y; } Render::PolyLine(x, y, count, colorLine); }
29.417722
247
0.689616
[ "render", "object", "vector" ]
c49daa1fe07e08897edbba3f2afc5b34efdce950
31,099
cpp
C++
source/RootGeoManager.cpp
cxwx/VecGeom
c86c00bd7d4db08f4fc20a625020da329784aaac
[ "ECL-2.0", "Apache-2.0" ]
1
2020-06-27T18:43:36.000Z
2020-06-27T18:43:36.000Z
source/RootGeoManager.cpp
cxwx/VecGeom
c86c00bd7d4db08f4fc20a625020da329784aaac
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
source/RootGeoManager.cpp
cxwx/VecGeom
c86c00bd7d4db08f4fc20a625020da329784aaac
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
// This file is part of VecGeom and is distributed under the // conditions in the file LICENSE.txt in the top directory. // For the full list of authors see CONTRIBUTORS.txt and `git log`. /// \file RootGeoManager.cpp /// \author created by Johannes de Fine Licht, Sandro Wenzel (CERN) #include "VecGeom/base/Transformation3D.h" #include "VecGeom/base/Stopwatch.h" #include "VecGeom/management/GeoManager.h" #include "VecGeom/management/RootGeoManager.h" #include "VecGeom/navigation/NavigationState.h" #include "VecGeom/volumes/LogicalVolume.h" #include "VecGeom/volumes/PlacedRootVolume.h" #include "VecGeom/volumes/PlacedVolume.h" #include "VecGeom/volumes/UnplacedBox.h" #include "VecGeom/volumes/UnplacedTube.h" #include "VecGeom/volumes/UnplacedCone.h" #include "VecGeom/volumes/UnplacedRootVolume.h" #include "VecGeom/volumes/UnplacedParaboloid.h" #include "VecGeom/volumes/UnplacedParallelepiped.h" #include "VecGeom/volumes/UnplacedPolyhedron.h" #include "VecGeom/volumes/UnplacedTrd.h" #include "VecGeom/volumes/UnplacedOrb.h" #include "VecGeom/volumes/UnplacedSphere.h" #include "VecGeom/volumes/UnplacedBooleanVolume.h" #include "VecGeom/volumes/UnplacedTorus2.h" #include "VecGeom/volumes/UnplacedTrapezoid.h" #include "VecGeom/volumes/UnplacedPolycone.h" #include "VecGeom/volumes/UnplacedScaledShape.h" #include "VecGeom/volumes/UnplacedGenTrap.h" #include "VecGeom/volumes/UnplacedSExtruVolume.h" #include "VecGeom/volumes/UnplacedExtruded.h" #include "VecGeom/volumes/PlanarPolygon.h" #include "VecGeom/volumes/UnplacedAssembly.h" #include "VecGeom/volumes/UnplacedCutTube.h" #include "TGeoManager.h" #include "TGeoNode.h" #include "TGeoMatrix.h" #include "TGeoVolume.h" #include "TGeoBBox.h" #include "TGeoSphere.h" #include "TGeoTube.h" #include "TGeoCone.h" #include "TGeoTrd1.h" #include "TGeoTrd2.h" #include "TGeoPara.h" #include "TGeoParaboloid.h" #include "TGeoPgon.h" #include "TGeoCompositeShape.h" #include "TGeoBoolNode.h" #include "TGeoTorus.h" #include "TGeoArb8.h" #include "TGeoPcon.h" #include "TGeoXtru.h" #include "TGeoShapeAssembly.h" #include "TGeoScaledShape.h" #include "TGeoEltu.h" #include <iostream> #include <list> namespace vecgeom { void RootGeoManager::LoadRootGeometry() { Clear(); GeoManager::Instance().Clear(); TGeoNode const *const world_root = ::gGeoManager->GetTopNode(); // Convert() will recursively convert daughters Stopwatch timer; timer.Start(); fWorld = Convert(world_root); timer.Stop(); if (fVerbose) { std::cout << "*** Conversion of ROOT -> VecGeom finished (" << timer.Elapsed() << " s) ***\n"; } GeoManager::Instance().SetWorld(fWorld); timer.Start(); GeoManager::Instance().CloseGeometry(); timer.Stop(); if (fVerbose) { std::cout << "*** Closing VecGeom geometry finished (" << timer.Elapsed() << " s) ***\n"; } // fix the world --> close geometry might have changed it ( "compactification" ) // this is very ugly of course: some observer patter/ super smart pointer might be appropriate fWorld = GeoManager::Instance().GetWorld(); // setup fast lookup table fTGeoNodeVector.resize(VPlacedVolume::GetIdCount(), nullptr); auto iter = fPlacedVolumeMap.begin(); for (; iter != fPlacedVolumeMap.end(); ++iter) { fTGeoNodeVector[iter->first] = iter->second; } } void RootGeoManager::LoadRootGeometry(std::string filename) { if (::gGeoManager != NULL) delete ::gGeoManager; TGeoManager::Import(filename.c_str()); LoadRootGeometry(); } bool RootGeoManager::ExportToROOTGeometry(VPlacedVolume const *topvolume, std::string filename) { if (gGeoManager != nullptr && gGeoManager->IsClosed()) { std::cerr << "will not export to ROOT file; gGeoManager already initialized and closed\n"; return false; } TGeoNode *world = Convert(topvolume); if (!world) { std::cerr << "The geometry cannot be converted to ROOT geometry\n"; return false; } ::gGeoManager->SetTopVolume(world->GetVolume()); ::gGeoManager->CloseGeometry(); ::gGeoManager->CheckOverlaps(); ::gGeoManager->Export(filename.c_str()); // setup fast lookup table fTGeoNodeVector.resize(VPlacedVolume::GetIdCount(), nullptr); auto iter = fPlacedVolumeMap.begin(); for (; iter != fPlacedVolumeMap.end(); ++iter) { fTGeoNodeVector[iter->first] = iter->second; } return true; } // a helper function to convert ROOT assembly constructs into a flat list of nodes // allows parsing of more complex ROOT geometries ( until VecGeom supports assemblies natively ) void FlattenAssemblies(TGeoNode *node, std::list<TGeoNode *> &nodeaccumulator, TGeoHMatrix const *globalmatrix, int currentdepth, int &count /* keeps track of number of flattenened nodes */, int &maxdepth) { maxdepth = currentdepth; if (RootGeoManager::Instance().GetFlattenAssemblies() && nullptr != dynamic_cast<TGeoVolumeAssembly *>(node->GetVolume())) { // it is an assembly --> so modify the matrix TGeoVolumeAssembly *assembly = dynamic_cast<TGeoVolumeAssembly *>(node->GetVolume()); for (int i = 0, Nd = assembly->GetNdaughters(); i < Nd; ++i) { TGeoHMatrix nextglobalmatrix = *globalmatrix; nextglobalmatrix.Multiply(assembly->GetNode(i)->GetMatrix()); FlattenAssemblies(assembly->GetNode(i), nodeaccumulator, &nextglobalmatrix, currentdepth + 1, count, maxdepth); } } else { if (currentdepth == 0) // can keep original node ( it was not an assembly ) nodeaccumulator.push_back(node); else { // need a new flattened node with a different transformation TGeoMatrix *newmatrix = new TGeoHMatrix(*globalmatrix); TGeoNodeMatrix *newnode = new TGeoNodeMatrix(node->GetVolume(), newmatrix); newnode->SetNumber(node->GetNumber()); // need a new name for the flattened node std::string *newname = new std::string(node->GetName()); *newname += "_assemblyinternalcount_" + std::to_string(count); newnode->SetName(newname->c_str()); nodeaccumulator.push_back(newnode); count++; } } } bool RootGeoManager::PostAdjustTransformation(Transformation3D *tr, TGeoNode const *node, Transformation3D *adjustment) const { // post-fixing the placement ... // unfortunately, in ROOT there is a special case in which a placement transformation // is hidden (or "misused") inside the Box shape via the origin property // // --> In this case we need to adjust the transformation for this placement bool adjust(false); if (node->GetVolume()->GetShape()->IsA() == TGeoBBox::Class()) { TGeoBBox const *const box = static_cast<TGeoBBox const *>(node->GetVolume()->GetShape()); auto o = box->GetOrigin(); if (o[0] != 0. || o[1] != 0. || o[2] != 0.) { if (fVerbose) { std::cerr << "Warning: **********************************************************\n"; std::cerr << "Warning: Found a box " << node->GetName() << " with non-zero origin\n"; std::cerr << "Warning: **********************************************************\n"; } *adjustment = Transformation3D::kIdentity; adjustment->SetTranslation(o[0] * LUnit(), o[1] * LUnit(), o[2] * LUnit()); adjustment->SetProperties(); tr->MultiplyFromRight(*adjustment); tr->SetProperties(); adjust = true; } } // other special cases may follow ... return adjust; } VPlacedVolume *RootGeoManager::Convert(TGeoNode const *const node) { if (fPlacedVolumeMap.Contains(node)) return const_cast<VPlacedVolume *>(GetPlacedVolume(node)); // convert node transformation Transformation3D const *const transformation = Convert(node->GetMatrix()); // possibly adjust transformation Transformation3D adjustmentTr; bool adjusted = PostAdjustTransformation(const_cast<Transformation3D *>(transformation), node, &adjustmentTr); LogicalVolume *const logical_volume = Convert(node->GetVolume()); VPlacedVolume *placed_volume = logical_volume->Place(node->GetName(), transformation); placed_volume->SetCopyNo(node->GetNumber()); int remaining_daughters = 0; { // All or no daughters should have been placed already remaining_daughters = node->GetNdaughters() - logical_volume->GetDaughters().size(); assert(remaining_daughters <= 0 || remaining_daughters == (int)node->GetNdaughters()); } // we have to convert here assemblies to list of normal nodes std::list<TGeoNode *> flattenenednodelist; int assemblydepth = 0; int flatteningcount = 0; for (int i = 0; i < remaining_daughters; ++i) { TGeoHMatrix trans = *node->GetDaughter(i)->GetMatrix(); FlattenAssemblies(node->GetDaughter(i), flattenenednodelist, &trans, 0, flatteningcount, assemblydepth); } if ((int)flattenenednodelist.size() > remaining_daughters) { std::cerr << "INFO: flattening of assemblies (depth " << assemblydepth << ") resulted in " << flattenenednodelist.size() << " daughters vs " << remaining_daughters << "\n"; } // for (auto &n : flattenenednodelist) { auto placed = Convert(n); logical_volume->PlaceDaughter(placed); // fixup placements in case the mother was shifted if (adjusted) { Transformation3D inv; adjustmentTr.Inverse(inv); inv.SetProperties(); Transformation3D *placedtr = const_cast<Transformation3D *>(placed->GetTransformation()); inv.MultiplyFromRight(*placedtr); inv.SetProperties(); placedtr->CopyFrom(inv); } } fPlacedVolumeMap.Set(node, placed_volume->id()); return placed_volume; } TGeoNode *RootGeoManager::Convert(VPlacedVolume const *const placed_volume) { if (fPlacedVolumeMap.Contains(placed_volume->id())) return const_cast<TGeoNode *>(fPlacedVolumeMap[placed_volume->id()]); TGeoVolume *geovolume = Convert(placed_volume, placed_volume->GetLogicalVolume()); // Protect for volumes that may not be convertible in some cases (e.g. tessellated) if (!geovolume) return nullptr; TGeoNode *node = new TGeoNodeMatrix(geovolume, NULL); node->SetNumber(placed_volume->GetCopyNo()); fPlacedVolumeMap.Set(node, placed_volume->id()); // only need to do daughterloop once for every logical volume. // So only need to check if // logical volume already done ( if it already has the right number of daughters ) auto remaining_daughters = placed_volume->GetDaughters().size() - geovolume->GetNdaughters(); assert(remaining_daughters == 0 || remaining_daughters == placed_volume->GetDaughters().size()); // do daughters for (size_t i = 0; i < remaining_daughters; ++i) { // get placed daughter VPlacedVolume const *daughter_placed = placed_volume->GetDaughters().operator[](i); // RECURSE DOWN HERE TGeoNode *daughternode = Convert(daughter_placed); if (!daughternode) return nullptr; // get matrix of daughter TGeoMatrix *geomatrixofdaughter = Convert(daughter_placed->GetTransformation()); // add node to the TGeoVolume; using the TGEO API // unfortunately, there is not interface allowing to add an existing // nodepointer directly geovolume->AddNode(daughternode->GetVolume(), i, geomatrixofdaughter); } return node; } Transformation3D *RootGeoManager::Convert(TGeoMatrix const *const geomatrix) { // if (fTransformationMap.Contains(geomatrix)) return const_cast<Transformation3D *>(fTransformationMap[geomatrix]); Double_t const *const t = geomatrix->GetTranslation(); Double_t const *const r = geomatrix->GetRotationMatrix(); Transformation3D *const transformation = new Transformation3D(t[0] * LUnit(), t[1] * LUnit(), t[2] * LUnit(), r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8]); // transformation->FixZeroes(); // transformation->SetProperties(); fTransformationMap.Set(geomatrix, transformation); return transformation; } TGeoMatrix *RootGeoManager::Convert(Transformation3D const *const trans) { if (fTransformationMap.Contains(trans)) return const_cast<TGeoMatrix *>(fTransformationMap[trans]); TGeoMatrix *const geomatrix = trans->ConvertToTGeoMatrix(); fTransformationMap.Set(geomatrix, trans); return geomatrix; } LogicalVolume *RootGeoManager::Convert(TGeoVolume const *const volume) { if (fLogicalVolumeMap.Contains(volume)) return const_cast<LogicalVolume *>(fLogicalVolumeMap[volume]); VUnplacedVolume const *unplaced; if (!volume->IsAssembly()) { unplaced = Convert(volume->GetShape()); } else { unplaced = ConvertAssembly(volume); } LogicalVolume *const logical_volume = new LogicalVolume(volume->GetName(), unplaced); // convert root material void *mat = fMaterialConversionLambda(volume->GetMedium()->GetMaterial()); const_cast<LogicalVolume *>(logical_volume)->SetMaterialPtr(mat); fLogicalVolumeMap.Set(volume, logical_volume); //// can be used to make a cross check for dimensions and other properties //// make a cross check using cubic volume property // if (! (dynamic_cast<TGeoCompositeShape *>(volume->GetShape()) || // logical_volume->GetUnplacedVolume()->IsAssembly())) // { // const auto v1 = logical_volume->GetUnplacedVolume()->Capacity(); // const auto v2 = volume->Capacity(); // std::cerr << "v1 " << v1 << " " << v2 << "\n"; // // assert(v1 > 0.); // assert(std::abs(v1 - v2 * LUnit() * LUnit() * LUnit())/v1 < 0.05); // } return logical_volume; } // the inverse: here we need both the placed volume and logical volume as input // they should match TGeoVolume *RootGeoManager::Convert(VPlacedVolume const *const placed_volume, LogicalVolume const *const logical_volume) { assert(placed_volume->GetLogicalVolume() == logical_volume); if (fLogicalVolumeMap.Contains(logical_volume)) return const_cast<TGeoVolume *>(fLogicalVolumeMap[logical_volume]); const TGeoShape *root_shape = placed_volume->ConvertToRoot(); // Some shapes do not exist in ROOT: we need to protect for that if (!root_shape) return nullptr; TGeoVolume *geovolume = new TGeoVolume(logical_volume->GetLabel().c_str(), /* the name */ root_shape, 0 /* NO MATERIAL FOR THE MOMENT */ ); fLogicalVolumeMap.Set(geovolume, logical_volume); return geovolume; } VUnplacedVolume *RootGeoManager::Convert(TGeoShape const *const shape) { if (fUnplacedVolumeMap.Contains(shape)) return const_cast<VUnplacedVolume *>(fUnplacedVolumeMap[shape]); VUnplacedVolume *unplaced_volume = NULL; // THE BOX if (shape->IsA() == TGeoBBox::Class()) { TGeoBBox const *const box = static_cast<TGeoBBox const *>(shape); unplaced_volume = GeoManager::MakeInstance<UnplacedBox>(box->GetDX() * LUnit(), box->GetDY() * LUnit(), box->GetDZ() * LUnit()); } // THE TUBE if (shape->IsA() == TGeoTube::Class()) { TGeoTube const *const tube = static_cast<TGeoTube const *>(shape); unplaced_volume = GeoManager::MakeInstance<UnplacedTube>(tube->GetRmin() * LUnit(), tube->GetRmax() * LUnit(), tube->GetDz() * LUnit(), 0., kTwoPi); } // THE TUBESEG if (shape->IsA() == TGeoTubeSeg::Class()) { TGeoTubeSeg const *const tube = static_cast<TGeoTubeSeg const *>(shape); unplaced_volume = GeoManager::MakeInstance<UnplacedTube>(tube->GetRmin() * LUnit(), tube->GetRmax() * LUnit(), tube->GetDz() * LUnit(), kDegToRad * tube->GetPhi1(), kDegToRad * (tube->GetPhi2() - tube->GetPhi1())); } // THE CONESEG if (shape->IsA() == TGeoConeSeg::Class()) { TGeoConeSeg const *const cone = static_cast<TGeoConeSeg const *>(shape); unplaced_volume = GeoManager::MakeInstance<UnplacedCone>( cone->GetRmin1() * LUnit(), cone->GetRmax1() * LUnit(), cone->GetRmin2() * LUnit(), cone->GetRmax2() * LUnit(), cone->GetDz() * LUnit(), kDegToRad * cone->GetPhi1(), kDegToRad * (cone->GetPhi2() - cone->GetPhi1())); } // THE CONE if (shape->IsA() == TGeoCone::Class()) { TGeoCone const *const cone = static_cast<TGeoCone const *>(shape); unplaced_volume = GeoManager::MakeInstance<UnplacedCone>(cone->GetRmin1() * LUnit(), cone->GetRmax1() * LUnit(), cone->GetRmin2() * LUnit(), cone->GetRmax2() * LUnit(), cone->GetDz() * LUnit(), 0., kTwoPi); } // THE PARABOLOID if (shape->IsA() == TGeoParaboloid::Class()) { TGeoParaboloid const *const p = static_cast<TGeoParaboloid const *>(shape); unplaced_volume = GeoManager::MakeInstance<UnplacedParaboloid>(p->GetRlo() * LUnit(), p->GetRhi() * LUnit(), p->GetDz() * LUnit()); } // THE PARALLELEPIPED if (shape->IsA() == TGeoPara::Class()) { TGeoPara const *const p = static_cast<TGeoPara const *>(shape); unplaced_volume = GeoManager::MakeInstance<UnplacedParallelepiped>( p->GetX() * LUnit(), p->GetY() * LUnit(), p->GetZ() * LUnit(), kDegToRad * p->GetAlpha(), kDegToRad * p->GetTheta(), kDegToRad * p->GetPhi()); } // Polyhedron/TGeoPgon if (shape->IsA() == TGeoPgon::Class()) { TGeoPgon const *pgon = static_cast<TGeoPgon const *>(shape); // fix dimensions - (requires making a copy of some arrays) const int NZs = pgon->GetNz(); double zs[NZs]; double rmins[NZs]; double rmaxs[NZs]; for (int i = 0; i < NZs; ++i) { zs[i] = pgon->GetZ()[i] * LUnit(); rmins[i] = pgon->GetRmin()[i] * LUnit(); rmaxs[i] = pgon->GetRmax()[i] * LUnit(); } unplaced_volume = GeoManager::MakeInstance<UnplacedPolyhedron>(pgon->GetPhi1() * kDegToRad, // phiStart pgon->GetDphi() * kDegToRad, // phiEnd pgon->GetNedges(), // sideCount pgon->GetNz(), // zPlaneCount zs, // zPlanes rmins, // rMin rmaxs // rMax ); } // TRD2 if (shape->IsA() == TGeoTrd2::Class()) { TGeoTrd2 const *const p = static_cast<TGeoTrd2 const *>(shape); unplaced_volume = GeoManager::MakeInstance<UnplacedTrd>(p->GetDx1() * LUnit(), p->GetDx2() * LUnit(), p->GetDy1() * LUnit(), p->GetDy2() * LUnit(), p->GetDz() * LUnit()); } // TRD1 if (shape->IsA() == TGeoTrd1::Class()) { TGeoTrd1 const *const p = static_cast<TGeoTrd1 const *>(shape); unplaced_volume = GeoManager::MakeInstance<UnplacedTrd>(p->GetDx1() * LUnit(), p->GetDx2() * LUnit(), p->GetDy() * LUnit(), p->GetDz() * LUnit()); } // TRAPEZOID if (shape->IsA() == TGeoTrap::Class()) { TGeoTrap const *const p = static_cast<TGeoTrap const *>(shape); if (!TGeoTrapIsDegenerate(p)) { unplaced_volume = GeoManager::MakeInstance<UnplacedTrapezoid>( p->GetDz() * LUnit(), p->GetTheta() * kDegToRad, p->GetPhi() * kDegToRad, p->GetH1() * LUnit(), p->GetBl1() * LUnit(), p->GetTl1() * LUnit(), p->GetAlpha1() * kDegToRad, p->GetH2() * LUnit(), p->GetBl2() * LUnit(), p->GetTl2() * LUnit(), p->GetAlpha2() * kDegToRad); } else { std::cerr << "Warning: this trap is degenerate -- will convert it to a generic trap!!\n"; unplaced_volume = ToUnplacedGenTrap((TGeoArb8 const *)p); } } // THE SPHERE | ORB if (shape->IsA() == TGeoSphere::Class()) { // make distinction TGeoSphere const *const p = static_cast<TGeoSphere const *>(shape); if (p->GetRmin() == 0. && p->GetTheta2() - p->GetTheta1() == 180. && p->GetPhi2() - p->GetPhi1() == 360.) { unplaced_volume = GeoManager::MakeInstance<UnplacedOrb>(p->GetRmax() * LUnit()); } else { unplaced_volume = GeoManager::MakeInstance<UnplacedSphere>( p->GetRmin() * LUnit(), p->GetRmax() * LUnit(), p->GetPhi1() * kDegToRad, (p->GetPhi2() - p->GetPhi1()) * kDegToRad, p->GetTheta1() * kDegToRad, (p->GetTheta2() - p->GetTheta1()) * kDegToRad); } } if (shape->IsA() == TGeoCompositeShape::Class()) { TGeoCompositeShape const *const compshape = static_cast<TGeoCompositeShape const *>(shape); TGeoBoolNode const *const boolnode = compshape->GetBoolNode(); // need the matrix; Transformation3D const *lefttrans = Convert(boolnode->GetLeftMatrix()); Transformation3D const *righttrans = Convert(boolnode->GetRightMatrix()); auto transformationadjust = [this](Transformation3D *tr, TGeoShape const *shape) { // TODO: combine this with external method Transformation3D adjustment; if (shape->IsA() == TGeoBBox::Class()) { TGeoBBox const *const box = static_cast<TGeoBBox const *>(shape); auto o = box->GetOrigin(); if (o[0] != 0. || o[1] != 0. || o[2] != 0.) { adjustment = Transformation3D::kIdentity; adjustment.SetTranslation(o[0] * LUnit(), o[1] * LUnit(), o[2] * LUnit()); adjustment.SetProperties(); tr->MultiplyFromRight(adjustment); tr->SetProperties(); } } }; // adjust transformation in case of shifted boxes transformationadjust(const_cast<Transformation3D *>(lefttrans), boolnode->GetLeftShape()); transformationadjust(const_cast<Transformation3D *>(righttrans), boolnode->GetRightShape()); // unplaced shapes VUnplacedVolume const *leftunplaced = Convert(boolnode->GetLeftShape()); VUnplacedVolume const *rightunplaced = Convert(boolnode->GetRightShape()); assert(leftunplaced != nullptr); assert(rightunplaced != nullptr); // the problem is that I can only place logical volumes VPlacedVolume *const leftplaced = (new LogicalVolume("inner_virtual", leftunplaced))->Place(lefttrans); VPlacedVolume *const rightplaced = (new LogicalVolume("inner_virtual", rightunplaced))->Place(righttrans); // now it depends on concrete type if (boolnode->GetBooleanOperator() == TGeoBoolNode::kGeoSubtraction) { unplaced_volume = GeoManager::MakeInstance<UnplacedBooleanVolume<kSubtraction>>(kSubtraction, leftplaced, rightplaced); } else if (boolnode->GetBooleanOperator() == TGeoBoolNode::kGeoIntersection) { unplaced_volume = GeoManager::MakeInstance<UnplacedBooleanVolume<kIntersection>>(kIntersection, leftplaced, rightplaced); } else if (boolnode->GetBooleanOperator() == TGeoBoolNode::kGeoUnion) { unplaced_volume = GeoManager::MakeInstance<UnplacedBooleanVolume<kUnion>>(kUnion, leftplaced, rightplaced); } } // THE TORUS if (shape->IsA() == TGeoTorus::Class()) { // make distinction TGeoTorus const *const p = static_cast<TGeoTorus const *>(shape); unplaced_volume = GeoManager::MakeInstance<UnplacedTorus2>(p->GetRmin() * LUnit(), p->GetRmax() * LUnit(), p->GetR() * LUnit(), p->GetPhi1() * kDegToRad, p->GetDphi() * kDegToRad); } // THE POLYCONE if (shape->IsA() == TGeoPcon::Class()) { TGeoPcon const *const p = static_cast<TGeoPcon const *>(shape); // fix dimensions - (requires making a copy of some arrays) const int NZs = p->GetNz(); double zs[NZs]; double rmins[NZs]; double rmaxs[NZs]; for (int i = 0; i < NZs; ++i) { zs[i] = p->GetZ()[i] * LUnit(); rmins[i] = p->GetRmin()[i] * LUnit(); rmaxs[i] = p->GetRmax()[i] * LUnit(); } unplaced_volume = GeoManager::MakeInstance<UnplacedPolycone>(p->GetPhi1() * kDegToRad, p->GetDphi() * kDegToRad, p->GetNz(), zs, rmins, rmaxs); } // THE SCALED SHAPE if (shape->IsA() == TGeoScaledShape::Class()) { TGeoScaledShape const *const p = static_cast<TGeoScaledShape const *>(shape); // First convert the referenced shape VUnplacedVolume *referenced_shape = Convert(p->GetShape()); const double *scale_root = p->GetScale()->GetScale(); unplaced_volume = GeoManager::MakeInstance<UnplacedScaledShape>(referenced_shape, scale_root[0], scale_root[1], scale_root[2]); } // THE ELLIPTICAL TUBE AS SCALED TUBE if (shape->IsA() == TGeoEltu::Class()) { TGeoEltu const *const p = static_cast<TGeoEltu const *>(shape); // Create the corresponding unplaced tube, with: // rmin=0, rmax=A, dz=dz, which is scaled with (1., A/B, 1.) UnplacedTube *tubeUnplaced = GeoManager::MakeInstance<UnplacedTube>(0, p->GetA() * LUnit(), p->GetDZ() * LUnit(), 0, kTwoPi); unplaced_volume = GeoManager::MakeInstance<UnplacedScaledShape>(tubeUnplaced, 1., p->GetB() / p->GetA(), 1.); } // THE ARB8 if (shape->IsA() == TGeoArb8::Class() || shape->IsA() == TGeoGtra::Class()) { TGeoArb8 *p = (TGeoArb8 *)(shape); unplaced_volume = ToUnplacedGenTrap(p); } // THE SIMPLE/GENERAL XTRU if (shape->IsA() == TGeoXtru::Class()) { TGeoXtru *p = (TGeoXtru *)(shape); // analyse convertability: the shape must have 2 planes with the same scaling // and offsets to make a simple extruded size_t Nvert = (size_t)p->GetNvert(); size_t Nsect = (size_t)p->GetNz(); if (Nsect == 2 && p->GetXOffset(0) == p->GetXOffset(1) && p->GetYOffset(0) == p->GetYOffset(1) && p->GetScale(0) == p->GetScale(1)) { double *x = new double[Nvert]; double *y = new double[Nvert]; for (size_t i = 0; i < Nvert; ++i) { // Normally offsets should be 0 and scales should be 1, but just to be safe x[i] = LUnit() * (p->GetXOffset(0) + p->GetX(i) * p->GetScale(0)); y[i] = LUnit() * (p->GetYOffset(0) + p->GetY(i) * p->GetScale(0)); } unplaced_volume = GeoManager::MakeInstance<UnplacedSExtruVolume>(p->GetNvert(), x, y, LUnit() * p->GetZ(0), LUnit() * p->GetZ(1)); delete[] x; delete[] y; } #ifndef VECGEOM_CUDA_INTERFACE else { // Make the general extruded solid. XtruVertex2 *vertices = new XtruVertex2[Nvert]; XtruSection *sections = new XtruSection[Nsect]; for (size_t i = 0; i < Nvert; ++i) { vertices[i].x = p->GetX(i); vertices[i].y = p->GetY(i); } for (size_t i = 0; i < Nsect; ++i) { sections[i].fOrigin.Set(p->GetXOffset(i), p->GetYOffset(i), p->GetZ(i)); sections[i].fScale = p->GetScale(i); } unplaced_volume = GeoManager::MakeInstance<UnplacedExtruded>(Nvert, vertices, Nsect, sections); delete[] vertices; delete[] sections; } #endif } // THE CUT TUBE if (shape->IsA() == TGeoCtub::Class()) { TGeoCtub *ctube = (TGeoCtub *)(shape); // Create the corresponding unplaced cut tube // TODO: consider moving this as a specialization to UnplacedTube unplaced_volume = GeoManager::MakeInstance<UnplacedCutTube>( ctube->GetRmin(), ctube->GetRmax(), ctube->GetDz(), kDegToRad * ctube->GetPhi1(), kDegToRad * (ctube->GetPhi2() - ctube->GetPhi1()), Vector3D<Precision>(ctube->GetNlow()[0], ctube->GetNlow()[1], ctube->GetNlow()[2]), Vector3D<Precision>(ctube->GetNhigh()[0], ctube->GetNhigh()[1], ctube->GetNhigh()[2])); } // New volumes should be implemented here... if (!unplaced_volume) { if (fVerbose) { printf("Unsupported shape for ROOT volume \"%s\" of type %s. " "Using ROOT implementation.\n", shape->GetName(), shape->ClassName()); } unplaced_volume = new UnplacedRootVolume(shape); } fUnplacedVolumeMap.Set(shape, unplaced_volume); return unplaced_volume; } VUnplacedVolume *RootGeoManager::ConvertAssembly(TGeoVolume const *const v) { if (TGeoVolumeAssembly const *va = dynamic_cast<TGeoVolumeAssembly const *>(v)) { // std::cerr << "treating volume assembly " << va->GetName() << "\n"; (void)va; return new UnplacedAssembly(); } return nullptr; } void RootGeoManager::PrintNodeTable() const { for (auto iter : fPlacedVolumeMap) { std::cerr << iter.first << " " << iter.second << "\n"; TGeoNode const *n = iter.second; n->Print(); } } void RootGeoManager::Clear() { fPlacedVolumeMap.Clear(); fUnplacedVolumeMap.Clear(); fLogicalVolumeMap.Clear(); fTransformationMap.Clear(); // this should be done by smart pointers // for (auto i = fPlacedVolumeMap.begin(); i != fPlacedVolumeMap.end(); ++i) { // delete i->first; // } // for (auto i = fUnplacedVolumeMap.begin(); i != fUnplacedVolumeMap.end(); ++i) { // delete i->first; // } // for (auto i = fLogicalVolumeMap.begin(); i != fLogicalVolumeMap.end(); ++i) { // delete i->first; // } for (auto i = fTransformationMap.begin(); i != fTransformationMap.end(); ++i) { delete i->first; delete i->second; } if (GeoManager::Instance().GetWorld() == fWorld) { GeoManager::Instance().SetWorld(nullptr); } } bool RootGeoManager::TGeoTrapIsDegenerate(TGeoTrap const *trap) { bool degeneracy = false; // const_cast because ROOT is lacking a const GetVertices() function auto const vertices = const_cast<TGeoTrap *>(trap)->GetVertices(); // check degeneracy within the layers (as vertices do not contains z information) for (int layer = 0; layer < 2; ++layer) { auto lowerindex = layer * 4; auto upperindex = (layer + 1) * 4; for (int i = lowerindex; i < upperindex; ++i) { auto currentx = vertices[2 * i]; auto currenty = vertices[2 * i + 1]; for (int j = lowerindex; j < upperindex; ++j) { if (j == i) { continue; } auto otherx = vertices[2 * j]; auto othery = vertices[2 * j + 1]; if (otherx == currentx && othery == currenty) { degeneracy = true; } } } } return degeneracy; } UnplacedGenTrap *RootGeoManager::ToUnplacedGenTrap(TGeoArb8 const *p) { // Create the corresponding GenTrap const double *vertices = const_cast<TGeoArb8 *>(p)->GetVertices(); Precision verticesx[8], verticesy[8]; for (auto ivert = 0; ivert < 8; ++ivert) { verticesx[ivert] = LUnit() * vertices[2 * ivert]; verticesy[ivert] = LUnit() * vertices[2 * ivert + 1]; } return GeoManager::MakeInstance<UnplacedGenTrap>(verticesx, verticesy, LUnit() * p->GetDz()); } // lookup the placed volume corresponding to a TGeoNode VPlacedVolume const *RootGeoManager::Lookup(TGeoNode const *node) const { if (node == nullptr) return nullptr; return Index2PVolumeConverter<NavStateIndex_t>::ToPlacedVolume(fPlacedVolumeMap[node]); } } // namespace vecgeom
40.546284
120
0.638702
[ "geometry", "shape", "solid" ]
c4a5605eb31055e25a89bfbb1aff8edd10941a4e
2,733
cpp
C++
src/win.cpp
phillip-h/todo
afb6436ef40d883b838c7c97d541a484dce47f7b
[ "MIT" ]
17
2015-09-21T14:38:26.000Z
2022-03-09T03:05:46.000Z
src/win.cpp
phillip-h/todo
afb6436ef40d883b838c7c97d541a484dce47f7b
[ "MIT" ]
2
2016-06-15T19:17:01.000Z
2019-02-10T10:03:22.000Z
src/win.cpp
phillip-h/todo
afb6436ef40d883b838c7c97d541a484dce47f7b
[ "MIT" ]
6
2017-07-15T07:53:36.000Z
2021-11-06T18:06:20.000Z
#include "win.hpp" using std::string; bool Win::colors; ///////////////////////////////////////////////// // constructor, set position and size variables // and create the WINDOW* and border Win::Win(unsigned x, unsigned y, unsigned w, unsigned h, string name, bool border) { this->x = x; this->y = y; this->width = width; this->height = height; this->name = name; this->border = newwin(h, w, y, x); if (border) win = newwin(h - 2, w - 2, y + 1, x + 1); else win = newwin(h, w, y, x); } ////////////////////////////////// // destructor, destroy the window Win::~Win() { delwin(border); delwin(win); } //////////////////////////////////////// // set if colors should be used or not void Win::setColors(bool colors) { Win::colors = colors; } //////////////////// // clear the window void Win::clear() { werase(border); werase(win); } /////////////////////////////////// // draw the current window buffer void Win::draw() { box(border, 0, 0); inverse(true); mvwprintw(border, 0, 0, string("[" + name + "]").c_str()); inverseOff(true); wrefresh(border); wrefresh(win); } ///////////////////////////////////////// // move window print position to (x, y) void Win::move(unsigned x, unsigned y) { wmove(win, y, x); } ///////////////////////////// // print text to the window void Win::print(string text) { wprintw(win, text.c_str()); } ////////////////////////////////////// // print text to the window at (x, y) void Win::print(string text, unsigned x, unsigned y) { mvwprintw(win, y, x, text.c_str()); } ////////////////////////// // turn on inverse mode void Win::inverse(bool border) { if (border) wattron(this->border, A_STANDOUT); else wattron(this->win, A_STANDOUT); } ////////////////////////// // turn off inverse mode void Win::inverseOff(bool border) { if (border) wattroff(this->border, A_STANDOUT); else wattroff(this->win, A_STANDOUT); } /////////////////////// // turn on color pair void Win::color(int pair, bool border) { if (border) wattron(this->border, COLOR_PAIR(pair)); else wattron(this->win, COLOR_PAIR(pair)); } //////////////////////// // turn off color pair void Win::colorOff(int pair, bool border) { if (border) wattroff(this->border, COLOR_PAIR(pair)); else wattroff(this->win, COLOR_PAIR(pair)); } //////////////////////////////////////////// // transform mouse click x, y to window // coordinates bool Win::mouse(int &x, int &y) { return wmouse_trafo(win, &y, &x, false); } /////////////////////// // get WINDOW pointer WINDOW* Win::getWin() { return win; }
19.804348
62
0.502744
[ "transform" ]
c4a5853275f49ce6d130b7ea9663926bc6d91367
17,091
cpp
C++
libs/rteutils/test/src/RteUtilsTest.cpp
VGRSTM/devtools
341c442bd8eab69ba0e1b75bf7803caf45edb7b2
[ "Apache-2.0", "MIT", "ECL-2.0", "BSL-1.0", "BSD-3-Clause" ]
2
2021-09-17T12:34:32.000Z
2022-01-13T12:43:04.000Z
libs/rteutils/test/src/RteUtilsTest.cpp
VGRSTM/devtools
341c442bd8eab69ba0e1b75bf7803caf45edb7b2
[ "Apache-2.0", "MIT", "ECL-2.0", "BSL-1.0", "BSD-3-Clause" ]
32
2021-11-18T13:58:59.000Z
2022-02-25T12:34:44.000Z
libs/rteutils/test/src/RteUtilsTest.cpp
soumeh01/devtools
f78a9dd84eedba43b75ba0f83b40d04dad81dbc9
[ "Apache-2.0", "MIT", "ECL-2.0", "BSL-1.0", "BSD-3-Clause" ]
1
2021-11-09T15:12:16.000Z
2021-11-09T15:12:16.000Z
/* * Copyright (c) 2020-2021 Arm Limited. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 */ #include "RteUtils.h" #include "gtest/gtest.h" using namespace std; static void CheckVendorMatch(const vector<string>& vendors, bool expect) { for (auto iter = vendors.cbegin(); iter != vendors.cend() - 1; iter++) { EXPECT_EQ(expect, DeviceVendor::Match(*iter, *(iter + 1))) << "Failed to compare " << (*iter) << " & " << *(iter + 1); } } TEST(RteUtilsTest, EqualNoCase) { EXPECT_TRUE(RteUtils::EqualNoCase("", "")); EXPECT_TRUE(RteUtils::EqualNoCase("SameCase", "SameCase")); EXPECT_TRUE(RteUtils::EqualNoCase("UPPER_CASE", "UPPER_CASE")); EXPECT_TRUE(RteUtils::EqualNoCase("lower case", "lower case")); EXPECT_TRUE(RteUtils::EqualNoCase("Mixed_Case", "mIXED_cASE")); EXPECT_FALSE(RteUtils::EqualNoCase("Mixed_Case1", "Mixed_Case01")); EXPECT_FALSE(RteUtils::EqualNoCase("Mixed_Case", "Mixed_Cake")); } TEST(RteUtilsTest, GetPrefix) { EXPECT_EQ(RteUtils::GetPrefix("prefix:suffix"), "prefix"); EXPECT_EQ(RteUtils::GetPrefix("prefix:suffix", '-'),"prefix:suffix"); EXPECT_EQ(RteUtils::GetPrefix("prefix:suffix",':', true) , "prefix:"); EXPECT_EQ( RteUtils::GetPrefix("prefix-suffix"), "prefix-suffix"); EXPECT_EQ( RteUtils::GetPrefix("prefix-suffix", '-'),"prefix"); } TEST(RteUtilsTest, GetSuffix) { EXPECT_EQ(RteUtils::GetSuffix("prefix:suffix"), "suffix"); EXPECT_TRUE(RteUtils::GetSuffix("prefix:suffix", '-').empty()); EXPECT_EQ(RteUtils::GetSuffix("prefix:suffix", ':', true), ":suffix"); EXPECT_TRUE(RteUtils::GetSuffix("prefix-suffix").empty()); EXPECT_EQ(RteUtils::GetSuffix("prefix-suffix", '-'), "suffix"); } TEST(RteUtilsTest, ExtractFileExtension) { EXPECT_TRUE(RteUtils::ExtractFileExtension("myfile").empty()); EXPECT_EQ(RteUtils::ExtractFileExtension("my.dir/my.file"), "file"); EXPECT_EQ(RteUtils::ExtractFileExtension("my.dir/my.file.ext"), "ext"); EXPECT_EQ(RteUtils::ExtractFileExtension("my.dir/my.file.ext", true), ".ext"); } TEST(RteUtilsTest, ExtractFileName) { EXPECT_EQ(RteUtils::ExtractFileName("myfile.ext"), "myfile.ext"); EXPECT_EQ(RteUtils::ExtractFileName("./my.dir/myfile"), "myfile"); EXPECT_EQ(RteUtils::ExtractFileName("./my.dir/my.file"), "my.file"); EXPECT_EQ(RteUtils::ExtractFileName("./my.dir/my.file.ext"), "my.file.ext"); EXPECT_EQ(RteUtils::ExtractFileName("..\\my.dir\\myfile"), "myfile"); EXPECT_EQ(RteUtils::ExtractFileName("..\\my.dir\\my.file"), "my.file"); EXPECT_EQ(RteUtils::ExtractFileName("..\\my.dir\\my.file.ext"), "my.file.ext"); } TEST(RteUtilsTest, ExtractFileBaseName) { EXPECT_EQ(RteUtils::ExtractFileBaseName("myfile.ext"), "myfile"); EXPECT_EQ(RteUtils::ExtractFileBaseName("my.dir/myfile"), "myfile"); EXPECT_EQ(RteUtils::ExtractFileBaseName("my.dir/my.file"), "my"); EXPECT_EQ(RteUtils::ExtractFileBaseName("my.dir/my.file.ext"), "my.file"); EXPECT_EQ(RteUtils::ExtractFileBaseName("my.dir\\myfile"), "myfile"); EXPECT_EQ(RteUtils::ExtractFileBaseName("my.dir\\my.file"), "my"); EXPECT_EQ(RteUtils::ExtractFileBaseName("my.file.ext"), "my.file"); } TEST(RteUtilsTest, ExpandInstancePlaceholders) { static string text = "#define USBD%Instance%_PORT %Instance%\n" "#define USBD%Instance%_HS 0"; static string text1 = "#define USBD0_PORT 0\n" "#define USBD0_HS 0\n"; static string text2 = "#define USBD0_PORT 0\n" "#define USBD0_HS 0\n" "#define USBD1_PORT 1\n" "#define USBD1_HS 0\n"; string expanded = RteUtils::ExpandInstancePlaceholders(text, 1); EXPECT_EQ(expanded, text1); expanded = RteUtils::ExpandInstancePlaceholders(text, 2); EXPECT_EQ(expanded, text2); } TEST(RteUtilsTest, VersionMatchMode) { EXPECT_EQ(VersionCmp::MatchModeFromString(""), VersionCmp::ANY_VERSION); EXPECT_EQ(VersionCmp::MatchModeFromString("fixed"), VersionCmp::VersionCmp::FIXED_VERSION); EXPECT_EQ(VersionCmp::MatchModeFromString("latest"), VersionCmp::VersionCmp::LATEST_VERSION); EXPECT_EQ(VersionCmp::MatchModeFromString("excluded"), VersionCmp::VersionCmp::EXCLUDED_VERSION); EXPECT_EQ(VersionCmp::MatchModeToString(VersionCmp::ANY_VERSION).empty(), true); EXPECT_EQ(VersionCmp::MatchModeToString(VersionCmp::VersionCmp::FIXED_VERSION),"fixed"); EXPECT_EQ(VersionCmp::MatchModeToString(VersionCmp::VersionCmp::LATEST_VERSION), "latest"); EXPECT_EQ(VersionCmp::MatchModeToString(VersionCmp::VersionCmp::EXCLUDED_VERSION), "excluded"); } TEST(RteUtilsTest, VersionCompare) { EXPECT_EQ( -1, VersionCmp::Compare("6.5.0-a", "6.5.0", true)); EXPECT_EQ( 0, VersionCmp::Compare("6.5.0-a", "6.5.0-A", true)); EXPECT_EQ( 0, VersionCmp::Compare("6.5.0+b", "6.5.0+A", true)); EXPECT_EQ( -1, VersionCmp::Compare("6.5.0-a", "6.5.0-B", true)); EXPECT_EQ( 0, VersionCmp::Compare("6.5.0-a", "6.5.0-A", false)); EXPECT_EQ( 0, VersionCmp::Compare("6.5.0", "6.5.0", false)); EXPECT_EQ( -1, VersionCmp::Compare("6.5.0", "6.5.1")); EXPECT_EQ( -2, VersionCmp::Compare("6.4.0", "6.5.0")); EXPECT_EQ( -3, VersionCmp::Compare("2.5.0", "6.5.0")); EXPECT_EQ( 1, VersionCmp::Compare("6.5.9", "6.5.1")); EXPECT_EQ( 2, VersionCmp::Compare("6.6.0", "6.5.0")); EXPECT_EQ( 3, VersionCmp::Compare("7.5.0", "6.5.0")); EXPECT_EQ(-1, VersionCmp::Compare("6.5.0-", "6.5.0-a", true)); /*Ideally It should fail as the input given is not compliant to Semantic versioning*/ EXPECT_EQ( 0, VersionCmp::Compare("1.2.5.0.1.2", "1.2.5.0.1.2")); EXPECT_EQ( 3, VersionCmp::Compare("Test", "1.2.5.0")); EXPECT_EQ( -3, VersionCmp::Compare("1.2.3", "v1.2.3")); } TEST(RteUtilsTest, VersionRangeCompare) { EXPECT_EQ(0, VersionCmp::RangeCompare("3.2.0", "3.1.0:3.8.0")); EXPECT_EQ(0, VersionCmp::RangeCompare("3.2.0", "3.1.0")); EXPECT_EQ(0, VersionCmp::RangeCompare("3.2.0", ":3.8.0")); EXPECT_EQ(0, VersionCmp::RangeCompare("3.2.0", "3.2.0")); EXPECT_EQ(1, VersionCmp::RangeCompare("3.2.0", ":3.2.0-")); EXPECT_EQ(0, VersionCmp::RangeCompare("1.0.0", "1.0.0:2.0.0")); EXPECT_EQ(0, VersionCmp::RangeCompare("2.0.0", "1.0.0:2.0.0")); EXPECT_EQ(0, VersionCmp::RangeCompare("1.99.99", "1.0.0:2.0.0")); EXPECT_EQ(1, VersionCmp::RangeCompare("1.99.99", "1.0.0:1.99.9")); EXPECT_EQ(0, VersionCmp::RangeCompare("1.0.0", "1.0.0:2.0.0-")); EXPECT_EQ(1, VersionCmp::RangeCompare("2.0.0", "1.0.0:2.0.0-")); EXPECT_EQ(1, VersionCmp::RangeCompare("2.0.0-a", "1.0.0:2.0.0-")); EXPECT_EQ(0, VersionCmp::RangeCompare("2.0.0-a", "2.0.0-:2.0.0")); EXPECT_EQ(0, VersionCmp::RangeCompare("1.99.99", "1.0.0:2.0.0-")); EXPECT_EQ( 3, VersionCmp::RangeCompare("9.0.0", "1.0.0:2.0.0")); EXPECT_EQ(-3, VersionCmp::RangeCompare("0.9.0", "1.0.0:2.0.0")); /* Greater than max version : Patch version out of range */ EXPECT_EQ( 1, VersionCmp::RangeCompare("3.8.2", "3.1.0:3.8.0")); /* Greater than max version : Minor version out of range */ EXPECT_EQ( 2, VersionCmp::RangeCompare("3.9.0", "3.1.0:3.8.0")); /* Greater than max version : Major version out of range */ EXPECT_EQ( 3, VersionCmp::RangeCompare("4.2.0", "3.1.0:3.8.0")); /* Version matches */ EXPECT_EQ( 0, VersionCmp::RangeCompare("3.1.0", "3.1.0:3.1.0")); /* less than Min version : Patch version out of range */ EXPECT_EQ( -1, VersionCmp::RangeCompare("3.3.8", "3.3.9:3.3.9")); /* less than Min version : Minor version out of range */ EXPECT_EQ( -2, VersionCmp::RangeCompare("3.2.9", "3.3.9:3.3.9")); /* less than Min version : Major version out of range */ EXPECT_EQ( -3, VersionCmp::RangeCompare("2.3.9", "3.3.9:3.3.9")); } TEST(RteUtilsTest, WildCardsTo) { string test_input = "This?? is a *test1* _string-!#."; string regex = "This.. is a .*test1.* _string-!#\\."; string replaced = "Thisxx_is_a_xtest1x__string-__."; string converted = WildCards::ToRegEx(test_input); EXPECT_EQ(converted, regex); converted = WildCards::ToX(test_input); EXPECT_EQ(converted, replaced); } TEST(RteUtilsTest, WildCardMatch) { EXPECT_EQ(true, WildCards::Match("a", "a")); EXPECT_EQ(false, WildCards::Match("a", "")); EXPECT_EQ(false, WildCards::Match("", "d")); EXPECT_EQ(false, WildCards::Match("", "*")); EXPECT_EQ(true, WildCards::Match("a*", "a*d")); EXPECT_EQ(false, WildCards::Match("a*", "*d")); EXPECT_EQ(true, WildCards::Match("a*", "abcd")); EXPECT_EQ(false, WildCards::Match("a*", "xycd")); EXPECT_EQ(true, WildCards::Match("a*d", "*d")); EXPECT_EQ(true, WildCards::Match("a*d", "abcd")); EXPECT_EQ(false, WildCards::Match("a*d", "abxx")); EXPECT_EQ(false, WildCards::Match("a*d", "abxyz")); EXPECT_EQ(false, WildCards::Match("a*d", "xycd")); EXPECT_EQ(true, WildCards::Match("*d", "abcd")); EXPECT_EQ(true, WildCards::Match("*d", "d")); EXPECT_EQ(true, WildCards::Match("*c*", "abcd")); EXPECT_EQ(true, WildCards::Match("abcd", "a**d")); EXPECT_EQ(true, WildCards::Match("abcd", "a??d")); EXPECT_EQ(true, WildCards::Match("abcd", "?bc?")); EXPECT_EQ(true, WildCards::Match("abc?", "abc*")); EXPECT_EQ(true, WildCards::Match("ab?d", "ab??")); EXPECT_EQ(false, WildCards::Match("ab?d", "abc??")); EXPECT_EQ(false, WildCards::Match("?bcd", "abc??")); EXPECT_EQ(true, WildCards::Match("?bcd", "*bcd")); EXPECT_EQ(false, WildCards::Match("?bcd", "abc???")); EXPECT_EQ(true, WildCards::Match("abc?", "ab??")); EXPECT_EQ(false, WildCards::Match("abc?", "abc??")); EXPECT_EQ(false, WildCards::Match("ab??", "abc??")); EXPECT_EQ(true, WildCards::Match("abc*", "ab*?")); EXPECT_EQ(true, WildCards::Match("abc*", "abc?*")); EXPECT_EQ(true, WildCards::Match("ab*?", "abc?*")); EXPECT_EQ(false, WildCards::Match("abcX-1", "abcX-2")); EXPECT_EQ(false, WildCards::Match("abcX-1", "abcX-3")); EXPECT_EQ(false, WildCards::Match("abcX-1", "abcY-1")); EXPECT_EQ(false, WildCards::Match("abcX-1", "abcY-2")); EXPECT_EQ(true, WildCards::Match("abcX-1", "abc[XY]-[12]")); EXPECT_EQ(false, WildCards::Match("abcZ-1", "abc[XY]-[12]")); EXPECT_EQ(true, WildCards::Match("abcY-2", "abc[XY]-[12]")); EXPECT_EQ(true, WildCards::Match("Prefix_*_Suffix", "Prefix_Mid_Suffix")); EXPECT_EQ(true, WildCards::Match("Prefix_*_Suffix", "Prefix_Mid_V_Suffix")); EXPECT_EQ(true, WildCards::Match("Prefix_*_Suffix", "Prefix_Mid_Suffix_Suffix")); EXPECT_EQ(true, WildCards::Match("Prefix*_Suffix", "Prefix_Mid_Suffix")); EXPECT_EQ(true, WildCards::Match("Prefix*Suffix", "Prefix_Mid_Suffix")); EXPECT_EQ(true, WildCards::Match("Prefix*Suffix", "Prefix_Mid_Suffix_Suffix")); EXPECT_EQ(true, WildCards::Match("Prefix_*Suffix", "Prefix_Mid_Suffix")); EXPECT_EQ(true, WildCards::Match("Prefix.*.Suffix", "Prefix.Mid.Suffix")); std::vector<string> inputStr{ "STM32F10[123]?[CDE]", "STM32F103ZE", "*", "*?", "?*", "?*?", "*?*", "**", "**?" }; for (auto iter = inputStr.cbegin(); iter != inputStr.cend() - 1; iter++) { EXPECT_TRUE(WildCards::Match(*iter, *(iter + 1))) << "Failed for " << (*iter) << " & " << *(iter + 1); } } TEST(RteUtilsTest, AlnumCmp_Char) { EXPECT_EQ( -1, AlnumCmp::Compare(nullptr, "2.1")); EXPECT_EQ( 1, AlnumCmp::Compare("10.1", nullptr)); EXPECT_EQ( 0, AlnumCmp::Compare(nullptr, nullptr)); EXPECT_EQ( 1, AlnumCmp::Compare("10.1", "2.1")); EXPECT_EQ( 0, AlnumCmp::Compare("2.01", "2.1")); // 01 is considered as 1 EXPECT_EQ( 0, AlnumCmp::Compare("2.01", "2.01")); EXPECT_EQ( -1, AlnumCmp::Compare("2.1", "2.15")); EXPECT_EQ( -1, AlnumCmp::Compare("2a1", "2a5")); EXPECT_EQ( 1, AlnumCmp::Compare("a21", "2a5")); // ascii value comparision EXPECT_EQ( -1, AlnumCmp::Compare("a21", "A25", false)); } TEST(RteUtilsTest, AlnumCmp_String) { EXPECT_EQ( -1, AlnumCmp::Compare(string(""), string("2.1"))); EXPECT_EQ( 1, AlnumCmp::Compare(string("10.1"), string(""))); EXPECT_EQ( 0, AlnumCmp::Compare(string(""), string(""))); EXPECT_EQ( 1, AlnumCmp::Compare(string("10.1"), string("2.1"))); EXPECT_EQ( 0, AlnumCmp::Compare(string("2.01"), string("2.1"))); // 01 is considered as 1 EXPECT_EQ( 0, AlnumCmp::Compare(string("2.01"), string("2.01"))); EXPECT_EQ( -1, AlnumCmp::Compare(string("2.1"), string("2.15"))); EXPECT_EQ( -1, AlnumCmp::Compare(string("2a1"), string("2a5"))); EXPECT_EQ( 1, AlnumCmp::Compare(string("a21"), string("2a5"))); // ascii value comparision EXPECT_EQ( -1, AlnumCmp::Compare(string("a21"), string("A25"), false)); } TEST(RteUtilsTest, AlnumLenCmp) { EXPECT_EQ( -1, AlnumCmp::CompareLen(string(""), string("2.1"))); EXPECT_EQ( 1, AlnumCmp::CompareLen(string("10.1"), string(""))); EXPECT_EQ( 0, AlnumCmp::CompareLen(string(""), string(""))); EXPECT_EQ( 1, AlnumCmp::CompareLen(string("10.1"), string("2.1"))); EXPECT_EQ( 1, AlnumCmp::CompareLen(string("2.01"), string("2.1"))); EXPECT_EQ( 0, AlnumCmp::CompareLen(string("2.01"), string("2.01"))); EXPECT_EQ( -1, AlnumCmp::CompareLen(string("2.1"), string("2.15"))); EXPECT_EQ( -1, AlnumCmp::CompareLen(string("2a1"), string("2a5"))); EXPECT_EQ( 1, AlnumCmp::CompareLen(string("a21"), string("2a5"))); EXPECT_EQ( -1, AlnumCmp::CompareLen(string("a21"), string("A25"), false)); } TEST(RteUtilsTest, VendorCompare) { CheckVendorMatch({ "ARM", "ARM CMSIS" }, false); CheckVendorMatch({ "ARM", "arm" }, false); CheckVendorMatch({ "ONSemiconductor", "onsemi" }, true); CheckVendorMatch({ "Cypress", "Cypress:114", "Cypress:100" }, true); CheckVendorMatch({ "Atmel", "Atmel:3", "Microchip", "Microchip:3"}, true); CheckVendorMatch({ "Milandr", "Milandr:99", "milandr", "milandr:99"}, true); CheckVendorMatch({ "ABOV", "ABOV:126", "ABOV Semiconductor", "ABOV Semiconductor:126" }, true); CheckVendorMatch({ "Realtek", "Realtek:124", "Realtek Semiconductor", "Realtek Semiconductor:124"}, true); CheckVendorMatch({ "Texas Instruments", "Texas Instruments:16", "TI", "TI:16"}, true); CheckVendorMatch({ "Spansion", "Spansion:19", "Cypress", "Cypress:19", "Fujitsu", "Fujitsu:19", "Fujitsu Semiconductor", "Fujitsu Semiconductor:19", "Fujitsu Semiconductors", "Fujitsu Semiconductors:19" }, true); CheckVendorMatch({ "NXP", "NXP:11", "Freescale","Freescale:11", "Freescale Semiconductor", "Freescale Semiconductor:11", "Freescale Semiconductors", "Freescale Semiconductors:11", "NXP (founded by Philips)", "NXP (founded by Philips):11", "nxp:78" }, true); CheckVendorMatch({ "Silicon Labs", "Silicon Labs:21", "Energy Micro", "Energy Micro:21", "Silicon Laboratories, Inc.", "Silicon Laboratories, Inc.:21", "Test:97" }, true); CheckVendorMatch({ "MyVendor", "MyVendor", "MyVendor:9999" }, true); CheckVendorMatch({ "MyVendor", "ThatVendor"}, false); CheckVendorMatch({ "MyVendor:9999", "ThatVendor:9998" }, false); CheckVendorMatch({ "MyVendor:9999", "MyVendor:9998" }, true); CheckVendorMatch({ "MyVendor:9999", "ThatVendor:9999" }, true); } TEST(RteUtilsTest, GetFullVendorString) { EXPECT_EQ("unknown", DeviceVendor::GetFullVendorString("unknown")); EXPECT_EQ("unknown:0000", DeviceVendor::GetFullVendorString("unknown:0000")); EXPECT_EQ("NXP:11", DeviceVendor::GetFullVendorString("NXP:11")); EXPECT_EQ("NXP:11", DeviceVendor::GetFullVendorString("NXP")); EXPECT_EQ("NXP:11", DeviceVendor::GetFullVendorString("anything:11")); EXPECT_EQ("NXP:11", DeviceVendor::GetFullVendorString("Freescale:78")); EXPECT_EQ("NXP:11", DeviceVendor::GetFullVendorString("Freescale")); EXPECT_EQ("NXP:11", DeviceVendor::GetFullVendorString(":78")); EXPECT_EQ("Cypress:19", DeviceVendor::GetFullVendorString("Fujitsu::114")); EXPECT_EQ("Cypress:19", DeviceVendor::GetFullVendorString("Spansion::100")); EXPECT_EQ("Silicon Labs:21", DeviceVendor::GetFullVendorString("EnergyMicro::97")); } TEST(RteUtilsTest, VendorFromPackageId) { string packageId, vendor; packageId = "Vendor.Name.version"; vendor = RteUtils::VendorFromPackageId(packageId); EXPECT_EQ(vendor, "Vendor"); packageId = "VendorNameversion"; vendor = RteUtils::VendorFromPackageId(packageId); EXPECT_EQ(false, (0 == vendor.compare("vendor")) ? true : false); } TEST(RteUtilsTest, NameFromPackageId) { string packageId, name; packageId = "Vendor.Name.Version"; name = RteUtils::NameFromPackageId(packageId); EXPECT_EQ(name, "Name"); packageId = "VendorNameversion"; name = RteUtils::NameFromPackageId(packageId); EXPECT_EQ(false, (0 == name.compare("Name")) ? true : false); } TEST(RteUtilsTest, RemoveVectorDuplicates) { vector<int> testInput = { 1,2,3,2,4,5,3,6 }; vector<int> expected = { 1,2,3,4,5,6 }; RteUtils::RemoveVectorDuplicates<int>(testInput); EXPECT_EQ(testInput, expected); testInput = { 1,1,3,3,1,2,2 }; expected = { 1,3,2 }; RteUtils::RemoveVectorDuplicates<int>(testInput); EXPECT_EQ(testInput, expected); testInput = { 1,1,1,1,1,1,1,1,1 }; expected = { 1 }; RteUtils::RemoveVectorDuplicates<int>(testInput); EXPECT_EQ(testInput, expected); testInput = { }; expected = { }; RteUtils::RemoveVectorDuplicates<int>(testInput); EXPECT_EQ(testInput, expected); }
43.159091
122
0.666316
[ "vector" ]
c4a6d0351160d32e455ecdec56bb5cd1d7a16127
1,448
cpp
C++
src/FE/Parser/Enum.cpp
Oj18/Ethereal
16a0a167693c27615e5c63044f1c38b5c8d863b2
[ "BSD-3-Clause" ]
null
null
null
src/FE/Parser/Enum.cpp
Oj18/Ethereal
16a0a167693c27615e5c63044f1c38b5c8d863b2
[ "BSD-3-Clause" ]
null
null
null
src/FE/Parser/Enum.cpp
Oj18/Ethereal
16a0a167693c27615e5c63044f1c38b5c8d863b2
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2019, Electrux All rights reserved. Using the BSD 3-Clause license for the project, main LICENSE file resides in project's root directory. Please read that file and understand the license terms before using or altering the project. */ #include "Internal.hpp" #include "../Ethereal.hpp" stmt_enum_t * parse_enum( const src_t & src, parse_helper_t * ph ) { int tok_ctr = ph->tok_ctr(); bool is_mask = false; if( ph->peak()->type == TOK_ENUM_MASK ) is_mask = true; const tok_t * name = nullptr; NEXT_VALID( TOK_IDEN ); name = ph->peak(); std::vector< tok_t * > vals; NEXT_VALID( TOK_LBRACE ); NEXT_VALID( TOK_IDEN ); val_begin: vals.push_back( ph->peak() ); if( ph->peak( 1 )->type == TOK_COMMA ) { ph->next(); if( ph->peak( 1 )->type == TOK_IDEN ) { ph->next(); goto val_begin; } } NEXT_VALID( TOK_RBRACE ); // now at RBRACE return new stmt_enum_t( name, vals, is_mask, tok_ctr ); } bool stmt_enum_t::bytecode( src_t & src ) const { for( auto v = m_vals.rbegin(); v != m_vals.rend(); ++v ) { src.bcode.push_back( { m_tok_ctr, ( * v )->line, ( * v )->col, IC_PUSH, { OP_CONST, ( * v )->data } } ); } src.bcode.push_back( { m_tok_ctr, m_name->line, m_name->col, IC_PUSH, { OP_CONST, m_name->data } } ); src.bcode.push_back( { m_tok_ctr, m_name->line, m_name->col, m_is_mask ? IC_BUILD_ENUM_MASK : IC_BUILD_ENUM, { OP_INT, std::to_string( m_vals.size() ) } } ); return true; }
26.814815
109
0.653315
[ "vector" ]
c4ab295343ca02ed06fcb5658dc60c41cdfae2d5
3,280
cpp
C++
groups/btl/btlmt/btlmt_listenoptions.cpp
apaprocki/bde
ba252cb776f92fae082d5d422aa2852a9be46849
[ "Apache-2.0" ]
1
2021-04-28T13:51:30.000Z
2021-04-28T13:51:30.000Z
groups/btl/btlmt/btlmt_listenoptions.cpp
apaprocki/bde
ba252cb776f92fae082d5d422aa2852a9be46849
[ "Apache-2.0" ]
null
null
null
groups/btl/btlmt/btlmt_listenoptions.cpp
apaprocki/bde
ba252cb776f92fae082d5d422aa2852a9be46849
[ "Apache-2.0" ]
1
2019-06-26T13:28:48.000Z
2019-06-26T13:28:48.000Z
// btlmt_listenoptions.cpp -*-C++-*- #include <btlmt_listenoptions.h> #include <bsls_ident.h> BSLS_IDENT_RCSID(btlmt_listenoptions_cpp,"$Id$ $CSID$") #include <bslim_printer.h> #include <bsl_ios.h> #include <bsl_ostream.h> namespace BloombergLP { namespace btlmt { // ------------------- // class ListenOptions // ------------------- // CREATORS ListenOptions::ListenOptions() : d_serverAddress() , d_backlog(1) , d_timeout() , d_enableRead(true) , d_allowHalfOpenConnections(false) , d_socketOptions() { } // MANIPULATORS ListenOptions& ListenOptions::operator=(const ListenOptions& rhs) { d_serverAddress = rhs.d_serverAddress; d_backlog = rhs.d_backlog; d_timeout = rhs.d_timeout; d_enableRead = rhs.d_enableRead; d_allowHalfOpenConnections = rhs.d_allowHalfOpenConnections; d_socketOptions = rhs.d_socketOptions; return *this; } void ListenOptions::reset() { d_serverAddress = btlso::IPv4Address(); d_backlog = 1; d_timeout.reset(); d_enableRead = true; d_allowHalfOpenConnections = false; d_socketOptions.reset(); } // ACCESSORS bsl::ostream& ListenOptions::print(bsl::ostream& stream, int level, int spacesPerLevel) const { bslim::Printer printer(&stream, level, spacesPerLevel); printer.start(); printer.printAttribute("serverAddress", d_serverAddress); printer.printAttribute("backlog", d_backlog); printer.printAttribute("timeout", d_timeout); printer.printAttribute("enableRead", d_enableRead); printer.printAttribute("allowHalfOpenConnections", d_allowHalfOpenConnections); printer.printAttribute("socketOptions", d_socketOptions); printer.end(); return stream; } bsl::ostream& operator<<(bsl::ostream& stream, const btlmt::ListenOptions& object) { bslim::Printer printer(&stream, 0, -1); printer.start(); printer.printValue(object.serverAddress()); printer.printValue(object.backlog()); printer.printValue(object.timeout()); printer.printValue(object.enableRead()); printer.printValue(object.allowHalfOpenConnections()); printer.printValue(object.socketOptions()); printer.end(); return stream; } } // close package namespace } // close enterprise namespace // ---------------------------------------------------------------------------- // Copyright 2016 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 ----------------------------------
30.37037
79
0.623476
[ "object" ]
c4b145b78b8d0e30ca50e6c5e5573d69d2cf5565
1,393
cpp
C++
src/sql_parser/create_statement.cpp
abhijat/matchboxdb
77c055690054deb96dffc29499ad99928370ae99
[ "BSD-2-Clause" ]
9
2021-11-09T13:55:41.000Z
2022-03-04T05:22:15.000Z
src/sql_parser/create_statement.cpp
abhijat/matchboxdb
77c055690054deb96dffc29499ad99928370ae99
[ "BSD-2-Clause" ]
null
null
null
src/sql_parser/create_statement.cpp
abhijat/matchboxdb
77c055690054deb96dffc29499ad99928370ae99
[ "BSD-2-Clause" ]
null
null
null
#include "create_statement.h" #include "field_definition.h" #include "statement_visitor.h" #include <utility> ast::CreateStatement::CreateStatement( ast::Table table_name, std::vector<ast::FieldDefinition> field_definitions ) : _table(std::move(table_name)), _field_definitions(std::move(field_definitions)) {} const ast::Table &ast::CreateStatement::table_name() const { return _table; } const std::vector<ast::FieldDefinition> &ast::CreateStatement::field_definitions() const { return _field_definitions; } void ast::CreateStatement::repr(std::ostream &os) const { os << "CREATE TABLE "; _table.repr(os); os << "( "; for (const auto &fd: _field_definitions) { fd.repr(os); os << " "; } os << ")"; } metadata::Metadata ast::CreateStatement::metadata() const { std::vector<std::string> names(_field_definitions.size()); std::vector<metadata::Kind> kinds(_field_definitions.size()); std::transform(_field_definitions.cbegin(), _field_definitions.cend(), names.begin(), [](const auto &fd) { return fd.field_name(); }); std::transform(_field_definitions.cbegin(), _field_definitions.cend(), kinds.begin(), [](const auto &fd) { return fd.field_kind(); }); return {names, kinds}; } void ast::CreateStatement::accept(ast::StatementVisitor &visitor) const { visitor.visit(*this); }
27.86
110
0.674803
[ "vector", "transform" ]
c4b535eb66e3361658560039bccfb1adb1e7768a
9,529
cpp
C++
mc_rtc_rviz_panel/src/SchemaWidget.cpp
anastasiabolotnikova/mc_rtc_ros
86c82c9e1e0b29ba9614106438436cd6c7f8f612
[ "BSD-2-Clause" ]
null
null
null
mc_rtc_rviz_panel/src/SchemaWidget.cpp
anastasiabolotnikova/mc_rtc_ros
86c82c9e1e0b29ba9614106438436cd6c7f8f612
[ "BSD-2-Clause" ]
null
null
null
mc_rtc_rviz_panel/src/SchemaWidget.cpp
anastasiabolotnikova/mc_rtc_ros
86c82c9e1e0b29ba9614106438436cd6c7f8f612
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright 2016-2019 CNRS-UM LIRMM, CNRS-AIST JRL */ #include "SchemaWidget.h" #include "FormElement.h" #include "FormWidget.h" #include <mc_rtc/logging.h> #include <boost/filesystem.hpp> namespace bfs = boost::filesystem; namespace mc_rtc_rviz { namespace { struct Schema; using SchemaStore = std::map<std::string, Schema>; using Form = std::vector<FormElement *>; using FormMaker = std::function<Form(QWidget *, const mc_rtc::Configuration &)>; struct Schema { Schema() = default; Schema(const std::string & file); const std::string & title() const { return title_; } bool is_object() const { return is_object_; } FormMaker create_form = [](QWidget *, const mc_rtc::Configuration &) -> Form { return {}; }; private: std::string title_; bool is_object_ = false; }; static SchemaStore store = {}; static const std::string schema_dir = std::string(MC_RTC_DOCDIR) + "/json/schemas/"; Schema::Schema(const std::string & file) { mc_rtc::Configuration s{file}; title_ = s("title", "No title property in " + file); auto required = s("required", std::vector<std::string>{}); auto is_required = [&required](const std::string & label) { return std::find(required.begin(), required.end(), label) != required.end(); }; /** Handle enum entries */ auto handle_enum = [this](const std::string & k, bool required, const std::vector<std::string> & values) { auto cf = create_form; create_form = [cf, k, required, values](QWidget * parent, const mc_rtc::Configuration & data) { auto v = cf(parent, data); v.emplace_back(new form::ComboInput(parent, k, required, values, false)); if(values.size() == 1 && required) { v.back()->hidden(true); } return v; }; }; /** Handle: boolean/integer/number/string */ auto handle_type = [this, &file](const std::string & k, bool required, const std::string & type) { auto cf = create_form; if(type == "boolean") { create_form = [cf, k, required](QWidget * parent, const mc_rtc::Configuration & data) { auto v = cf(parent, data); v.emplace_back(new form::Checkbox(parent, k, required, true)); return v; }; } else if(type == "integer") { if(k == "robotIndex") { create_form = [cf, required](QWidget * parent, const mc_rtc::Configuration & data) { auto v = cf(parent, data); v.emplace_back(new form::DataComboInput(parent, "robot", required, data, {"robots"}, true, "robotIndex")); return v; }; return; } create_form = [cf, k, required](QWidget * parent, const mc_rtc::Configuration & data) { auto v = cf(parent, data); v.emplace_back(new form::IntegerInput(parent, k, required, 0)); return v; }; } else if(type == "number") { create_form = [cf, k, required](QWidget * parent, const mc_rtc::Configuration & data) { auto v = cf(parent, data); v.emplace_back(new form::NumberInput(parent, k, required, 0)); return v; }; } else { if(type != "string") { LOG_WARNING("Property " << k << " in " << file << " has unknown or missing type (value: " << type << "), treating as string") } if(k == "body") { create_form = [cf, k, required](QWidget * parent, const mc_rtc::Configuration & data) { auto v = cf(parent, data); v.emplace_back(new form::DataComboInput(parent, "body", required, data, {"bodies", "$robot"}, false)); return v; }; } else if(k == "surface") { create_form = [cf, k, required](QWidget * parent, const mc_rtc::Configuration & data) { auto v = cf(parent, data); v.emplace_back(new form::DataComboInput(parent, "surface", required, data, {"surfaces", "$robot"}, false)); return v; }; } else { create_form = [cf, k, required](QWidget * parent, const mc_rtc::Configuration & data) { auto v = cf(parent, data); v.emplace_back(new form::StringInput(parent, k, required, "")); return v; }; } } }; /** Handle an array */ auto handle_array = [this, &file](const std::string & k, bool required, const std::string & type, size_t min, size_t max) { auto cf = create_form; if(type == "integer") { create_form = [cf, k, required, min, max](QWidget * parent, const mc_rtc::Configuration & data) { auto v = cf(parent, data); v.emplace_back(new form::IntegerArrayInput(parent, k, required, min == max, min, max)); return v; }; } else if(type == "number") { create_form = [cf, k, required, min, max](QWidget * parent, const mc_rtc::Configuration & data) { auto v = cf(parent, data); v.emplace_back(new form::NumberArrayInput(parent, k, required, min == max, min, max)); return v; }; } else if(type == "array") { LOG_WARNING("Property " << k << " in " << file << " is an array of array, will not display for now") } else { if(type != "string") { LOG_WARNING("Property " << k << " in " << file << " has unknonw or missing array items' type (value: " << type << "), treating as string") } create_form = [cf, k, required, min, max](QWidget * parent, const mc_rtc::Configuration & data) { auto v = cf(parent, data); v.emplace_back(new form::StringArrayInput(parent, k, required, min == max, min, max)); return v; }; } }; std::string type = s("type"); if(type == "array") { handle_array(title_, false, s("items", mc_rtc::Configuration{})("type", std::string{""}), s("minItems", 0), s("maxItems", 256)); return; } if(type != "object") { LOG_ERROR(title_ << " from " << file << " has unexpected type: " << type) return; } is_object_ = true; auto properties = s("properties", mc_rtc::Configuration{}); for(const auto & k : properties.keys()) { auto prop = properties(k); if(prop.has("enum")) { handle_enum(k, is_required(k), prop("enum")); } else if(prop.has("type")) { std::string type = prop("type"); if(type == "array") { handle_array(k, is_required(k), prop("items", mc_rtc::Configuration{})("type", std::string{""}), prop("minItems", 0), prop("maxItems", 256)); } else { handle_type(k, is_required(k), type); } } else if(prop.has("$ref")) { std::string ref = prop("$ref"); ref = ref.substr(3); // remove leading /.. bfs::path ref_schema{file}; ref_schema = bfs::canonical(ref_schema.parent_path() / ref); if(!store.count(ref_schema.string())) { store[ref_schema.string()] = Schema{ref_schema.string()}; } auto cf = create_form; bool required = is_required(k); std::string ref_schema_str = ref_schema.string(); create_form = [cf, k, required, ref_schema_str](QWidget * parent, const mc_rtc::Configuration & data) { auto v = cf(parent, data); const auto & schema = store.at(ref_schema_str); if(schema.is_object()) { v.emplace_back(new form::Form(parent, k, required, store.at(ref_schema_str).create_form(parent, data))); } else { auto el = schema.create_form(parent, data).at(0); el->name(k); v.push_back(el); } return v; }; } else { LOG_ERROR("Cannot handle property " << k << " in " << file << ": " << prop.dump()) } } } } // namespace SchemaWidget::SchemaWidget(const ClientWidgetParam & params, const std::string & schema, const mc_rtc::Configuration & data) : ClientWidget(params) { bfs::path schema_path = schema_dir; schema_path /= schema; if(!bfs::exists(schema_path)) { LOG_ERROR("Schema path: " << schema_path.string() << " does not exist in this machine") return; } bfs::directory_iterator dit(schema_path), endit; std::vector<bfs::path> drange; std::copy(dit, endit, std::back_inserter(drange)); std::sort(std::begin(drange), std::end(drange)); auto layout = new QVBoxLayout(this); auto combo = new QComboBox(this); stack_ = new QStackedWidget(this); stack_->addWidget(new QWidget(this)); for(const auto & p : drange) { auto path = bfs::canonical(p); Schema s{path.string()}; store[path.string()] = s; auto form = new FormWidget(params); for(auto el : s.create_form(this, data)) { form->add_element(el); } form->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored); combo->addItem(s.title().c_str()); stack_->addWidget(form); } combo->setCurrentIndex(-1); stack_->setCurrentIndex(-1); connect(combo, SIGNAL(currentIndexChanged(int)), this, SLOT(currentIndexChanged(int))); layout->addWidget(combo); layout->addWidget(stack_); } void SchemaWidget::currentIndexChanged(int idx) { stack_->currentWidget()->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored); stack_->setCurrentIndex(idx + 1); stack_->currentWidget()->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); stack_->currentWidget()->adjustSize(); stack_->adjustSize(); } } // namespace mc_rtc_rviz
31.345395
118
0.583587
[ "object", "vector" ]
c4bb0d2ec43d1d073540d71890775fbe67ffd415
4,035
cpp
C++
wrappers/opencv/latency-tool/rs-latency-tool.cpp
seagull1993/librealsense
18cf36775c16efd1f727b656c7e88a928a53a427
[ "Apache-2.0" ]
7
2018-06-05T01:46:57.000Z
2020-02-28T10:30:04.000Z
wrappers/opencv/latency-tool/rs-latency-tool.cpp
seagull1993/librealsense
18cf36775c16efd1f727b656c7e88a928a53a427
[ "Apache-2.0" ]
6
2018-06-17T19:28:03.000Z
2021-09-09T14:29:25.000Z
wrappers/opencv/latency-tool/rs-latency-tool.cpp
seagull1993/librealsense
18cf36775c16efd1f727b656c7e88a928a53a427
[ "Apache-2.0" ]
4
2018-07-17T17:49:40.000Z
2019-09-01T00:21:12.000Z
// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2017 Intel Corporation. All Rights Reserved. #include "latency-detector.h" // This demo is presenting one way to estimate latency without access to special equipment // See ReadMe.md for more information int main(int argc, char * argv[]) try { using namespace cv; using namespace rs2; // Start RealSense camera // Uncomment the configuration you wish to test pipeline pipe; config cfg; //cfg.enable_stream(RS2_STREAM_COLOR, RS2_FORMAT_BGR8); //cfg.enable_stream(RS2_STREAM_COLOR, 640, 480, RS2_FORMAT_BGR8, 30); cfg.enable_stream(RS2_STREAM_COLOR, 1920, 1080, RS2_FORMAT_BGR8, 30); //cfg.enable_stream(RS2_STREAM_INFRARED, 640, 480, RS2_FORMAT_Y8); //cfg.enable_stream(RS2_STREAM_INFRARED, 1280, 720, RS2_FORMAT_Y8); pipe.start(cfg); // To test with a regular webcam, comment-out the previous block // And uncomment the following code: //context ctx; //auto dev = ctx.query_devices().front(); //auto sensor = dev.query_sensors().front(); //auto sps = sensor.get_stream_profiles(); //stream_profile selected; //for (auto& sp : sps) //{ // if (auto vid = sp.as<video_stream_profile>()) // { // if (vid.format() == RS2_FORMAT_BGR8 && // vid.width() == 640 && vid.height() == 480 && // vid.fps() == 30) // selected = vid; // } //} //sensor.open(selected); //syncer pipe; //sensor.start(pipe); const auto window_name = "Display Image"; namedWindow(window_name, CV_WINDOW_NORMAL); setWindowProperty(window_name, WND_PROP_FULLSCREEN, WINDOW_FULLSCREEN); const int display_w = 1280; const int digits = 16; const int circle_w = (display_w - 120) / (digits + 2); const int display_h = 720; bit_packer packer(digits); detector d(digits, display_w); while (cvGetWindowHandle(window_name)) { // Wait for frameset from the camera for (auto f : pipe.wait_for_frames()) { // Unfortunately depth frames do not register well using this method if (f.get_profile().stream_type() != RS2_STREAM_DEPTH) { d.submit_frame(f); break; } } // Commit to the next clock value before starting rendering the frame auto next_value = d.get_next_value(); // Start measuring rendering time for the next frame // We substract rendering time since during that time // the clock is already captured, but there is zero chance // for the clock to appear on screen (until done rendering) d.begin_render(); Mat display = Mat::zeros(display_h, display_w, CV_8UC1); // Copy preview image generated by the detector (to not waste time in the main thread) d.copy_preview_to(display); // Pack the next value into binary form packer.try_pack(next_value); // Render the clock encoded in circles for (int i = 0; i < digits + 2; i++) { const int rad = circle_w / 2 - 6; // Always render the corner two circles (as markers) if (i == 0 || i == digits + 1 || packer.get()[i - 1]) { circle(display, Point(50 + circle_w * i + rad, 70 + rad), rad, Scalar(255, 255, 255), -1, 8); } } // Display current frame. WaitKey is doing the actual rendering imshow(window_name, display); if (waitKey(1) >= 0) break; // Report rendering of current frame is done d.end_render(); } return EXIT_SUCCESS; } catch (const rs2::error & e) { std::cerr << "RealSense error calling " << e.get_failed_function() << "(" << e.get_failed_args() << "):\n " << e.what() << std::endl; return EXIT_FAILURE; } catch (const std::exception& e) { std::cerr << e.what() << std::endl; return EXIT_FAILURE; }
32.804878
140
0.6057
[ "render" ]
c4cb963838c1727327120f6c1ca70909b37de9e6
1,384
cpp
C++
Biconex/main.cpp
rusucosmin/Cplusplus
0e95cd01d20b22404aa4166c71d5a9e834a5a21b
[ "MIT" ]
11
2015-08-29T13:41:22.000Z
2020-01-08T20:34:06.000Z
Biconex/main.cpp
rusucosmin/Cplusplus
0e95cd01d20b22404aa4166c71d5a9e834a5a21b
[ "MIT" ]
null
null
null
Biconex/main.cpp
rusucosmin/Cplusplus
0e95cd01d20b22404aa4166c71d5a9e834a5a21b
[ "MIT" ]
5
2016-01-20T18:17:01.000Z
2019-10-30T11:57:15.000Z
#include <fstream> #include <vector> #include <stack> #include <set> using namespace std; ifstream fin("biconex.in"); ofstream fout("biconex.out"); const int maxn = 100005; int n, m, dflevel[maxn], lowlink[maxn]; vector <int> g[maxn]; set <set<int> > bcc; stack <pair<int, int> > st; inline void extractbcc(int x, int y) { int tx, ty; set<int> s; do { tx = st.top().first; ty = st.top().second; st.pop(); s.insert(tx); s.insert(ty); } while(x != tx || y != ty); bcc.insert(s); } inline void dfs(int node, int father) { dflevel[node] = lowlink[node] = dflevel[father] + 1; for(auto it : g[node]) { if(it == father) continue; if(!dflevel[it]) { st.push(make_pair(node, it)); dfs(it, node); lowlink[node] = min(lowlink[node], lowlink[it]); if(lowlink[it] >= dflevel[node]) extractbcc(node, it); } else lowlink[node] = min(lowlink[node], dflevel[it]); } } int main() { fin >> n >> m; for(int i = 1 ; i <= m ; ++ i) { int x, y; fin >> x >> y; g[x].push_back(y); g[y].push_back(x); } dfs(1, 0); fout << bcc.size() << '\n'; for(auto comp : bcc) { for(auto it : comp) fout << it << ' '; fout << '\n'; } }
21.625
60
0.483382
[ "vector" ]
c4cc81bb688be7ea3dccffbec976e4f04308d823
811
cpp
C++
MemcpyBenchmarks/main.cpp
pauldoo/scratch
1c8703d8b8e5cc5a026bfd5f0b036b9632faf161
[ "0BSD" ]
null
null
null
MemcpyBenchmarks/main.cpp
pauldoo/scratch
1c8703d8b8e5cc5a026bfd5f0b036b9632faf161
[ "0BSD" ]
4
2021-08-31T22:03:39.000Z
2022-02-19T07:12:05.000Z
MemcpyBenchmarks/main.cpp
pauldoo/scratch
1c8703d8b8e5cc5a026bfd5f0b036b9632faf161
[ "0BSD" ]
1
2022-02-23T13:46:49.000Z
2022-02-23T13:46:49.000Z
#include <cstdlib> #include <ctime> #include <iostream> #include <vector> int main(void) { const int bufferSizeInMegabytes = 50; const int repeats = 200; const std::vector<char> source(bufferSizeInMegabytes * 1024 * 1024); std::vector<char> destination(bufferSizeInMegabytes * 1024 * 1024); const clock_t startTime = clock(); for (int i = 0; i < repeats; i++) { memcpy(&(destination.at(0)), &(source.at(0)), source.size()); } const clock_t endTime = clock(); const double timeInSeconds = (endTime - startTime) / static_cast<double>(CLOCKS_PER_SEC); const double gigabytesCopied = (bufferSizeInMegabytes * repeats) / 1024.0; std::cout << gigabytesCopied << " GiB copied in " << timeInSeconds << " s, " << (gigabytesCopied / timeInSeconds) << " GiB/s\n"; return 0; }
30.037037
130
0.669544
[ "vector" ]
c4da80e327d366b0606ffc5d208cfdb49f770dd2
2,066
cpp
C++
CoverTree/src/driver_main.cpp
alexandersvozil/DynamicKCenterClustering
6c30815558965a49689cdfbde4b603cd2b6841a6
[ "MIT" ]
1
2021-03-10T18:12:20.000Z
2021-03-10T18:12:20.000Z
CoverTree/src/driver_main.cpp
alexandersvozil/DynamicKCenterClustering
6c30815558965a49689cdfbde4b603cd2b6841a6
[ "MIT" ]
null
null
null
CoverTree/src/driver_main.cpp
alexandersvozil/DynamicKCenterClustering
6c30815558965a49689cdfbde4b603cd2b6841a6
[ "MIT" ]
null
null
null
#include <chrono> #include <iostream> #include <exception> #include <ratio> #include <random> #include <unordered_set> #include <limits> #include <future> #include <thread> #include <string> #include "math.h" #include "cover_tree.h" #include "updates.h" #include "algorithm.h" #include "data_utils.h" int main(int argc, char** argv){ if(argc < 4){ throw std::runtime_error("Usage: /kcenter <path_to_points> <path_to_updates> k epsilon nr_of_points"); } std::string instance_path {argv[1]}; std::string updates_path {argv[2]}; uint k = stoui(argv[3]); coordType eps = std::stod(argv[4]); int nr_of_points {std::numeric_limits<int>::max()}; if(argc >= 5){ nr_of_points = std::stoi(argv[5]); } assert(nr_of_points >= k); std::vector<pointType> points = read_points(instance_path, nr_of_points); std::vector<Update> updates = parse_updates(updates_path,points); std::chrono::steady_clock::time_point ts = std::chrono::steady_clock::now(); Tree_Algorithm alg(points,updates,k ,eps); alg.run(); std::chrono::steady_clock::time_point te = std::chrono::steady_clock::now(); std::chrono::duration<coordType, std::milli> duration = te - ts; std::cout << duration.count() << "ms" << std::endl; } //DEBUGGING A SOLUTION (this checks if the pairwise distance between points is at least the //covdist of the least level //std::cout << "debugging solution for " << base << " and exp " << exp << std::endl; //for(size_t i = 0; i<solution.size(); i++){ // for(size_t j = 0; j<solution.size(); j++){ // if(j==i) continue; // if(solution[i]->dist(solution[j]) <= covdist(lastlevel)){ // std::cout << solution[i]->ID << " " << solution[j]->ID << " sepdist: " << covdist(lastlevel) << " dist: " << solution[i]->dist(solution[j]) << " lastlevel: " << lastlevel << " level i: " << solution[i]->level << " level j: " << solution[j]->level << std::endl; // } // //assert(solution[i]->dist(solution[j]) > covdist(lastlevel)); // } //} //for(uint id: check){ // std::cout << id << std::endl; //} //std::cout << "debugging done" << std::endl;
28.694444
266
0.650048
[ "vector" ]
c4e8271c43fb8c779b1d54ccdd15b9ce075396a0
4,672
cpp
C++
src/test/benchmark/hyproBenchmark/box/affineTransformation.cpp
hypro/hypro
52ae4ffe0a8427977fce8d7979fffb82a1bc28f6
[ "MIT" ]
22
2016-10-05T12:19:01.000Z
2022-01-23T09:14:41.000Z
src/test/benchmark/hyproBenchmark/box/affineTransformation.cpp
hypro/hypro
52ae4ffe0a8427977fce8d7979fffb82a1bc28f6
[ "MIT" ]
23
2017-05-08T15:02:39.000Z
2021-11-03T16:43:39.000Z
src/test/benchmark/hyproBenchmark/box/affineTransformation.cpp
hypro/hypro
52ae4ffe0a8427977fce8d7979fffb82a1bc28f6
[ "MIT" ]
12
2017-06-07T23:51:09.000Z
2022-01-04T13:06:21.000Z
#include "benchmarkBox.h" namespace benchmark { namespace box { Results<std::size_t> affineTransformation(const Settings& settings) { Results<std::size_t> ress; hypro::Box<::benchmark::Number> box; // benchmark against PPL #ifdef HYPRO_USE_PPL using pplItv = Parma_Polyhedra_Library::Interval<double,Parma_Polyhedra_Library::Interval_Info_Null<benchmark::box::Double_Interval_Policy>>; using pplbox = Parma_Polyhedra_Library::Box<pplItv>; #endif box.insert(carl::Interval<::benchmark::Number>(-1,1)); // initialize random number generator std::mt19937 generator; std::uniform_int_distribution<int> dist = std::uniform_int_distribution<int>(0,10); bool timeout = false; bool timeoutNaive = false; bool timeoutPpl = false; // iterate over dimensions for(std::size_t d = 1; d < settings.maxDimension; ++d) { // create instances std::vector<hypro::matrix_t<::benchmark::Number>> matrices; std::vector<hypro::vector_t<::benchmark::Number>> vectors; if(!timeout) { Timer creationTimer; for(std::size_t i = 0; i < settings.iterations; ++i) { hypro::matrix_t<::benchmark::Number> matrix = hypro::matrix_t<::benchmark::Number>(d,d); hypro::vector_t<::benchmark::Number> vector = hypro::vector_t<::benchmark::Number>(d); for(std::size_t row = 0; row < d; ++row) { for(std::size_t col = 0; col < d; ++col) { matrix(row,col) = dist(generator); } vector(row) = dist(generator); } matrices.emplace_back(std::move(matrix)); vectors.emplace_back(std::move(vector)); } auto creationTime = creationTimer.elapsed(); //std::cout << "Dimension " << d << ": Creation took " << creationTime.count() << " sec." << std::endl; ress.mCreationTime += creationTime; // run instances Timer runTimerHyPro; for(std::size_t i = 0; i < settings.iterations; ++i) { box.affineTransformation(matrices[i], vectors[i]); } auto runningTime = runTimerHyPro.elapsed(); ress.emplace_back({"affineTransformation",runningTime/settings.iterations,static_cast<int>(d)}); std::cout << "Dimension " << d << ": Running took " << runningTime.count() << " sec." << std::endl; if(runningTime.count() > settings.timeoutSec) { timeout = true; } ress.mRunningTime += runningTime; } if(!timeoutNaive) { Timer runTimerHyProNaive; for(std::size_t i = 0; i < settings.iterations; ++i) { std::vector<hypro::Point<::benchmark::Number>> vertices = box.vertices(); hypro::Point<::benchmark::Number> manualMin = hypro::Point<::benchmark::Number>(matrices[i]*(vertices.begin()->rawCoordinates())); hypro::Point<::benchmark::Number> manualMax = hypro::Point<::benchmark::Number>(matrices[i]*(vertices.begin()->rawCoordinates())); for(const auto& v : vertices) { hypro::Point<::benchmark::Number> t = hypro::Point<::benchmark::Number>(matrices[i]*v.rawCoordinates()); for(std::size_t d = 0; d < box.dimension(); ++d) { if(manualMin.at(d) > t.at(d)) { manualMin[d] = t[d]; } if(manualMax.at(d) < t.at(d)) { manualMax[d] = t[d]; } } } manualMin += vectors[i]; manualMax += vectors[i]; } auto runningTimeNaive = runTimerHyProNaive.elapsed(); ress.emplace_back({"affineTransformationNaive",runningTimeNaive/settings.iterations,static_cast<int>(d)}); std::cout << "Dimension " << d << ": Running took " << runningTimeNaive.count() << " sec." << std::endl; if(runningTimeNaive.count() > settings.timeoutSec) { timeoutNaive = true; } } // prepare next run box.insert(carl::Interval<::benchmark::Number>(-1,1)); } return ress; } } // box } // benchmark
47.191919
150
0.514555
[ "vector" ]
c4ecd76584b8e7a7b17f7dc4b4201054ba5fb1ad
15,307
cpp
C++
Tools/FontWithFeatures/FontWithFeatures/main.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
6
2021-07-05T16:09:39.000Z
2022-03-06T22:44:42.000Z
Tools/FontWithFeatures/FontWithFeatures/main.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
7
2022-03-15T13:25:39.000Z
2022-03-15T13:25:44.000Z
Tools/FontWithFeatures/FontWithFeatures/main.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (C) 2015 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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 "FontCreator.h" #include <CoreFoundation/CoreFoundation.h> #include <CoreGraphics/CoreGraphics.h> #include <CoreServices/CoreServices.h> #include <CoreText/CoreText.h> #include <ImageIO/ImageIO.h> #include <fstream> static CTFontDescriptorRef constructFontWithTrueTypeFeature(CTFontDescriptorRef fontDescriptor, int type, int selector) { CFNumberRef typeValue = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &type); CFNumberRef selectorValue = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &selector); CFTypeRef featureDictionaryKeys[] = { kCTFontFeatureTypeIdentifierKey, kCTFontFeatureSelectorIdentifierKey }; CFTypeRef featureDictionaryValues[] = { typeValue, selectorValue }; CFDictionaryRef featureDictionary = CFDictionaryCreate(kCFAllocatorDefault, featureDictionaryKeys, featureDictionaryValues, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFRelease(typeValue); CFRelease(selectorValue); CFTypeRef featureSettingsValues[] = { featureDictionary }; CFArrayRef fontFeatureSettings = CFArrayCreate(kCFAllocatorDefault, featureSettingsValues, 1, &kCFTypeArrayCallBacks); CFRelease(featureDictionary); CFTypeRef fontDescriptorKeys[] = { kCTFontFeatureSettingsAttribute }; CFTypeRef fontDescriptorValues[] = { fontFeatureSettings }; CFDictionaryRef fontDescriptorAttributes = CFDictionaryCreate(kCFAllocatorDefault, fontDescriptorKeys, fontDescriptorValues, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFRelease(fontFeatureSettings); CTFontDescriptorRef modifiedFontDescriptor = CTFontDescriptorCreateCopyWithAttributes(fontDescriptor, fontDescriptorAttributes); CFRelease(fontDescriptorAttributes); return modifiedFontDescriptor; } static CTFontDescriptorRef constructFontWithOpenTypeFeature(CTFontDescriptorRef fontDescriptor, CFStringRef feature, int value) { CFNumberRef featureValue = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &value); CFTypeRef featureDictionaryKeys[] = { kCTFontOpenTypeFeatureTag, kCTFontOpenTypeFeatureValue }; CFTypeRef featureDictionaryValues[] = { feature, featureValue }; CFDictionaryRef featureDictionary = CFDictionaryCreate(kCFAllocatorDefault, featureDictionaryKeys, featureDictionaryValues, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFRelease(featureValue); CFTypeRef featureSettingsValues[] = { featureDictionary }; CFArrayRef fontFeatureSettings = CFArrayCreate(kCFAllocatorDefault, featureSettingsValues, 1, &kCFTypeArrayCallBacks); CFRelease(featureDictionary); CFTypeRef fontDescriptorKeys[] = { kCTFontFeatureSettingsAttribute }; CFTypeRef fontDescriptorValues[] = { fontFeatureSettings }; CFDictionaryRef fontDescriptorAttributes = CFDictionaryCreate(kCFAllocatorDefault, fontDescriptorKeys, fontDescriptorValues, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFRelease(fontFeatureSettings); CTFontDescriptorRef modifiedFontDescriptor = CTFontDescriptorCreateCopyWithAttributes(fontDescriptor, fontDescriptorAttributes); CFRelease(fontDescriptorAttributes); return modifiedFontDescriptor; } static void drawText(CGContextRef context, CTFontDescriptorRef fontDescriptor, CFStringRef prefix, CGPoint location) { CGContextSetTextMatrix(context, CGAffineTransformScale(CGAffineTransformIdentity, 1, 1)); CGContextSetTextPosition(context, location.x, location.y); CGFloat fontSize = 25; CTFontRef font = CTFontCreateWithFontDescriptor(fontDescriptor, fontSize, nullptr); CFMutableStringRef string = CFStringCreateMutable(kCFAllocatorDefault, 0); CFStringAppend(string, prefix); CFStringAppend(string, CFSTR("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")); CGColorRef red = CGColorCreateGenericRGB(1, 0, 0, 1); CFTypeRef lineKeys[] = { kCTForegroundColorAttributeName }; CFTypeRef lineValues[] = { red }; CFDictionaryRef lineAttributes = CFDictionaryCreate(kCFAllocatorDefault, lineKeys, lineValues, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CGColorRelease(red); CFAttributedStringRef attributedString = CFAttributedStringCreate(kCFAllocatorDefault, string, lineAttributes); CFRelease(lineAttributes); CFMutableAttributedStringRef mutableAttributedString = CFAttributedStringCreateMutableCopy(kCFAllocatorDefault, 0, attributedString); CFRelease(attributedString); CTFontRef monospaceFont = CTFontCreateWithName(CFSTR("Courier"), fontSize, nullptr); CFAttributedStringSetAttribute(mutableAttributedString, CFRangeMake(0, CFStringGetLength(prefix)), kCTFontAttributeName, monospaceFont); CFRelease(monospaceFont); CFAttributedStringSetAttribute(mutableAttributedString, CFRangeMake(CFStringGetLength(prefix), CFStringGetLength(string) - CFStringGetLength(prefix)), kCTFontAttributeName, font); CFRelease(string); CFRelease(font); CTLineRef line = CTLineCreateWithAttributedString(mutableAttributedString); CFRelease(mutableAttributedString); CTLineDraw(line, context); CFRelease(line); } int main(int argc, const char * argv[]) { size_t width = 2500; size_t height = 2000; CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(nullptr, width, height, 8, width * 4, colorSpace, kCGImageAlphaNoneSkipLast); CGColorSpaceRelease(colorSpace); Type type = Type::TrueType; const std::vector<uint8_t> fontVector = generateFont(type); std::ofstream outputFile("/Volumes/Data/home/mmaxfield/src/WebKit/OpenSource/LayoutTests/css3/resources/FontWithFeatures.ttf", std::ios::out | std::ios::binary); for (uint8_t b : fontVector) outputFile << b; outputFile.close(); CFDataRef fontData = CFDataCreate(kCFAllocatorDefault, fontVector.data(), fontVector.size()); CTFontDescriptorRef fontDescriptor = CTFontManagerCreateFontDescriptorFromData(fontData); CFRelease(fontData); if (type == Type::OpenType) { CFTypeRef featureValuesOpenType[] = { CFSTR("liga"), CFSTR("clig"), CFSTR("dlig"), CFSTR("hlig"), CFSTR("calt"), CFSTR("subs"), CFSTR("sups"), CFSTR("smcp"), CFSTR("c2sc"), CFSTR("pcap"), CFSTR("c2pc"), CFSTR("unic"), CFSTR("titl"), CFSTR("onum"), CFSTR("pnum"), CFSTR("tnum"), CFSTR("frac"), CFSTR("afrc"), CFSTR("ordn"), CFSTR("zero"), CFSTR("hist"), CFSTR("jp78"), CFSTR("jp83"), CFSTR("jp90"), CFSTR("jp04"), CFSTR("smpl"), CFSTR("trad"), CFSTR("fwid"), CFSTR("pwid"), CFSTR("ruby") }; CFArrayRef features = CFArrayCreate(kCFAllocatorDefault, featureValuesOpenType, 30, &kCFTypeArrayCallBacks); for (CFIndex i = 0; i < CFArrayGetCount(features); ++i) { CFStringRef feature = static_cast<CFStringRef>(CFArrayGetValueAtIndex(features, i)); CTFontDescriptorRef modifiedFontDescriptor = constructFontWithOpenTypeFeature(fontDescriptor, feature, 1); CFMutableStringRef prefix = CFStringCreateMutable(kCFAllocatorDefault, 0); CFStringAppend(prefix, feature); CFStringAppend(prefix, CFSTR(" (on): ")); drawText(context, modifiedFontDescriptor, prefix, CGPointMake(25, 1950 - 50 * i)); CFRelease(prefix); CFRelease(modifiedFontDescriptor); modifiedFontDescriptor = constructFontWithOpenTypeFeature(fontDescriptor, feature, 0); prefix = CFStringCreateMutable(kCFAllocatorDefault, 0); CFStringAppend(prefix, feature); CFStringAppend(prefix, CFSTR(" (off): ")); drawText(context, modifiedFontDescriptor, prefix, CGPointMake(25, 1925 - 50 * i)); CFRelease(prefix); CFRelease(modifiedFontDescriptor); } CFRelease(features); } else { __block int i = 0; void (^handler)(uint16_t type, CFStringRef typeString, uint16_t selector, CFStringRef selectorString) = ^(uint16_t type, CFStringRef typeString, uint16_t selector, CFStringRef selectorString) { CTFontDescriptorRef modifiedFontDescriptor = constructFontWithTrueTypeFeature(fontDescriptor, type, selector); CFMutableStringRef prefix = CFStringCreateMutable(kCFAllocatorDefault, 0); CFStringAppend(prefix, typeString); CFStringAppend(prefix, CFSTR(": ")); CFStringAppend(prefix, selectorString); CFStringAppend(prefix, CFSTR(": ")); while (CFStringGetLength(prefix) < 65) CFStringAppend(prefix, CFSTR(" ")); drawText(context, modifiedFontDescriptor, prefix, CGPointMake(25, 1950 - 40 * i)); CFRelease(prefix); CFRelease(modifiedFontDescriptor); ++i; }; handler(kLigaturesType, CFSTR("kLigaturesType"), kCommonLigaturesOnSelector, CFSTR("kCommonLigaturesOnSelector")); handler(kLigaturesType, CFSTR("kLigaturesType"), kContextualLigaturesOnSelector, CFSTR("kContextualLigaturesOnSelector")); handler(kLigaturesType, CFSTR("kLigaturesType"), kCommonLigaturesOffSelector, CFSTR("kCommonLigaturesOffSelector")); handler(kLigaturesType, CFSTR("kLigaturesType"), kContextualLigaturesOffSelector, CFSTR("kContextualLigaturesOffSelector")); handler(kLigaturesType, CFSTR("kLigaturesType"), kRareLigaturesOnSelector, CFSTR("kRareLigaturesOnSelector")); handler(kLigaturesType, CFSTR("kLigaturesType"), kRareLigaturesOffSelector, CFSTR("kRareLigaturesOffSelector")); handler(kLigaturesType, CFSTR("kLigaturesType"), kHistoricalLigaturesOnSelector, CFSTR("kHistoricalLigaturesOnSelector")); handler(kLigaturesType, CFSTR("kLigaturesType"), kHistoricalLigaturesOffSelector, CFSTR("kHistoricalLigaturesOffSelector")); handler(kContextualAlternatesType, CFSTR("kContextualAlternatesType"), kContextualAlternatesOnSelector, CFSTR("kContextualAlternatesOnSelector")); handler(kContextualAlternatesType, CFSTR("kContextualAlternatesType"), kContextualAlternatesOffSelector, CFSTR("kContextualAlternatesOffSelector")); handler(kVerticalPositionType, CFSTR("kVerticalPositionType"), kInferiorsSelector, CFSTR("kInferiorsSelector")); handler(kVerticalPositionType, CFSTR("kVerticalPositionType"), kSuperiorsSelector, CFSTR("kSuperiorsSelector")); handler(kLowerCaseType, CFSTR("kLowerCaseType"), kLowerCaseSmallCapsSelector, CFSTR("kLowerCaseSmallCapsSelector")); handler(kUpperCaseType, CFSTR("kUpperCaseType"), kUpperCaseSmallCapsSelector, CFSTR("kUpperCaseSmallCapsSelector")); handler(kLowerCaseType, CFSTR("kLowerCaseType"), kLowerCasePetiteCapsSelector, CFSTR("kLowerCasePetiteCapsSelector")); handler(kUpperCaseType, CFSTR("kUpperCaseType"), kUpperCasePetiteCapsSelector, CFSTR("kUpperCasePetiteCapsSelector")); handler(kLetterCaseType, CFSTR("kLetterCaseType"), 14, CFSTR("14")); handler(kStyleOptionsType, CFSTR("kStyleOptionsType"), kTitlingCapsSelector, CFSTR("kTitlingCapsSelector")); handler(kNumberCaseType, CFSTR("kNumberCaseType"), kUpperCaseNumbersSelector, CFSTR("kUpperCaseNumbersSelector")); handler(kNumberCaseType, CFSTR("kNumberCaseType"), kLowerCaseNumbersSelector, CFSTR("kLowerCaseNumbersSelector")); handler(kNumberSpacingType, CFSTR("kNumberSpacingType"), kProportionalNumbersSelector, CFSTR("kProportionalNumbersSelector")); handler(kNumberSpacingType, CFSTR("kNumberSpacingType"), kMonospacedNumbersSelector, CFSTR("kMonospacedNumbersSelector")); handler(kFractionsType, CFSTR("kFractionsType"), kDiagonalFractionsSelector, CFSTR("kDiagonalFractionsSelector")); handler(kFractionsType, CFSTR("kFractionsType"), kVerticalFractionsSelector, CFSTR("kVerticalFractionsSelector")); handler(kVerticalPositionType, CFSTR("kVerticalPositionType"), kOrdinalsSelector, CFSTR("kOrdinalsSelector")); handler(kTypographicExtrasType, CFSTR("kTypographicExtrasType"), kSlashedZeroOnSelector, CFSTR("kSlashedZeroOnSelector")); handler(kLigaturesType, CFSTR("kLigaturesType"), kHistoricalLigaturesOnSelector, CFSTR("kHistoricalLigaturesOnSelector")); handler(kCharacterShapeType, CFSTR("kCharacterShapeType"), kJIS1978CharactersSelector, CFSTR("kJIS1978CharactersSelector")); handler(kCharacterShapeType, CFSTR("kCharacterShapeType"), kJIS1983CharactersSelector, CFSTR("kJIS1983CharactersSelector")); handler(kCharacterShapeType, CFSTR("kCharacterShapeType"), kJIS1990CharactersSelector, CFSTR("kJIS1990CharactersSelector")); handler(kCharacterShapeType, CFSTR("kCharacterShapeType"), kJIS2004CharactersSelector, CFSTR("kJIS2004CharactersSelector")); handler(kCharacterShapeType, CFSTR("kCharacterShapeType"), kSimplifiedCharactersSelector, CFSTR("kSimplifiedCharactersSelector")); handler(kCharacterShapeType, CFSTR("kCharacterShapeType"), kTraditionalCharactersSelector, CFSTR("kTraditionalCharactersSelector")); handler(kTextSpacingType, CFSTR("kTextSpacingType"), kMonospacedTextSelector, CFSTR("kMonospacedTextSelector")); handler(kTextSpacingType, CFSTR("kTextSpacingType"), kProportionalTextSelector, CFSTR("kProportionalTextSelector")); handler(kRubyKanaType, CFSTR("kRubyKanaType"), kRubyKanaOnSelector, CFSTR("kRubyKanaOnSelector")); } CFRelease(fontDescriptor); CGImageRef image = CGBitmapContextCreateImage(context); CGContextRelease(context); CFURLRef url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, CFSTR("/Volumes/Data/home/mmaxfield/tmp/output.png"), kCFURLPOSIXPathStyle, FALSE); CGImageDestinationRef imageDestination = CGImageDestinationCreateWithURL(url, kUTTypePNG, 1, nullptr); CFRelease(url); CGImageDestinationAddImage(imageDestination, image, nullptr); CGImageRelease(image); CGImageDestinationFinalize(imageDestination); CFRelease(imageDestination); return 0; }
66.842795
497
0.769387
[ "vector" ]
c4f3d5c3b2f2626c4baf637db16efcef287a3752
1,814
cc
C++
smallest-k-lcci.cc
ArCan314/leetcode
8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd
[ "MIT" ]
null
null
null
smallest-k-lcci.cc
ArCan314/leetcode
8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd
[ "MIT" ]
null
null
null
smallest-k-lcci.cc
ArCan314/leetcode
8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd
[ "MIT" ]
null
null
null
#include <vector> #include <algorithm> #include <queue> #include <functional> class Solution { public: std::vector<int> smallestK(std::vector<int> &arr, int k) { if (k == 0) return {}; return smallestKLinearSelect(arr, k); } std::vector<int> smallestKSort(std::vector<int> &arr, int k) { std::sort(arr.begin(), arr.end()); return {arr.begin(), arr.begin() + k}; } std::vector<int> smallestKHeap(std::vector<int> &arr, int k) { std::priority_queue<int, std::vector<int>, std::less<int>> heap; for (int i = 0; i < arr.size(); i++) { heap.push(arr[i]); if (heap.size() > k) heap.pop(); } std::vector<int> res(k); for (int i = 0; i < k; i++) { res[i] = heap.top(); heap.pop(); } return res; } void __linearSelect(std::vector<int> &arr, int l, int r, int k) { if (!k) return; int i = l, j = l + 1; int pivot = arr[l]; while (j <= r) { if (arr[j] < pivot) std::swap(arr[++i], arr[j]); j++; } std::swap(arr[l], arr[i]); int left_size = i - l + 1; if (k < left_size) __linearSelect(arr, l, i, k); else __linearSelect(arr, i + 1, r, k - left_size); } std::vector<int> smallestKLinearSelect(std::vector<int> &arr, int k) { __linearSelect(arr, 0, arr.size() - 1, k); return {arr.begin(), arr.begin() + k}; } std::vector<int> smallestKSTL(std::vector<int> &arr, int k) { std::partial_sort(arr.begin(), arr.begin() + k, arr.end()); return {arr.begin(), arr.begin() + k}; } };
23.558442
72
0.466924
[ "vector" ]
c4f7071ce680d8109f874617c040a2ec67ee2ae8
10,610
cpp
C++
src/bitwise-cpp/main_opt_cpu_3.cpp
rogerdahl/cuda-bitwise
4fc1576ecafc6521cc02b5ffd5a1ae7e6feb1ea0
[ "MIT" ]
null
null
null
src/bitwise-cpp/main_opt_cpu_3.cpp
rogerdahl/cuda-bitwise
4fc1576ecafc6521cc02b5ffd5a1ae7e6feb1ea0
[ "MIT" ]
1
2018-02-22T02:14:41.000Z
2018-02-22T04:07:37.000Z
src/bitwise-cpp/main_opt_cpu_3.cpp
rogerdahl/cuda-bitwise
4fc1576ecafc6521cc02b5ffd5a1ae7e6feb1ea0
[ "MIT" ]
null
null
null
// Style: http://geosoft.no/development/cppstyle.html #include <chrono> #include <cmath> #include <fstream> #include <iostream> #include <vector> #include <omp.h> #include <cppformat/format.h> #include "int_types.h" using namespace std; using namespace fmt; // 8 operations enum Operation { LD_A, LD_B, LD_C, LD_D, AND, OR, XOR, NOT, ENUM_END }; //const s32 operationStackDiffArr[]{1, 1, 1, 1, -1, -1, -1, 0}; const u32 operationStackRequireArr[]{0, 0, 0, 0, 2, 2, 2, 1}; const vector<string> opStrVec = {"v1", "v2", "v3", "v4", "and", "or", "xor", "not", "ENUM_END"}; // 12 operations //enum Operation { // LD_A, LD_B, LD_C, LD_D, LD_ONES, LD_ZEROS, AND, OR, XOR, NOT, DUP, POP, ENUM_END //}; //const s32 operationStackDiffArr[]{1, 1, 1, 1, 1, 1, -1, -1, -1, 0, 1, -1}; //const s32 operationStackRequireArr[]{0, 0, 0, 0, 0, 0, 2, 2, 2, 1, 1, 1}; //const vector<string> opStrVec = {"v1", "v2", "v3", "v4", "ones", "zeros", "and", "or", "xor", "not", "dup", "pop", "ENUM_END"}; //typedef vector<Operation> ProgramVec; typedef u16 Bits; typedef vector<Bits> BitsStack; typedef chrono::high_resolution_clock Time; typedef chrono::duration<float> Fsec; struct Frame { Operation op; BitsStack stack; }; typedef vector<Frame> FrameVec; typedef vector<FrameVec> OptimalProgramVec; //u64 countValidPrograms(u32 nSearchLevels); void testProgramGenerator(u32 nSearchLevels); inline bool nextValidProgram(FrameVec& frameVec, u32 nSearchLevels, u32 nBaseLevels); inline Frame nextFrame(Frame frame, Operation operation); //inline bool stackUnderflows(bool& hasOneStackItem, const ProgramVec& program); //Bits evalProgram(const ProgramVec& program); void evalOperation(BitsStack& s, const Operation operation); inline Bits pop(BitsStack& s); void writeResults(const string& resultPath, const OptimalProgramVec& programVec); string serializeProgram(const FrameVec& frameVec); u64 pow(u32 base, u32 exp); int main() { const u32 nSearchLevels = 15; const u32 nTotalTruthTables = 1 << 16; const u64 nTotalPossiblePrograms = pow(static_cast<int>(ENUM_END), nSearchLevels); // Switch from C locale to user's locale. This will typically cause integers to be printed with thousands // separators. locale::global(locale("")); cout.imbue(locale("")); // testProgramGenerator(4); // return 0; print("Total possible programs: {}\n", nTotalPossiblePrograms); // print("Total valid programs: {}\n", countValidPrograms(nSearchLevels)); OptimalProgramVec optimalProgramVec(nTotalTruthTables); u32 nFilledTruthTables = 0; #pragma omp parallel for for (auto opIdx = static_cast<int>(LD_A); opIdx <= static_cast<int>(LD_D); opIdx++) { auto baseOperation = static_cast<Operation>(opIdx); auto baseFrame = nextFrame({ENUM_END, {}}, baseOperation); FrameVec frameVec = {baseFrame}; auto startTime = Time::now(); #pragma omp critical { print("Starting thread {}/{} with program: {}\n", omp_get_thread_num(), omp_get_num_threads(), serializeProgram(frameVec)); } u64 nValidProgramsFound = 0; while (true) { ++nValidProgramsFound; Bits truthTable = frameVec.back().stack.back(); if (!optimalProgramVec[truthTable].size() || optimalProgramVec[truthTable].size() > frameVec.size()) { #pragma omp critical { if (!optimalProgramVec[truthTable].size()) { ++nFilledTruthTables; } // print("{} {:016b}: {}\n", opIdx, truthTable, serializeProgram(frameVec)); optimalProgramVec[truthTable] = frameVec; } } if (!opIdx && ((!(nValidProgramsFound & 0xfffff)) || nFilledTruthTables == nTotalTruthTables)) { #pragma omp critical { Fsec elapsedSec = Time::now() - startTime; print("\nThread: {}\n", opIdx); print("Walltime, this thread: {:.2f}s\n", elapsedSec.count()); print("Valid found, this thread: {} ({:d} per sec)\n", nValidProgramsFound, static_cast<u32>(nValidProgramsFound / elapsedSec.count())); print("Filled truth tables, all threads: {} ({:.2f}%)\n", nFilledTruthTables, static_cast<float>(nFilledTruthTables) / nTotalTruthTables * 100.0f); print("Last evaluated: {} ({} ops)\n", serializeProgram(frameVec), frameVec.size()); } } if (!nextValidProgram(frameVec, nSearchLevels, 1)) { break; } } } writeResults("bitwise.txt", optimalProgramVec); // getchar(); return 0; } //u64 countValidPrograms(u32 nSearchLevels) //{ // u64 nValidPrograms = 1; // ProgramVec program = { LD_A }; // while (nextValidProgram(program, nSearchLevels, 1)) { // ++nValidPrograms; // if (!(nValidPrograms & 0xffffff)) { // print("{}...\n", nValidPrograms); // } // } // return nValidPrograms; //} void testProgramGenerator(u32 nSearchLevels) { auto baseFrame = nextFrame({ENUM_END, {}}, LD_A); FrameVec frameVec = {baseFrame}; while (nextValidProgram(frameVec, nSearchLevels, 1)); } // Given a current program, generate the next valid program. Return false when there are no more programs. bool nextValidProgram(FrameVec& frameVec, u32 nSearchLevels, u32 nBaseLevels) { bool descendIfPossible = true; while (true) { bool newLevel = false; // When the function is called, we start by checking if it's possible to descend one step down. // If that's possible, we descend and return the program if it's valid. if (descendIfPossible) { descendIfPossible = false; if (frameVec.size() < nSearchLevels) { // It's possible to descend... u32 nUnusedLevels = (u32) (nSearchLevels - frameVec.size()); if (frameVec.back().stack.size() <= nUnusedLevels) { // And also useful to descend. So do it. frameVec.push_back(nextFrame(frameVec.back(), LD_A)); newLevel = true; } else { // print("{:<50}{} stackSize={} nUnusedLevels={}\n", "Skipped hopeless branch.", // serializeProgram(frameVec), frameVec.back().stack.size(), nUnusedLevels); } } } // "else" because we don't want to go to the next operation if pushed a new frame with LD_A to the stack. if (!newLevel) { auto newOpIdx = static_cast<int>(frameVec.back().op) + 1; frameVec.back().op = static_cast<Operation>(newOpIdx); if (frameVec.back().op == ENUM_END) { // We have iterated over all possible variations at this level. Drop back to a higher level. frameVec.pop_back(); if (frameVec.size() == nBaseLevels) { // print("{:<50}{}\n", "Back at the base program. Iteration is complete", serializeProgram(frameVec)); return false; } // print("{:<50}{}\n", "Ascend to higher level, checked earlier", serializeProgram(frameVec)); // We're back to a level that has already been returned. We jump to the top to generate the next // variation on the same level. If the new variation passes the tests, it is returned as the next // valid program and then becomes the root for further programs. continue; } } auto opIdx = static_cast<int>(frameVec.back().op); if (frameVec.rbegin()[1].stack.size() < operationStackRequireArr[opIdx]) { // print("{:<50}{}\n", "Skipping program that underflows", serializeProgram(frameVec)); // Generate the next variation while staying on the same level. This causes a move away from the current // program, which prevents it from becoming the root for any new programs, all of which would be invalid. continue; } frameVec.back() = nextFrame(frameVec.rbegin()[1], frameVec.back().op); if (frameVec.back().stack.size() != 1) { // print("{:<50}{} results={}\n", "Skipping program that returns <> 1 results", serializeProgram(frameVec), frameVec.back().stack.size()); // Move to a lower level if possible. Programs that don't underflow but return a stack with more or less // than one item may become valid when adding one or more operations, so those branches must be searched. descendIfPossible = true; continue; } // print("{:<50}{}\n", "########## Returning valid program ##########", serializeProgram(frameVec)); return true; } } Frame nextFrame(Frame frame, Operation operation) { frame.op = operation; evalOperation(frame.stack, operation); return frame; } void evalOperation(BitsStack& s, const Operation operation) { switch (operation) { case LD_A: s.push_back(0b0000000011111111); break; case LD_B: s.push_back(0b0000111100001111); break; case LD_C: s.push_back(0b0011001100110011); break; case LD_D: s.push_back(0b0101010101010101); break; case AND: s.push_back(pop(s) & pop(s)); break; case OR: s.push_back(pop(s) | pop(s)); break; case XOR: s.push_back(pop(s) ^ pop(s)); break; case NOT: s.push_back(~pop(s)); break; case ENUM_END: assert(false); break; default: assert(false); break; } } Bits pop(BitsStack& s) { Bits v = s.back(); s.pop_back(); return v; } void writeResults(const string& resultPath, const OptimalProgramVec& programVec) { ofstream f(resultPath, ios::out); Bits truthTable = 0; for (auto program : programVec) { if (program.size()) { f << format("{:016b}: {}\n", truthTable, serializeProgram(program)); } ++truthTable; } } string serializeProgram(const FrameVec& frameVec) { string s; for (auto frame : frameVec) { s += format("{} ", opStrVec[static_cast<int>(frame.op)]); } return s; } u64 pow(u32 base, u32 exp) { u64 r = base; for (u32 i = 0; i < exp; ++i) { r *= base; } return r; }
38.442029
149
0.596795
[ "vector" ]
f205df50e35c8436c5999c40ab1cc07dcf8d0a66
383
cpp
C++
opencl-opengl-framework/Camera.cpp
BrassLion/opengl-opencl-framework
5b515cf80a3af659c39c238cb810a5ef738340b2
[ "MIT" ]
1
2021-06-06T12:14:08.000Z
2021-06-06T12:14:08.000Z
opencl-opengl-framework/Camera.cpp
BrassLion/opengl-opencl-framework
5b515cf80a3af659c39c238cb810a5ef738340b2
[ "MIT" ]
null
null
null
opencl-opengl-framework/Camera.cpp
BrassLion/opengl-opencl-framework
5b515cf80a3af659c39c238cb810a5ef738340b2
[ "MIT" ]
1
2019-02-18T13:09:43.000Z
2019-02-18T13:09:43.000Z
// // Camera.cpp // OpenGLTest // // Created by Samuel Hall on 24/07/2016. // // #include <iostream> #include "Camera.hpp" glm::mat4 Camera::get_projection_matrix() { return m_projection; } glm::mat4 Camera::get_view_matrix() { return m_view; } void Camera::update_model_matrix() { Object::update_model_matrix(); m_view = glm::inverse(m_model_matrix); }
13.206897
42
0.665796
[ "object" ]
f20f73dc21a48d6f2c0e85f5bc4f4554de61f8a6
721
cpp
C++
tools/punkty_wspolliniowe.cpp
marcel2012/algorytmy
03582793877bc4dfed3847b1bf9f456186d22e11
[ "MIT" ]
null
null
null
tools/punkty_wspolliniowe.cpp
marcel2012/algorytmy
03582793877bc4dfed3847b1bf9f456186d22e11
[ "MIT" ]
null
null
null
tools/punkty_wspolliniowe.cpp
marcel2012/algorytmy
03582793877bc4dfed3847b1bf9f456186d22e11
[ "MIT" ]
null
null
null
#include <cstdio> #include <vector> inline double deg(int x1,int y1,int x2,int y2,int x3,int y3) { return x1 * y2 + x2 * y3 + x3 * y1 - y2 * x3 - y3 * x1 - y1 * x2; } int main() { int n; scanf("%d",&n); std::vector <std::pair<int,int> > points(n); for(int i=0; i<n; i++) { scanf("%d %d",&points.at(i).first,&points.at(i).second); for(int j=i-1;j>=0;j--) for(int k=j-1;k>=0;k--) if(!deg(points.at(i).first,points.at(i).second,points.at(j).first,points.at(j).second,points.at(k).first,points.at(k).second)) { printf("ERROR\n"); return -1; } } printf("OK\n"); return 0; }
27.730769
142
0.479889
[ "vector" ]
f20f76389f69ab26e54b2fb1c3b755eb94772e2b
599
hpp
C++
Server/include/commands/today.hpp
radu781/Train-manager
74f41dc7f3a61df56f670956b7d65d89e956ee4d
[ "MIT" ]
null
null
null
Server/include/commands/today.hpp
radu781/Train-manager
74f41dc7f3a61df56f670956b7d65d89e956ee4d
[ "MIT" ]
null
null
null
Server/include/commands/today.hpp
radu781/Train-manager
74f41dc7f3a61df56f670956b7d65d89e956ee4d
[ "MIT" ]
null
null
null
#pragma once #include "pc.h" #include "command.hpp" class Today : public Command { public: Today(const Command *other, const std::vector<std::string> *command); std::string execute() override; std::string undo() override; private: /** * @brief Split the command member into two strings by following the rule: * [begin, i], (i, end], where 0 < i < command.size() * * \return 2 valid city names if found, empty strings otherwise */ std::pair<std::unordered_set<std::string>, std::unordered_set<std::string>> splitNames(); };
24.958333
94
0.621035
[ "vector" ]
f210e8a812f253ca2dad7337114a96b5b4b4c6c2
2,156
hpp
C++
QuantExt/qle/models/cpicapfloorhelper.hpp
mrslezak/Engine
c46ff278a2c5f4162db91a7ab500a0bb8cef7657
[ "BSD-3-Clause" ]
335
2016-10-07T16:31:10.000Z
2022-03-02T07:12:03.000Z
QuantExt/qle/models/cpicapfloorhelper.hpp
mrslezak/Engine
c46ff278a2c5f4162db91a7ab500a0bb8cef7657
[ "BSD-3-Clause" ]
59
2016-10-31T04:20:24.000Z
2022-01-03T16:39:57.000Z
QuantExt/qle/models/cpicapfloorhelper.hpp
mrslezak/Engine
c46ff278a2c5f4162db91a7ab500a0bb8cef7657
[ "BSD-3-Clause" ]
180
2016-10-08T14:23:50.000Z
2022-03-28T10:43:05.000Z
/* Copyright (C) 2017 Quaternion Risk Management Ltd All rights reserved. This file is part of ORE, a free-software/open-source library for transparent pricing and risk analysis - http://opensourcerisk.org ORE is free software: you can redistribute it and/or modify it under the terms of the Modified BSD License. You should have received a copy of the license along with this program. The license is also available online at <http://opensourcerisk.org> This program is distributed on the basis that it will form a useful contribution to risk analytics and model standardisation, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ /*! \file cpicapfloorhelper.hpp \brief CPI Cap Floor calibration helper \ingroup models */ #ifndef quantext_cpicapfloor_calibration_helper_hpp #define quantext_cpicapfloor_calibration_helper_hpp #include <ql/instruments/cpicapfloor.hpp> #include <ql/models/calibrationhelper.hpp> namespace QuantExt { using namespace QuantLib; /* Note that calibration helpers that are not based on a implied volatility but directly on a premium are part of QL PR 18 */ //! CPI cap floor helper /*! \ingroup models */ class CpiCapFloorHelper : public BlackCalibrationHelper { public: CpiCapFloorHelper( Option::Type type, Real baseCPI, const Date& maturity, const Calendar& fixCalendar, BusinessDayConvention fixConvention, const Calendar& payCalendar, BusinessDayConvention payConvention, Real strike, const Handle<ZeroInflationIndex>& infIndex, const Period& observationLag, Real marketPremium, CPI::InterpolationType observationInterpolation = CPI::AsIndex, BlackCalibrationHelper::CalibrationErrorType errorType = BlackCalibrationHelper::RelativePriceError); Real modelValue() const; Real blackPrice(Volatility volatility) const; void addTimesTo(std::list<Time>&) const {} boost::shared_ptr<CPICapFloor> instrument() const { return instrument_; } private: boost::shared_ptr<CPICapFloor> instrument_; }; } // namespace QuantExt #endif
35.344262
114
0.775046
[ "model" ]
f219829403d4bce98238ace8b4db04d228bf7098
35,532
cpp
C++
include/CombBLAS/SpParHelper.cpp
vishalbelsare/CombBLAS
426f6be0b29831025cdcacc1f8f69e3520bfb0ff
[ "BSD-3-Clause-LBNL" ]
22
2020-08-14T19:14:13.000Z
2022-02-05T20:14:59.000Z
include/CombBLAS/SpParHelper.cpp
vishalbelsare/CombBLAS
426f6be0b29831025cdcacc1f8f69e3520bfb0ff
[ "BSD-3-Clause-LBNL" ]
8
2020-10-09T23:23:36.000Z
2021-08-05T20:35:18.000Z
include/CombBLAS/SpParHelper.cpp
vishalbelsare/CombBLAS
426f6be0b29831025cdcacc1f8f69e3520bfb0ff
[ "BSD-3-Clause-LBNL" ]
8
2020-12-04T09:10:06.000Z
2022-01-04T15:37:59.000Z
/****************************************************************/ /* Parallel Combinatorial BLAS Library (for Graph Computations) */ /* version 1.6 -------------------------------------------------*/ /* date: 6/15/2017 ---------------------------------------------*/ /* authors: Ariful Azad, Aydin Buluc --------------------------*/ /****************************************************************/ /* Copyright (c) 2010-2017, The Regents of the University of California 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 "usort/parUtils.h" namespace combblas { template <typename IT> void SpParHelper::ReDistributeToVector(int* & map_scnt, std::vector< std::vector< IT > > & locs_send, std::vector< std::vector< std::string > > & data_send, std::vector<std::array<char, MAXVERTNAME>> & distmapper_array, const MPI_Comm & comm) { int nprocs, myrank; MPI_Comm_size(comm, &nprocs); MPI_Comm_rank(comm, &myrank); int * map_rcnt = new int[nprocs]; MPI_Alltoall(map_scnt, 1, MPI_INT, map_rcnt, 1, MPI_INT, comm); int * map_sdspl = new int[nprocs](); int * map_rdspl = new int[nprocs](); std::partial_sum(map_scnt, map_scnt+nprocs-1, map_sdspl+1); std::partial_sum(map_rcnt, map_rcnt+nprocs-1, map_rdspl+1); IT totmapsend = map_sdspl[nprocs-1] + map_scnt[nprocs-1]; IT totmaprecv = map_rdspl[nprocs-1] + map_rcnt[nprocs-1]; // sendbuf is a pointer to array of MAXVERTNAME chars. // Explicit grouping syntax is due to precedence of [] over * // char* sendbuf[MAXVERTNAME] would have declared a MAXVERTNAME-length array of char pointers char (*sendbuf)[MAXVERTNAME]; // each sendbuf[i] is type char[MAXVERTNAME] sendbuf = (char (*)[MAXVERTNAME]) malloc(sizeof(char[MAXVERTNAME])* totmapsend); // notice that this is allocating a contiguous block of memory IT * sendinds = new IT[totmapsend]; for(int i=0; i<nprocs; ++i) { int loccnt = 0; for(std::string s:data_send[i]) { std::strcpy(sendbuf[map_sdspl[i]+loccnt], s.c_str()); loccnt++; } std::vector<std::string>().swap(data_send[i]); // free memory } for(int i=0; i<nprocs; ++i) // sanity check: received indices should be sorted by definition { std::copy(locs_send[i].begin(), locs_send[i].end(), sendinds+map_sdspl[i]); std::vector<IT>().swap(locs_send[i]); // free memory } char (*recvbuf)[MAXVERTNAME]; // recvbuf is of type char (*)[MAXVERTNAME] recvbuf = (char (*)[MAXVERTNAME]) malloc(sizeof(char[MAXVERTNAME])* totmaprecv); MPI_Datatype MPI_STRING; // this is not necessary (we could just use char) but easier for bookkeeping MPI_Type_contiguous(sizeof(char[MAXVERTNAME]), MPI_CHAR, &MPI_STRING); MPI_Type_commit(&MPI_STRING); MPI_Alltoallv(sendbuf, map_scnt, map_sdspl, MPI_STRING, recvbuf, map_rcnt, map_rdspl, MPI_STRING, comm); free(sendbuf); // can't delete[] so use free MPI_Type_free(&MPI_STRING); IT * recvinds = new IT[totmaprecv]; MPI_Alltoallv(sendinds, map_scnt, map_sdspl, MPIType<IT>(), recvinds, map_rcnt, map_rdspl, MPIType<IT>(), comm); DeleteAll(sendinds, map_scnt, map_sdspl, map_rcnt, map_rdspl); if(!std::is_sorted(recvinds, recvinds+totmaprecv)) std::cout << "Assertion failed at proc " << myrank << ": Received indices are not sorted, this is unexpected" << std::endl; for(IT i=0; i< totmaprecv; ++i) { assert(i == recvinds[i]); std::copy(recvbuf[i], recvbuf[i]+MAXVERTNAME, distmapper_array[i].begin()); } free(recvbuf); delete [] recvinds; } template<typename KEY, typename VAL, typename IT> void SpParHelper::MemoryEfficientPSort(std::pair<KEY,VAL> * array, IT length, IT * dist, const MPI_Comm & comm) { int nprocs, myrank; MPI_Comm_size(comm, &nprocs); MPI_Comm_rank(comm, &myrank); int nsize = nprocs / 2; // new size if(nprocs < 10000) { bool excluded = false; if(dist[myrank] == 0) excluded = true; int nreals = 0; for(int i=0; i< nprocs; ++i) if(dist[i] != 0) ++nreals; //SpParHelper::MemoryEfficientPSort(vecpair, nnz, dist, World); if(nreals == nprocs) // general case { long * dist_in = new long[nprocs]; for(int i=0; i< nprocs; ++i) dist_in[i] = (long) dist[i]; vpsort::parallel_sort (array, array+length, dist_in, comm); delete [] dist_in; } else { long * dist_in = new long[nreals]; int * dist_out = new int[nprocs-nreals]; // ranks to exclude int indin = 0; int indout = 0; for(int i=0; i< nprocs; ++i) { if(dist[i] == 0) dist_out[indout++] = i; else dist_in[indin++] = (long) dist[i]; } #ifdef DEBUG std::ostringstream outs; outs << "To exclude indices: "; std::copy(dist_out, dist_out+indout, std::ostream_iterator<int>(outs, " ")); outs << std::endl; SpParHelper::Print(outs.str()); #endif MPI_Group sort_group, real_group; MPI_Comm_group(comm, &sort_group); MPI_Group_excl(sort_group, indout, dist_out, &real_group); MPI_Group_free(&sort_group); // The Create() function should be executed by all processes in comm, // even if they do not belong to the new group (in that case MPI_COMM_NULL is returned as real_comm?) // MPI::Intracomm MPI::Intracomm::Create(const MPI::Group& group) const; MPI_Comm real_comm; MPI_Comm_create(comm, real_group, &real_comm); if(!excluded) { vpsort::parallel_sort (array, array+length, dist_in, real_comm); MPI_Comm_free(&real_comm); } MPI_Group_free(&real_group); delete [] dist_in; delete [] dist_out; } } else { IT gl_median = std::accumulate(dist, dist+nsize, static_cast<IT>(0)); // global rank of the first element of the median processor sort(array, array+length); // re-sort because we might have swapped data in previous iterations int color = (myrank < nsize)? 0: 1; std::pair<KEY,VAL> * low = array; std::pair<KEY,VAL> * upp = array; GlobalSelect(gl_median, low, upp, array, length, comm); BipartiteSwap(low, array, length, nsize, color, comm); if(color == 1) dist = dist + nsize; // adjust for the second half of processors // recursive call; two implicit 'spawn's where half of the processors execute different paramaters // MPI::Intracomm MPI::Intracomm::Split(int color, int key) const; MPI_Comm halfcomm; MPI_Comm_split(comm, color, myrank, &halfcomm); // split into two communicators MemoryEfficientPSort(array, length, dist, halfcomm); } } /* TODO: This function is just a hack at this moment. The payload (VAL) can only be integer at this moment. FIX this. */ template<typename KEY, typename VAL, typename IT> std::vector<std::pair<KEY,VAL>> SpParHelper::KeyValuePSort(std::pair<KEY,VAL> * array, IT length, IT * dist, const MPI_Comm & comm) { int nprocs, myrank; MPI_Comm_size(comm, &nprocs); MPI_Comm_rank(comm, &myrank); int nsize = nprocs / 2; // new size bool excluded = false; if(dist[myrank] == 0) excluded = true; int nreals = 0; for(int i=0; i< nprocs; ++i) if(dist[i] != 0) ++nreals; std::vector<IndexHolder<KEY>> in(length); #ifdef THREADED #pragma omp parallel for #endif for(int i=0; i< length; ++i) { in[i] = IndexHolder<KEY>(array[i].first, static_cast<unsigned long>(array[i].second)); } if(nreals == nprocs) // general case { par::sampleSort(in, comm); } else { long * dist_in = new long[nreals]; int * dist_out = new int[nprocs-nreals]; // ranks to exclude int indin = 0; int indout = 0; for(int i=0; i< nprocs; ++i) { if(dist[i] == 0) dist_out[indout++] = i; else dist_in[indin++] = (long) dist[i]; } #ifdef DEBUG std::ostringstream outs; outs << "To exclude indices: "; std::copy(dist_out, dist_out+indout, std::ostream_iterator<int>(outs, " ")); outs << std::endl; SpParHelper::Print(outs.str()); #endif MPI_Group sort_group, real_group; MPI_Comm_group(comm, &sort_group); MPI_Group_excl(sort_group, indout, dist_out, &real_group); MPI_Group_free(&sort_group); // The Create() function should be executed by all processes in comm, // even if they do not belong to the new group (in that case MPI_COMM_NULL is returned as real_comm?) // MPI::Intracomm MPI::Intracomm::Create(const MPI::Group& group) const; MPI_Comm real_comm; MPI_Comm_create(comm, real_group, &real_comm); if(!excluded) { par::sampleSort(in, real_comm); MPI_Comm_free(&real_comm); } MPI_Group_free(&real_group); delete [] dist_in; delete [] dist_out; } std::vector<std::pair<KEY,VAL>> sorted(in.size()); for(int i=0; i<in.size(); i++) { sorted[i].second = static_cast<VAL>(in[i].index); sorted[i].first = in[i].value; } return sorted; } template<typename KEY, typename VAL, typename IT> void SpParHelper::GlobalSelect(IT gl_rank, std::pair<KEY,VAL> * & low, std::pair<KEY,VAL> * & upp, std::pair<KEY,VAL> * array, IT length, const MPI_Comm & comm) { int nprocs, myrank; MPI_Comm_size(comm, &nprocs); MPI_Comm_rank(comm, &myrank); IT begin = 0; IT end = length; // initially everyone is active std::pair<KEY, double> * wmminput = new std::pair<KEY,double>[nprocs]; // (median, #{actives}) MPI_Datatype MPI_sortType; MPI_Type_contiguous (sizeof(std::pair<KEY,double>), MPI_CHAR, &MPI_sortType); MPI_Type_commit (&MPI_sortType); KEY wmm; // our median pick IT gl_low, gl_upp; IT active = end-begin; // size of the active range IT nacts = 0; bool found = 0; int iters = 0; /* changes by shan : to add begin0 and end0 for exit condition */ IT begin0, end0; do { iters++; begin0 = begin; end0 = end; KEY median = array[(begin + end)/2].first; // median of the active range wmminput[myrank].first = median; wmminput[myrank].second = static_cast<double>(active); MPI_Allgather(MPI_IN_PLACE, 0, MPI_sortType, wmminput, 1, MPI_sortType, comm); double totact = 0; // total number of active elements for(int i=0; i<nprocs; ++i) totact += wmminput[i].second; // input to weighted median of medians is a set of (object, weight) pairs // the algorithm computes the first set of elements (according to total // order of "object"s), whose sum is still less than or equal to 1/2 for(int i=0; i<nprocs; ++i) wmminput[i].second /= totact ; // normalize the weights sort(wmminput, wmminput+nprocs); // sort w.r.t. medians double totweight = 0; int wmmloc=0; while( wmmloc<nprocs && totweight < 0.5 ) { totweight += wmminput[wmmloc++].second; } wmm = wmminput[wmmloc-1].first; // weighted median of medians std::pair<KEY,VAL> wmmpair = std::make_pair(wmm, VAL()); low =std::lower_bound (array+begin, array+end, wmmpair); upp =std::upper_bound (array+begin, array+end, wmmpair); IT loc_low = low-array; // #{elements smaller than wmm} IT loc_upp = upp-array; // #{elements smaller or equal to wmm} MPI_Allreduce( &loc_low, &gl_low, 1, MPIType<IT>(), MPI_SUM, comm); MPI_Allreduce( &loc_upp, &gl_upp, 1, MPIType<IT>(), MPI_SUM, comm); if(gl_upp < gl_rank) { // our pick was too small; only recurse to the right begin = (low - array); } else if(gl_rank < gl_low) { // our pick was too big; only recurse to the left end = (upp - array); } else { found = true; } active = end-begin; MPI_Allreduce(&active, &nacts, 1, MPIType<IT>(), MPI_SUM, comm); if (begin0 == begin && end0 == end) break; // ABAB: Active range did not shrink, so we break (is this kosher?) } while((nacts > 2*nprocs) && (!found)); delete [] wmminput; MPI_Datatype MPI_pairType; MPI_Type_contiguous (sizeof(std::pair<KEY,VAL>), MPI_CHAR, &MPI_pairType); MPI_Type_commit (&MPI_pairType); int * nactives = new int[nprocs]; nactives[myrank] = static_cast<int>(active); // At this point, actives are small enough MPI_Allgather(MPI_IN_PLACE, 0, MPI_INT, nactives, 1, MPI_INT, comm); int * dpls = new int[nprocs](); // displacements (zero initialized pid) std::partial_sum(nactives, nactives+nprocs-1, dpls+1); std::pair<KEY,VAL> * recvbuf = new std::pair<KEY,VAL>[nacts]; low = array + begin; // update low to the beginning of the active range MPI_Allgatherv(low, active, MPI_pairType, recvbuf, nactives, dpls, MPI_pairType, comm); std::pair<KEY,int> * allactives = new std::pair<KEY,int>[nacts]; int k = 0; for(int i=0; i<nprocs; ++i) { for(int j=0; j<nactives[i]; ++j) { allactives[k] = std::make_pair(recvbuf[k].first, i); k++; } } DeleteAll(recvbuf, dpls, nactives); sort(allactives, allactives+nacts); MPI_Allreduce(&begin, &gl_low, 1, MPIType<IT>(), MPI_SUM, comm); // update int diff = gl_rank - gl_low; for(int k=0; k < diff; ++k) { if(allactives[k].second == myrank) ++low; // increment the local pointer } delete [] allactives; begin = low-array; MPI_Allreduce(&begin, &gl_low, 1, MPIType<IT>(), MPI_SUM, comm); // update } template<typename KEY, typename VAL, typename IT> void SpParHelper::BipartiteSwap(std::pair<KEY,VAL> * low, std::pair<KEY,VAL> * array, IT length, int nfirsthalf, int color, const MPI_Comm & comm) { int nprocs, myrank; MPI_Comm_size(comm, &nprocs); MPI_Comm_rank(comm, &myrank); IT * firsthalves = new IT[nprocs]; IT * secondhalves = new IT[nprocs]; firsthalves[myrank] = low-array; secondhalves[myrank] = length - (low-array); MPI_Allgather(MPI_IN_PLACE, 0, MPIType<IT>(), firsthalves, 1, MPIType<IT>(), comm); MPI_Allgather(MPI_IN_PLACE, 0, MPIType<IT>(), secondhalves, 1, MPIType<IT>(), comm); int * sendcnt = new int[nprocs](); // zero initialize int totrecvcnt = 0; std::pair<KEY,VAL> * bufbegin = NULL; if(color == 0) // first processor half, only send second half of data { bufbegin = low; totrecvcnt = length - (low-array); IT beg_oftransfer = std::accumulate(secondhalves, secondhalves+myrank, static_cast<IT>(0)); IT spaceafter = firsthalves[nfirsthalf]; int i=nfirsthalf+1; while(i < nprocs && spaceafter < beg_oftransfer) { spaceafter += firsthalves[i++]; // post-incremenet } IT end_oftransfer = beg_oftransfer + secondhalves[myrank]; // global index (within second half) of the end of my data IT beg_pour = beg_oftransfer; IT end_pour = std::min(end_oftransfer, spaceafter); sendcnt[i-1] = end_pour - beg_pour; while( i < nprocs && spaceafter < end_oftransfer ) // find other recipients until I run out of data { beg_pour = end_pour; spaceafter += firsthalves[i]; end_pour = std::min(end_oftransfer, spaceafter); sendcnt[i++] = end_pour - beg_pour; // post-increment } } else if(color == 1) // second processor half, only send first half of data { bufbegin = array; totrecvcnt = low-array; // global index (within the second processor half) of the beginning of my data IT beg_oftransfer = std::accumulate(firsthalves+nfirsthalf, firsthalves+myrank, static_cast<IT>(0)); IT spaceafter = secondhalves[0]; int i=1; while( i< nfirsthalf && spaceafter < beg_oftransfer) { //spacebefore = spaceafter; spaceafter += secondhalves[i++]; // post-increment } IT end_oftransfer = beg_oftransfer + firsthalves[myrank]; // global index (within second half) of the end of my data IT beg_pour = beg_oftransfer; IT end_pour = std::min(end_oftransfer, spaceafter); sendcnt[i-1] = end_pour - beg_pour; while( i < nfirsthalf && spaceafter < end_oftransfer ) // find other recipients until I run out of data { beg_pour = end_pour; spaceafter += secondhalves[i]; end_pour = std::min(end_oftransfer, spaceafter); sendcnt[i++] = end_pour - beg_pour; // post-increment } } DeleteAll(firsthalves, secondhalves); int * recvcnt = new int[nprocs]; MPI_Alltoall(sendcnt, 1, MPI_INT, recvcnt, 1, MPI_INT, comm); // get the recv counts // Alltoall is actually unnecessary, because sendcnt = recvcnt // If I have n_mine > n_yours data to send, then I can send you only n_yours // as this is your space, and you'll send me identical amount. // Then I can only receive n_mine - n_yours from the third processor and // that processor can only send n_mine - n_yours to me back. // The proof follows from induction MPI_Datatype MPI_valueType; MPI_Type_contiguous(sizeof(std::pair<KEY,VAL>), MPI_CHAR, &MPI_valueType); MPI_Type_commit(&MPI_valueType); std::pair<KEY,VAL> * receives = new std::pair<KEY,VAL>[totrecvcnt]; int * sdpls = new int[nprocs](); // displacements (zero initialized pid) int * rdpls = new int[nprocs](); std::partial_sum(sendcnt, sendcnt+nprocs-1, sdpls+1); std::partial_sum(recvcnt, recvcnt+nprocs-1, rdpls+1); MPI_Alltoallv(bufbegin, sendcnt, sdpls, MPI_valueType, receives, recvcnt, rdpls, MPI_valueType, comm); // sparse swap DeleteAll(sendcnt, recvcnt, sdpls, rdpls); std::copy(receives, receives+totrecvcnt, bufbegin); delete [] receives; } template<typename KEY, typename VAL, typename IT> void SpParHelper::DebugPrintKeys(std::pair<KEY,VAL> * array, IT length, IT * dist, MPI_Comm & World) { int rank, nprocs; MPI_Comm_rank(World, &rank); MPI_Comm_size(World, &nprocs); MPI_File thefile; char _fn[] = "temp_sortedkeys"; // AL: this is to avoid the problem that C++ string literals are const char* while C string literals are char*, leading to a const warning (technically error, but compilers are tolerant) MPI_File_open(World, _fn, MPI_MODE_CREATE | MPI_MODE_WRONLY, MPI_INFO_NULL, &thefile); // The cast in the last parameter is crucial because the signature of the function is // T accumulate ( InputIterator first, InputIterator last, T init ) // Hence if init if of type "int", the output also becomes an it (remember C++ signatures are ignorant of return value) IT sizeuntil = std::accumulate(dist, dist+rank, static_cast<IT>(0)); MPI_Offset disp = sizeuntil * sizeof(KEY); // displacement is in bytes MPI_File_set_view(thefile, disp, MPIType<KEY>(), MPIType<KEY>(), "native", MPI_INFO_NULL); KEY * packed = new KEY[length]; for(int i=0; i<length; ++i) { packed[i] = array[i].first; } MPI_File_write(thefile, packed, length, MPIType<KEY>(), NULL); MPI_File_close(&thefile); delete [] packed; // Now let processor-0 read the file and print if(rank == 0) { FILE * f = fopen("temp_sortedkeys", "r"); if(!f) { std::cerr << "Problem reading binary input file\n"; return; } IT maxd = *std::max_element(dist, dist+nprocs); KEY * data = new KEY[maxd]; for(int i=0; i<nprocs; ++i) { // read n_per_proc integers and print them fread(data, sizeof(KEY), dist[i],f); std::cout << "Elements stored on proc " << i << ": " << std::endl; std::copy(data, data+dist[i], std::ostream_iterator<KEY>(std::cout, "\n")); } delete [] data; } } /** * @param[in,out] MRecv {an already existing, but empty SpMat<...> object} * @param[in] essentials {carries essential information (i.e. required array sizes) about ARecv} * @param[in] arrwin {windows array of size equal to the number of built-in arrays in the SpMat data structure} * @param[in] ownind {processor index (within this processor row/column) of the owner of the matrix to be received} * @remark {The communicator information is implicitly contained in the MPI::Win objects} **/ template <class IT, class NT, class DER> void SpParHelper::FetchMatrix(SpMat<IT,NT,DER> & MRecv, const std::vector<IT> & essentials, std::vector<MPI_Win> & arrwin, int ownind) { MRecv.Create(essentials); // allocate memory for arrays Arr<IT,NT> arrinfo = MRecv.GetArrays(); assert( (arrwin.size() == arrinfo.totalsize())); // C-binding for MPI::Get // int MPI_Get(void *origin_addr, int origin_count, MPI_Datatype origin_datatype, int target_rank, MPI_Aint target_disp, // int target_count, MPI_Datatype target_datatype, MPI_Win win) IT essk = 0; for(int i=0; i< arrinfo.indarrs.size(); ++i) // get index arrays { //arrwin[essk].Lock(MPI::LOCK_SHARED, ownind, 0); MPI_Get( arrinfo.indarrs[i].addr, arrinfo.indarrs[i].count, MPIType<IT>(), ownind, 0, arrinfo.indarrs[i].count, MPIType<IT>(), arrwin[essk++]); } for(int i=0; i< arrinfo.numarrs.size(); ++i) // get numerical arrays { //arrwin[essk].Lock(MPI::LOCK_SHARED, ownind, 0); MPI_Get(arrinfo.numarrs[i].addr, arrinfo.numarrs[i].count, MPIType<NT>(), ownind, 0, arrinfo.numarrs[i].count, MPIType<NT>(), arrwin[essk++]); } } /** * @param[in] Matrix {For the root processor, the local object to be sent to all others. * For all others, it is a (yet) empty object to be filled by the received data} * @param[in] essentials {irrelevant for the root} **/ template<typename IT, typename NT, typename DER> void SpParHelper::BCastMatrix(MPI_Comm & comm1d, SpMat<IT,NT,DER> & Matrix, const std::vector<IT> & essentials, int root) { int myrank; MPI_Comm_rank(comm1d, &myrank); if(myrank != root) { Matrix.Create(essentials); // allocate memory for arrays } Arr<IT,NT> arrinfo = Matrix.GetArrays(); for(unsigned int i=0; i< arrinfo.indarrs.size(); ++i) // get index arrays { MPI_Bcast(arrinfo.indarrs[i].addr, arrinfo.indarrs[i].count, MPIType<IT>(), root, comm1d); } for(unsigned int i=0; i< arrinfo.numarrs.size(); ++i) // get numerical arrays { MPI_Bcast(arrinfo.numarrs[i].addr, arrinfo.numarrs[i].count, MPIType<NT>(), root, comm1d); } } /** * @param[in] Matrix {For the root processor, the local object to be sent to all others. * For all others, it is a (yet) empty object to be filled by the received data} * @param[in] essentials {irrelevant for the root} **/ template<typename IT, typename NT, typename DER> void SpParHelper::IBCastMatrix(MPI_Comm & comm1d, SpMat<IT,NT,DER> & Matrix, const std::vector<IT> & essentials, int root, std::vector<MPI_Request> & indarrayReq , std::vector<MPI_Request> & numarrayReq) { int myrank; MPI_Comm_rank(comm1d, &myrank); if(myrank != root) { Matrix.Create(essentials); // allocate memory for arrays } Arr<IT,NT> arrinfo = Matrix.GetArrays(); for(unsigned int i=0; i< arrinfo.indarrs.size(); ++i) // get index arrays { MPI_Ibcast(arrinfo.indarrs[i].addr, arrinfo.indarrs[i].count, MPIType<IT>(), root, comm1d, &indarrayReq[i]); } for(unsigned int i=0; i< arrinfo.numarrs.size(); ++i) // get numerical arrays { MPI_Ibcast(arrinfo.numarrs[i].addr, arrinfo.numarrs[i].count, MPIType<NT>(), root, comm1d, &numarrayReq[i]); } } /** * Just a test function to see the time to gather a matrix on an MPI process * The ultimate object would be to create the whole matrix on rank 0 (TODO) * @param[in] Matrix {For the root processor, the local object to be sent to all others. * For all others, it is a (yet) empty object to be filled by the received data} * @param[in] essentials {irrelevant for the root} **/ template<typename IT, typename NT, typename DER> void SpParHelper::GatherMatrix(MPI_Comm & comm1d, SpMat<IT,NT,DER> & Matrix, int root) { int myrank, nprocs; MPI_Comm_rank(comm1d, &myrank); MPI_Comm_size(comm1d,&nprocs); /* if(myrank != root) { Matrix.Create(essentials); // allocate memory for arrays } */ Arr<IT,NT> arrinfo = Matrix.GetArrays(); std::vector<std::vector<int>> recvcnt_ind(arrinfo.indarrs.size()); std::vector<std::vector<int>> recvcnt_num(arrinfo.numarrs.size()); for(unsigned int i=0; i< arrinfo.indarrs.size(); ++i) // get index arrays { recvcnt_ind[i].resize(nprocs); int lcount = (int)arrinfo.indarrs[i].count; MPI_Gather(&lcount, 1, MPI_INT, recvcnt_ind[i].data(),1, MPI_INT, root, comm1d); } for(unsigned int i=0; i< arrinfo.numarrs.size(); ++i) // get numerical arrays { recvcnt_num[i].resize(nprocs); int lcount = (int) arrinfo.numarrs[i].count; MPI_Gather(&lcount, 1, MPI_INT, recvcnt_num[i].data(),1, MPI_INT, root, comm1d); } // now gather the actual vector std::vector<std::vector<int>> recvdsp_ind(arrinfo.indarrs.size()); std::vector<std::vector<int>> recvdsp_num(arrinfo.numarrs.size()); std::vector<std::vector<IT>> recvind(arrinfo.indarrs.size()); std::vector<std::vector<IT>> recvnum(arrinfo.numarrs.size()); for(unsigned int i=0; i< arrinfo.indarrs.size(); ++i) // get index arrays { recvdsp_ind[i].resize(nprocs); recvdsp_ind[i][0] = 0; for(int j=1; j<nprocs; j++) recvdsp_ind[i][j] = recvdsp_ind[i][j-1] + recvcnt_ind[i][j-1]; recvind[i].resize(recvdsp_ind[i][nprocs-1] + recvcnt_ind[i][nprocs-1]); MPI_Gatherv(arrinfo.indarrs[i].addr, arrinfo.indarrs[i].count, MPIType<IT>(), recvind[i].data(),recvcnt_ind[i].data(), recvdsp_ind[i].data(), MPIType<IT>(), root, comm1d); } for(unsigned int i=0; i< arrinfo.numarrs.size(); ++i) // gather num arrays { recvdsp_num[i].resize(nprocs); recvdsp_num[i][0] = 0; for(int j=1; j<nprocs; j++) recvdsp_num[i][j] = recvdsp_num[i][j-1] + recvcnt_num[i][j-1]; recvnum[i].resize(recvdsp_num[i][nprocs-1] + recvcnt_num[i][nprocs-1]); MPI_Gatherv(arrinfo.numarrs[i].addr, arrinfo.numarrs[i].count, MPIType<NT>(), recvnum[i].data(),recvcnt_num[i].data(), recvdsp_num[i].data(), MPIType<NT>(), root, comm1d); } } template <class IT, class NT, class DER> void SpParHelper::SetWindows(MPI_Comm & comm1d, const SpMat< IT,NT,DER > & Matrix, std::vector<MPI_Win> & arrwin) { Arr<IT,NT> arrs = Matrix.GetArrays(); // static MPI::Win MPI::Win::create(const void *base, MPI::Aint size, int disp_unit, MPI::Info info, const MPI_Comm & comm); // The displacement unit argument is provided to facilitate address arithmetic in RMA operations // *** COLLECTIVE OPERATION ***, everybody exposes its own array to everyone else in the communicator for(int i=0; i< arrs.indarrs.size(); ++i) { MPI_Win nWin; MPI_Win_create(arrs.indarrs[i].addr, arrs.indarrs[i].count * sizeof(IT), sizeof(IT), MPI_INFO_NULL, comm1d, &nWin); arrwin.push_back(nWin); } for(int i=0; i< arrs.numarrs.size(); ++i) { MPI_Win nWin; MPI_Win_create(arrs.numarrs[i].addr, arrs.numarrs[i].count * sizeof(NT), sizeof(NT), MPI_INFO_NULL, comm1d, &nWin); arrwin.push_back(nWin); } } inline void SpParHelper::LockWindows(int ownind, std::vector<MPI_Win> & arrwin) { for(std::vector<MPI_Win>::iterator itr = arrwin.begin(); itr != arrwin.end(); ++itr) { MPI_Win_lock(MPI_LOCK_SHARED, ownind, 0, *itr); } } inline void SpParHelper::UnlockWindows(int ownind, std::vector<MPI_Win> & arrwin) { for(std::vector<MPI_Win>::iterator itr = arrwin.begin(); itr != arrwin.end(); ++itr) { MPI_Win_unlock( ownind, *itr); } } /** * @param[in] owner {target processor rank within the processor group} * @param[in] arrwin {start access epoch only to owner's arrwin (-windows) } */ inline void SpParHelper::StartAccessEpoch(int owner, std::vector<MPI_Win> & arrwin, MPI_Group & group) { /* Now start using the whole comm as a group */ int acc_ranks[1]; acc_ranks[0] = owner; MPI_Group access; MPI_Group_incl(group, 1, acc_ranks, &access); // take only the owner // begin the ACCESS epochs for the arrays of the remote matrices A and B // Start() *may* block until all processes in the target group have entered their exposure epoch for(unsigned int i=0; i< arrwin.size(); ++i) MPI_Win_start(access, 0, arrwin[i]); MPI_Group_free(&access); } /** * @param[in] self {rank of "this" processor to be excluded when starting the exposure epoch} */ inline void SpParHelper::PostExposureEpoch(int self, std::vector<MPI_Win> & arrwin, MPI_Group & group) { // begin the EXPOSURE epochs for the arrays of the local matrices A and B for(unsigned int i=0; i< arrwin.size(); ++i) MPI_Win_post(group, MPI_MODE_NOPUT, arrwin[i]); } template <class IT, class DER> void SpParHelper::AccessNFetch(DER * & Matrix, int owner, std::vector<MPI_Win> & arrwin, MPI_Group & group, IT ** sizes) { StartAccessEpoch(owner, arrwin, group); // start the access epoch to arrwin of owner std::vector<IT> ess(DER::esscount); // pack essentials to a vector for(int j=0; j< DER::esscount; ++j) ess[j] = sizes[j][owner]; Matrix = new DER(); // create the object first FetchMatrix(*Matrix, ess, arrwin, owner); // then start fetching its elements } template <class IT, class DER> void SpParHelper::LockNFetch(DER * & Matrix, int owner, std::vector<MPI_Win> & arrwin, MPI_Group & group, IT ** sizes) { LockWindows(owner, arrwin); std::vector<IT> ess(DER::esscount); // pack essentials to a vector for(int j=0; j< DER::esscount; ++j) ess[j] = sizes[j][owner]; Matrix = new DER(); // create the object first FetchMatrix(*Matrix, ess, arrwin, owner); // then start fetching its elements } /** * @param[in] sizes 2D array where * sizes[i] is an array of size r/s representing the ith essential component of all local blocks within that row/col * sizes[i][j] is the size of the ith essential component of the jth local block within this row/col */ template <class IT, class NT, class DER> void SpParHelper::GetSetSizes(const SpMat<IT,NT,DER> & Matrix, IT ** & sizes, MPI_Comm & comm1d) { std::vector<IT> essentials = Matrix.GetEssentials(); int index; MPI_Comm_rank(comm1d, &index); for(IT i=0; (unsigned)i < essentials.size(); ++i) { sizes[i][index] = essentials[i]; MPI_Allgather(MPI_IN_PLACE, 1, MPIType<IT>(), sizes[i], 1, MPIType<IT>(), comm1d); } } inline void SpParHelper::PrintFile(const std::string & s, const std::string & filename) { int myrank; MPI_Comm_rank(MPI_COMM_WORLD, &myrank); if(myrank == 0) { std::ofstream out(filename.c_str(), std::ofstream::app); out << s; out.close(); } } inline void SpParHelper::PrintFile(const std::string & s, const std::string & filename, MPI_Comm & world) { int myrank; MPI_Comm_rank(world, &myrank); if(myrank == 0) { std::ofstream out(filename.c_str(), std::ofstream::app); out << s; out.close(); } } inline void SpParHelper::Print(const std::string & s) { int myrank; MPI_Comm_rank(MPI_COMM_WORLD, &myrank); if(myrank == 0) { std::cerr << s; } } inline void SpParHelper::Print(const std::string & s, MPI_Comm & world) { int myrank; MPI_Comm_rank(world, &myrank); if(myrank == 0) { std::cerr << s; } } inline void SpParHelper::check_newline(int *bytes_read, int bytes_requested, char *buf) { if ((*bytes_read) < bytes_requested) { // fewer bytes than expected, this means EOF if (buf[(*bytes_read) - 1] != '\n') { // doesn't terminate with a newline, add one to prevent infinite loop later buf[(*bytes_read) - 1] = '\n'; std::cout << "Error in Matrix Market format, appending missing newline at end of file" << std::endl; (*bytes_read)++; } } } inline bool SpParHelper::FetchBatch(MPI_File & infile, MPI_Offset & curpos, MPI_Offset end_fpos, bool firstcall, std::vector<std::string> & lines, int myrank) { size_t bytes2fetch = ONEMILLION; // we might read more than needed but no problem as we won't process them MPI_Status status; int bytes_read; if(firstcall && myrank != 0) { curpos -= 1; // first byte is to check whether we started at the beginning of a line bytes2fetch += 1; } char * buf = new char[bytes2fetch]; // needs to happen **after** bytes2fetch is updated char * originalbuf = buf; // so that we can delete it later because "buf" will move MPI_File_read_at(infile, curpos, buf, bytes2fetch, MPI_CHAR, &status); MPI_Get_count(&status, MPI_CHAR, &bytes_read); // MPI_Get_Count can only return 32-bit integers if(!bytes_read) { delete [] originalbuf; return true; // done } SpParHelper::check_newline(&bytes_read, bytes2fetch, buf); if(firstcall && myrank != 0) { if(buf[0] == '\n') // we got super lucky and hit the line break { buf += 1; bytes_read -= 1; curpos += 1; } else // skip to the next line and let the preceeding processor take care of this partial line { char *c = (char*)memchr(buf, '\n', MAXLINELENGTH); // return a pointer to the matching byte or NULL if the character does not occur if (c == NULL) { std::cout << "Unexpected line without a break" << std::endl; } int n = c - buf + 1; bytes_read -= n; buf += n; curpos += n; } } while(bytes_read > 0 && curpos < end_fpos) // this will also finish the last line { char *c = (char*)memchr(buf, '\n', bytes_read); // return a pointer to the matching byte or NULL if the character does not occur if (c == NULL) { delete [] originalbuf; return false; // if bytes_read stops in the middle of a line, that line will be re-read next time since curpos has not been moved forward yet } int n = c - buf + 1; // string constructor from char * buffer: copies the first n characters from the array of characters pointed by s lines.push_back(std::string(buf, n-1)); // no need to copy the newline character bytes_read -= n; // reduce remaining bytes buf += n; // move forward the buffer curpos += n; } delete [] originalbuf; if (curpos >= end_fpos) return true; // don't call it again, nothing left to read else return false; } inline void SpParHelper::WaitNFree(std::vector<MPI_Win> & arrwin) { // End the exposure epochs for the arrays of the local matrices A and B // The Wait() call matches calls to Complete() issued by ** EACH OF THE ORIGIN PROCESSES ** // that were granted access to the window during this epoch. for(unsigned int i=0; i< arrwin.size(); ++i) { MPI_Win_wait(arrwin[i]); } FreeWindows(arrwin); } inline void SpParHelper::FreeWindows(std::vector<MPI_Win> & arrwin) { for(unsigned int i=0; i< arrwin.size(); ++i) { MPI_Win_free(&arrwin[i]); } } }
37.245283
222
0.655691
[ "object", "vector" ]
35f832161eb6cff169f8eed4b160a322cfc4b6f3
1,432
hxx
C++
src/Options.hxx
casavi/potoo
f40fc04624726907b32ff33e357ad14015c99778
[ "MIT" ]
5
2016-07-08T09:49:43.000Z
2020-03-28T23:32:17.000Z
src/Options.hxx
casavi/potoo
f40fc04624726907b32ff33e357ad14015c99778
[ "MIT" ]
1
2017-08-03T17:48:02.000Z
2020-05-06T07:57:23.000Z
src/Options.hxx
casavi/potoo
f40fc04624726907b32ff33e357ad14015c99778
[ "MIT" ]
3
2016-10-13T08:27:38.000Z
2019-05-14T13:38:47.000Z
#ifndef CONVERTER_OPTIONS_HXX #define CONVERTER_OPTIONS_HXX #include <vector> #include <string> #include <memory> #include <boost/optional.hpp> /** * Helper struct for all options included in the supplied config file. */ struct Options { /** * One set of crop settings: * - type: the type of the area, any string * - x: x-coordinate in percent * - y: y-coordinate in percent * - w: width in percent * - h: height in percent */ struct Crop { Crop(const std::string &type_, float x_, float y_, float w_, float h_) : type(type_), x(x_), y(y_), w(w_), h(h_) {} std::string type; float x; float y; float w; float h; }; Options(const std::string &inputPDF, int dpi, bool parallel_processing, std::string language, bool force_ocr) : _inputPDF(inputPDF), _dpi(dpi), _parallel_processing(parallel_processing), _language(language), _force_ocr(force_ocr) {} void addCrop(Crop crop) { _crops.push_back(crop); } std::vector<Crop> _crops; std::string _inputPDF; int _dpi; bool _parallel_processing; std::string _language; bool _force_ocr; boost::optional<int> _start; boost::optional<int> _end; boost::optional<int> _page; }; std::shared_ptr<Options> read_config(const std::string &path); #endif //CONVERTER_OPTIONS_HXX
23.866667
78
0.62081
[ "vector" ]
35fd93ec3d95c1bc7f2ab1b1d895e4ba47e21e85
348
hpp
C++
sources/_headers_std.hpp
unvrtool/unvrtool
1f9601f1b3f7db16244cec6064e648a3df45d2f6
[ "BSD-3-Clause" ]
null
null
null
sources/_headers_std.hpp
unvrtool/unvrtool
1f9601f1b3f7db16244cec6064e648a3df45d2f6
[ "BSD-3-Clause" ]
null
null
null
sources/_headers_std.hpp
unvrtool/unvrtool
1f9601f1b3f7db16244cec6064e648a3df45d2f6
[ "BSD-3-Clause" ]
null
null
null
// // Copyright (c) 2020, Jan Ove Haaland, all rights reserved. // // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. #pragma once #include <vector> #include <string> #include <fstream> #include <sstream> #include <iostream> #include <filesystem> #include <chrono>
21.75
72
0.732759
[ "vector" ]
c40258d61462e45ae82e1941c16ccab43830431f
2,028
hpp
C++
boost/geometry/extensions/strategies/buffer.hpp
ballisticwhisper/boost
f72119ab640b564c4b983bd457457046b52af9ee
[ "BSL-1.0" ]
2
2015-01-02T14:24:56.000Z
2015-01-02T14:25:17.000Z
boost/geometry/extensions/strategies/buffer.hpp
ballisticwhisper/boost
f72119ab640b564c4b983bd457457046b52af9ee
[ "BSL-1.0" ]
2
2019-01-13T23:45:51.000Z
2019-02-03T08:13:26.000Z
boost/geometry/extensions/strategies/buffer.hpp
ballisticwhisper/boost
f72119ab640b564c4b983bd457457046b52af9ee
[ "BSL-1.0" ]
1
2016-05-29T13:41:15.000Z
2016-05-29T13:41:15.000Z
// Boost.Geometry (aka GGL, Generic Geometry Library) // Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands. // Copyright (c) 2008-2012 Bruno Lalande, Paris, France. // Copyright (c) 2009-2012 Mateusz Loskot, London, UK. // Parts of Boost.Geometry are redesigned from Geodan's Geographic Library // (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands. // Use, modification and distribution is subject to 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_GEOMETRY_EXTENSIONS_STRATEGIES_BUFFER_HPP #define BOOST_GEOMETRY_EXTENSIONS_STRATEGIES_BUFFER_HPP // Buffer strategies #include <boost/geometry/extensions/strategies/buffer_side.hpp> #include <boost/geometry/extensions/strategies/buffer_join_miter.hpp> #include <boost/geometry/extensions/strategies/buffer_join_round.hpp> #include <boost/geometry/extensions/strategies/buffer_join_round_by_divide.hpp> #include <boost/geometry/extensions/strategies/buffer_distance_symmetric.hpp> #include <boost/geometry/extensions/strategies/buffer_distance_asymmetric.hpp> namespace boost { namespace geometry { namespace strategy { namespace buffer { /* A Buffer-join strategy gets 4 input points. On the two consecutive segments s1 and s2 (joining at vertex v): The lines from parallel at s1, s2 (at buffer-distance) end/start in two points perpendicular to the segments: p1 and p2. These parallel lines interesct in point ip (s2) | | ^ | (p2) |(v) * +----<--- (s1) x(ip) *(p1) So, in clockwise order: v : vertex point p1: perpendicular on left side of segment1<1> (perp1) ip: intersection point p2: perpendicular on left side of segment2<0> (perp2) */ }} // namespace strategy::buffer }} // namespace boost::geometry #endif // BOOST_GEOMETRY_EXTENSIONS_STRATEGIES_BUFFER_HPP
28.971429
79
0.717949
[ "geometry" ]
c4040d9ac1c0e721e90bbc40ca6c6bf95916b3fc
592
cpp
C++
Il2Native.Logic/NativeImplementations/System.Private.CoreLib/System/Runtime/Serialization/FormatterServices.cpp
Vinay1705/cs2cpp
d07d3206fb57edb959df8536562909a4d516e359
[ "MIT" ]
192
2016-03-23T04:33:24.000Z
2022-03-28T14:41:06.000Z
Il2Native.Logic/NativeImplementations/System.Private.CoreLib/System/Runtime/Serialization/FormatterServices.cpp
Vinay1705/cs2cpp
d07d3206fb57edb959df8536562909a4d516e359
[ "MIT" ]
9
2017-03-08T14:45:16.000Z
2021-09-06T09:28:47.000Z
Il2Native.Logic/NativeImplementations/System.Private.CoreLib/System/Runtime/Serialization/FormatterServices.cpp
Vinay1705/cs2cpp
d07d3206fb57edb959df8536562909a4d516e359
[ "MIT" ]
56
2016-03-22T20:37:08.000Z
2022-03-28T12:20:47.000Z
#include "System.Private.CoreLib.h" namespace CoreLib { namespace System { namespace Runtime { namespace Serialization { namespace _ = ::CoreLib::System::Runtime::Serialization; // Method : System.Runtime.Serialization.FormatterServices.nativeGetUninitializedObject(System.RuntimeType) object* FormatterServices::nativeGetUninitializedObject(::CoreLib::System::RuntimeType* type) { throw 3221274624U; } }}}} namespace CoreLib { namespace System { namespace Runtime { namespace Serialization { namespace _ = ::CoreLib::System::Runtime::Serialization; }}}}
37
111
0.744932
[ "object" ]
c4077bdc756e78a941ee6dd5048f37437acd8268
20,716
cpp
C++
read_WDS_catalog.cpp
jlprieur/Pisco1
7dc54ab240b1c353cc14ba578b2fce3113216832
[ "MIT" ]
null
null
null
read_WDS_catalog.cpp
jlprieur/Pisco1
7dc54ab240b1c353cc14ba578b2fce3113216832
[ "MIT" ]
null
null
null
read_WDS_catalog.cpp
jlprieur/Pisco1
7dc54ab240b1c353cc14ba578b2fce3113216832
[ "MIT" ]
null
null
null
/************************************************************************ * "raed_WDS_catalog.c" * To retrieve data from the WDS catalog * * JLP * Version 20/11/2009 *************************************************************************/ #include <stdio.h> #include <stdlib.h> /* exit() */ #include <string.h> #include <ctype.h> /* isprint... */ #include <math.h> #include <time.h> /* date */ #include "psc1_defs.h" // Binary_Parameters ... #include "jlp_string.h" // jlp_compact_string,... #include "read_WDS_catalog.h" /* Prototypes of the routines defined here */ #define ABS(a) ((a) < 0.0 ? (-(a)) : (a)) #ifndef PI #define PI 3.14159265 #endif #define DEGTORAD (PI/180.00) /* #define DEBUG #define DEBUG_1 */ /* Defined here: int search_discov_name_in_WDS_catalog(char *WDS_catalog, char *discov_name, char *WDS_name, int *found); int get_data_from_WDS_catalog(char *WDS_catalog, char *discov_name, char *WDS_name, double *WY, double *WR, double *WT, int *found); int read_coordinates_from_WDS_catalog(char *WDS_name, char *WDS_catalog, float *alpha, float *delta, float *equinox, int *found); */ static int WDS_name_to_coordinates(char *WDS_name0, double *alpha0, double *delta0, char *err_message); static int read_WDS_precise_coordinates(char *cat_line0, double *alpha0, double *delta0, char *err_message); /************************************************************************* * Format of WDS catalog (version of 2009-2012): * COLUMN Format DATA -------- ------ ---------------------------- 1 - 10 A10 2000 Coordinates 11 - 17 A7 Discoverer & Number 18 - 22 A5 Components 24 - 27 I4 Date (first) 29 - 32 I4 Date (last) 34 - 37 I4 Number of Observations (up to 9999) 39 - 41 I3 Position Angle (first - XXX) 43 - 45 I3 Position Angle (last - XXX) 47 - 51 F5.1 Separation (first) 53 - 57 F5.1 Separation (last) 59 - 63 F5.2 Magnitude of First Component 65 - 69 F5.2 Magnitude of Second Component 71 - 79 A9 Spectral Type (Primary/Secondary) 81 - 84 I4 Primary Proper Motion (RA) 85 - 88 I4 Primary Proper Motion (Dec) 90 - 93 I4 Secondary Proper Motion (RA) 94 - 97 I4 Secondary Proper Motion (Dec) 99 - 106 A8 Durchmusterung Number 108 - 111 A4 Notes 113 - 130 A18 2000 arcsecond coordinates * * INPUT: * WDS_catalog: name of the WDS catalog * discov_name: discoverer's name of the object to be searched for * * OUTPUT: * WDS_name: WDS name corresponding to discov_name * found: 1 is object was found, 0 otherwise *************************************************************************/ int search_discov_name_in_WDS_catalog(char *WDS_catalog, char *discov_name2, char *comp_name2, char *WDS_name2, double *alpha2, double *delta2, int *found, char *err_message) { FILE *fp_WDS_cat; char cat_line0[256], discov_name0[20], comp_name0[20], WDS_name0[20]; char discov_name1[20], comp_name1[20], buff1[128]; int iline, status; WDS_name2[0] = '\0'; *alpha2 = 0.; *delta2 = 0.; // Removes all the blanks strncpy(discov_name1, discov_name2, 20); jlp_compact_string(discov_name1, 20); strncpy(comp_name1, comp_name2, 20); jlp_compact_string(comp_name1, 20); if(comp_name1[0] == '\0') strcpy(comp_name1, "AB"); /* Open input file containing the WDS catalog */ if((fp_WDS_cat = fopen(WDS_catalog, "r")) == NULL) { sprintf(err_message, "search_discov_name_in_WDS_catalog/Fatal error opening WDS catalog: %s\n", WDS_catalog); return(-1); } /* Look for the data concerning this object: */ *found = 0; iline = 0; while(!feof(fp_WDS_cat)) { if(fgets(cat_line0, 256, fp_WDS_cat)) { iline++; if(cat_line0[0] != '%') { /* 1 - 10 A10 2000 Coordinates 11 - 17 A7 Discoverer & Number 18 - 22 A5 Components */ strncpy(WDS_name0, &cat_line0[0], 10); WDS_name0[10] = '\0'; /* 7 characters for WDS, 8 characters for Marco's file */ strncpy(discov_name0, &cat_line0[10], 7); discov_name0[7] = '\0'; jlp_compact_string(discov_name0, 20); strncpy(comp_name0, &cat_line0[17], 5); comp_name0[5] = '\0'; jlp_compact_string(comp_name0, 20); if(comp_name0[0] == '\0') strcpy(comp_name0, "AB"); /* DEBUG { wxString buff; buff.Printf(wxT("iline=%d name=%s (%s) comp=%s (%s)"), iline, discov_name1, discov_name0, comp_name1, comp_name0); wxMessageBox(buff, wxT("ZZZFIND"), wxOK); if(iline >= 8)return(-1); } */ // Check first if discoverer is the same: if(!strcmp(discov_name1, discov_name0)) { // Then check if companion is the same: if(!strcmp(comp_name0, comp_name1)) { #ifdef DEBUG_1 printf("Object found in WDS catalog (discov_name =%s)\n", discov_name); printf(" WDS=%s discov=%s comp=%s\n", WDS_name0, discov_name0, comp_name0); #endif strcpy(WDS_name2, WDS_name0); *found = 1; status = read_WDS_precise_coordinates(cat_line0, alpha2, delta2, buff1); if(status) WDS_name_to_coordinates(WDS_name0, alpha2, delta2, buff1); break; } /// comp_name is OK } // discov_name is OK } /* EOF cat_line[0] != '%' */ } /* EOF fgets... */ } /* EOF while */ fclose(fp_WDS_cat); return(0); } /************************************************************************* * Search in the WDS catalog * * Format of WDS catalog (version of 2009-2012): * COLUMN Format DATA -------- ------ ---------------------------- 1 - 10 A10 2000 Coordinates 11 - 17 A7 Discoverer & Number 18 - 22 A5 Components 24 - 27 I4 Date (first) 29 - 32 I4 Date (last) 34 - 37 I4 Number of Observations (up to 9999) 39 - 41 I3 Position Angle (first - XXX) 43 - 45 I3 Position Angle (last - XXX) 47 - 51 F5.1 Separation (first) 53 - 57 F5.1 Separation (last) 59 - 63 F5.2 Magnitude of First Component 65 - 69 F5.2 Magnitude of Second Component 71 - 79 A9 Spectral Type (Primary/Secondary) 81 - 84 I4 Primary Proper Motion (RA) 85 - 88 I4 Primary Proper Motion (Dec) 90 - 93 I4 Secondary Proper Motion (RA) 94 - 97 I4 Secondary Proper Motion (Dec) 99 - 106 A8 Durchmusterung Number 108 - 111 A4 Notes 113 - 130 A18 2000 arcsecond coordinates * * * INPUT: * WDS_catalog: name of the WDS catalog * bpr1: containing alpha_min, alpha_max, delta_min, delta_max, etc * * OUTPUT: * WDS_name: WDS name corresponding to discov_name * bpa1: containing parameters of the object found: * discov_name: discoverer's name * WY, WR, WT: year, rho, theta of the last observation reported in the WDS * found: 1 is an object was found, 0 otherwise ***********************************************************************/ int search_in_WDS_catalog(char *WDS_catalog, Binary_Profile bpr1, Binary_Parameters *bpa1, int *found, const bool search_all_and_save, char *save_fname, char *err_message) { FILE *fp_WDS_cat, *fp_save; char cat_line0[256], discov_name0[20], comp_name0[20], WDS_name0[20]; char cvalue[64], buff1[256]; int iline, ivalue; double alpha0, alpha_min, alpha_max, delta0, delta_min, delta_max; double dvalue; int status; bpa1->WDS_name = wxT(""); bpa1->Companion_name = wxT(""); bpa1->Discover_name = wxT(""); bpa1->epoch = 0.; bpa1->rho = 0.; bpa1->theta = 0.; bpa1->alpha = 0.; bpa1->delta = 0.; bpa1->mag = -1.; bpa1->dmag = -1.; // Open input file containing the WDS catalog if((fp_WDS_cat = fopen(WDS_catalog, "r")) == NULL) { fprintf(stderr, "get_data_from_WDS_catalog/Fatal error opening WDS catalog: %s\n", WDS_catalog); return(-1); } // Open output file with the found selection if(search_all_and_save) { if((fp_save = fopen(save_fname, "w")) == NULL) { fprintf(stderr, "get_data_from_WDS_catalog/Fatal error opening output file: %s\n", save_fname); return(-1); } } // Look for the data concerning this object: *found = 0; iline = 0; while(!feof(fp_WDS_cat)) { if(fgets(cat_line0, 256, fp_WDS_cat)) { iline++; if(cat_line0[0] != '%') { /* 1 - 10 A10 2000 Coordinates 11 - 17 A7 Discoverer & Number 18 - 22 A5 Components Columns 1- 10: The hours, minutes, and tenths of minutes of Right Ascension for 2000, followed by the degrees and minutes of Declination for 2000, with + and - indicating north and south declinations. The positions given represent our best estimates of these values. Where possible, these are based on the ACRS and PPM data, with proper motion incorporated. 0123456789 hhmmn+ddmm 12345+1234 */ strncpy(WDS_name0, &cat_line0[0], 10); WDS_name0[10] = '\0'; // WDS name: bpa1->WDS_name = wxString(WDS_name0); status = WDS_name_to_coordinates(WDS_name0, &alpha0, &delta0, err_message); // Save coordinates (temporarily, since they may be improved later...) bpa1->alpha = alpha0; bpa1->delta = delta0; alpha_min = bpr1.alpha_min; alpha_max = alpha_min + bpr1.alpha_range; delta_min = bpr1.delta_min; delta_max = bpr1.delta_max; // DEBUG: /* { wxString buffer; buffer.Printf(wxT("iline=%d WDS=%s alpha0=%.1f alpha_min=%.1f alpha_max=%.1f\n\ delta0=%.1f delta_min=%.1f delta_max=%.1f\n\ rho=%.1f rho_min=%.1f rho_max=%.1f mag=%.1f mag_min=%.1f mag_max=%.1f"), iline, WDS_name0, alpha0, alpha_min, alpha_max, delta0, delta_min, delta_max, bpa1->rho, bpr1.rho_min, bpr1.rho_max, bpa1->mag, bpr1.mag_min, bpr1.mag_max); wxMessageBox(buffer, bpa1->WDS_name, wxOK); if(iline >= 7) return(-1); } */ // First selection with the raw coordinates: if((alpha0 > alpha_min) && (alpha0 <= alpha_max) && (delta0 > delta_min) && (delta0 <= delta_max)) { // Discoverer's name: strncpy(discov_name0, &cat_line0[10], 7); discov_name0[7] = '\0'; bpa1->Discover_name = wxString(discov_name0); // Companion name strncpy(comp_name0, &cat_line0[17], 5); comp_name0[5] = '\0'; bpa1->Companion_name = wxString(comp_name0); /* Read WY, WR, WT: 24 - 27 I4 Date (first) 29 - 32 I4 Date (last) 34 - 37 I4 Number of Observations (up to 9999) 39 - 41 I3 Position Angle (first - XXX) 43 - 45 I3 Position Angle (last - XXX) 47 - 51 F5.1 Separation (first) 53 - 57 F5.1 Separation (last) */ // (last) year strncpy(cvalue, &cat_line0[28], 4); cvalue[4] = '\0'; if(sscanf(cvalue, "%d", &ivalue) == 1) bpa1->epoch = (double)ivalue; // (last) theta strncpy(cvalue, &cat_line0[42], 3); cvalue[3] = '\0'; if(sscanf(cvalue, "%d", &ivalue) == 1) bpa1->theta = (double)ivalue; // (last) rho strncpy(cvalue, &cat_line0[52], 5); cvalue[5] = '\0'; if(sscanf(cvalue, "%lf", &dvalue) == 1) bpa1->rho = (double)dvalue; /* 59 - 63 F5.2 Magnitude of First Component 65 - 69 F5.2 Magnitude of Second Component 71 - 79 A9 Spectral Type (Primary/Secondary) */ strncpy(cvalue, &cat_line0[58], 5); cvalue[5] = '\0'; if(sscanf(cvalue, "%lf", &dvalue) == 1) bpa1->mag = (double)dvalue; else wxMessageBox(wxString(cvalue), wxT("WDS catalog/Error reading magnitude"), wxOK); strncpy(cvalue, &cat_line0[64], 5); cvalue[5] = '\0'; if(sscanf(cvalue, "%lf", &dvalue) == 1) bpa1->dmag = (double)dvalue - bpa1->mag; // Object is found when the last (following) criteria are verified: if((bpa1->rho >= bpr1.rho_min) && (bpa1->rho <= bpr1.rho_max) && (bpa1->mag >= bpr1.mag_min) && (bpa1->mag <= bpr1.mag_max)) { status = read_WDS_precise_coordinates(cat_line0, &alpha0, &delta0, buff1); if(status) { sprintf(err_message, " %s of WDS%s in line%d\n", buff1, WDS_name0, iline); } else { bpa1->alpha = alpha0; bpa1->delta = delta0; } // Second criterium (to allow NEXT to work): // Last selection with the precise coordinates: if((alpha0 > alpha_min) && (alpha0 <= alpha_max) && (delta0 > delta_min) && (delta0 <= delta_max)) { // wxMessageBox(wxT("OK: found!"), bpa1->WDS_name, wxOK); *found = 1; if(search_all_and_save){ fprintf(fp_save, "%s", cat_line0); } else { break; } } } // EOF mag_min <= mag <= mag_max } // EOF alpha_min <= alpha <= alpha_max } // EOF not a commented line starting with '%' } // EOF fgets... } // EOF while fclose(fp_WDS_cat); if(search_all_and_save) fclose(fp_save); return(0); } /*********************************************************************** * Look for raw coordinates in WDS catalog * Columns 1- 10: The hours, minutes, and tenths of minutes of Right Ascension for 2000, followed by the degrees and minutes of Declination for 2000, with + and - indicating north and south declinations. The positions given represent our best estimates of these values. Where possible, these are based on the ACRS and PPM data, with proper motion incorporated. * Example: 06019+6052 in 1-10 *********************************************************************************/ static int WDS_name_to_coordinates(char *WDS_name0, double *alpha0, double *delta0, char *err_message) { char sign[1]; int status = -1, hh, htm, dd, dm; if(sscanf(WDS_name0, "%02d%03d%c%02d%02d", &hh, &htm, sign, &dd, &dm) == 5) { *alpha0 = (double)hh + ((double)htm)/600.; *delta0 = (double)dd + ((double)dm)/60.; if(sign[0] == '-') *delta0 *= -1.; status = 0; } else { sprintf(err_message,"read_WDS_precise_coordinates/Error reading >%s<", WDS_name0); } return(status); } /*********************************************************************** * Look for accurate coordinates in WDS catalog * Columns 1- 10: The hours, minutes, and tenths of minutes of Right Ascension for 2000, followed by the degrees and minutes of Declination for 2000, with + and - indicating north and south declinations. The positions given represent our best estimates of these values. Where possible, these are based on the ACRS and PPM data, with proper motion incorporated. Columns 113-130: The hours, minutes, seconds and tenths of seconds (when known) of Right Ascension for equinox=2000, followed by the degrees, minutes, and seconds of Declination for 2000, with + and - indicating north and south declinations. The positions given represent our best estimates of these values. Where possible, these are based on the Hipparcos and Tycho data, with proper motion incorporated. While the arcminute coordinate (columns 1-10) refer to the primary of a multiple system, the arcsecond coordinate (columns 113-130) refer to the primary of the subsystem. For example, while the BC pair of an A-BC multiple will have the same 10 digit WDS coordinate, the arcsecond coordinate of the BC pair will be at the "B" position. * Example: 06019+6052 in 1-10 060156.93+605244.8 in 113-130 *********************************************************************************/ static int read_WDS_precise_coordinates(char *cat_line0, double *alpha0, double *delta0, char *err_message) { char cvalue[64], sign[1]; int status = -1, hh, hm, hs, hss, dd, dm, ds, dss; /* 113 - 130 A18 2000 precise coordinates Example: 060156.93+605244.8 in 113-130 */ strncpy(cvalue, &cat_line0[112], 18); cvalue[18] = '\0'; if(sscanf(cvalue, "%02d%02d%02d.%02d%c%02d%02d%02d.%d", &hh, &hm, &hs, &hss, sign, &dd, &dm, &ds, &dss) == 9) { *alpha0 = (double)hh + ((double)hm)/60. + ((double)hs + (double)hss/10.)/3600.; *delta0 = (double)dd + ((double)dm)/60. + ((double)ds + (double)dss/10.)/3600.; if(sign[0] == '-') *delta0 *= -1.; status = 0; } else { sprintf(err_message,"read_WDS_precise_coordinates/Error reading >%s<", cvalue); } return(status); } /************************************************************************ * Conversion of WDS name to ADS (if possible) * * INPUT: * WDS_name1, Discov_name1: WDS name * ADS_WDS_cross: name of the ADS/WDS cross-reference file * * OUTPUT: * ADS_name1: ADS name **************************************************************************/ int WDS_to_ADS_name(char *WDS_name2, char *Discov_name2, char *ADS_name2, char *ADS_WDS_cross, int *found, char *err_message) { char in_line[80], ADS_name0[20], WDS_name0[20], discov_name0[20]; char WDS_name1[20], Discov_name1[20]; int iline, status = -1; FILE *fp_ADS_WDS_cross; register int i; strcpy(Discov_name1, Discov_name2); jlp_compact_string(Discov_name1, 20); strcpy(WDS_name1, WDS_name2); jlp_compact_string(WDS_name1, 20); strcpy(ADS_name2, ""); *found = 0; /* Open input file containing the ADS_WDS cross-references */ if((fp_ADS_WDS_cross = fopen(ADS_WDS_cross, "r")) == NULL) { sprintf(err_message, "WDS_to_ADS_name/Error opening ADS-WDS cross-ref.: %s\n", ADS_WDS_cross); return(-1); } /* Scan the cross-reference file: */ /* Syntax: BDS ADS Discovr Comp WDS Omit? 13663 17158 A 1248 00000+7530 12704 1 STF3053 AB 00026+6606 13664 17180 BGH 1 AB-C 00024+1047 ADS numbers in fields 11 to 15 Discov names in fields 21 to 27 Components in fields 30 to 36 WDS numbers in fields 39 to 48 (NB: C arrays start at 0, hence should remove one from field numbers) */ iline = 0; while(!feof(fp_ADS_WDS_cross)) { if(fgets(in_line, 120, fp_ADS_WDS_cross)) { iline++; if(in_line[0] != '%') { // ADS name: for(i = 0; i < 6; i++) ADS_name0[i] = in_line[10+i]; ADS_name0[6] = '\0'; jlp_trim_string(ADS_name0, 20); // Discoverer: for(i = 0; i < 7; i++) discov_name0[i] = in_line[20+i]; discov_name0[7] = '\0'; jlp_compact_string(discov_name0, 20); // WDS name: for(i = 0; i < 10; i++) WDS_name0[i] = in_line[38+i]; WDS_name0[10] = '\0'; // DEBUG: /* { wxString buff; buff.Printf(wxT("ADS=%s WDS=%s (%s) Disc=%s (%s)"), ADS_name0, WDS_name1, WDS_name0, Discov_name1, discov_name0); if(iline > 7 && iline < 11) wxMessageBox(buff, wxT("ZZZ"), wxOK); } */ // Break from loop when found: if(!strcmp(WDS_name1, WDS_name0) && !strcmp(Discov_name1, discov_name0)) { strcpy(ADS_name2, ADS_name0); *found = 1; break; } } /* EOF inline[0] == '%" */ } /* EOF fgets */ } /* EOF while */ /* Close cross-reference file */ fclose(fp_ADS_WDS_cross); return(0); }
36.730496
99
0.547982
[ "object" ]
c40d359d76eb173f137948dea65a5ee17f2e8fa9
3,142
hpp
C++
Runtime/World/CScriptPlayerActor.hpp
henriquegemignani/urde
78185e682e16c3e1b41294d92f2841357272acb2
[ "MIT" ]
1
2020-06-09T07:49:34.000Z
2020-06-09T07:49:34.000Z
Runtime/World/CScriptPlayerActor.hpp
henriquegemignani/urde
78185e682e16c3e1b41294d92f2841357272acb2
[ "MIT" ]
6
2020-06-09T07:49:45.000Z
2021-04-06T22:19:57.000Z
Runtime/World/CScriptPlayerActor.hpp
henriquegemignani/urde
78185e682e16c3e1b41294d92f2841357272acb2
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include <string_view> #include "Runtime/CPlayerState.hpp" #include "Runtime/RetroTypes.hpp" #include "Runtime/World/CScriptActor.hpp" namespace urde { class CScriptPlayerActor : public CScriptActor { CAnimRes x2e8_suitRes; CPlayerState::EBeamId x304_beam; CPlayerState::EPlayerSuit x308_suit = CPlayerState::EPlayerSuit::Invalid; CPlayerState::EBeamId x30c_setBeamId = CPlayerState::EBeamId::Invalid; s32 x310_loadedCharIdx = -1; std::unique_ptr<CModelData> x314_beamModelData; std::unique_ptr<CModelData> x318_suitModelData; TLockedToken<CModel> x31c_beamModel; // Used to be single_ptr TLockedToken<CModel> x320_suitModel; // Used to be single_ptr TLockedToken<CSkinRules> x324_suitSkin; // Used to be single_ptr TLockedToken<CSkinnedModel> x328_backupModelData; // Used to be optional TLockedToken<CTexture> x338_phazonIndirectTexture; // Used to be optional u32 x348_deallocateBackupCountdown = 0; float x34c_phazonOffsetAngle = 0.f; u32 x350_flags; /* 0x1: suit transition, 0x2: previous suit, 0x4: force reset * 0x8: track in area data, 0x10: keep in state manager */ bool x354_24_setBoundingBox : 1; bool x354_25_deferOnlineModelData : 1 = false; bool x354_26_deferOfflineModelData : 1 = false; bool x354_27_beamModelLoading : 1 = false; bool x354_28_suitModelLoading : 1 = false; bool x354_29_loading : 1 = true; bool x354_30_enableLoading : 1 = true; bool x354_31_deferOnlineLoad : 1 = false; bool x355_24_areaTrackingLoad : 1 = false; TUniqueId x356_nextPlayerActor = kInvalidUniqueId; u32 GetSuitCharIdx(const CStateManager& mgr, CPlayerState::EPlayerSuit suit) const; u32 GetNextSuitCharIdx(const CStateManager& mgr) const; void LoadSuit(u32 charIdx); void LoadBeam(CPlayerState::EBeamId beam); void PumpBeamModel(CStateManager& mgr); void BuildBeamModelData(); void PumpSuitModel(CStateManager& mgr); void SetupOfflineModelData(); void SetupOnlineModelData(); void SetupEnvFx(CStateManager& mgr, bool set); void SetIntoStateManager(CStateManager& mgr, bool set); void TouchModels_Internal(const CStateManager& mgr) const; public: CScriptPlayerActor(TUniqueId uid, std::string_view name, const CEntityInfo& info, const zeus::CTransform& xf, const CAnimRes& animRes, CModelData&& mData, const zeus::CAABox& aabox, bool setBoundingBox, const CMaterialList& list, float mass, float zMomentum, const CHealthInfo& hInfo, const CDamageVulnerability& dVuln, const CActorParameters& aParams, bool loop, bool active, u32 flags, CPlayerState::EBeamId beam); void Think(float, CStateManager&) override; void AcceptScriptMsg(EScriptObjectMessage, TUniqueId, CStateManager&) override; void SetActive(bool active) override; void PreRender(CStateManager&, const zeus::CFrustum&) override; void AddToRenderer(const zeus::CFrustum&, CStateManager&) override; void Render(CStateManager& mgr) override; void TouchModels(const CStateManager& mgr) const; }; } // namespace urde
44.885714
113
0.746976
[ "render" ]
c412050c06bc2ecc6164625f6b0c52cbdeed3a19
6,436
cpp
C++
Engine/source/EtRendering/GraphicsTypes/TextureData.cpp
logzero/ETEngine
f766f1a0d702b826b94023edbf64da83dbcf7bc6
[ "MIT" ]
null
null
null
Engine/source/EtRendering/GraphicsTypes/TextureData.cpp
logzero/ETEngine
f766f1a0d702b826b94023edbf64da83dbcf7bc6
[ "MIT" ]
null
null
null
Engine/source/EtRendering/GraphicsTypes/TextureData.cpp
logzero/ETEngine
f766f1a0d702b826b94023edbf64da83dbcf7bc6
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "TextureData.h" #include <stb/stb_image.h> #include <stb/stb_image_resize.h> #include <EtCore/Reflection/Registration.h> #include <EtRendering/GlobalRenderingSystems/GlobalRenderingSystems.h> namespace et { namespace render { //============== // Texture Data //============== //--------------------------------- // TextureData::c-tor // // Create the texture and generate a new GPU texture resource // TextureData::TextureData(ivec2 const res, E_ColorFormat const intern, E_ColorFormat const format, E_DataType const type, int32 const depth) : m_Resolution(res) , m_Internal(intern) , m_Format(format) , m_DataType(type) , m_Depth(depth) , m_TargetType((depth > 1) ? E_TextureType::Texture3D : E_TextureType::Texture2D) { m_Location = Viewport::GetCurrentApiContext()->GenerateTexture(); } //--------------------------------- // TextureData::TextureData // // Create a texture of a specific type with a preexisting handle // TextureData::TextureData(E_TextureType const targetType, ivec2 const res) : m_TargetType(targetType) , m_Resolution(res) , m_Internal(E_ColorFormat::RGB) , m_Format(E_ColorFormat::RGB) , m_DataType(E_DataType::Float) { m_Location = Viewport::GetCurrentApiContext()->GenerateTexture(); } //--------------------------------- // TextureData::d-tor // // Destroys the GPU resource // TextureData::~TextureData() { I_GraphicsApiContext* const api = Viewport::GetCurrentApiContext(); if (m_Handle != 0u) { api->SetTextureHandleResidency(m_Handle, false); } api->DeleteTexture(m_Location); } //--------------------------------- // TextureData::Build // // send the data to the GPU location. Can be initialized without any image data // void TextureData::Build(void* data) { ET_ASSERT(m_Handle == 0u, "Shouldn't build after a handle was created!"); Viewport::GetCurrentApiContext()->SetTextureData(*this, data); } //--------------------------------- // TextureData::SetParameters // // Sets parameters on a texture, can optionally be enforced // This function should be called either way when a new texture is created, // - because if we leave the default parameters OpenGL expects us to generate a mip map, or we can disable mip maps which will change the min filter // void TextureData::SetParameters(TextureParameters const& params, bool const force) { ET_ASSERT(m_Handle == 0u, "Shouldn't set parameters after a handle was created!"); Viewport::GetCurrentApiContext()->SetTextureParams(*this, m_MipLevels, m_Parameters, params, force); } //--------------------------------- // TextureData::Resize // // returns true if regenerated // - if the texture is a framebuffer texture upscaling won't work properly unless it is reatached to the framebuffer object // bool TextureData::Resize(ivec2 const& newSize) { bool const hasHandle = (m_Handle != 0u); bool const regenerate = (newSize.x > m_Resolution.x) || (newSize.y > m_Resolution.y) || hasHandle; m_Resolution = newSize; if (regenerate) { I_GraphicsApiContext* const api = Viewport::GetCurrentApiContext(); if (hasHandle) { api->SetTextureHandleResidency(m_Handle, false); m_Handle = 0u; } api->DeleteTexture(m_Location); m_Location = api->GenerateTexture(); } Build(); if (regenerate) { SetParameters(m_Parameters, true); } if (hasHandle) { CreateHandle(); } return regenerate; } //--------------------------------- // TextureData::CreateHandle // // Create a handle that allows bindless use of the texture. After the handle is created, no other modifying operations should be done (except resize) // void TextureData::CreateHandle() { I_GraphicsApiContext* const api = Viewport::GetCurrentApiContext(); m_Handle = api->GetTextureHandle(m_Location); api->SetTextureHandleResidency(m_Handle, true); // #todo: in the future we should have a system that makes inactive handles non resident after a while } //=================== // Texture Asset //=================== // reflection RTTR_REGISTRATION { BEGIN_REGISTER_POLYMORPHIC_CLASS(TextureAsset, "texture asset") .property("use SRGB", &TextureAsset::m_UseSrgb) .property("force resolution", &TextureAsset::m_ForceResolution) .property("parameters", &TextureAsset::m_Parameters) END_REGISTER_POLYMORPHIC_CLASS(TextureAsset, core::I_Asset); } DEFINE_FORCED_LINKING(TextureAsset) // force the shader class to be linked as it is only used in reflection //--------------------------------- // TextureAsset::LoadFromMemory // // Load texture data from binary asset content, and place it on the GPU // bool TextureAsset::LoadFromMemory(std::vector<uint8> const& data) { // check image format stbi_set_flip_vertically_on_load(false); int32 width = 0; int32 height = 0; int32 channels = 0; static int32 const s_TargetNumChannels = 3; // for now we only support opaque textures // option to load 16 bit texture uint8* bits = stbi_load_from_memory(data.data(), static_cast<int32>(data.size()), &width, &height, &channels, s_TargetNumChannels); if (bits == nullptr) { LOG("TextureAsset::LoadFromMemory > Failed to load texture bytes from data!", core::LogLevel::Warning); return false; } if ((width == 0) || (height == 0)) { LOG("TextureAsset::LoadFromMemory > Image is too small to display!", core::LogLevel::Warning); stbi_image_free(bits); return false; } render::GraphicsSettings const& graphicsSettings = RenderingSystems::Instance()->GetGraphicsSettings(); if (!math::nearEquals(graphicsSettings.TextureScaleFactor, 1.f)) { if (!m_ForceResolution) { // resize int32 const outWidth = static_cast<int32>(static_cast<float>(width) * graphicsSettings.TextureScaleFactor); int32 const outHeight = static_cast<int32>(static_cast<float>(height) * graphicsSettings.TextureScaleFactor); uint8* outBits = new uint8[outWidth * outHeight * channels]; stbir_resize_uint8(bits, width, height, 0, outBits, outWidth, outHeight, 0, channels); stbi_image_free(bits); bits = outBits; width = outWidth; height = outHeight; } } // convert data type // check number of channels //Upload to GPU m_Data = new TextureData(ivec2(width, height), (m_UseSrgb ? E_ColorFormat::SRGB : E_ColorFormat::RGB), E_ColorFormat::RGB, E_DataType::UByte); m_Data->Build((void*)bits); m_Data->SetParameters(m_Parameters); m_Data->CreateHandle(); stbi_image_free(bits); bits = nullptr; return true; } } // namespace render } // namespace et
27.156118
151
0.699347
[ "render", "object", "vector" ]
c41666270ba39cb2ec023dd48135d6273dbc49af
1,657
cpp
C++
aws-cpp-sdk-kinesisanalyticsv2/source/model/S3ContentLocation.cpp
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-kinesisanalyticsv2/source/model/S3ContentLocation.cpp
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-kinesisanalyticsv2/source/model/S3ContentLocation.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-12-30T04:25:33.000Z
2021-12-30T04:25:33.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/kinesisanalyticsv2/model/S3ContentLocation.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace KinesisAnalyticsV2 { namespace Model { S3ContentLocation::S3ContentLocation() : m_bucketARNHasBeenSet(false), m_fileKeyHasBeenSet(false), m_objectVersionHasBeenSet(false) { } S3ContentLocation::S3ContentLocation(JsonView jsonValue) : m_bucketARNHasBeenSet(false), m_fileKeyHasBeenSet(false), m_objectVersionHasBeenSet(false) { *this = jsonValue; } S3ContentLocation& S3ContentLocation::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("BucketARN")) { m_bucketARN = jsonValue.GetString("BucketARN"); m_bucketARNHasBeenSet = true; } if(jsonValue.ValueExists("FileKey")) { m_fileKey = jsonValue.GetString("FileKey"); m_fileKeyHasBeenSet = true; } if(jsonValue.ValueExists("ObjectVersion")) { m_objectVersion = jsonValue.GetString("ObjectVersion"); m_objectVersionHasBeenSet = true; } return *this; } JsonValue S3ContentLocation::Jsonize() const { JsonValue payload; if(m_bucketARNHasBeenSet) { payload.WithString("BucketARN", m_bucketARN); } if(m_fileKeyHasBeenSet) { payload.WithString("FileKey", m_fileKey); } if(m_objectVersionHasBeenSet) { payload.WithString("ObjectVersion", m_objectVersion); } return payload; } } // namespace Model } // namespace KinesisAnalyticsV2 } // namespace Aws
18.411111
69
0.729632
[ "model" ]
c437c46bf7fa45ff66ad6f9ec7591ed5d344e156
3,205
hpp
C++
src/Distinct.hpp
sebrockm/Linqpp
6689f6cbb076b30f260ef4cee2dd657cd6b8cc36
[ "MIT" ]
7
2017-08-09T06:12:15.000Z
2021-09-23T01:00:51.000Z
src/Distinct.hpp
sebrockm/Linqpp
6689f6cbb076b30f260ef4cee2dd657cd6b8cc36
[ "MIT" ]
null
null
null
src/Distinct.hpp
sebrockm/Linqpp
6689f6cbb076b30f260ef4cee2dd657cd6b8cc36
[ "MIT" ]
null
null
null
#include "From.hpp" #include <algorithm> #include <memory> #include <set> #include <unordered_set> #include <vector> namespace Linqpp { template <class InputIterator> auto From(InputIterator first, InputIterator last); template <class InputIterator, class LessThanComparer> auto Distinct(InputIterator first, InputIterator last, LessThanComparer comparer) { using Value = typename std::iterator_traits<InputIterator>::value_type; auto distinguisher = [spSet = std::make_shared<std::set<Value, LessThanComparer>>(comparer)] (auto const& item) { return spSet->insert(item).second; }; return From(first, last).Where(std::move(distinguisher)); } template <class InputIterator, class EqualityComparer, class Hash> auto Distinct(InputIterator first, InputIterator last, EqualityComparer comparer, Hash hash) { using Value = typename std::iterator_traits<InputIterator>::value_type; auto distinguisher = [spSet = std::make_shared<std::unordered_set<Value, Hash, EqualityComparer>>(1024, hash, comparer)] (auto const& item) { return spSet->insert(item).second; }; return From(first, last).Where(std::move(distinguisher)); } namespace Detail { // has no less template <class InputIterator> auto InternalDistinct2(InputIterator first, InputIterator last, ...) { using Value = typename std::iterator_traits<InputIterator>::value_type; auto distinguisher = [spSet = std::make_shared<std::vector<Value>>()] (auto const& item) { if (std::find(spSet->begin(), spSet->end(), item) != spSet->end()) return false; spSet->push_back(item); return true; }; return From(first, last).Where(std::move(distinguisher)); } // has less template <class InputIterator, class Value = typename std::iterator_traits<InputIterator>::value_type, class = decltype(std::declval<Value>() < std::declval<Value>())> auto InternalDistinct2(InputIterator first, InputIterator last, int) { return Distinct(first, last, std::less<>()); } // has hash template <class InputIterator, class Value = typename std::iterator_traits<InputIterator>::value_type, class = decltype(std::hash<Value>()(std::declval<Value>())), class = decltype(std::declval<Value>() == std::declval<Value>())> auto InternalDistinct1(InputIterator first, InputIterator last, int) { return Distinct(first, last, std::equal_to<>(), std::hash<Value>()); } // has no hash template <class InputIterator> auto InternalDistinct1(InputIterator first, InputIterator last, ...) { return InternalDistinct2(first, last, 0); } } template <class InputIterator> auto Distinct(InputIterator first, InputIterator last) { return Detail::InternalDistinct1(first, last, 0); } }
33.736842
175
0.61248
[ "vector" ]
c4411d3362cb274a2621c71a4b3f019dd6e47661
1,397
cc
C++
cpp/merge_contacts.cc
powernit/epicode
e81d4387d2ae442d21631dfc958690d424e1d84d
[ "MIT" ]
258
2016-07-18T03:28:15.000Z
2021-12-05T09:08:44.000Z
cpp/merge_contacts.cc
powernit/epicode
e81d4387d2ae442d21631dfc958690d424e1d84d
[ "MIT" ]
7
2016-08-13T22:12:29.000Z
2022-02-25T17:50:11.000Z
cpp/merge_contacts.cc
powernit/epicode
e81d4387d2ae442d21631dfc958690d424e1d84d
[ "MIT" ]
154
2016-07-18T06:29:24.000Z
2021-09-20T18:33:05.000Z
// Copyright (c) 2015 Elements of Programming Interviews. All rights reserved. #include <algorithm> #include <cassert> #include <string> #include <unordered_set> #include <vector> using std::hash; using std::string; using std::unordered_set; using std::vector; // @include struct ContactList { // Equal function for hash. bool operator==(const ContactList& that) const { return unordered_set<string>(names.begin(), names.end()) == unordered_set<string>(that.names.begin(), that.names.end()); } vector<string> names; }; // Hash function for ContactList. struct HashContactList { size_t operator()(const ContactList& contacts) const { size_t hash_code = 0; for (const string& name : unordered_set<string>(contacts.names.begin(), contacts.names.end())) { hash_code ^= hash<string>()(name); } return hash_code; } }; vector<ContactList> MergeContactLists(const vector<ContactList>& contacts) { unordered_set<ContactList, HashContactList> unique_contacts( contacts.begin(), contacts.end()); return {unique_contacts.begin(), unique_contacts.end()}; } // @exclude int main(int argc, char* argv[]) { vector<ContactList> contacts = { {{"a", "b", "c"}}, {{"a", "c", "b"}}, {{"b", "c", "d"}}}; auto result = MergeContactLists(contacts); assert(result.size() == 2); return 0; }
27.392157
78
0.649964
[ "vector" ]
c44ebeaf2082b1b854e114aff04f5991139ac2d6
16,540
cpp
C++
BufferUploads/MemoryManagement.cpp
djewsbury/XLE
7806e4b5c9de5631c94c2020f6adcd4bd8e3d91e
[ "MIT" ]
3
2015-12-04T09:16:53.000Z
2021-05-28T23:22:49.000Z
BufferUploads/MemoryManagement.cpp
djewsbury/XLE
7806e4b5c9de5631c94c2020f6adcd4bd8e3d91e
[ "MIT" ]
null
null
null
BufferUploads/MemoryManagement.cpp
djewsbury/XLE
7806e4b5c9de5631c94c2020f6adcd4bd8e3d91e
[ "MIT" ]
2
2015-03-03T05:32:39.000Z
2015-12-04T09:16:54.000Z
// Copyright 2015 XLGAMES Inc. // // Distributed under the MIT License (See // accompanying file "LICENSE" or the website // http://www.opensource.org/licenses/mit-license.php) #include "MemoryManagement.h" #include "../Core/Prefix.h" #include "../Utility/MemoryUtils.h" #include "../Utility/PtrUtils.h" #include <algorithm> #include <assert.h> #pragma warning(disable:4245) namespace BufferUploads { ///////////////////////////////////////////////////////////////////////////////// ////// R E F E R E N C E C O U N T I N G L A Y E R ////// ///////////////////////////////////////////////////////////////////////////////// std::pair<signed,signed> ReferenceCountingLayer::AddRef(unsigned start, unsigned size, const char name[]) { ScopedLock(_lock); Marker internalStart = ToInternalSize(start); Marker internalSize = ToInternalSize(AlignSize(size)); if (_entries.empty()) { Entry newBlock; newBlock._start = internalStart; newBlock._end = internalStart+internalSize; newBlock._refCount = 1; DEBUG_ONLY(if (name) newBlock._name = name); _entries.insert(_entries.end(), newBlock); return std::make_pair(newBlock._refCount, newBlock._refCount); } std::vector<Entry>::iterator i = std::lower_bound(_entries.begin(), _entries.end(), internalStart, CompareStart()); if (i != _entries.begin() && ((i-1)->_end > internalStart)) { --i; } Marker currentStart = internalStart; Marker internalEnd = internalStart+internalSize; signed refMin = INT_MAX, refMax = INT_MIN; for (;;++i) { if (i >= _entries.end() || currentStart < i->_start) { // this this is past the end of any other blocks -- add new a block Entry newBlock; newBlock._start = currentStart; newBlock._end = std::min(internalEnd, Marker((i<_entries.end())?i->_start:INT_MAX)); newBlock._refCount = 1; DEBUG_ONLY(if (name) newBlock._name = name); assert(newBlock._start < newBlock._end); assert(newBlock._end != 0xbaad); bool end = i >= _entries.end() || internalEnd <= i->_start; i = _entries.insert(i, newBlock)+1; refMin = std::min(refMin, 1); refMax = std::max(refMax,1); if (end) { break; // it's the end } currentStart = i->_start; } if (i->_start == currentStart) { if (internalEnd >= i->_end) { // we've hit a block identical to the one we're looking for. Just increase the ref count signed newRefCount = ++i->_refCount; refMin = std::min(refMin, newRefCount); refMax = std::max(refMax, newRefCount); assert(i->_start < i->_end); assert(i->_end != 0xbaad); currentStart = i->_end; if (name && name[0]) { DEBUG_ONLY(i->_name = name); // we have to take on the new name here. Sometimes we'll get a number of sub blocks inside of a super block. The last sub block will allocate the entirely remaining part of the super block. When this happens, rename to the sub block name. } if (internalEnd == i->_end) { break; // it's the end } } else { // split the block and add a new one in front Entry newBlock; newBlock._start = i->_start; newBlock._end = internalEnd; DEBUG_ONLY(if (name) newBlock._name = name); signed newRefCount = newBlock._refCount = i->_refCount+1; i->_start = internalEnd; assert(newBlock._start < newBlock._end && i->_start < i->_end); assert(i->_end != 0xbaad && newBlock._end != 0xbaad); _entries.insert(i, newBlock); refMin = std::min(refMin, newRefCount); refMax = std::max(refMax, newRefCount); break; // it's the end } } else { if (internalEnd < i->_end) { // This is a block that falls entirely within the old block. We need to create a new block, splitting the old one if necessary // we need do split the end part of the old block off too, and then insert 2 blocks Entry newBlock[2]; newBlock[0]._start = i->_start; newBlock[0]._end = currentStart; newBlock[0]._refCount = i->_refCount; DEBUG_ONLY(newBlock[0]._name = i->_name); newBlock[1]._start = currentStart; newBlock[1]._end = internalEnd; DEBUG_ONLY(if (name) newBlock[1]._name = name); signed newRefCount = newBlock[1]._refCount = i->_refCount+1; i->_start = internalEnd; assert(newBlock[0]._start < newBlock[0]._end && newBlock[1]._start < newBlock[1]._end&& i->_start < i->_end); assert(i->_end != 0xbaad && newBlock[0]._end != 0xbaad && newBlock[1]._end != 0xbaad); _entries.insert(i, newBlock, &newBlock[2]); refMin = std::min(refMin, newRefCount); refMax = std::max(refMax, newRefCount); break; } else { Marker iEnd = i->_end; Entry newBlock; newBlock._start = i->_start; newBlock._end = currentStart; newBlock._refCount = i->_refCount; DEBUG_ONLY(newBlock._name.swap(i->_name)); i->_start = currentStart; DEBUG_ONLY(if (name) i->_name = name); signed newRefCount = ++i->_refCount; assert(newBlock._start < newBlock._end && i->_start < i->_end); assert(i->_end != 0xbaad && newBlock._end != 0xbaad); i = _entries.insert(i, newBlock)+1; refMin = std::min(refMin, newRefCount); refMax = std::max(refMax, newRefCount); if (internalEnd == iEnd) { break; } currentStart = iEnd; // this block extends into the next area -- so continue around the loop again } } } return std::make_pair(refMin, refMax); } size_t ReferenceCountingLayer::Validate() { size_t result = 0; for (std::vector<Entry>::iterator i=_entries.begin(); i<_entries.end(); ++i) { assert(i->_start < i->_end); if ((i+1)<_entries.end()) { assert(i->_end <= (i+1)->_start); } assert(i->_start <= 0x800 && i->_end <= 0x800); result += i->_refCount*size_t(i->_end-i->_start); } return result; } unsigned ReferenceCountingLayer::CalculatedReferencedSpace() const { ScopedLock(_lock); unsigned result = 0; for (std::vector<Entry>::const_iterator i=_entries.begin(); i<_entries.end(); ++i) { result += ToExternalSize(i->_end-i->_start); } return result; } void ReferenceCountingLayer::PerformDefrag(const std::vector<DefragStep>& defrag) { ScopedLock(_lock); std::vector<Entry>::iterator entryIterator = _entries.begin(); for ( std::vector<DefragStep>::const_iterator s=defrag.begin(); s!=defrag.end() && entryIterator!=_entries.end();) { unsigned entryStart = ToExternalSize(entryIterator->_start); unsigned entryEnd = ToExternalSize(entryIterator->_end); if (s->_sourceEnd <= entryStart) { ++s; continue; } if (s->_sourceStart >= entryEnd) { // This deallocate iterator doesn't have an adjustment ++entryIterator; continue; } // // We shouldn't have any blocks that are stretched between multiple // steps. If we've got a match it must match the entire deallocation block // assert(entryStart >= s->_sourceStart && entryStart < s->_sourceEnd); assert(entryEnd > s->_sourceStart && entryEnd <= s->_sourceEnd); signed offset = s->_destination - signed(s->_sourceStart); entryIterator->_start = ToInternalSize(entryStart+offset); entryIterator->_end = ToInternalSize(entryEnd+offset); ++entryIterator; } // The defrag process may have modified the order of the entries (in the heap space) // We need to resort by start std::sort(_entries.begin(), _entries.end(), CompareStart()); } std::pair<signed,signed> ReferenceCountingLayer::Release(unsigned start, unsigned size) { ScopedLock(_lock); Marker internalStart = ToInternalSize(start); Marker internalSize = ToInternalSize(AlignSize(size)); if (_entries.empty()) { return std::make_pair(INT_MIN, INT_MIN); } std::vector<Entry>::iterator i = std::lower_bound(_entries.begin(), _entries.end(), internalStart, CompareStart()); if (i != _entries.begin() && ((i-1)->_end > internalStart)) { --i; } Marker currentStart = internalStart; Marker internalEnd = internalStart+internalSize; signed refMin = INT_MAX, refMax = INT_MIN; for (;;) { if (i >= _entries.end() || currentStart < i->_start) { if (i >= _entries.end() || internalEnd <= i->_start) break; currentStart = i->_start; } assert(i>=_entries.begin() && i<_entries.end()); #if defined(_DEBUG) if (i->_start == currentStart) { assert(internalEnd >= i->_end); } else { assert(currentStart >= i->_end); } #endif if (i->_start == currentStart) { if (internalEnd >= i->_end) { signed newRefCount = --i->_refCount; Marker iEnd = i->_end; if (!newRefCount) { i = _entries.erase(i); } refMin = std::min(refMin, newRefCount); refMax = std::max(refMax, newRefCount); if (internalEnd == iEnd) { break; // it's the end } currentStart = iEnd; if (!newRefCount) continue; // continue to skip the next ++i (because we've just done an erase) } else { // split the block and add a new one in front signed newRefCount = i->_refCount-1; if (newRefCount == 0) { i->_start = internalEnd; } else { Entry newBlock; newBlock._start = currentStart; newBlock._end = internalEnd; newBlock._refCount = newRefCount; DEBUG_ONLY(newBlock._name = i->_name); i->_start = internalEnd; assert(newBlock._start < newBlock._end && i->_start < i->_end); assert(i->_end != 0xbaad && newBlock._end != 0xbaad); i = _entries.insert(i, newBlock); } refMin = std::min(refMin, newRefCount); refMax = std::max(refMax, newRefCount); break; // it's the end } } else { if (internalEnd < i->_end) { signed newRefCount = i->_refCount-1; if (newRefCount==0) { Entry newBlock; newBlock._start = i->_start; newBlock._end = currentStart; newBlock._refCount = i->_refCount; DEBUG_ONLY(newBlock._name = i->_name); i->_start = internalEnd; assert(newBlock._start < newBlock._end && i->_start < i->_end); assert(i->_end != 0xbaad && newBlock._end != 0xbaad); i = _entries.insert(i, newBlock); } else { // This is a block that falls entirely within the old block. We need to create a new block, splitting the old one if necessary // we need do split the end part of the old block off too, and then insert 2 blocks Entry newBlock[2]; newBlock[0]._start = i->_start; newBlock[0]._end = currentStart; newBlock[0]._refCount = i->_refCount; DEBUG_ONLY(newBlock[0]._name = i->_name); newBlock[1]._start = currentStart; newBlock[1]._end = internalEnd; newBlock[1]._refCount = newRefCount; DEBUG_ONLY(newBlock[1]._name = i->_name); i->_start = internalEnd; assert(newBlock[0]._start < newBlock[0]._end && newBlock[1]._start < newBlock[1]._end && i->_start < i->_end); assert(i->_end != 0xbaad && newBlock[0]._end != 0xbaad && newBlock[1]._end != 0xbaad); size_t offset = std::distance(_entries.begin(),i); _entries.insert(i, newBlock, &newBlock[2]); i = _entries.begin()+offset+2; } refMin = std::min(refMin, newRefCount); refMax = std::max(refMax, newRefCount); break; } else { Marker iEnd = i->_end; signed newRefCount = i->_refCount-1; if (newRefCount==0) { i->_end = currentStart; } else { Entry newBlock; newBlock._start = i->_start; newBlock._end = currentStart; newBlock._refCount = i->_refCount; DEBUG_ONLY(newBlock._name = i->_name); i->_start = currentStart; i->_refCount = newRefCount; assert(i>=_entries.begin() && i<_entries.end()); assert(newBlock._start < newBlock._end && i->_start < i->_end); assert(i->_end != 0xbaad && newBlock._end != 0xbaad); i = _entries.insert(i, newBlock)+1; } refMin = std::min(refMin, newRefCount); refMax = std::max(refMax, newRefCount); if (internalEnd == iEnd) { break; } currentStart = iEnd; // this block extends into the next area -- so continue around the loop again } } ++i; } return std::make_pair(refMin, refMax); } bool ReferenceCountingLayer::ValidateBlock(unsigned start, unsigned size) const { ScopedLock(_lock); Marker internalStart = ToInternalSize(start); Marker internalEnd = internalStart+ToInternalSize(AlignSize(size)); std::vector<Entry>::const_iterator i = std::lower_bound(_entries.begin(), _entries.end(), internalStart, CompareStart()); return (i != _entries.end() && i->_start == internalStart && i->_end == internalEnd); } ReferenceCountingLayer::ReferenceCountingLayer(size_t size) { _entries.reserve(64); } ReferenceCountingLayer::ReferenceCountingLayer(const ReferenceCountingLayer& cloneFrom) : _entries(cloneFrom._entries) {} }
46.201117
295
0.493289
[ "vector" ]
c461e97dbe3293a2f00344ca4b464c9c0f642611
10,113
cpp
C++
engine/source/resources/AssimpSceneLoader.cpp
lechkulina/RealmsOfSteel
adeb53295abfa236a273c2641f3f9f4d4c6110e1
[ "Apache-2.0" ]
null
null
null
engine/source/resources/AssimpSceneLoader.cpp
lechkulina/RealmsOfSteel
adeb53295abfa236a273c2641f3f9f4d4c6110e1
[ "Apache-2.0" ]
null
null
null
engine/source/resources/AssimpSceneLoader.cpp
lechkulina/RealmsOfSteel
adeb53295abfa236a273c2641f3f9f4d4c6110e1
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017 Lech Kulina * * This file is part of the Realms Of Steel. * For conditions of distribution and use, see copyright details in the LICENSE file. */ #include <application/Logger.h> #include "AssimpIOSystem.h" #include "AssimpSceneLoader.h" ros::AssimpSceneLoader::AssimpSceneLoader() : importer(ROS_NULL) { importer = new Assimp::Importer; importer->SetIOHandler(new AssimpIOSystem()); } ros::AssimpSceneLoader::~AssimpSceneLoader() { delete importer; } bool ros::AssimpSceneLoader::isLoadable(const std::string& name) const { if (name.length() <= MAX_EXTENSION_LENGTH) { return false; } const std::string extension = name.substr(name.length() - MAX_EXTENSION_LENGTH); return importer->IsExtensionSupported(extension); } ros::MaterialPtr ros::AssimpSceneLoader::createMaterial(const aiMaterial* src) { aiString name; if (src->Get(AI_MATKEY_NAME, name) != AI_SUCCESS) { ROS_ERROR(boost::format("Failed to get material name")); return MaterialPtr(); } MaterialPtr material = boost::make_shared<Material>(); material->setName(name.C_Str()); aiColor3D diffuseColor; if (src->Get(AI_MATKEY_COLOR_DIFFUSE, diffuseColor) == AI_SUCCESS) { material->setDiffuseColor(glm::vec3(diffuseColor.r, diffuseColor.g, diffuseColor.b)); } else { ROS_WARNING(boost::format("Failed to get diffuse color form material %s") % name.C_Str()); } aiColor3D specularColor; if (src->Get(AI_MATKEY_COLOR_SPECULAR, specularColor) == AI_SUCCESS) { material->setSpecularColor(glm::vec3(specularColor.r, specularColor.g, specularColor.b)); } else { ROS_WARNING(boost::format("Failed to get specular color form material %s") % name.C_Str()); } aiColor3D ambientColor; if (src->Get(AI_MATKEY_COLOR_AMBIENT, ambientColor) == AI_SUCCESS) { material->setAmbientColor(glm::vec3(ambientColor.r, ambientColor.g, ambientColor.b)); } else { ROS_WARNING(boost::format("Failed to get ambient color form material %s") % name.C_Str()); } aiColor3D emissiveColor; if (src->Get(AI_MATKEY_COLOR_EMISSIVE, emissiveColor) == AI_SUCCESS) { material->setEmissiveColor(glm::vec3(emissiveColor.r, emissiveColor.g, emissiveColor.b)); } else { ROS_WARNING(boost::format("Failed to get emissive color form material %s") % name.C_Str()); } int twoSided = 0; if (src->Get(AI_MATKEY_TWOSIDED, twoSided) == AI_SUCCESS) { material->setTwoSided(twoSided != 0); } else { ROS_WARNING(boost::format("Failed to get sides info form material %s") % name.C_Str()); } float opacity = 0.0f; if (src->Get(AI_MATKEY_OPACITY, opacity) == AI_SUCCESS) { material->setOpacity(opacity); } else { ROS_WARNING(boost::format("Failed to get opacity form material %s") % name.C_Str()); } float shininess = 0.0f; if (src->Get(AI_MATKEY_SHININESS, shininess) == AI_SUCCESS) { material->setShininess(shininess); } else { ROS_WARNING(boost::format("Failed to get shininess form material %s") % name.C_Str()); } return material; } ros::MaterialsVector ros::AssimpSceneLoader::createMaterials(const aiScene* src) { MaterialsVector materials; if (!src->HasMaterials()) { return materials; } for (unsigned int i=0; i < src->mNumMaterials; ++i) { MaterialPtr material = createMaterial(src->mMaterials[i]); if (!material) { materials.clear(); return materials; } materials.push_back(material); } return materials; } ros::MeshPtr ros::AssimpSceneLoader::createMesh(const aiMesh* src, const MaterialsVector& materials) { const aiString& name = src->mName; if (!src->HasPositions() || !src->HasFaces()) { ROS_ERROR(boost::format("Mesh %s is missing faces data") % name.C_Str()); return MeshPtr(); } if (src->mPrimitiveTypes != aiPrimitiveType_TRIANGLE) { ROS_ERROR(boost::format("Mesh %s uses non-triangular primitive type") % name.C_Str()); return MeshPtr(); } MeshPtr mesh = boost::make_shared<Mesh>(); mesh->setName(name.C_Str()); bool hasNormals = src->HasNormals(); if (hasNormals) { mesh->setVerticesProps(Mesh::VERTICES_PROPS_NORMALS); } bool hasTangents = src->HasTangentsAndBitangents(); if (hasTangents) { mesh->setVerticesProps(Mesh::VERTICES_PROPS_TENGENTS); mesh->setVerticesProps(Mesh::VERTICES_PROPS_BITANGENTS); } unsigned int colorChannels = src->GetNumColorChannels(); if (colorChannels > 0) { mesh->setVerticesProps(Mesh::VERTICES_PROPS_COLORS); if (colorChannels > 1) { ROS_WARNING(boost::format("Mesh %s has %d colors per vertex but only 1 is supported") % name.C_Str() % colorChannels); } } unsigned int uvChannels = src->GetNumUVChannels(); if (uvChannels > 0) { mesh->setVerticesProps(Mesh::VERTICES_PROPS_TEXTURE_COORDS); if (uvChannels > 1) { ROS_WARNING(boost::format("Mesh %s has %d texture coords per vertex but only 1 is supported") % name.C_Str() % uvChannels); } } for (unsigned int j=1; j < uvChannels; ++j) { if (src->mNumUVComponents[j] != 2) { ROS_WARNING(boost::format("Mesh %s uses %d texture coords components but only 2 are supported") % name.C_Str() % src->mNumUVComponents[j]); } } for (unsigned int j=0; j < src->mNumVertices; ++j) { Vertex vertex; const aiVector3D& position = src->mVertices[j]; vertex.position = glm::vec3(position.x, position.y, position.z); if (hasNormals) { const aiVector3D& normal = src->mNormals[j]; vertex.normal = glm::vec3(normal.x, normal.y, normal.z); } if (hasTangents) { const aiVector3D& tangent = src->mTangents[j]; const aiVector3D& bitangent = src->mBitangents[j]; vertex.tangent = glm::vec3(tangent.x, tangent.y, tangent.z); vertex.bitangent = glm::vec3(bitangent.x, bitangent.y, bitangent.z); } if (colorChannels > 0) { const aiColor4D& color = src->mColors[0][j]; vertex.color = glm::vec4(color.r, color.g, color.b, color.a); } if (uvChannels > 0) { const aiVector3D& textureCoords = src->mTextureCoords[0][j]; vertex.textureCoords = glm::vec2(textureCoords.x, textureCoords.y); } mesh->addVertex(vertex); } for (unsigned int j=0; j < src->mNumFaces; ++j) { const aiFace& face = src->mFaces[j]; if (face.mNumIndices != 3) { ROS_ERROR(boost::format("Mesh %s uses unsupported number of indices %d") % name.C_Str() % face.mNumIndices); return MeshPtr(); } mesh->addIndices(face.mIndices[0], face.mIndices[1], face.mIndices[2]); } unsigned int materialIndex = src->mMaterialIndex; if (materialIndex >= materials.size()) { ROS_ERROR(boost::format("Mesh %s uses invalid material index %d - number of found materials is %d)") % name.C_Str() % materialIndex % materials.size()); return MeshPtr(); } mesh->setMaterial(materials[materialIndex]); return mesh; } ros::MeshesVector ros::AssimpSceneLoader::createMeshes(const aiScene* src, const MaterialsVector& materials) { MeshesVector meshes; if (!src->HasMeshes()) { return meshes; } for (unsigned int i=0; i < src->mNumMeshes; ++i) { MeshPtr mesh = createMesh(src->mMeshes[i], materials); if (!mesh) { meshes.clear(); return meshes; } meshes.push_back(mesh); } return meshes; } ros::SceneNodePtr ros::AssimpSceneLoader::createSceneNode(const aiNode* src, const MeshesVector& meshes, SceneNodeWeakPtr parent /*= SceneNodeWeakPtr()*/) { const aiString& name = src->mName; SceneNodePtr sceneNode = boost::make_shared<SceneNode>(); sceneNode->setName(name.C_Str()); sceneNode->setParent(parent); for (unsigned int i=0; i < src->mNumMeshes; ++i) { unsigned int meshIndex = src->mMeshes[i]; if (meshIndex >= meshes.size()) { ROS_ERROR(boost::format("Scene node %s uses invalid mesh index %d - number of found meshes is %d") % name.C_Str() % meshIndex % meshes.size()); return SceneNodePtr(); } sceneNode->addMesh(meshes[meshIndex]); } const aiMatrix4x4& trans = src->mTransformation; sceneNode->setTransformation(glm::mat4x4( trans[0][0], trans[0][1], trans[0][2], trans[0][3], trans[1][0], trans[1][1], trans[1][2], trans[1][3], trans[2][0], trans[2][1], trans[2][2], trans[2][3], trans[3][0], trans[3][1], trans[3][2], trans[3][3] )); for (unsigned int i=0; i < src->mNumChildren; ++i) { SceneNodePtr child = createSceneNode(src->mChildren[i], meshes, sceneNode); if (!child) { return SceneNodePtr(); } sceneNode->addChild(child); } return sceneNode; } ros::ScenePtr ros::AssimpSceneLoader::createScene(const aiScene* src) { MaterialsVector materials = createMaterials(src); MeshesVector meshes = createMeshes(src, materials); if (meshes.empty()) { return ScenePtr(); } SceneNodePtr root = createSceneNode(src->mRootNode, meshes); if (!root) { return ScenePtr(); } ScenePtr scene = boost::make_shared<Scene>(); scene->setRoot(root); return scene; } ros::ResourcePtr ros::AssimpSceneLoader::loadResource(const std::string& name) { const aiScene* const src = importer->ReadFile(name.c_str(), aiProcess_Triangulate|aiProcess_SortByPType); if (!src) { ROS_ERROR(boost::format("Failed to load scene for resource %s - Assimp error occured %s") % name % importer->GetErrorString()); return ScenePtr(); } ScenePtr scene = createScene(src); importer->FreeScene(); return scene; }
36.774545
156
0.633244
[ "mesh" ]
c4687018ac707f64eb61e8dd5ba188010c5902f1
48,763
cpp
C++
reporting/crashsender/FilePreviewCtrl.cpp
AnotherFoxGuy/crashrpt2
0c6ca1054fb7883f092a7c9bae1d5cd44467e33a
[ "BSD-3-Clause" ]
37
2017-06-01T23:38:05.000Z
2020-11-06T02:29:47.000Z
reporting/crashsender/FilePreviewCtrl.cpp
AnotherFoxGuy/crashrpt2
0c6ca1054fb7883f092a7c9bae1d5cd44467e33a
[ "BSD-3-Clause" ]
11
2017-07-26T01:22:37.000Z
2021-01-08T07:27:02.000Z
reporting/crashsender/FilePreviewCtrl.cpp
AnotherFoxGuy/crashrpt2
0c6ca1054fb7883f092a7c9bae1d5cd44467e33a
[ "BSD-3-Clause" ]
20
2018-01-07T00:13:08.000Z
2021-01-08T07:54:03.000Z
/************************************************************************************* This file is a part of CrashRpt library. Copyright (c) 2003-2013 The CrashRpt project authors. All Rights Reserved. Use of this source code is governed by a BSD-style license that can be found in the License.txt file in the root of the source tree. All contributing project authors may be found in the Authors.txt file in the root of the source tree. ***************************************************************************************/ #include "stdafx.h" #include "FilePreviewCtrl.h" #include "png.h" #include "jpeglib.h" #include "strconv.h" #pragma warning(disable:4611) // DIBSIZE calculates the number of bytes required by an image #define WIDTHBYTES(bits) ((DWORD)(((bits)+31) & (~31)) / 8) #define DIBWIDTHBYTES(bi) (DWORD)WIDTHBYTES((DWORD)(bi).biWidth * (DWORD)(bi).biBitCount) #define _DIBSIZE(bi) (DIBWIDTHBYTES(bi) * (DWORD)(bi).biHeight) #define DIBSIZE(bi) ((bi).biHeight < 0 ? (-1)*(_DIBSIZE(bi)) : _DIBSIZE(bi)) static inline unsigned char CLAMP(int x) { return (unsigned char)((x > 255) ? 255 : (x < 0) ? 0 : x); } //----------------------------------------------------------------------------- // CFileMemoryMapping implementation //----------------------------------------------------------------------------- CFileMemoryMapping::CFileMemoryMapping() { // Set member vars to the default values m_hFile = INVALID_HANDLE_VALUE; m_uFileLength = 0; m_hFileMapping = NULL; SYSTEM_INFO si; GetSystemInfo(&si); m_dwAllocGranularity = si.dwAllocationGranularity; } CFileMemoryMapping::~CFileMemoryMapping() { Destroy(); } BOOL CFileMemoryMapping::Init(LPCTSTR szFileName) { if(m_hFile!=INVALID_HANDLE_VALUE) { // If a file mapping already created, destroy it Destroy(); } // Open file handle m_hFile = CreateFile(szFileName, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0); if(m_hFile == INVALID_HANDLE_VALUE) return FALSE; // Create file mapping m_hFileMapping = CreateFileMapping(m_hFile, 0, PAGE_READONLY, 0, 0, 0); LARGE_INTEGER size; GetFileSizeEx(m_hFile, &size); m_uFileLength = size.QuadPart; return TRUE; } BOOL CFileMemoryMapping::Destroy() { // Unmap all views std::map<DWORD, LPBYTE>::iterator it; for(it=m_aViewStartPtrs.begin(); it!=m_aViewStartPtrs.end(); it++) { if(it->second != NULL) UnmapViewOfFile(it->second); } m_aViewStartPtrs.clear(); // Close file mapping handle if(m_hFileMapping!=NULL) { CloseHandle(m_hFileMapping); } // Close file handle if(m_hFile!=INVALID_HANDLE_VALUE) { CloseHandle(m_hFile); } m_hFileMapping = NULL; m_hFile = INVALID_HANDLE_VALUE; m_uFileLength = 0; return TRUE; } ULONG64 CFileMemoryMapping::GetSize() { return m_uFileLength; } LPBYTE CFileMemoryMapping::CreateView(DWORD dwOffset, DWORD dwLength) { DWORD dwThreadId = GetCurrentThreadId(); DWORD dwBaseOffs = dwOffset-dwOffset%m_dwAllocGranularity; DWORD dwDiff = dwOffset-dwBaseOffs; LPBYTE pPtr = NULL; CAutoLock lock(&m_csLock); std::map<DWORD, LPBYTE>::iterator it = m_aViewStartPtrs.find(dwThreadId); if(it!=m_aViewStartPtrs.end()) { UnmapViewOfFile(it->second); } pPtr = (LPBYTE)MapViewOfFile(m_hFileMapping, FILE_MAP_READ, 0, dwBaseOffs, dwLength+dwDiff); if(it!=m_aViewStartPtrs.end()) { it->second = pPtr; } else { m_aViewStartPtrs[dwThreadId] = pPtr; } return (pPtr+dwDiff); } CImage::CImage() { m_hBitmap = NULL; m_hPalette = NULL; m_bLoadCancelled = FALSE; } CImage::~CImage() { Destroy(); } BOOL CImage::IsBitmap(FILE* f) { rewind(f); BITMAPFILEHEADER bfh; size_t n = fread(&bfh, sizeof(bfh), 1, f); if(n!=1) return FALSE; if(memcmp(&bfh.bfType, "BM", 2)!=0) return FALSE; return TRUE; } BOOL CImage::IsPNG(FILE* f) { png_byte header[8]; rewind(f); fread(header, 1, 8, f); if(png_sig_cmp(header, 0, 8)) return FALSE; return TRUE; } BOOL CImage::IsJPEG(FILE* f) { rewind(f); // Read first two bytes (SOI marker). // Each JPEG file begins with SOI marker (0xD8FF). WORD wSOIMarker; int n = (int)fread(&wSOIMarker, 1, 2, f); if(n!=2) return FALSE; if(wSOIMarker==0xD8FF) return TRUE; // This is a JPEG file return FALSE; } BOOL CImage::IsImageFile(CString sFileName) { FILE* f = NULL; _TFOPEN_S(f, sFileName.GetBuffer(0), _T("rb")); if(f==NULL) return FALSE; if(IsBitmap(f) || IsPNG(f) || IsJPEG(f)) { fclose(f); return TRUE; } fclose(f); return FALSE; } void CImage::Destroy() { CAutoLock lock(&m_csLock); if(m_hBitmap) { DeleteObject(m_hBitmap); m_hBitmap = NULL; } if(m_hPalette) { DeleteObject(m_hPalette); m_hPalette = NULL; } m_bLoadCancelled = FALSE; } BOOL CImage::IsValid() { CAutoLock lock(&m_csLock); return m_hBitmap!=NULL; } BOOL CImage::Load(CString sFileName) { Destroy(); FILE* f = NULL; _TFOPEN_S(f, sFileName.GetBuffer(0), _T("rb")); if(f==NULL) return FALSE; if(IsBitmap(f)) { fclose(f); return LoadBitmapFromBMPFile(sFileName.GetBuffer(0)); } else if(IsPNG(f)) { fclose(f); return LoadBitmapFromPNGFile(sFileName.GetBuffer(0)); } else if(IsJPEG(f)) { fclose(f); return LoadBitmapFromJPEGFile(sFileName.GetBuffer(0)); } fclose(f); return FALSE; } void CImage::Cancel() { CAutoLock lock(&m_csLock); m_bLoadCancelled = TRUE; } // The following code was taken from http://support.microsoft.com/kb/158898 BOOL CImage::LoadBitmapFromBMPFile(LPTSTR szFileName) { CAutoLock lock(&m_csLock); BITMAP bm; // Use LoadImage() to get the image loaded into a DIBSection m_hBitmap = (HBITMAP)LoadImage( NULL, szFileName, IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION | LR_DEFAULTSIZE | LR_LOADFROMFILE ); if( m_hBitmap == NULL ) return FALSE; // Get the color depth of the DIBSection GetObject(m_hBitmap, sizeof(BITMAP), &bm ); // If the DIBSection is 256 color or less, it has a color table if( ( bm.bmBitsPixel * bm.bmPlanes ) <= 8 ) { HDC hMemDC = NULL; HBITMAP hOldBitmap = NULL; RGBQUAD rgb[256]; LPLOGPALETTE pLogPal = NULL; WORD i = 0; // Create a memory DC and select the DIBSection into it hMemDC = CreateCompatibleDC( NULL ); hOldBitmap = (HBITMAP)SelectObject( hMemDC, m_hBitmap ); // Get the DIBSection's color table GetDIBColorTable( hMemDC, 0, 256, rgb ); // Create a palette from the color tabl pLogPal = (LOGPALETTE *)malloc( sizeof(LOGPALETTE) + (256*sizeof(PALETTEENTRY)) ); pLogPal->palVersion = 0x300; pLogPal->palNumEntries = 256; for(i=0;i<256;i++) { pLogPal->palPalEntry[i].peRed = rgb[i].rgbRed; pLogPal->palPalEntry[i].peGreen = rgb[i].rgbGreen; pLogPal->palPalEntry[i].peBlue = rgb[i].rgbBlue; pLogPal->palPalEntry[i].peFlags = 0; } m_hPalette = CreatePalette( pLogPal ); // Clean up free( pLogPal ); SelectObject( hMemDC, hOldBitmap ); DeleteDC( hMemDC ); } else // It has no color table, so use a halftone palette { HDC hRefDC = NULL; hRefDC = GetDC( NULL ); m_hPalette = CreateHalftonePalette( hRefDC ); ReleaseDC( NULL, hRefDC ); } return TRUE; } BOOL CImage::LoadBitmapFromPNGFile(LPTSTR szFileName) { BOOL bStatus = FALSE; FILE *fp = NULL; const int number = 8; png_byte header[number]; png_structp png_ptr = NULL; png_infop info_ptr = NULL; png_infop end_info = NULL; png_uint_32 rowbytes = 0; png_uint_32 width = 0; png_uint_32 height = 0; png_bytep row = NULL; int y = 0; BITMAPINFO* pBMI = NULL; HDC hDC = NULL; _TFOPEN_S(fp, szFileName, _T("rb")); if (!fp) { return FALSE; } fread(header, 1, number, fp); if(png_sig_cmp(header, 0, number)) { goto cleanup; } png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr) goto cleanup; if (setjmp(png_ptr->jmpbuf)) goto cleanup; info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) goto cleanup; end_info = png_create_info_struct(png_ptr); if (!end_info) goto cleanup; png_init_io(png_ptr, fp); png_set_sig_bytes(png_ptr, number); // Read PNG information png_read_info(png_ptr, info_ptr); // Get count of bytes per row rowbytes = png_get_rowbytes(png_ptr, info_ptr); row = new png_byte[rowbytes]; width = png_get_image_width(png_ptr, info_ptr); height = png_get_image_height(png_ptr, info_ptr); if(info_ptr->channels==3) { png_set_strip_16(png_ptr); png_set_packing(png_ptr); png_set_bgr(png_ptr); } hDC = GetDC(NULL); { CAutoLock lock(&m_csLock); if(m_bLoadCancelled) goto cleanup; m_hBitmap = CreateCompatibleBitmap(hDC, width, height); } pBMI = (BITMAPINFO*)new BYTE[sizeof(BITMAPINFO)+256*4]; memset(pBMI, 0, sizeof(BITMAPINFO)+256*4); pBMI->bmiHeader.biSize = sizeof(BITMAPINFO); pBMI->bmiHeader.biBitCount = 8*info_ptr->channels; pBMI->bmiHeader.biWidth = width; pBMI->bmiHeader.biHeight = height; pBMI->bmiHeader.biPlanes = 1; pBMI->bmiHeader.biCompression = BI_RGB; pBMI->bmiHeader.biSizeImage = rowbytes*height; if( info_ptr->channels == 1 ) { RGBQUAD* palette = pBMI->bmiColors; int i; for( i = 0; i < 256; i++ ) { palette[i].rgbBlue = palette[i].rgbGreen = palette[i].rgbRed = (BYTE)i; palette[i].rgbReserved = 0; } palette[256].rgbBlue = palette[256].rgbGreen = palette[256].rgbRed = 255; } for(y=height-1; y>=0; y--) { png_read_rows(png_ptr, &row, png_bytepp_NULL, 1); { CAutoLock lock(&m_csLock); int n = SetDIBits(hDC, m_hBitmap, y, 1, row, pBMI, DIB_RGB_COLORS); if(n==0) goto cleanup; } } /* Read rest of file, and get additional chunks in info_ptr - REQUIRED */ png_read_end(png_ptr, info_ptr); bStatus = TRUE; cleanup: if(fp!=NULL) { fclose(fp); } if(png_ptr) { png_destroy_read_struct(&png_ptr, (png_infopp)&info_ptr, (png_infopp)&end_info); } if(row) { delete [] row; } if(pBMI) { delete [] pBMI; } if(!bStatus) { Destroy(); } return bStatus; } BOOL CImage::LoadBitmapFromJPEGFile(LPTSTR szFileName) { BOOL bStatus = false; struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; FILE* fp = NULL; JSAMPROW row = NULL; BITMAPINFO bmi; HDC hDC = NULL; cinfo.err = jpeg_std_error(&jerr); jpeg_create_decompress(&cinfo); _TFOPEN_S(fp, szFileName, _T("rb")); if (!fp) { goto cleanup; } jpeg_stdio_src(&cinfo, fp); jpeg_read_header(&cinfo, TRUE); jpeg_start_decompress(&cinfo); row = new BYTE[cinfo.output_width*3+10]; hDC = GetDC(NULL); { CAutoLock lock(&m_csLock); if(m_bLoadCancelled) goto cleanup; m_hBitmap = CreateCompatibleBitmap(hDC, cinfo.output_width, cinfo.output_height); } memset(&bmi, 0, sizeof(bmi)); bmi.bmiHeader.biSize = sizeof(bmi); bmi.bmiHeader.biBitCount = 24; bmi.bmiHeader.biWidth = cinfo.output_width; bmi.bmiHeader.biHeight = cinfo.output_height; bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biCompression = BI_RGB; bmi.bmiHeader.biSizeImage = cinfo.output_width*cinfo.output_height*3; while (cinfo.output_scanline < cinfo.output_height) { jpeg_read_scanlines(&cinfo, &row, 1); if(cinfo.out_color_components==3) { // Convert RGB to BGR UINT i; for(i=0; i<cinfo.output_width; i++) { BYTE tmp = row[i*3+0]; row[i*3+0] = row[i*3+2]; row[i*3+2] = tmp; } } else { // Convert grayscale to BGR int i; for(i=cinfo.output_width-1; i>=0; i--) { row[i*3+0] = row[i]; row[i*3+1] = row[i]; row[i*3+2] = row[i]; } } { CAutoLock lock(&m_csLock); int n = SetDIBits(hDC, m_hBitmap, cinfo.output_height-cinfo.output_scanline, 1, row, &bmi, DIB_RGB_COLORS); if(n==0) goto cleanup; } } jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); bStatus = true; cleanup: if(row) delete [] row; if(!bStatus) { Destroy(); } if(fp!=NULL) { fclose(fp); fp = NULL; } return bStatus; } void CImage::Draw(HDC hDC, LPRECT prcDraw) { CAutoLock lock(&m_csLock); HPALETTE hOldPalette = NULL; CRect rcDraw = prcDraw; BITMAP bm; GetObject( m_hBitmap, sizeof(BITMAP), &bm ); HDC hMemDC = CreateCompatibleDC( hDC ); HBITMAP hOldBitmap = (HBITMAP)SelectObject(hMemDC, m_hBitmap ); if(m_hPalette) { hOldPalette = SelectPalette(hDC, m_hPalette, FALSE ); RealizePalette( hDC ); } if((float)rcDraw.Width()/(float)bm.bmWidth < (float)rcDraw.Height()/(float)bm.bmHeight) { int nDstMid = rcDraw.top + rcDraw.Height()/2; int nDstHeight = (int)( rcDraw.Width()*(float)bm.bmHeight/bm.bmWidth ); rcDraw.top = nDstMid - nDstHeight/2; rcDraw.bottom = nDstMid + nDstHeight/2; } else { int nDstMid = rcDraw.left + rcDraw.Width()/2; int nDstWidth = (int)( rcDraw.Height()*(float)bm.bmWidth/bm.bmHeight ); rcDraw.left = nDstMid - nDstWidth/2; rcDraw.right = nDstMid + nDstWidth/2; } int nOldMode = SetStretchBltMode(hDC, HALFTONE); StretchBlt(hDC, rcDraw.left, rcDraw.top, rcDraw.Width(), rcDraw.Height(), hMemDC, 0, 0, bm.bmWidth, bm.bmHeight, SRCCOPY ); SetStretchBltMode(hDC, nOldMode); SelectObject( hMemDC, hOldBitmap ); if(m_hPalette) { SelectPalette( hDC, hOldPalette, FALSE ); } } //----------------------------------------------------------------------------- // CVideo implementation //----------------------------------------------------------------------------- CVideo::CVideo() { m_pf = NULL; m_hbmpFrame = NULL; m_pFrameBits = NULL; m_pDIB = NULL; m_hDC = NULL; m_hOldBitmap = NULL; m_buf = NULL; m_psetup = NULL; m_pctx = NULL; m_pos = 0; m_nFrameWidth = 0; m_nFrameHeight = 0; m_nFrameInterval = 0; ogg_sync_init(&m_state); ogg_stream_init(&m_stream, 0); memset(&m_packet, 0, sizeof(m_packet)); th_info_init(&m_info); th_comment_init(&m_comment); } CVideo::~CVideo() { Destroy(); } BOOL CVideo::IsVideoFile(LPCTSTR szFileName) { FILE* f = NULL; _TFOPEN_S(f, szFileName, _T("rb")); if(f==NULL) return FALSE; if(IsOGG(f)) { fclose(f); return TRUE; } fclose(f); return FALSE; } BOOL CVideo::IsOGG(FILE* f) { rewind(f); // Read first three bytes (Ogg). BYTE uchBytes[4]; int n = (int)fread(uchBytes, 1, 3, f); if(n!=3) return FALSE; if(memcmp(uchBytes, "Ogg", 3)==0) return TRUE; // This is an OGG file return FALSE; } // Loads video from file. BOOL CVideo::Load(LPCTSTR szFileName) { // Destroy if previously loaded if(!m_sFileName.IsEmpty()) Destroy(); // Open file FILE* f = NULL; _TFOPEN_S(f, szFileName, _T("rb")); if(f==NULL) return FALSE; // Check OGG signature if(IsOGG(f)) { fclose(f); // Load OGG video return LoadOggFile(szFileName); } // Close file fclose(f); return FALSE; } void CVideo::Destroy() { m_sFileName.Empty(); if(m_pf) { fclose(m_pf); m_pf = NULL; } //ogg_packet_clear(&m_packet); ogg_stream_clear(&m_stream); // Call th_decode_free() to release all decoder memory. if(m_pctx) { th_decode_free(m_pctx); m_pctx = NULL; } ogg_sync_clear(&m_state); th_info_clear(&m_info); th_comment_clear(&m_comment); if(m_hbmpFrame!=NULL) { DeleteObject(m_hbmpFrame); m_hbmpFrame = NULL; } if(m_pDIB) { delete [] m_pDIB; m_pDIB = NULL; } m_pFrameBits = NULL; if(m_hDC!=NULL) { DeleteDC(m_hDC); m_hDC = NULL; } m_hOldBitmap = NULL; } BOOL CVideo::LoadOggFile(LPCTSTR szFileName) { bool bStatus = false; int ret = -1; // Open OGG file _TFOPEN_S(m_pf, szFileName, _T("rb")); if(m_pf==NULL) goto cleanup; // Error opening file // Init theora decoder structures th_info_init(&m_info); th_comment_init(&m_comment); // The first thing we need to do when reading an Ogg file is find // the first page of data. We use a ogg_sync_state structure to keep // track of search for the page data. This needs to be initialized // with ogg_sync_init and later cleaned up with ogg_sync_clear: if(0!=ogg_sync_init(&m_state)) goto cleanup; // Error initializing sync state // Parse the header packets by repeatedly calling th_decode_headerin() while(ReadOGGPacket()) { ret = th_decode_headerin(&m_info, &m_comment, &m_psetup, &m_packet); if(ret==0) { // Video data encountered break; } else if(ret==TH_EFAULT) { // Some parameters are incorrect goto cleanup; } else if(ret==TH_EBADHEADER) { //goto cleanup; } else if(ret==TH_EVERSION) { //goto cleanup; } else if(ret==TH_ENOTFORMAT ) { //goto cleanup; } } /*Allocate YV12 image */ m_nFrameWidth = m_info.frame_width; m_nFrameHeight = m_info.frame_height; m_nFrameInterval = (int)((float)m_info.fps_denominator/(float)m_info.fps_numerator*1000); if(m_hbmpFrame==NULL) { // Calculate frame size CreateFrameDIB(m_nFrameWidth, m_nFrameHeight, 24); } // Allocate a th_dec_ctx handle with th_decode_alloc(). m_pctx = th_decode_alloc(&m_info, m_psetup); // Call th_setup_free() to free any memory used for codec setup information. th_setup_free(m_psetup); m_psetup = NULL; // Perform any additional decoder configuration with th_decode_ctl(). m_sFileName = szFileName; // Done bStatus = true; cleanup: return bStatus; } BOOL CVideo::ReadOGGPage() { BOOL bStatus = FALSE; size_t nBytes = 0; // Read an entire page from OGG file while(ogg_sync_pageout(&m_state, &m_page) != 1) { // Allocate buffer m_buf = ogg_sync_buffer(&m_state, 4096); if(m_buf==NULL) goto cleanup; // Read a portion of data from file nBytes = fread(m_buf, 1, 4096, m_pf); if(nBytes==0) goto cleanup; // End of file if(0!=ogg_sync_wrote(&m_state, (long)nBytes)) goto cleanup; // Failed } bStatus = true; cleanup: return bStatus; } BOOL CVideo::ReadOGGPacket() { BOOL bStatus = FALSE; int ret = -1; while(1) { // Call ogg_stream_packetout. This will return a value indicating if // a packet of data is available in the stream. If it is not then we // need to read another page (following the same steps previously) and // add it to the stream, calling ogg_stream_packetout again until it // tells us a packet is available. The packet’s data is stored in an // ogg_packet object. ret = ogg_stream_packetout(&m_stream, &m_packet); if (ret == 0) { // Need more data to be able to complete the packet // New page if(!ReadOGGPage()) goto cleanup; // If this page is the beginning of the logical stream... if (ogg_page_bos(&m_page)) { // Get page's serial number int serial = ogg_page_serialno(&m_page); // Init OGG stream ret = ogg_stream_init(&m_stream, serial); if(ret != 0) goto cleanup; // Failed to init stream } // Pass the page data to stream ret = ogg_stream_pagein(&m_stream, &m_page); if(ret!=0) goto cleanup; continue; } else if (ret == -1) { // We are out of sync and there is a gap in the data. // We lost a page somewhere. break; } // A packet is available, this is what we pass to the // theora library to decode. bStatus = true; break; } cleanup: return bStatus; } // Decodes next video frame and returns pointer to bitmap. HBITMAP CVideo::DecodeFrame(BOOL bFirstFrame, CSize& FrameSize, int& nDuration) { FrameSize.cx = m_nFrameWidth; FrameSize.cy = m_nFrameHeight; nDuration = m_nFrameInterval; // For the first frame, we use the packet that was read previously // For next frames, we need to read new packets if(!bFirstFrame) { // Read packet if(!ReadOGGPacket()) return NULL; // No more packets } // Feed the packet to decoder int ret = th_decode_packetin(m_pctx, &m_packet, &m_pos); if(ret!=0 && ret!=TH_DUPFRAME) return NULL; // Decoding error if(ret!=TH_DUPFRAME) { // Retrieve the uncompressed video data via th_decode_ycbcr_out(). th_decode_ycbcr_out(m_pctx, &m_raw[0]); CAutoLock lock(&m_csLock); // Convert YV12 to RGB YV12_To_RGB((unsigned char*)m_pFrameBits, m_nFrameWidth, m_nFrameHeight, m_nFrameWidth*3+(m_nFrameWidth*3)%4, &m_raw[0]); } // Return bitmap return m_hbmpFrame; } void CVideo::DrawFrame(HDC hDC, LPRECT prcDraw) { CAutoLock lock(&m_csLock); CRect rcDraw = prcDraw; BITMAP bm; GetObject(m_hbmpFrame, sizeof(BITMAP), &bm ); if((float)rcDraw.Width()/(float)bm.bmWidth < (float)rcDraw.Height()/(float)bm.bmHeight) { int nDstMid = rcDraw.top + rcDraw.Height()/2; int nDstHeight = (int)( rcDraw.Width()*(float)bm.bmHeight/bm.bmWidth ); rcDraw.top = nDstMid - nDstHeight/2; rcDraw.bottom = nDstMid + nDstHeight/2; } else { int nDstMid = rcDraw.left + rcDraw.Width()/2; int nDstWidth = (int)( rcDraw.Height()*(float)bm.bmWidth/bm.bmHeight ); rcDraw.left = nDstMid - nDstWidth/2; rcDraw.right = nDstMid + nDstWidth/2; } int nOldMode = SetStretchBltMode(hDC, HALFTONE); StretchBlt(hDC, rcDraw.left, rcDraw.top, rcDraw.Width(), rcDraw.Height(), m_hDC, 0, 0, bm.bmWidth, bm.bmHeight, SRCCOPY ); SetStretchBltMode(hDC, nOldMode); } void CVideo::Reset() { } // Returns TRUE if video is valid, otherwise returns FALSE BOOL CVideo::IsValid() { return m_sFileName.IsEmpty()?FALSE:TRUE; } // Converts an YV12 image to RGB24 image. void CVideo::YV12_To_RGB(unsigned char *pRGBData, int nFrameWidth, int nFrameHeight, int nRGBStride, th_ycbcr_buffer raw) { int x, y; for(y=0; y<nFrameHeight;y++) { for (x=0; x < nFrameWidth; x ++) { int nRGBOffs = y*nRGBStride+x*3; float Y = raw[0].data[y*raw[0].stride+x]; float U = raw[1].data[y/2*raw[1].stride+x/2]; float V = raw[2].data[y/2*raw[2].stride+x/2]; pRGBData[nRGBOffs+0] = CLAMP((int)(1.164*(Y - 16) + 2.018*(U - 128))); pRGBData[nRGBOffs+1] = CLAMP((int)(1.164*(Y - 16) - 0.813*(V - 128) - 0.391*(U - 128))); pRGBData[nRGBOffs+2] = CLAMP((int)(1.164*(Y - 16) + 1.596*(V - 128))); } } } BOOL CVideo::CreateFrameDIB(DWORD dwWidth, DWORD dwHeight, int nBits) { if (m_pDIB) return FALSE; const DWORD dwcBihSize = sizeof(BITMAPINFOHEADER); // Calculate the memory required for the DIB DWORD dwSize = dwcBihSize + (2>>nBits) * sizeof(RGBQUAD) + ((nBits * dwWidth) * dwHeight); m_pDIB = (LPBITMAPINFO)new BYTE[dwSize]; if (!m_pDIB) return FALSE; m_pDIB->bmiHeader.biSize = dwcBihSize; m_pDIB->bmiHeader.biWidth = dwWidth; m_pDIB->bmiHeader.biHeight = -(LONG)dwHeight; m_pDIB->bmiHeader.biBitCount = (WORD)nBits; m_pDIB->bmiHeader.biPlanes = 1; m_pDIB->bmiHeader.biCompression = BI_RGB; m_pDIB->bmiHeader.biXPelsPerMeter = 1000; m_pDIB->bmiHeader.biYPelsPerMeter = 1000; m_pDIB->bmiHeader.biClrUsed = 0; m_pDIB->bmiHeader.biClrImportant = 0; LPRGBQUAD lpColors = (LPRGBQUAD)(m_pDIB+m_pDIB->bmiHeader.biSize); int nColors=2>>m_pDIB->bmiHeader.biBitCount; for(int i=0;i<nColors;i++) { lpColors[i].rgbRed=0; lpColors[i].rgbBlue=0; lpColors[i].rgbGreen=0; lpColors[i].rgbReserved=0; } m_hDC = CreateCompatibleDC(GetDC(NULL)); m_hbmpFrame = CreateDIBSection(m_hDC, m_pDIB, DIB_RGB_COLORS, &m_pFrameBits, NULL, 0); m_hOldBitmap = (HBITMAP)SelectObject(m_hDC, m_hbmpFrame); return TRUE; } //----------------------------------------------------------------------------- // CFilePreviewCtrl implementation //----------------------------------------------------------------------------- CFilePreviewCtrl::CFilePreviewCtrl() { m_xChar = 10; m_yChar = 10; m_nHScrollPos = 0; m_nHScrollMax = 0; m_nMaxColsPerPage = 0; m_nMaxLinesPerPage = 0; m_nMaxDisplayWidth = 0; m_uNumLines = 0; m_nVScrollPos = 0; m_nVScrollMax = 0; m_nBytesPerLine = 16; m_cchTabLength = 4; m_sEmptyMsg = _T("No data to display"); m_hFont = CreateFont(14, 7, 0, 0, 0, 0, 0, 0, ANSI_CHARSET, 0, 0, ANTIALIASED_QUALITY, FIXED_PITCH, _T("Courier")); m_hWorkerThread = NULL; m_bCancelled = FALSE; m_PreviewMode = PREVIEW_HEX; m_TextEncoding = ENC_ASCII; m_nEncSignatureLen = 0; } CFilePreviewCtrl::~CFilePreviewCtrl() { m_bmp.Destroy(); m_fm.Destroy(); DeleteObject(m_hFont); } LPCTSTR CFilePreviewCtrl::GetFile() { if(m_sFileName.IsEmpty()) return NULL; return m_sFileName; } BOOL CFilePreviewCtrl::SetFile(LPCTSTR szFileName, PreviewMode mode, TextEncoding enc) { // If we are currently processing some file in background, // stop the worker thread if(m_hWorkerThread!=NULL) { m_bCancelled = TRUE; m_bmp.Cancel(); WaitForSingleObject(m_hWorkerThread, INFINITE); m_hWorkerThread = NULL; } CAutoLock lock(&m_csLock); m_sFileName = szFileName; if(mode==PREVIEW_AUTO) m_PreviewMode = DetectPreviewMode(m_sFileName); else m_PreviewMode = mode; if(szFileName==NULL) { m_fm.Destroy(); } else { if(!m_fm.Init(m_sFileName)) { m_sFileName.Empty(); return FALSE; } } CRect rcClient; GetClientRect(&rcClient); HDC hDC = GetDC(); HFONT hOldFont = (HFONT)SelectObject(hDC, m_hFont); LOGFONT lf; ZeroMemory(&lf, sizeof(LOGFONT)); GetObject(m_hFont, sizeof(LOGFONT), &lf); m_xChar = lf.lfWidth; m_yChar = lf.lfHeight; SelectObject(hDC, hOldFont); m_nVScrollPos = 0; m_nVScrollMax = 0; m_nHScrollPos = 0; m_nHScrollMax = 0; m_aTextLines.clear(); m_uNumLines = 0; m_nMaxDisplayWidth = 0; m_bmp.Destroy(); m_video.Destroy(); if(m_PreviewMode==PREVIEW_HEX) { if(m_fm.GetSize()!=0) { m_nMaxDisplayWidth = 8 + //adress 2 + //padding m_nBytesPerLine * 3 + //hex column 1 + //padding m_nBytesPerLine; //ascii column } m_uNumLines = m_fm.GetSize() / m_nBytesPerLine; if(m_fm.GetSize() % m_nBytesPerLine) m_uNumLines++; } else if(m_PreviewMode==PREVIEW_TEXT) { if(enc==ENC_AUTO) m_TextEncoding = DetectTextEncoding(m_sFileName, m_nEncSignatureLen); else { m_TextEncoding = enc; // Determine the length of the signature. int nSignatureLen = 0; TextEncoding enc2 = DetectTextEncoding(m_sFileName, nSignatureLen); if(enc==enc2) m_nEncSignatureLen = nSignatureLen; } m_bCancelled = FALSE; m_hWorkerThread = CreateThread(NULL, 0, WorkerThread, this, 0, NULL); ::SetTimer(m_hWnd, 0, 250, NULL); } else if(m_PreviewMode==PREVIEW_IMAGE) { m_bCancelled = FALSE; m_hWorkerThread = CreateThread(NULL, 0, WorkerThread, this, 0, NULL); ::SetTimer(m_hWnd, 0, 250, NULL); } else if(m_PreviewMode==PREVIEW_VIDEO) { m_bCancelled = FALSE; m_hWorkerThread = CreateThread(NULL, 0, WorkerThread, this, 0, NULL); //::SetTimer(m_hWnd, 0, 250, NULL); } SetupScrollbars(); InvalidateRect(NULL, FALSE); UpdateWindow(); return TRUE; } PreviewMode CFilePreviewCtrl::GetPreviewMode() { return m_PreviewMode; } void CFilePreviewCtrl::SetPreviewMode(PreviewMode mode) { SetFile(m_sFileName, mode); } TextEncoding CFilePreviewCtrl::GetTextEncoding() { return m_TextEncoding; } void CFilePreviewCtrl::SetTextEncoding(TextEncoding enc) { SetFile(m_sFileName, m_PreviewMode, enc); } PreviewMode CFilePreviewCtrl::DetectPreviewMode(LPCTSTR szFileName) { PreviewMode mode = PREVIEW_HEX; CString sFileName; std::set<CString>::iterator it; std::set<CString> aTextFileExtensions; CString sExtension; sFileName = szFileName; if(CImage::IsImageFile(sFileName)) { mode = PREVIEW_IMAGE; goto cleanup; } else if(CVideo::IsVideoFile(sFileName)) { mode = PREVIEW_VIDEO; goto cleanup; } int backslash_pos = sFileName.ReverseFind('\\'); if(backslash_pos>=0) sFileName = sFileName.Mid(backslash_pos+1); int dot_pos = sFileName.ReverseFind('.'); if(dot_pos>0) sExtension = sFileName.Mid(dot_pos+1); sExtension.MakeUpper(); aTextFileExtensions.insert(_T("TXT")); aTextFileExtensions.insert(_T("INI")); aTextFileExtensions.insert(_T("LOG")); aTextFileExtensions.insert(_T("XML")); aTextFileExtensions.insert(_T("HTM")); aTextFileExtensions.insert(_T("HTML")); aTextFileExtensions.insert(_T("JS")); aTextFileExtensions.insert(_T("C")); aTextFileExtensions.insert(_T("H")); aTextFileExtensions.insert(_T("CPP")); aTextFileExtensions.insert(_T("HPP")); it = aTextFileExtensions.find(sExtension); if(it!=aTextFileExtensions.end()) { mode = PREVIEW_TEXT; } cleanup: return mode; } TextEncoding CFilePreviewCtrl::DetectTextEncoding(LPCTSTR szFileName, int& nSignatureLen) { TextEncoding enc = ENC_ASCII; nSignatureLen = 0; FILE* f = NULL; #if _MSC_VER<1400 f = _tfopen(szFileName, _T("rb")); #else _tfopen_s(&f, szFileName, _T("rb")); #endif if(f==NULL) goto cleanup; BYTE signature2[2]; size_t nRead = fread(signature2, 1, 2, f); if(nRead!=2) goto cleanup; // Compare with UTF-16 LE signature if(signature2[0]==0xFF && signature2[1]==0xFE ) { enc = ENC_UTF16_LE; nSignatureLen = 2; goto cleanup; } // Compare with UTF-16 BE signature if(signature2[0]==0xFE && signature2[1]==0xFF ) { enc = ENC_UTF16_BE; nSignatureLen = 2; goto cleanup; } rewind(f); BYTE signature3[3]; nRead = fread(signature3, 1, 3, f); if(nRead!=3) goto cleanup; // Compare with UTF-8 signature if(signature3[0]==0xEF && signature3[1]==0xBB && signature3[2]==0xBF ) { enc = ENC_UTF8; nSignatureLen = 3; goto cleanup; } cleanup: fclose(f); return enc; } DWORD WINAPI CFilePreviewCtrl::WorkerThread(LPVOID lpParam) { CFilePreviewCtrl* pCtrl = (CFilePreviewCtrl*)lpParam; pCtrl->DoInWorkerThread(); return 0; } void CFilePreviewCtrl::DoInWorkerThread() { if(m_PreviewMode==PREVIEW_TEXT) ParseText(); else if(m_PreviewMode==PREVIEW_IMAGE) LoadBitmap(); if(m_PreviewMode==PREVIEW_VIDEO) LoadVideo(); } WCHAR swap_bytes(WCHAR src_char) { return (WCHAR)MAKEWORD((src_char>>8), (src_char&0xFF)); } void CFilePreviewCtrl::ParseText() { DWORD dwFileSize = (DWORD)m_fm.GetSize(); DWORD dwOffset = 0; DWORD dwPrevOffset = 0; int nTabs = 0; if(dwFileSize!=0) { CAutoLock lock(&m_csLock); if(m_PreviewMode==PREVIEW_TEXT) { dwOffset+=m_nEncSignatureLen; m_aTextLines.push_back(dwOffset); } else { m_aTextLines.push_back(0); } m_uNumLines++; } for(;;) { { CAutoLock lock(&m_csLock); if(m_bCancelled) break; } DWORD dwLength = 4096; if(dwOffset+dwLength>=dwFileSize) dwLength = dwFileSize-dwOffset; if(dwLength==0) break; LPBYTE ptr = m_fm.CreateView(dwOffset, dwLength); UINT i; for(i=0; i<dwLength; ) { { CAutoLock lock(&m_csLock); if(m_bCancelled) break; } if(m_TextEncoding==ENC_UTF16_LE || m_TextEncoding==ENC_UTF16_BE) { WCHAR src_char = ((WCHAR*)ptr)[i/2]; WCHAR c = m_TextEncoding==ENC_UTF16_LE?src_char:swap_bytes(src_char); if(c=='\t') { nTabs++; } else if(c=='\n') { CAutoLock lock(&m_csLock); m_aTextLines.push_back(dwOffset+i+2); int cchLineLength = dwOffset+i+2-dwPrevOffset; if(nTabs!=0) cchLineLength += nTabs*(m_cchTabLength-1); m_nMaxDisplayWidth = max(m_nMaxDisplayWidth, cchLineLength); m_uNumLines++; dwPrevOffset = dwOffset+i+2; nTabs = 0; } i+=2; } else { char c = ((char*)ptr)[i]; if(c=='\t') { nTabs++; } else if(c=='\n') { CAutoLock lock(&m_csLock); m_aTextLines.push_back(dwOffset+i+1); int cchLineLength = dwOffset+i+1-dwPrevOffset; if(nTabs!=0) cchLineLength += nTabs*(m_cchTabLength-1); m_nMaxDisplayWidth = max(m_nMaxDisplayWidth, cchLineLength); m_uNumLines++; dwPrevOffset = dwOffset+i+1; nTabs = 0; } i++; } } dwOffset += dwLength; } PostMessage(WM_FPC_COMPLETE); } void CFilePreviewCtrl::LoadBitmap() { m_bmp.Load(m_sFileName); PostMessage(WM_FPC_COMPLETE); } void CFilePreviewCtrl::LoadVideo() { int nFrame = 0; CSize FrameSize; int nFrameInterval; if(m_video.Load(m_sFileName)) { while(m_video.DecodeFrame(nFrame==0?TRUE:FALSE, FrameSize, nFrameInterval)) { if(m_bCancelled) break; nFrame++; InvalidateRect(NULL); Sleep(nFrameInterval); } } PostMessage(WM_FPC_COMPLETE); } void CFilePreviewCtrl::SetEmptyMessage(CString sText) { m_sEmptyMsg = sText; } BOOL CFilePreviewCtrl::SetBytesPerLine(int nBytesPerLine) { if(nBytesPerLine<0) return FALSE; m_nBytesPerLine = nBytesPerLine; return TRUE; } void CFilePreviewCtrl::SetupScrollbars() { CAutoLock lock(&m_csLock); CRect rcClient; GetClientRect(&rcClient); SCROLLINFO sInfo; // Vertical scrollbar m_nMaxLinesPerPage = (int)min(m_uNumLines, rcClient.Height() / m_yChar); m_nVScrollMax = (int)max(0, m_uNumLines-1); m_nVScrollPos = (int)min(m_nVScrollPos, m_nVScrollMax-m_nMaxLinesPerPage+1); sInfo.cbSize = sizeof(SCROLLINFO); sInfo.fMask = SIF_PAGE | SIF_POS | SIF_RANGE; sInfo.nMin = 0; sInfo.nMax = m_nVScrollMax; sInfo.nPos = m_nVScrollPos; sInfo.nPage = min(m_nMaxLinesPerPage, m_nVScrollMax+1); SetScrollInfo (SB_VERT, &sInfo, TRUE); // Horizontal scrollbar m_nMaxColsPerPage = min(m_nMaxDisplayWidth+1, rcClient.Width() / m_xChar); m_nHScrollMax = max(0, m_nMaxDisplayWidth-1); m_nHScrollPos = min(m_nHScrollPos, m_nHScrollMax-m_nMaxColsPerPage+1); sInfo.cbSize = sizeof(SCROLLINFO); sInfo.fMask = SIF_POS | SIF_PAGE | SIF_RANGE; sInfo.nMin = 0; sInfo.nMax = m_nHScrollMax; sInfo.nPos = m_nHScrollPos; sInfo.nPage = min(m_nMaxColsPerPage, m_nHScrollMax+1); SetScrollInfo (SB_HORZ, &sInfo, TRUE); } // // Create 1 line of a hex-dump, given a buffer of BYTES // CString CFilePreviewCtrl::FormatHexLine(LPBYTE pData, int nBytesInLine, ULONG64 uLineOffset) { CString sResult; CString str; int i; //print the hex address str.Format(_T("%08X "), uLineOffset); sResult += str; //print hex data for(i = 0; i < nBytesInLine; i++) { str.Format(_T("%02X "), pData[i]); sResult += str; } //print some blanks if this isn't a full line for(; i < m_nBytesPerLine; i++) { str.Format(_T(" ")); sResult += str; } //print a gap between the hex and ascii sResult += _T(" "); //print the ascii for(i = 0; i < nBytesInLine; i++) { BYTE c = pData[i]; if(c < 32 || c > 128) c = '.'; str.Format( _T("%c"), c); sResult += str; } //print some blanks if this isn't a full line for(; i < m_nBytesPerLine; i++) { sResult += _T(" "); } return sResult; } // // Draw 1 line to the display // void CFilePreviewCtrl::DrawHexLine(HDC hdc, DWORD nLineNo) { int nBytesPerLine = m_nBytesPerLine; if(m_fm.GetSize() - nLineNo * m_nBytesPerLine < (UINT)m_nBytesPerLine) nBytesPerLine= (DWORD)m_fm.GetSize() - nLineNo * m_nBytesPerLine; //get data from our file mapping LPBYTE ptr = m_fm.CreateView(nLineNo * m_nBytesPerLine, nBytesPerLine); //convert the data into a one-line hex-dump CString str = FormatHexLine(ptr, nBytesPerLine, nLineNo*m_nBytesPerLine ); //draw this line to the screen TextOut(hdc, -(int)(m_nHScrollPos * m_xChar), (nLineNo - m_nVScrollPos) * (m_yChar-1) , str, str.GetLength()); } void CFilePreviewCtrl::DrawTextLine(HDC hdc, DWORD nLineNo) { CRect rcClient; GetClientRect(&rcClient); DWORD dwOffset = 0; DWORD dwLength = 0; { CAutoLock lock(&m_csLock); dwOffset = m_aTextLines[nLineNo]; if(nLineNo==m_uNumLines-1) dwLength = (DWORD)m_fm.GetSize() - dwOffset; else dwLength = m_aTextLines[nLineNo+1]-dwOffset-1; } if(dwLength==0) return; //get data from our file mapping LPBYTE ptr = m_fm.CreateView(dwOffset, dwLength); //draw this line to the screen CRect rcText; rcText.left = -(int)(m_nHScrollPos * m_xChar); rcText.top = (nLineNo - m_nVScrollPos) * m_yChar; rcText.right = rcClient.right; rcText.bottom = rcText.top + m_yChar; DRAWTEXTPARAMS params; memset(&params, 0, sizeof(DRAWTEXTPARAMS)); params.cbSize = sizeof(DRAWTEXTPARAMS); params.iTabLength = m_xChar*m_cchTabLength; DWORD dwFlags = DT_LEFT|DT_TOP|DT_SINGLELINE|DT_NOPREFIX|DT_EXPANDTABS; if(m_TextEncoding==ENC_UTF8) { // Decode line strconv_t strconv; LPCWSTR szLine = strconv.utf82w((char*)ptr, dwLength-1); DrawTextExW(hdc, (LPWSTR)szLine, -1, &rcText, dwFlags, &params); } else if(m_TextEncoding==ENC_UTF16_LE) { DrawTextExW(hdc, (WCHAR*)ptr, dwLength/2-1, &rcText, dwFlags, &params); } else if(m_TextEncoding==ENC_UTF16_BE) { // Decode line strconv_t strconv; LPCWSTR szLine = strconv.w2w_be((WCHAR*)ptr, dwLength/2-1); DrawTextExW(hdc, (LPWSTR)szLine, -1, &rcText, dwFlags, &params); } else // ASCII { DrawTextExA(hdc, (char*)ptr, dwLength-1, &rcText, dwFlags, &params); } } void CFilePreviewCtrl::DoPaintEmpty(HDC hDC) { RECT rcClient; GetClientRect(&rcClient); HFONT hOldFont = (HFONT)SelectObject(hDC, m_hFont); FillRect(hDC, &rcClient, (HBRUSH)GetStockObject(WHITE_BRUSH)); CRect rcText; DrawTextEx(hDC, m_sEmptyMsg.GetBuffer(0), -1, &rcText, DT_CALCRECT, NULL); rcText.MoveToX(rcClient.right/2-rcText.right/2); DrawTextEx(hDC, m_sEmptyMsg.GetBuffer(0), -1, &rcText, DT_LEFT, NULL); SelectObject(hDC, hOldFont); } void CFilePreviewCtrl::DoPaintText(HDC hDC) { HFONT hOldFont = (HFONT)SelectObject(hDC, m_hFont); RECT rcClient; GetClientRect(&rcClient); HRGN hRgn = CreateRectRgn(0, 0, rcClient.right, rcClient.bottom); SelectClipRgn(hDC, hRgn); FillRect(hDC, &rcClient, (HBRUSH)GetStockObject(WHITE_BRUSH)); int iPaintBeg = max(0, m_nVScrollPos); //only update the lines that int iPaintEnd = (int)min(m_uNumLines, m_nVScrollPos + rcClient.bottom / m_yChar); //need updating!!!!!!!!!!!!! if(rcClient.bottom % m_yChar) iPaintEnd++; if(iPaintEnd > m_uNumLines) iPaintEnd--; // // Only paint what needs to be! // int i; for(i = iPaintBeg; i < iPaintEnd; i++) { if(m_PreviewMode==PREVIEW_HEX) DrawHexLine(hDC, i); else DrawTextLine(hDC, i); } SelectObject(hDC, hOldFont); } void CFilePreviewCtrl::DoPaintBitmap(HDC hDC) { RECT rcClient; GetClientRect(&rcClient); HRGN hRgn = CreateRectRgn(0, 0, rcClient.right, rcClient.bottom); SelectClipRgn(hDC, hRgn); FillRect(hDC, &rcClient, (HBRUSH)GetStockObject(WHITE_BRUSH)); if(m_bmp.IsValid()) { m_bmp.Draw(hDC, &rcClient); } else { DoPaintEmpty(hDC); } } void CFilePreviewCtrl::DoPaintVideo(HDC hDC) { RECT rcClient; GetClientRect(&rcClient); HRGN hRgn = CreateRectRgn(0, 0, rcClient.right, rcClient.bottom); SelectClipRgn(hDC, hRgn); FillRect(hDC, &rcClient, (HBRUSH)GetStockObject(WHITE_BRUSH)); if(m_video.IsValid()) { m_video.DrawFrame(hDC, &rcClient); } else { DoPaintEmpty(hDC); } } void CFilePreviewCtrl::DoPaint(HDC hDC) { if(m_PreviewMode==PREVIEW_TEXT || m_PreviewMode==PREVIEW_HEX) { DoPaintText(hDC); } else if(m_PreviewMode==PREVIEW_IMAGE) { DoPaintBitmap(hDC); } else if(m_PreviewMode==PREVIEW_VIDEO) { DoPaintVideo(hDC); } } LRESULT CFilePreviewCtrl::OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled) { m_fm.Destroy(); bHandled = FALSE; return 0; } LRESULT CFilePreviewCtrl::OnSize(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { SetupScrollbars(); InvalidateRect(NULL, FALSE); UpdateWindow(); return 0; } LRESULT CFilePreviewCtrl::OnHScroll(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/) { SCROLLINFO info; int nHScrollInc = 0; int nOldHScrollPos = m_nHScrollPos; switch (LOWORD(wParam)) { case SB_LEFT: m_nHScrollPos = 0; break; case SB_RIGHT: m_nHScrollPos = m_nHScrollMax + 1; break; case SB_LINELEFT: if(m_nHScrollPos > 0) --m_nHScrollPos; break; case SB_LINERIGHT: m_nHScrollPos++; break; case SB_PAGELEFT: m_nHScrollPos -= m_nMaxColsPerPage; if(m_nHScrollPos > nOldHScrollPos) m_nHScrollPos = 0; break; case SB_PAGERIGHT: m_nHScrollPos += m_nMaxColsPerPage; break; case SB_THUMBPOSITION: info.cbSize = sizeof(SCROLLINFO); info.fMask = SIF_TRACKPOS; GetScrollInfo(SB_HORZ, &info); m_nHScrollPos = info.nTrackPos; break; case SB_THUMBTRACK: info.cbSize = sizeof(SCROLLINFO); info.fMask = SIF_TRACKPOS; GetScrollInfo(SB_HORZ, &info); m_nHScrollPos = info.nTrackPos; break; default: nHScrollInc = 0; } //keep scroll position in range if(m_nHScrollPos > m_nHScrollMax - m_nMaxColsPerPage + 1) m_nHScrollPos = m_nHScrollMax - m_nMaxColsPerPage + 1; nHScrollInc = m_nHScrollPos - nOldHScrollPos; if (nHScrollInc) { //finally setup the actual scrollbar! info.cbSize = sizeof(SCROLLINFO); info.fMask = SIF_POS; info.nPos = m_nHScrollPos; SetScrollInfo(SB_HORZ, &info, TRUE); InvalidateRect(NULL); } return 0; } LRESULT CFilePreviewCtrl::OnVScroll(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/) { // React to the various vertical scroll related actions. // CAUTION: // All sizes are in unsigned values, so be carefull // when testing for < 0 etc SCROLLINFO info; int nVScrollInc; int nOldVScrollPos = m_nVScrollPos; switch (LOWORD(wParam)) { case SB_TOP: m_nVScrollPos = 0; break; case SB_BOTTOM: m_nVScrollPos = m_nVScrollMax - m_nMaxLinesPerPage + 1; break; case SB_LINEUP: if(m_nVScrollPos > 0) --m_nVScrollPos; break; case SB_LINEDOWN: m_nVScrollPos++; break; case SB_PAGEUP: m_nVScrollPos -= max(1, m_nMaxLinesPerPage); if(m_nVScrollPos > nOldVScrollPos) m_nVScrollPos = 0; break; case SB_PAGEDOWN: m_nVScrollPos += max(1, m_nMaxLinesPerPage); break; case SB_THUMBPOSITION: info.cbSize = sizeof(SCROLLINFO); info.fMask = SIF_TRACKPOS; GetScrollInfo(SB_VERT, &info); m_nVScrollPos = info.nTrackPos; break; case SB_THUMBTRACK: info.cbSize = sizeof(SCROLLINFO); info.fMask = SIF_TRACKPOS; GetScrollInfo(SB_VERT, &info); m_nVScrollPos = info.nTrackPos; break; default: nVScrollInc = 0; } //keep scroll position in range if(m_nVScrollPos > m_nVScrollMax - m_nMaxLinesPerPage+1) m_nVScrollPos = m_nVScrollMax - m_nMaxLinesPerPage+1; if(m_nVScrollPos<0) m_nVScrollPos = 0; nVScrollInc = m_nVScrollPos - nOldVScrollPos; if (nVScrollInc) { //finally setup the actual scrollbar! info.cbSize = sizeof(SCROLLINFO); info.fMask = SIF_POS; info.nPos = m_nVScrollPos; SetScrollInfo(SB_VERT, &info, TRUE); InvalidateRect(NULL); } return 0; } LRESULT CFilePreviewCtrl::OnEraseBkgnd(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { // Do nothing return 0; } LRESULT CFilePreviewCtrl::OnPaint(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { PAINTSTRUCT ps; HDC hDC = BeginPaint(&ps); { CMemoryDC memDC(hDC, ps.rcPaint); if(m_fm.GetSize()==0) DoPaintEmpty(memDC); else DoPaint(memDC); } EndPaint(&ps); return 0; } LRESULT CFilePreviewCtrl::OnTimer(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { SetupScrollbars(); InvalidateRect(NULL); return 0; } LRESULT CFilePreviewCtrl::OnComplete(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { KillTimer(0); SetupScrollbars(); InvalidateRect(NULL); return 0; } LRESULT CFilePreviewCtrl::OnLButtonDown(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { SetFocus(); return 0; } LRESULT CFilePreviewCtrl::OnRButtonUp(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { NMHDR nmhdr; nmhdr.hwndFrom = m_hWnd; nmhdr.code = NM_RCLICK; nmhdr.idFrom = GetWindowLong(GWL_ID); HWND hWndParent = GetParent(); ::SendMessage(hWndParent, WM_NOTIFY, 0, (LPARAM)&nmhdr); return 0; } LRESULT CFilePreviewCtrl::OnMouseWheel(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/) { if(m_PreviewMode!=PREVIEW_TEXT && m_PreviewMode!=PREVIEW_HEX) return 0; int nDistance = GET_WHEEL_DELTA_WPARAM(wParam)/WHEEL_DELTA; int nLinesPerDelta = m_nMaxLinesPerPage!=0?m_nVScrollMax/m_nMaxLinesPerPage:0; SCROLLINFO info; memset(&info, 0, sizeof(SCROLLINFO)); info.cbSize = sizeof(SCROLLINFO); info.fMask = SIF_ALL; GetScrollInfo(SB_VERT, &info); info.nPos -=nDistance*nLinesPerDelta; SetScrollInfo(SB_VERT, &info, TRUE); SendMessage(WM_VSCROLL, MAKEWPARAM(SB_THUMBPOSITION, info.nPos), 0); return 0; }
23.409986
119
0.609417
[ "object" ]
c46875c7dd108e5e568ef74ee3bf47256ddbbc1e
14,484
hpp
C++
src/main/cpp/cn/edu/SUSTech/YeCanming/Algs/DivideAndConquer/ClosestPoint.hpp
2catycm/P_Algorithm_Design_and_Analysis_cpp
d1678d4db6f59a11215a8c790c2852bf9ad852dd
[ "MulanPSL-1.0" ]
null
null
null
src/main/cpp/cn/edu/SUSTech/YeCanming/Algs/DivideAndConquer/ClosestPoint.hpp
2catycm/P_Algorithm_Design_and_Analysis_cpp
d1678d4db6f59a11215a8c790c2852bf9ad852dd
[ "MulanPSL-1.0" ]
null
null
null
src/main/cpp/cn/edu/SUSTech/YeCanming/Algs/DivideAndConquer/ClosestPoint.hpp
2catycm/P_Algorithm_Design_and_Analysis_cpp
d1678d4db6f59a11215a8c790c2852bf9ad852dd
[ "MulanPSL-1.0" ]
null
null
null
// // Created by 叶璨铭 on 2022/3/31. // #pragma once #include "BinarySearch.hpp" #include <algorithm> #include <array> #include <cassert> #include <cmath> #include <limits> #include <vector> namespace cn::edu::SUSTech::YeCanming::Algs::DivideAndConquer { namespace ThisPackage = cn::edu::SUSTech::YeCanming::Algs::DivideAndConquer; class ClosestPoint { public: template<typename T, typename It = typename std::vector<std::array<T, 2>>::const_iterator> std::tuple<std::array<It, 2>, T> findClosestPointPair2D(const std::vector<std::array<T, 2>> &vec2d) const { return findClosestPointPair2D<T>(vec2d.cbegin(), vec2d.cend()); } /** * Efficient algorithm implementation for finding closest 2d point pair among a set of points. * @tparam T the number type of 2d points. For example, <1,-2> is a int point and <2.0, -10> is a double point. * the type of the point is assumed to be std::array<T, 2>. * @param first the inclusive start of the range where you want to find the closest 2d point pair. * @param last the exclusive end of the range where you want to find the closest 2d point pair. * first and last should be const_iterator of std::vector<std::array<T, 2>>. * @return a tuple [pair, dist] where pair is the two iterators whose points are closest and dist is the smallest distance. * Time complexity: if N = std::distance(first, last), then the time complexity is θ(NlogN) . * System workflow: * Firstly, this method sorts the iterators according to x, which allows us to * use "divide" algorithm according to x. * Then, we will call another recursive method, who will not only compute closest pair and distance, * but also sorts the iterators in the order of y. * After getting the answer for sub-problems, it conquers by computing new closest pair and distance, * while also merges the sorted iterators in the order of y. * Known system defects: * 1. when the x coordinate of the inputs are the same, it degenerate to O(N^2). * 2. std::inplace_merge may be nlogn * 3. divide should always use mid point but not binary searched point to avoid n=1 problem. * */ template<typename T, typename It = typename std::vector<std::array<T, 2>>::const_iterator> std::tuple<std::array<It, 2>, T> findClosestPointPair2D(const It first, const It last) const { //for example, first-to-last-container is [<3,0>, <1,0>, <2,0>] const auto N = std::distance(first, last); //for example, size=3 std::vector<It> vec2d_its(N);//rather than add an attribute to record the index, we use iterator instead. auto to = vec2d_its.begin(); for (It from = first; from != last; std::advance(from, 1), std::advance(to, 1)) { *to = from; }//for example, vec2d_its=[0, 1, 2]. 0,1,2 are pointers or indexes or so-called iterator. std::sort(vec2d_its.begin(), vec2d_its.end(), [](It a, It b) { return (*a)[0]==(*b)[0]?(*a)[1] < (*b)[1]:(*a)[0] < (*b)[0]; });//for example, vec2d_its=[1, 0, 2]. meaning that first-to-last-container c satisfies c[1].x < c[0].x < c[2].x . std::vector<bool> isLeft(N); std::vector<It> withoutXIllegal(N); return findClosestPointPair2DRecursively<T>(vec2d_its.begin(), vec2d_its.end(), isLeft, first, withoutXIllegal.begin()); } private: template<typename T, typename It = typename std::vector<std::array<T, 2>>::const_iterator, typename ItIt = typename std::vector<It>::iterator> std::tuple<std::array<It, 2>, T> findClosestPointPair2DRecursively(const ItIt first, const ItIt last, std::vector<bool> &isLeft, const It &firstIt, ItIt withoutXIllegalFirst) const { const auto n = std::distance(first, last); #define Point2D(it) (*(it)) #define X_VALUE(it) (Point2D(it)[0]) #define Y_VALUE(it) (Point2D(it)[1]) //for example, size=3 //1.递归基情况 assert(n >= 2); if (n == 2) { //先要按照y排好序 if (Y_VALUE(first[0])>Y_VALUE(first[1])) std::swap(first[0], first[1]); //交换了first作为迭代器数组的迭代器的那个数组中,数组第0个元素和第1个元素的值。(0,1是相对于first而言的坐标) return {{first[0], first[1]}, euclideanDistance(Point2D(first[0]), Point2D(first[1]))}; } if (n <= 5) { //先要按照y排好序 std::sort(first, last, [](It a, It b) { return Y_VALUE(a) < Y_VALUE(b); }); return __findClosestPointPairND<T, 2, typename std::vector<std::array<T, 2>>::const_iterator, typename std::vector<It>::iterator>(first, last); } //2.递归求解左右 const auto midIt = first + (n >> 1);//左右的size可以相等或者差1,由于size=3和size=2都特殊处理,不会产生n=1的问题。 const auto midX = X_VALUE(*midIt); //不作为切分左右的依据。这是用来过滤点的。 //2.1 处理左右问题的标记 //firstIt是原本的点对数组的首位,每个迭代器It有唯一的序号。 #define OriginalIndex(it) std::distance(firstIt, (it)) #define SetLeft(it) isLeft[OriginalIndex(it)] = true #define SetRight(it) isLeft[OriginalIndex(it)] = false #define GetIsLeft(it) isLeft[OriginalIndex(it)] std::for_each(first, midIt, [&](It it) { SetLeft(it); }); std::for_each(midIt, last, [&](It it) { SetRight(it); }); //2.2 递归求解得到答案,同时左右变成了y有序。 auto [leftClosestPair, leftClosestDist] = findClosestPointPair2DRecursively<T>(first, midIt, isLeft, firstIt, withoutXIllegalFirst); auto [rightClosestPair, rightClosestDist] = findClosestPointPair2DRecursively<T>(midIt, last, isLeft, firstIt, withoutXIllegalFirst); //3. 归并按照y排序。 std::inplace_merge(first, midIt, last, [](It a, It b) { return Y_VALUE(a) < Y_VALUE(b); }); //4. 归并求最近点对 //4.1 左右中 更小的那个,记为 mergedClosestPoint 。 std::array<It, 2> mergedClosestPoint{}; T merged_min_dist{std::numeric_limits<T>::max()}; if (leftClosestDist < rightClosestDist) { merged_min_dist = leftClosestDist; mergedClosestPoint = leftClosestPair; } else { merged_min_dist = rightClosestDist; mergedClosestPoint = rightClosestPair; } //4.2 准备归并范围 T x_left = midX - merged_min_dist; T x_right = midX + merged_min_dist; const auto withoutXIllegalLast = std::copy_if(first, last, withoutXIllegalFirst, [&](It it){ return (x_left <= (X_VALUE(it)) && (X_VALUE(it)) <= x_right); }); //4.2 开始归并,寻找更近的点对 for (; withoutXIllegalFirst != withoutXIllegalLast; ++withoutXIllegalFirst) { int validJ = 0; for (ItIt another = withoutXIllegalFirst + 1; validJ < 6 && another != withoutXIllegalLast; ++another) { if (GetIsLeft(*withoutXIllegalFirst) == GetIsLeft(*another)) continue;//找异边的点, 如果同边,就过滤掉 validJ++; T dist = euclideanDistance(Point2D(*withoutXIllegalFirst), Point2D(*another)); if (dist < merged_min_dist) { merged_min_dist = dist; mergedClosestPoint = {*withoutXIllegalFirst, *another}; } } } return std::make_tuple(mergedClosestPoint, merged_min_dist); } public: #define ARR_T(T, N) std::array<T, N> #define CItARR_T(T, N) typename std::vector<ARR_T(T, N)>::const_iterator #define CIt_T(T) typename std::vector<T>::const_iterator template<typename T> std::tuple<std::array<CIt_T(T), 2>, T> findClosestPointPair1D(const std::vector<T> &vec) const { return findClosestPointPair1D<T>(vec.cbegin(), vec.cend()); } template<typename T> std::tuple<std::array<CIt_T(T), 2>, T> findClosestPointPair1D(const CIt_T(T) first, const CIt_T(T) last) const { using It = CIt_T(T); using ItIt = typename std::vector<It>::iterator; //for example, first-to-last-container is [<3,0>, <1,0>, <2,0>] const auto N = std::distance(first, last); //for example, size=3 std::vector<It> vec2d_its(N);//rather than add an attribute to record the index, we use iterator instead. auto to = vec2d_its.begin(); for (It from = first; from != last; std::advance(from, 1), std::advance(to, 1)) { *to = from; }//for example, vec2d_its=[0, 1, 2]. 0,1,2 are pointers or indexes or so-called iterator. std::sort(vec2d_its.begin(), vec2d_its.end(), [](It a, It b) { return (*a) < (*b); });//for example, vec2d_its=[1, 0, 2]. meaning that first-to-last-container c satisfies c[1].x < c[0].x < c[2].x . ItIt minIt = vec2d_its.begin(); T min_diff = *(minIt[1]) - *(minIt[0]); // T min_diff = std::numeric_limits<T>::max(); for (ItIt it = vec2d_its.begin()+1;it!=(vec2d_its.end()-1); ++it) { T diff = *(it[1]) - *(it[0]); if (diff < min_diff) { minIt = it; min_diff = diff; } } return {{minIt[0], minIt[1]}, min_diff}; } template<typename T> std::tuple<std::array<CItARR_T(T, 1), 2>, T> findClosestPointPair1D(const std::vector<std::array<T, 1>> &vec) const { return findClosestPointPair1D(vec.cbegin(), vec.cend()); } template<typename T> std::tuple<std::array<CItARR_T(T, 1), 2>, T> findClosestPointPair1D(const CItARR_T(T, 1) first, const CItARR_T(T, 1) last) const { using It = CItARR_T(T, 1); using ItIt = typename std::vector<It>::iterator; //for example, first-to-last-container is [<3,0>, <1,0>, <2,0>] const auto N = std::distance(first, last); //for example, size=3 std::vector<It> vec2d_its(N);//rather than add an attribute to record the index, we use iterator instead. auto to = vec2d_its.begin(); for (It from = first; from != last; std::advance(from, 1), std::advance(to, 1)) { *to = from; }//for example, vec2d_its=[0, 1, 2]. 0,1,2 are pointers or indexes or so-called iterator. std::sort(vec2d_its.begin(), vec2d_its.end(), [](It a, It b) { return (*a)[0] < (*b)[0]; });//for example, vec2d_its=[1, 0, 2]. meaning that first-to-last-container c satisfies c[1].x < c[0].x < c[2].x . ItIt minIt = vec2d_its.begin(); T min_diff = **minIt[1] - **minIt[0]; // T min_diff = std::numeric_limits<T>::max(); for (ItIt it = vec2d_its.begin()+1;it!=vec2d_its.end(); ++it) { T diff = **it[1] - **it[0]; if (diff < min_diff) { minIt = it; min_diff = diff; } } return std::make_tuple({minIt[0], minIt[1]}, min_diff); } template<typename T, size_t N, typename It = typename std::vector<std::array<T, N>>::const_iterator> std::tuple<std::array<It, 2>, T> findClosestPointPairND(const std::vector<std::array<T, N>> &vec_nd) const { return findClosestPointPairND<T, N, typename std::vector<std::array<T, N>>::const_iterator>(vec_nd.cbegin(), vec_nd.cend()); } template<typename T, size_t N, typename It = typename std::vector<std::array<T, N>>::const_iterator> std::tuple<std::array<It, 2>, T> findClosestPointPairND(It first, const It last) const { const auto size = std::distance(first, last); assert(size >= 2); T min_dist = std::numeric_limits<T>::max(); std::array<It, 2> min_index{first, first + 1}; for (; first != last; ++first) { for (It another = first + 1; another != last; ++another) { T dist = this->euclideanDistance(*first, *another); if (min_dist > dist) { min_dist = dist; min_index[0] = first; min_index[1] = another; } } } return std::make_tuple(min_index, min_dist); } private: template<typename T, size_t N, typename It = typename std::vector<std::array<T, N>>::const_iterator, typename ItIt = typename std::vector<It>::iterator> std::tuple<std::array<It, 2>, T> __findClosestPointPairND(ItIt first, const ItIt last) const { const auto size = std::distance(first, last); assert(size >= 2); T min_dist = std::numeric_limits<T>::max(); std::array<It, 2> min_index{first[0], first[1]}; for (; first != last; ++first) { for (ItIt another = first + 1; another != last; ++another) { T dist = this->euclideanDistance(**first, **another); if (min_dist > dist) { min_dist = dist; min_index[0] = *first; min_index[1] = *another; } } } return std::make_tuple(min_index, min_dist); } public: template<typename T, size_t K> T euclideanDistance(const std::array<T, K> &a, const std::array<T, K> &b) const { T sum = 0; for (int i = 0; i < K; ++i) { T diff = a[i] - b[i]; sum += diff * diff; } return std::sqrt(sum); } }; }// namespace cn::edu::SUSTech::YeCanming::Algs::DivideAndConquer
53.25
145
0.540389
[ "vector" ]
c46b8200529c5069d8332d3bc1a746d7ee261735
1,116
hpp
C++
src/stan/math/prim/mat/fun/num_elements.hpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
1
2019-09-06T15:53:17.000Z
2019-09-06T15:53:17.000Z
src/stan/math/prim/mat/fun/num_elements.hpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
8
2019-01-17T18:51:16.000Z
2019-01-17T18:51:39.000Z
src/stan/math/prim/mat/fun/num_elements.hpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
null
null
null
#ifndef STAN_MATH_PRIM_MAT_FUN_NUM_ELEMENTS_HPP #define STAN_MATH_PRIM_MAT_FUN_NUM_ELEMENTS_HPP #include <stan/math/prim/mat/fun/Eigen.hpp> #include <vector> namespace stan { namespace math { /** * Returns 1, the number of elements in a primitive type. * * @param x Argument of primitive type. * @return 1 */ template <typename T> inline int num_elements(const T& x) { return 1; } /** * Returns the size of the specified matrix. * * @param m argument matrix * @return size of matrix */ template <typename T, int R, int C> inline int num_elements(const Eigen::Matrix<T, R, C>& m) { return m.size(); } /** * Returns the number of elements in the specified vector. * This assumes it is not ragged and that each of its contained * elements has the same number of elements. * * @param v argument vector * @return number of contained arguments */ template <typename T> inline int num_elements(const std::vector<T>& v) { if (v.size() == 0) return 0; return v.size() * num_elements(v[0]); } } // namespace math } // namespace stan #endif
22.32
64
0.670251
[ "vector" ]
c46c93d799c6641a01deae57cc3f1a8077b5d3ac
751
cpp
C++
POJ/2739/12870385_AC_157ms_708kB.cpp
BakaErii/ACM_Collection
d368b15c7f1c84472424d5e61e5ebc667f589025
[ "WTFPL" ]
null
null
null
POJ/2739/12870385_AC_157ms_708kB.cpp
BakaErii/ACM_Collection
d368b15c7f1c84472424d5e61e5ebc667f589025
[ "WTFPL" ]
null
null
null
POJ/2739/12870385_AC_157ms_708kB.cpp
BakaErii/ACM_Collection
d368b15c7f1c84472424d5e61e5ebc667f589025
[ "WTFPL" ]
null
null
null
/** * @author Moe_Sakiya sakiya@tun.moe * @date 2018-01-18 23:24:09 * */ #include <iostream> #include <string> #include <algorithm> #include <set> #include <map> #include <vector> #include <stack> #include <queue> #include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> using namespace std; int prime[10001]; int main(void) { int i, j, ans, tot, n, pn; pn = 0; for (i = 2; i < 10001; i++) { for (j = 2; j < i; j++) if (i % j == 0) break; if (j == i) prime[pn++] = i; } while (~scanf("%d", &n) && n != 0) { ans = 0; for (i = 0; i < pn; i++) { tot = 0; for (j = i; j < pn && tot < n; j++) { tot += prime[j]; if (tot == n) ans++; } } printf("%d\n", ans ); } return 0; }
15.645833
40
0.505992
[ "vector" ]
c47192af5bf765e2d276992d6419b49a0e023262
8,847
hpp
C++
StringUtility.hpp
Atlan522/cpp-lib4
2ef5174e86b3db797734a4832e9aa60e9fc9ac60
[ "Apache-2.0" ]
null
null
null
StringUtility.hpp
Atlan522/cpp-lib4
2ef5174e86b3db797734a4832e9aa60e9fc9ac60
[ "Apache-2.0" ]
null
null
null
StringUtility.hpp
Atlan522/cpp-lib4
2ef5174e86b3db797734a4832e9aa60e9fc9ac60
[ "Apache-2.0" ]
null
null
null
#ifndef __ACL__STRING_UTILITY_H__ #define __ACL__STRING_UTILITY_H__ #ifdef WIN32 #pragma warning(disable: 4786) #endif //WIN32 #include <iostream> #include <fstream> #include <string> #include <vector> #include <algorithm> namespace acl { namespace StringUtility{ static std::string getFileNameFromPath(const std::string& sPath) { std::string sName; int i,tail = sPath.length()-1; for(i=tail; i>-1; i--) { if(sPath[i] == '\\' || sPath[i] == '/') { sName = sPath.substr(i+1); break; } } if(sName.empty()) { sName = sPath; } return sName; } static std::string getPathFromFilePath(const std::string& sFilePath) { std::string sPath; int i,tail = sFilePath.length()-1; for(i=tail; i>-1; i--) { if(sFilePath[i] == '/' || sFilePath[i] == '\\') { return sFilePath.substr(0,i); } } return sPath; } static std::string generatePathWithRelativePath(const std::string& basePath, const std::string& relativePath) { std::string newBasePath = getPathFromFilePath(basePath); if(!newBasePath.empty()) { return newBasePath+ '/' + relativePath; } else { return relativePath; } } static std::string getStringBetween(const std::string& s, const std::string& head, const std::string& tail) { size_t hPos = s.find(head); if(hPos == std::string::npos) return ""; size_t tPos = s.find(tail,hPos+head.length()); if(tPos == std::string::npos) return ""; return s.substr(hPos+head.length(),tPos-hPos-head.length()); } static void switchBoolTag(bool& tag) { if(tag == true) { tag = false; } else { tag = true; } } static bool isTranslatedChar(const std::string& s, const int& pos) { bool ret = false; for(int i=pos-1; i>-1; i--) { if(s[i] == '\\') { switchBoolTag(ret); } else { break; } } return ret; } static std::string convertTranslateChar(const std::string& s) { std::string result; for(int i=s.length()-1; i>-1; i--) { result += s[i]; if( isTranslatedChar(s,i) ) { i--; } } std::reverse(result.begin(),result.end()); return result; } static std::vector<std::string> divide(std::string input, const std::string &sep) { std::vector<std::string> v; int pos; if(sep.length() == 1) { //use escape sequence int start = 0; while(1) { pos = input.find(sep,start); if(pos != (int)std::string::npos) { if(pos != 0) { if(isTranslatedChar(input,pos) == true) { start = pos + 1; } else { v.push_back(input.substr(0, pos)); input = input.substr(pos + sep.length()); start = 0; } } else if(pos == (int)input.length()-1) { if(isTranslatedChar(input,pos) == true) { v.push_back(input); break; } else { v.push_back(input.substr(0, pos)); input = input.substr(pos + sep.length()); start = 0; } } else { v.push_back(input.substr(0, pos)); input = input.substr(pos + sep.length()); start = 0; } } else { v.push_back(input); break; } } } else { //do not use escape sequence while(1) { pos = input.find(sep); if(pos != (int)std::string::npos) { v.push_back(input.substr(0, pos)); input = input.substr(pos + sep.length()); } else { v.push_back(input); break; } } } return v; } static std::string int2Str(const int& num) { char cache[32]; #ifdef WIN32 sprintf_s(cache,"%d",num); #else sprintf(cache,"%d",num); #endif return cache; } static bool isNumber(const std::string& s) { for(size_t i=0; i<s.length(); i++) { if(s[i] == '-' || s[i] == '+') continue; if(s[i] < '0' || s[i] > '9') { return false; } } return true; } static bool isPureNumber(const std::string& s) { for(size_t i=0; i<s.length(); i++) { if(s[i] < '0' || s[i] > '9') { return false; } } return true; } static void removeSpace(std::string& s) { std::string str; for(size_t i=0; i<s.length(); i++) { if(s[i] != ' ') { str += s[i]; } } s.swap(str); } static void removeSpaceNear(std::string& s, const std::string& tar) { int pos = s.find(tar); if(pos == (int)std::string::npos) return; int p=-1; std::string str; size_t i; for(i=pos-1; i>=0; i--) { if(s[i] != ' ') { p = i; break; } } str = s.substr(0,p+1); str += tar; p=0; for(i=pos+tar.length(); i<s.length(); i++) { if(s[i] != ' ') { p = i; break; } } str += s.substr(p); s.swap(str); } static int hasEmptyCell(const std::vector<std::string>& v) { for(size_t i=0; i<v.size(); i++) { if(v[i].empty()) { return i; } } return -1; } static std::string trimLeft(std::string& s, const std::string& sep) { std::string sLeft; int pos = s.find(sep); if(pos != (int)std::string::npos) { sLeft = s.substr(0,pos); s = s.substr(pos+sep.length()); } else { sLeft = s; } return sLeft; } static std::string toUpper(const std::string& word) { std::string result; for(size_t i = 0; i < word.length(); i++) { if(word[i] > 0x40 && word[i] < 0x5b) { if(result.empty()) { result = word; } result[i] = word[i] | 0x20; continue; } else if(word[i] > 0x60 && word[i] < 0x7b) { continue; } else if(word[i] == 0x20) { continue; } else { return ""; } } return result; } static bool isHexadecimalNumber(const std::string& s) { size_t length = s.length(); if(length < 3 || length > 10) return false; for(size_t i=0; i<length; i++) { if((s[i]<'0' || s[i]>'9') && s[i]!='x' && s[i]!='X' && (s[i]<'a' || s[i]>'f')) { return false; } } return true; } static void toUpper(std::string& s) { for(size_t i=0; i<s.length(); i++) { s[i] = toupper(s[i]); } } static std::string removeBackTabsAndSpaces(const std::string& s) { std::string sResult; for(int i=(int)s.length()-1; i>-1; i--) { if(s[i] != '\t' && s[i] != ' ') { sResult = s.substr(0,i+1); break; } } return sResult; } static std::string divideLineTypeComment(const std::string& s) { std::string sResult; int pos = s.find("//"); sResult = s.substr(0,pos); sResult = removeBackTabsAndSpaces(sResult); return sResult; } static int scaleNumberToLegalNumber(const int& num, const int& maxNum) { if(num < 0) { return 0; } else if(num > maxNum) { return maxNum; } else { return num; } } static std::string getIndexCharInString(const std::string& str, const int& index) { std::string word; int length = str.length(); int i=0,count=0,lastPos=0; while(1) { if(i >= length) break; lastPos = i; if((str[i] & 0x80) == 0x00) { i++; } else if((str[i] & 0xE0) == 0xC0) { i+=2; } else if((str[i] & 0xF0) == 0xE0) { i+=3; } if(count == index) { word = str.substr(lastPos,i-lastPos); break; } count++; } return word; } static bool isStringHasLowerCaseAphabet(const std::string& str) { int length = str.length(); int i=0,count=0,lastPos=0; while(1) { if(i >= length) break; lastPos = i; if((str[i] & 0x80) == 0x00) { if('a'<= str[i] && str[i]<='z') { return true; } i++; } else if((str[i] & 0xE0) == 0xC0) { i+=2; } else if((str[i] & 0xF0) == 0xE0) { i+=3; } count++; } return false; } static int isVectorHasLowerCaseAphabet(const std::vector<std::string>& v) { for(size_t i=0; i<v.size(); i++) { if(isStringHasLowerCaseAphabet(v[i])) { return i; } } return -1; } }//namespace StringUtility }//namespace acl #endif
22.454315
109
0.479145
[ "vector" ]
c48273b74adcdf191d8bd92c8f8e3431212ff8f1
657
cc
C++
HDU/5090_Game with Pearls/5090_v2.cc
pdszhh/ACM
956b3d03a5d3f070ef24c940b7459f5cccb11d6c
[ "MIT" ]
1
2019-05-05T03:51:20.000Z
2019-05-05T03:51:20.000Z
HDU/5090_Game with Pearls/5090_v2.cc
pdszhh/ACM
956b3d03a5d3f070ef24c940b7459f5cccb11d6c
[ "MIT" ]
null
null
null
HDU/5090_Game with Pearls/5090_v2.cc
pdszhh/ACM
956b3d03a5d3f070ef24c940b7459f5cccb11d6c
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; int main() { int m; cin >> m; while (m--) { int n, k; cin >> n >> k; vector<int> cnt(n+1); for (int i = 0; i < n; ++i) { int t; cin >> t; for ( ; t <= n; t += k) cnt[t]++; } bool flag = true; for (int i = 1; i <= n; ++i) { if (cnt[i] <= 0) { flag = false; break; } for (int t = i; t <= n; t += k) --cnt[t]; } cout << (flag ? "Jerry" : "Tom") << endl; } return 0; }
18.771429
49
0.315068
[ "vector" ]
c4898daf90a9bb38c60b24c6b1b58c7c043d56dc
1,439
cpp
C++
libraries/common/src/DataSaveArguments.cpp
awf/ELL
25c94a1422efc41d5560db11b136f9d8f957ad41
[ "MIT" ]
2,094
2016-09-28T05:55:24.000Z
2019-05-04T19:06:36.000Z
libraries/common/src/DataSaveArguments.cpp
awesomemachinelearning/ELL
cb897e3aec148a1e9bd648012b5f53ab9d0dd20c
[ "MIT" ]
213
2017-06-30T12:53:40.000Z
2019-05-03T06:35:38.000Z
libraries/common/src/DataSaveArguments.cpp
awesomemachinelearning/ELL
cb897e3aec148a1e9bd648012b5f53ab9d0dd20c
[ "MIT" ]
301
2017-03-24T08:40:00.000Z
2019-05-02T21:22:28.000Z
//////////////////////////////////////////////////////////////////////////////////////////////////// // // Project: Embedded Learning Library (ELL) // File: DataSaveArguments.cpp (common) // Authors: Ofer Dekel // //////////////////////////////////////////////////////////////////////////////////////////////////// #include "DataSaveArguments.h" #include <vector> namespace ell { namespace common { void ParsedDataSaveArguments::AddArgs(utilities::CommandLineParser& parser) { parser.AddOption( outputDataFilename, "outputDataFilename", "odf", "Path to the output data file", ""); } utilities::CommandLineParseResult ParsedDataSaveArguments::PostProcess(const utilities::CommandLineParser& parser) { if (outputDataFilename == "null") { outputDataStream = utilities::OutputStreamImpostor(utilities::OutputStreamImpostor::StreamType::null); } else if (outputDataFilename == "") { outputDataStream = utilities::OutputStreamImpostor(utilities::OutputStreamImpostor::StreamType::cout); } else // treat argument as filename { outputDataStream = utilities::OutputStreamImpostor(outputDataFilename); } std::vector<std::string> parseErrorMessages; return parseErrorMessages; } } // namespace common } // namespace ell
30.617021
118
0.548992
[ "vector" ]
c48fdc254daf0321ce7ce8e47edd12c893c2c07a
2,881
hpp
C++
include/Lynx/System/Loader.hpp
ichi-raven/LynxEngine
c3541498e15d526f78f80ece1ce8a725457ae1c1
[ "MIT" ]
null
null
null
include/Lynx/System/Loader.hpp
ichi-raven/LynxEngine
c3541498e15d526f78f80ece1ce8a725457ae1c1
[ "MIT" ]
null
null
null
include/Lynx/System/Loader.hpp
ichi-raven/LynxEngine
c3541498e15d526f78f80ece1ce8a725457ae1c1
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include <variant> #include <vector> // #include "../ThirdParty/tiny_obj_loader.h" // #include "../ThirdParty/tiny_gltf.h" #include <assimp/Importer.hpp> #include <assimp/scene.h> #include <assimp/postprocess.h> #include <Lynx/Components/MeshComponent.hpp> #include <Lynx/Components/SkeletalMeshComponent.hpp> #include <Lynx/Components/MaterialComponent.hpp> #include <Lynx/Components/SpriteComponent.hpp> #include <Lynx/Components/TextComponent.hpp> namespace Cutlass { class Context; } namespace Lynx { class Loader { public: struct VertexBoneData { VertexBoneData() { weights[0] = weights[1] = weights[2] = weights[3] = 0; id[0] = id[1] = id[2] = id[3] = 0; } float weights[4]; float id[4]; }; Loader(const std::shared_ptr<Cutlass::Context>& context); virtual ~Loader(); //virtual void load(const char* path); virtual void load ( const char* path, std::weak_ptr<MeshComponent>& mesh_out, std::weak_ptr<MaterialComponent>& material_out ); virtual void load ( const char* path, std::weak_ptr<SkeletalMeshComponent>& skeletalMesh_out, std::weak_ptr<MaterialComponent>& material_out ); //if type was nullptr, type will be last section of path virtual void load(const char* path, const char* type, std::weak_ptr<MaterialComponent>& material_out); virtual void load(const char* path, std::weak_ptr<SpriteComponent>& sprite_out); virtual void load(std::vector<const char*> pathes, std::weak_ptr<SpriteComponent>& sprite_out); virtual void load(const char* path, std::weak_ptr<TextComponent>& text_out); private: void unload(); void processNode(const aiNode* node); MeshComponent::Mesh processMesh(const aiNode* node, const aiMesh* mesh); std::vector<MaterialComponent::Texture> loadMaterialTextures(aiMaterial* mat, aiTextureType type, std::string typeName); void loadBones(const aiNode* node, const aiMesh* mesh, std::vector<VertexBoneData>& vbdata_out); MaterialComponent::Texture loadTexture(const char* path, const char* type); std::shared_ptr<Cutlass::Context> mContext; bool mLoaded; bool mSkeletal; std::string mDirectory; std::string mPath; std::vector<MeshComponent::Mesh> mMeshes; SkeletalMeshComponent::Skeleton mSkeleton;//単体前提 std::vector<MaterialComponent::Texture> mTexturesLoaded; uint32_t mBoneNum; Assimp::Importer mImporter; //std::shared_ptr<const aiScene> mScene; std::vector<std::shared_ptr<const aiScene>> mScenes; }; }
28.245098
128
0.634849
[ "mesh", "vector" ]
c4945449fb2b920a76087cfa7b8f31e0a4225834
3,377
cpp
C++
src/conf.cpp
aaronpuchert/throttle
50f3005e9b2c9cb1ec2962cf5e9852c08eab101c
[ "MIT" ]
2
2018-06-13T17:41:30.000Z
2021-03-27T03:21:26.000Z
src/conf.cpp
aaronpuchert/throttle
50f3005e9b2c9cb1ec2962cf5e9852c08eab101c
[ "MIT" ]
1
2018-06-13T18:04:44.000Z
2018-06-18T23:52:09.000Z
src/conf.cpp
aaronpuchert/throttle
50f3005e9b2c9cb1ec2962cf5e9852c08eab101c
[ "MIT" ]
null
null
null
#include <algorithm> #include <fstream> #include <limits> #include <sstream> #include <stdexcept> #include <string> #include <utility> #include <vector> #include <errno.h> #include <fcntl.h> #include <unistd.h> #include "throttle.hpp" /** * Read a configuration file. * * This function is guaranteed to read in all syntactically correct files, but * might also accept others. */ Conf::Conf(const char *config_fn) { // open the file std::ifstream conf_file(config_fn); if (!conf_file) throw std::runtime_error(std::string("Couldn't open config file '") + config_fn + '\''); // Read every line and put it in the list. char line[LINE_LENGTH]; std::string name; // parse: first comes the name of the command while (conf_file >> name) { // if line starts with '#', ignore it if (name[0] == '#') { conf_file.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); continue; } conf_file.ignore(std::numeric_limits<std::streamsize>::max(), '='); conf_file.ignore(std::numeric_limits<std::streamsize>::max(), ' '); conf_file.getline(line, LINE_LENGTH); DEBUG_PRINT("[Conf] " << name << " = " << line); // Write into attribute list attributes.emplace_back(name, std::string(line)); } } const std::string& Conf::GetAttr(const char *name) const { auto it = std::find_if(attributes.begin(), attributes.end(), [name](const std::pair<std::string, std::string>& p) { return p.first == name; }); if (it != attributes.end()) return it->second; else throw std::runtime_error(std::string("No such attribute: ") + name); } /** * Construct a command queue. * * We want to know the parent, where we can write changes to, * and which pipe to listen on. */ CommQueue::CommQueue(Throttle *parent, const char *pipe_fn) : Throt(parent) { // Open the command pipe comm_file = open(pipe_fn, O_RDONLY | O_NONBLOCK); if (comm_file < 0) throw std::runtime_error(std::string("Couldn't open command pipe '") + pipe_fn + '\''); } /** * Destruct the command queue. * * We have to close the file manually here. */ CommQueue::~CommQueue() { close(comm_file); } /** * Look for updates from the command pipe and process them. */ void CommQueue::update() { char buf[LINE_LENGTH]; ssize_t ret; while (true) { ret = read(comm_file, buf, LINE_LENGTH-1); if (ret <= 0) break; processCommand(std::string(buf, ret)); } // This should be because there's nothing more to read if (ret != 0 && errno != EAGAIN) throw std::runtime_error("Read error while checking command pipe"); } /** * Process a command coming through the pipe. */ void CommQueue::processCommand(const std::string &comm) { std::istringstream stream(comm); std::string command; stream >> command; if (command == "min") { int temp; stream >> temp; Throt->setMinTemp(temp); DEBUG_PRINT("[CommQueue] Set minimum temperature to " << temp); } else if (command == "max") { int temp; stream >> temp; Throt->setMaxTemp(temp); DEBUG_PRINT("[CommQueue] Set maximum temperature to " << temp); } else if (command == "freq") { int freq; stream >> freq; Throt->setOverrideFreq(freq); DEBUG_PRINT("[CommQueue] Set frequency to " << freq); } else if (command == "reset") { Throt->setOverrideFreq(0); DEBUG_PRINT("[CommQueue] Reset mechanism"); } else { DEBUG_PRINT("[CommQueue] Ignored unknown command: " << command); } }
23.289655
90
0.665383
[ "vector" ]
c498d487b86cfde2fce1b27d462f445a5b86ee75
5,240
cpp
C++
Coda/src/nlp-stack/Dictionary/SuffixModelTrieBinaryFileCreator.cpp
Samsung/veles.nlp
972fde27203cb04d301e34274b57435ed58372c4
[ "Apache-2.0" ]
8
2016-02-16T10:15:39.000Z
2020-03-12T21:14:36.000Z
Coda/src/nlp-stack/Dictionary/SuffixModelTrieBinaryFileCreator.cpp
Samsung/veles.nlp
972fde27203cb04d301e34274b57435ed58372c4
[ "Apache-2.0" ]
null
null
null
Coda/src/nlp-stack/Dictionary/SuffixModelTrieBinaryFileCreator.cpp
Samsung/veles.nlp
972fde27203cb04d301e34274b57435ed58372c4
[ "Apache-2.0" ]
6
2016-02-16T10:15:47.000Z
2020-01-20T20:33:25.000Z
/** * SuffixModelTrieBinaryFileCreator.cpp */ #include "SuffixModelTrieBinaryFileCreator.h" #include "Dictionary.h" #define N_GRAM_MAX_BUFFER_SIZE 15000000 //#define BINARY_SUFFIX_PATH "SuffixModel.bin" SuffixModelTrieBinaryFileCreator::SuffixModelTrieBinaryFileCreator(Dictionary* _dic) : SuffixModelTrieBuild(_dic) { max_frequency_size = 974; max_frequency = 42031; max_feature_frequency = 265360; saveToBinaryFile(BINARY_SUFFIX_PATH); } SuffixModelTrieBinaryFileCreator::~SuffixModelTrieBinaryFileCreator(void) { } void SuffixModelTrieBinaryFileCreator::writeToBuffer(vector<unsigned char> charVector) { for (int i = 0; i < (int) charVector.size(); ++i) { buffer[bufferSize] = charVector.at(i); bufferSize++; } } vector<unsigned char> SuffixModelTrieBinaryFileCreator::binarySuffixModelNode(SuffixModelNode * _node, int _parentId) { vector<unsigned char> _result; _result.push_back(getDictionary()->getDictionaryTools()->wcharToChar(_node->getCharacter())); vector<unsigned char> binParentId = getDictionary()->getDictionaryTools()->intToCharVector3(_parentId); _result.insert(_result.end(), binParentId.begin(), binParentId.end()); if (max_frequency_size < (int) _node->getFeatureFrequencyMap().size()) { max_frequency_size = (int) _node->getFeatureFrequencyMap().size(); wcout << "update max_frequency_size = " << max_frequency_size << endl; } map<int, int> _frequencyMap = _node->getFeatureFrequencyMap(); vector<unsigned char> binSizeOfFrequencyMap = getDictionary()->getDictionaryTools()->intToCharVector2((int) _frequencyMap.size()); _result.insert(_result.end(), binSizeOfFrequencyMap.begin(), binSizeOfFrequencyMap.end()); if (!_frequencyMap.size()) { return _result; } map<int, int>::iterator iter; for (iter = _frequencyMap.begin(); iter != _frequencyMap.end(); ++iter) { int _featureId = iter->first; vector<unsigned char> binFeatureId = getDictionary()->getDictionaryTools()->intToCharVector3(_featureId); _result.insert(_result.end(), binFeatureId.begin(), binFeatureId.end()); int _frequency = iter->second; if (max_frequency < _frequency) { max_frequency = _frequency; wcout << "update max_frequency = " << max_frequency << endl; } vector<unsigned char> binFrequency = getDictionary()->getDictionaryTools()->intToCharVector2(_frequency); _result.insert(_result.end(), binFrequency.begin(), binFrequency.end()); } return _result; } void SuffixModelTrieBinaryFileCreator::buildBuffer(void) { wcout << "SuffixModelTrieBinaryFileCreator build buffer ..."; buffer = new unsigned char[N_GRAM_MAX_BUFFER_SIZE]; bufferSize = 0; wcout << "numberOfNodes = " << numberOfNodes << endl; vector<unsigned char> binNumberOfNode = getDictionary()->getDictionaryTools()->intToCharVector3(numberOfNodes); writeToBuffer(binNumberOfNode); queue<SuffixModelNode*> nodeQueue = queue<SuffixModelNode*>(); nodeQueue.push(root); int currentNodeId = -1; int _count = 1; // write root vector<unsigned char> binRoot = binarySuffixModelNode(root, currentNodeId); writeToBuffer(binRoot); while (!nodeQueue.empty()) { SuffixModelNode* currentNode = nodeQueue.front(); nodeQueue.pop(); currentNodeId++; vector<SuffixModelNode*> childrenNodes = currentNode->getChildrenNode(); for (int i = 0; i < (int) childrenNodes.size(); ++i) { SuffixModelNode* childNode = childrenNodes.at(i); nodeQueue.push(childNode); _count++; // write node vector<unsigned char> binCurrentNode = binarySuffixModelNode(childNode, currentNodeId); writeToBuffer(binCurrentNode); } } wcout << " Node count = " << _count << endl; _count = 0; // featureIdFrequency wcout << "featureIdFrequency.size = " << (int) featureIdFrequency.size() << endl; vector<unsigned char> binFeatureIdFrequencySize = getDictionary()->getDictionaryTools()->intToCharVector2((int) featureIdFrequency.size()); writeToBuffer(binFeatureIdFrequencySize); map<int, int>::iterator iter; for (iter = featureIdFrequency.begin(); iter != featureIdFrequency.end(); ++iter) { int _featureId = iter->first; vector<unsigned char> binFeatureId = getDictionary()->getDictionaryTools()->intToCharVector3(_featureId); writeToBuffer(binFeatureId); int _frequency = iter->second; vector<unsigned char> binFrequency = getDictionary()->getDictionaryTools()->intToCharVector3(_frequency); writeToBuffer(binFrequency); _count++; if (max_feature_frequency < _frequency) { max_feature_frequency = _frequency; //wcout << "update max_frequency = " << max_frequency << endl; } } wcout << "Done! Count = " << _count << endl; wcout << "max_frequency_size = " << max_frequency_size << endl; wcout << "max_frequency = " << max_frequency << endl; wcout << "max_feature_frequency = " << max_feature_frequency << endl; } /** * Save N-Gram to binary file */ void SuffixModelTrieBinaryFileCreator::saveToBinaryFile(string _filePath) { wcout << "SuffixModelTrieBinaryFileCreator saveToBinaryFile ..." << endl; buildBuffer(); ofstream f(_filePath.c_str(), ios::out|ios::binary); f.write((char*)&buffer[0], bufferSize); f.close(); wcout << "SuffixModelTrieBinaryFileCreator saveToBinaryFile done!" << endl; }
35.405405
143
0.73416
[ "vector" ]
7bce2fb065595dff740f34051288dfa46aa9d2a5
3,621
cpp
C++
aws-cpp-sdk-monitoring/source/model/DashboardEntry.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-monitoring/source/model/DashboardEntry.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-monitoring/source/model/DashboardEntry.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/monitoring/model/DashboardEntry.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <utility> using namespace Aws::Utils::Xml; using namespace Aws::Utils; namespace Aws { namespace CloudWatch { namespace Model { DashboardEntry::DashboardEntry() : m_dashboardNameHasBeenSet(false), m_dashboardArnHasBeenSet(false), m_lastModifiedHasBeenSet(false), m_size(0), m_sizeHasBeenSet(false) { } DashboardEntry::DashboardEntry(const XmlNode& xmlNode) : m_dashboardNameHasBeenSet(false), m_dashboardArnHasBeenSet(false), m_lastModifiedHasBeenSet(false), m_size(0), m_sizeHasBeenSet(false) { *this = xmlNode; } DashboardEntry& DashboardEntry::operator =(const XmlNode& xmlNode) { XmlNode resultNode = xmlNode; if(!resultNode.IsNull()) { XmlNode dashboardNameNode = resultNode.FirstChild("DashboardName"); if(!dashboardNameNode.IsNull()) { m_dashboardName = Aws::Utils::Xml::DecodeEscapedXmlText(dashboardNameNode.GetText()); m_dashboardNameHasBeenSet = true; } XmlNode dashboardArnNode = resultNode.FirstChild("DashboardArn"); if(!dashboardArnNode.IsNull()) { m_dashboardArn = Aws::Utils::Xml::DecodeEscapedXmlText(dashboardArnNode.GetText()); m_dashboardArnHasBeenSet = true; } XmlNode lastModifiedNode = resultNode.FirstChild("LastModified"); if(!lastModifiedNode.IsNull()) { m_lastModified = DateTime(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(lastModifiedNode.GetText()).c_str()).c_str(), DateFormat::ISO_8601); m_lastModifiedHasBeenSet = true; } XmlNode sizeNode = resultNode.FirstChild("Size"); if(!sizeNode.IsNull()) { m_size = StringUtils::ConvertToInt64(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(sizeNode.GetText()).c_str()).c_str()); m_sizeHasBeenSet = true; } } return *this; } void DashboardEntry::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const { if(m_dashboardNameHasBeenSet) { oStream << location << index << locationValue << ".DashboardName=" << StringUtils::URLEncode(m_dashboardName.c_str()) << "&"; } if(m_dashboardArnHasBeenSet) { oStream << location << index << locationValue << ".DashboardArn=" << StringUtils::URLEncode(m_dashboardArn.c_str()) << "&"; } if(m_lastModifiedHasBeenSet) { oStream << location << index << locationValue << ".LastModified=" << StringUtils::URLEncode(m_lastModified.ToGmtString(DateFormat::ISO_8601).c_str()) << "&"; } if(m_sizeHasBeenSet) { oStream << location << index << locationValue << ".Size=" << m_size << "&"; } } void DashboardEntry::OutputToStream(Aws::OStream& oStream, const char* location) const { if(m_dashboardNameHasBeenSet) { oStream << location << ".DashboardName=" << StringUtils::URLEncode(m_dashboardName.c_str()) << "&"; } if(m_dashboardArnHasBeenSet) { oStream << location << ".DashboardArn=" << StringUtils::URLEncode(m_dashboardArn.c_str()) << "&"; } if(m_lastModifiedHasBeenSet) { oStream << location << ".LastModified=" << StringUtils::URLEncode(m_lastModified.ToGmtString(DateFormat::ISO_8601).c_str()) << "&"; } if(m_sizeHasBeenSet) { oStream << location << ".Size=" << m_size << "&"; } } } // namespace Model } // namespace CloudWatch } // namespace Aws
29.201613
163
0.695664
[ "model" ]
7bd100d35dc2f083e197094b5e4ea8d2ea1ad7ed
50,710
cpp
C++
Samples/AppWindow/cppwinrt/Code/BU/Musion - Copy/CodeLine.cpp
OSIREM/ecoin-minimal
7d8314484c0cd47c673046c86c273cc48eaa43d2
[ "MIT" ]
null
null
null
Samples/AppWindow/cppwinrt/Code/BU/Musion - Copy/CodeLine.cpp
OSIREM/ecoin-minimal
7d8314484c0cd47c673046c86c273cc48eaa43d2
[ "MIT" ]
null
null
null
Samples/AppWindow/cppwinrt/Code/BU/Musion - Copy/CodeLine.cpp
OSIREM/ecoin-minimal
7d8314484c0cd47c673046c86c273cc48eaa43d2
[ "MIT" ]
null
null
null
/* CodeLine - osirem.com Copyright OSIREM LTD (C) 2016 www.bitolyl.com/osirem bitcoin-office.com ecn.world This source is proprietary, and cannot be used, in part or in full without the express permission of the original author. The original author retain the rights to use, modify, and/or relicense this code without notice. */ #include "pch.h" #include "Code/Work/Contract.h" #include "Class.h" using namespace ecoin; namespace ecoin { std::shared_ptr<ClassVar> g_BaseNode; std::vector<std::shared_ptr<ClassVar>> g_vec_BaseNode; template<class T> T ag_any_cast(boost::any f_Any) { #ifdef ECOIN_SECURE try { return boost::any_cast<T>(f_Any); } catch (boost::bad_any_cast &e) { #if 1 std::cerr << e.what() << '\n'; #endif for(;;) { //pause } } #else return boost::any_cast<T>(f_Any); #endif } CodeLine::CodeLine(std::string f_Line, uint f_CHK, System* f_System) { //////////////// //////////////// // Construct // // acClear(); m_CodeString = f_Line; m_Chk = f_CHK; m_System = f_System; bool f_Scan = true; int f_Size = f_Line.size(); if(m_Chk < f_Size - 6) { std::shared_ptr<Code> f_CodeB = std::make_shared<Code>(f_Line, m_Chk, 0); if (f_CodeB->m_Code_DigitA == '#' || f_CodeB->m_Code_DigitB == '#' || f_CodeB->m_Code_DigitC == '#') { f_Scan = false; } else { m_vec_Code.push_back(f_CodeB); } ////////// ////////// // END if(f_Scan) { m_END = f_CodeB->acDecide_END(); m_Chk = f_CodeB->acDecide_MAX(); uint f_Cntr = 1; while(f_Scan) { if(m_Chk < f_Line.size() - 6) { std::shared_ptr<Code> f_CodeA = std::make_shared<Code>(f_Line, m_Chk, f_Cntr); m_Chk = f_CodeA->m_Chk; if(f_CodeA->m_Code_DigitA == '/' && f_CodeA->m_Code_DigitB == '/') { f_Scan = false; } if (f_CodeA->m_Code_DigitA == '#' || f_CodeA->m_Code_DigitB == '#' || f_CodeA->m_Code_DigitC == '#') { f_Scan = false; } else { m_vec_Code.push_back(f_CodeA); } } else { f_Scan = false; } f_Cntr++; } } } ////////////////////// ////////////// // Setup // // uint f_CodeSize = m_vec_Code.size(); uint f_Count = 0; while(f_Count < f_CodeSize) { std::shared_ptr<Code> f_Code = m_vec_Code[f_Count]; if((f_Code->m_Code_DigitB != '/') && (f_Code->m_Code_DigitB != '#')) { switch(f_Code->m_Code) { case MuCode_Var: //var socket...accepts Variable stdptr from result of either { f_Code->acPrepare_CallNames(); if(f_Count == 0) { if(f_CodeSize == 3) { std::shared_ptr<Code> f_CodePositionOne = m_vec_Code[1]; if(f_CodePositionOne->m_Code == MuCode_Condition) { m_CodeLine = MuLine_Condition_Ajax; if(f_Code->m_Number.size() > 0) { m_vec_Variable.push_back(f_Code->m_Number[0]->m_MxVar); } else { m_vec_Variable.push_back(std::make_shared<Variable>(f_Code->m_Name[0]->m_MxName, f_Code->m_Code)); } } else if(f_CodePositionOne->m_Code == MuCode_Function) { m_CodeLine = MuLine_Function; if(f_CodePositionOne->m_Code == MuCode_Function) { if(f_Code->m_Number.size() > 0) { //m_vec_Variable.push_back(f_Code->m_Number[0]->m_MxVar); throw; } else { m_Result_V = std::make_shared<Variable>(f_Code->m_Name[0]->m_MxName, f_Code->m_Code); m_Returning = true; } } } else if(f_CodePositionOne->m_Code == MuCode_Operator) { m_CodeLine = MuLine_Assign_Opr; if(f_Code->m_Number.size() > 0) { m_vec_Variable.push_back(f_Code->m_Number[0]->m_MxVar); } else { m_vec_Variable.push_back(std::make_shared<Variable>(f_Code->m_Name[0]->m_MxName, f_Code->m_Code)); } } } else if(f_CodeSize == 1) { m_CodeLine = MuLine_Init_Var; if(f_Code->m_Number.size() > 0) { m_vec_Variable.push_back(f_Code->m_Number[0]->m_MxVar); } else { //mebbe add debug message int var no number or ignore if(f_Code->m_Number.size() > 0) { m_vec_Variable.push_back(f_Code->m_Number[0]->m_MxVar); } else { m_vec_Variable.push_back(std::make_shared<Variable>(f_Code->m_Name[0]->m_MxName, f_Code->m_Code)); } } } else if(f_CodeSize == 2) { std::shared_ptr<Code> f_CodePositionOne = m_vec_Code[1]; if(f_Code->m_Code == MuCode_Return) { m_CodeLine = MuLine_Function_Return; //not possible } else if(f_Code->m_Code == MuCode_Template) { m_CodeLine = MuLine_Template; //not possible } else if(f_CodePositionOne->m_Code == MuLine_Function) { m_CodeLine = MuLine_Function; if(f_Code->m_Number.size() > 0) { //m_vec_Variable.push_back(f_Code->m_Number[0]->m_MxVar); throw; } else { m_Result_V = std::make_shared<Variable>(f_Code->m_Name[0]->m_MxName, f_Code->m_Code); m_Returning = true; } } else { m_CodeLine = MuLine_Assign; m_vec_Variable.push_back(f_Code->m_Number[0]->m_MxVar); } } else if(f_CodeSize == 4) { std::shared_ptr<Code> f_CodePositionOne = m_vec_Code[1]; if(f_CodePositionOne->m_Code == MuLine_Function) { m_CodeLine = MuLine_Function; if(f_Code->m_Number.size() > 0) { //m_vec_Variable.push_back(f_Code->m_Number[0]->m_MxVar); throw; } else { m_Result_V = std::make_shared<Variable>(f_Code->m_Name[0]->m_MxName, f_Code->m_Code); m_Returning = true; } } else if(f_Code->m_Code == MuCode_For_Loop) { m_CodeLine = MuLine_For_Loop; } else { throw; //also line length exceeded } } else { throw; //add debug message multiple operators and conditions not yet implemented please reduce line length } } else if(f_Count == 1) //position one { if(f_CodeSize == 3) { std::shared_ptr<Code> f_CodePositionZero = m_vec_Code[0]; if(f_CodePositionZero->m_Code == MuCode_Function) { m_CodeLine = MuLine_Function; if(f_Code->m_Number.size() > 0) { m_vec_Variable.push_back(f_Code->m_Number[0]->m_MxVar); } else { m_vec_Variable.push_back(std::make_shared<Variable>(f_Code->m_Name[0]->m_MxName, f_Code->m_Code)); } } else if(f_CodePositionZero->m_Code == MuCode_FunctionStart) { m_CodeLine = MuLine_Function_Custom; if(f_Code->m_Number.size() > 0) { m_vec_Variable.push_back(f_Code->m_Number[0]->m_MxVar); } else { m_vec_Variable.push_back(std::make_shared<Variable>(f_Code->m_Name[0]->m_MxName, f_Code->m_Code)); } } else if(f_CodePositionZero->m_Code == MuCode_ClassVar) { m_CodeLine = MuLine_Init_ClassVar; if(f_Code->m_Number.size() > 0) { m_vec_Variable.push_back(f_Code->m_Number[0]->m_MxVar); } else { m_vec_Variable.push_back(std::make_shared<Variable>(f_Code->m_Name[0]->m_MxName, f_Code->m_Code)); } } else if(f_Code->m_Code == MuCode_Operator) { m_CodeLine = MuLine_Assign_Opr; } } else if(f_CodeSize == 1) { throw; //add debug message impossible } else if(f_CodeSize == 2) { std::shared_ptr<Code> f_CodePositionZero = m_vec_Code[0]; if(f_CodePositionZero->m_Code == MuCode_Template) { m_CodeLine = MuLine_Template; //not possible if(f_Code->m_Number.size() > 0) { m_vec_Variable.push_back(f_Code->m_Number[0]->m_MxVar); } else { m_vec_Variable.push_back(std::make_shared<Variable>(f_Code->m_Name[0]->m_MxName, f_Code->m_Code)); } } else if(f_CodePositionZero->m_Code == MuCode_Function) { m_CodeLine = MuLine_Function; if(f_Code->m_Number.size() > 0) { m_vec_Variable.push_back(f_Code->m_Number[0]->m_MxVar); } else { m_vec_Variable.push_back(std::make_shared<Variable>(f_Code->m_Name[0]->m_MxName, f_Code->m_Code)); } } else if(f_CodePositionZero->m_Code == MuCode_FunctionStart) { m_CodeLine = MuLine_Function_Custom; if(f_Code->m_Number.size() > 0) { m_vec_Variable.push_back(f_Code->m_Number[0]->m_MxVar); } else { m_vec_Variable.push_back(std::make_shared<Variable>(f_Code->m_Name[0]->m_MxName, f_Code->m_Code)); } } else if(f_CodePositionZero->m_Code == MuCode_Return) { m_CodeLine = MuLine_Function_Return; if(f_Code->m_Number.size() > 0) { m_vec_Variable.push_back(f_Code->m_Number[0]->m_MxVar); } else { m_vec_Variable.push_back(std::make_shared<Variable>(f_Code->m_Name[0]->m_MxName, f_Code->m_Code)); } } else { m_CodeLine = MuLine_Assign; if(f_Code->m_Number.size() > 0) { m_vec_Variable.push_back(f_Code->m_Number[0]->m_MxVar); } else { m_vec_Variable.push_back(std::make_shared<Variable>(f_Code->m_Name[0]->m_MxName, f_Code->m_Code)); } } } else if(f_CodeSize == 4) { std::shared_ptr<Code> f_CodePositionZero = m_vec_Code[0]; if(f_CodePositionZero->m_Code == MuCode_Function) { m_CodeLine = MuLine_Function; if(f_Code->m_Number.size() > 0) { m_vec_Variable.push_back(f_Code->m_Number[0]->m_MxVar); } else { m_vec_Variable.push_back(std::make_shared<Variable>(f_Code->m_Name[0]->m_MxName, f_Code->m_Code)); } } else if(f_CodePositionZero->m_Code == MuCode_FunctionStart) { m_CodeLine = MuLine_Function_Custom; if(f_Code->m_Number.size() > 0) { m_vec_Variable.push_back(f_Code->m_Number[0]->m_MxVar); } else { m_vec_Variable.push_back(std::make_shared<Variable>(f_Code->m_Name[0]->m_MxName, f_Code->m_Code)); } } else if(f_CodePositionZero->m_Code == MuCode_Return) { m_CodeLine = MuLine_Function_Return; if(f_Code->m_Number.size() > 0) { m_vec_Variable.push_back(f_Code->m_Number[0]->m_MxVar); } else { m_vec_Variable.push_back(std::make_shared<Variable>(f_Code->m_Name[0]->m_MxName, f_Code->m_Code)); } } else if(f_CodePositionZero->m_Code == MuCode_For_Loop) { m_CodeLine = MuLine_For_Loop; if(f_Code->m_Number.size() > 0) { m_vec_Variable.push_back(f_Code->m_Number[0]->m_MxVar); } else { m_vec_Variable.push_back(std::make_shared<Variable>(f_Code->m_Name[0]->m_MxName, f_Code->m_Code)); } } } } else if(f_Count == 2) { if(f_CodeSize == 3) { std::shared_ptr<Code> f_CodePositionZero = m_vec_Code[0]; std::shared_ptr<Code> f_CodePositionOne = m_vec_Code[1]; if(f_CodePositionOne->m_Code == MuCode_Condition) { m_CodeLine = MuLine_Condition_Ajax; if(f_Code->m_Number.size() > 0) { m_vec_Variable.push_back(f_Code->m_Number[0]->m_MxVar); } else { m_vec_Variable.push_back(std::make_shared<Variable>(f_Code->m_Name[0]->m_MxName, f_Code->m_Code)); } } else if(f_CodePositionOne->m_Code == MuCode_Function) { m_CodeLine = MuLine_Function; if(f_Code->m_Number.size() > 0) { m_vec_Variable.push_back(f_Code->m_Number[0]->m_MxVar); } else { m_vec_Variable.push_back(std::make_shared<Variable>(f_Code->m_Name[0]->m_MxName, f_Code->m_Code)); } } else if(f_CodePositionZero->m_Code == MuCode_FunctionStart) { m_CodeLine = MuLine_Function_Custom; if(f_Code->m_Number.size() > 0) { m_vec_Variable.push_back(f_Code->m_Number[0]->m_MxVar); } else { m_vec_Variable.push_back(std::make_shared<Variable>(f_Code->m_Name[0]->m_MxName, f_Code->m_Code)); } } else if(f_CodePositionZero->m_Code == MuCode_ClassVar) { m_CodeLine = MuLine_Init_ClassVar; if(f_Code->m_Number.size() > 0) { m_vec_Variable.push_back(f_Code->m_Number[0]->m_MxVar); } else { m_vec_Variable.push_back(std::make_shared<Variable>(f_Code->m_Name[0]->m_MxName, f_Code->m_Code)); } } } else if(f_CodeSize == 1) { throw; //add debug message impossible } else if(f_CodeSize == 2) { throw; //add debug message impossible } else if(f_CodeSize == 4) { std::shared_ptr<Code> f_CodePositionOne = m_vec_Code[1]; if(m_CodeLine == MuLine_Function) { if(f_Code->m_Number.size() > 0) { m_vec_Variable.push_back(f_Code->m_Number[0]->m_MxVar); } else { m_vec_Variable.push_back(std::make_shared<Variable>(f_Code->m_Name[0]->m_MxName, f_Code->m_Code)); } } else if(f_Code->m_Code == MuCode_For_Loop) { m_CodeLine = MuLine_For_Loop; if(f_Code->m_Number.size() > 0) { m_vec_Variable.push_back(f_Code->m_Number[0]->m_MxVar); } else { m_vec_Variable.push_back(std::make_shared<Variable>(f_Code->m_Name[0]->m_MxName, f_Code->m_Code)); } } else { throw; //also line length exceeded } } else { throw; //add debug message multiple operators and conditions not yet implemented please reduce line length } } else if(f_Count == 3) { if(f_CodeSize == 3) { throw; //add debug messages impossible } else if(f_CodeSize == 1) { throw; //add debug message impossible } else if(f_CodeSize == 2) { throw; //add debug message impossible } else if(f_CodeSize == 4) { std::shared_ptr<Code> f_CodePositionZero = m_vec_Code[0]; std::shared_ptr<Code> f_CodePositionOne = m_vec_Code[0]; if((f_CodePositionOne->m_Code == MuCode_Function) || (f_CodePositionZero->m_Code == MuCode_Function)) { if(f_Code->m_Number.size() > 0) { m_vec_Variable.push_back(f_Code->m_Number[0]->m_MxVar); } else { m_vec_Variable.push_back(std::make_shared<Variable>(f_Code->m_Name[0]->m_MxName, f_Code->m_Code)); } } else if(f_CodePositionZero->m_Code == MuCode_For_Loop) { m_CodeLine = MuLine_For_Loop; if(f_Code->m_Number.size() > 0) { m_vec_Variable.push_back(f_Code->m_Number[0]->m_MxVar); } else { m_vec_Variable.push_back(std::make_shared<Variable>(f_Code->m_Name[0]->m_MxName, f_Code->m_Code)); } } else { throw; //also line length exceeded } } else { throw; //add debug message multiple operators and conditions not yet implemented please reduce line length } } else { throw; //add debug message } }break; case MuCode_ClassVar: { if(f_Count == 0) { if(f_CodeSize == 1) { m_CodeLine = MuLine_Init_ClassVar; } else if(f_CodeSize == 2) { std::shared_ptr<Code> f_CodePositionOne = m_vec_Code[0]; if(f_Code->m_Code == MuCode_Function) { m_CodeLine = MuLine_Function; } else if(f_CodePositionOne->m_Code == MuCode_Function) { m_CodeLine = MuLine_Function; } else { m_CodeLine = MuLine_Init_ClassVar; } } else if(f_CodeSize == 3) { if(f_Code->m_Code == MuCode_FunctionStart) { m_CodeLine = MuLine_Function; } } else if(f_CodeSize == 4) { m_CodeLine = MuLine_Function; } } else if(f_Count == 1) { if(f_CodeSize == 2) { std::shared_ptr<Code> f_CodePositionZero = m_vec_Code[0]; if(f_CodePositionZero->m_Code == MuCode_Return) { m_CodeLine = MuLine_Function_Return; m_Returning = true; } else if(f_CodePositionZero->m_Code == MuCode_Template) { m_CodeLine = MuLine_Template; } else if(f_CodePositionZero->m_Code == MuCode_Function) { m_CodeLine = MuLine_Function; } else { m_CodeLine = MuLine_Init_ClassVar; } } else if(f_CodeSize == 3) { std::shared_ptr<Code> f_CodePositionZero = m_vec_Code[0]; if(f_CodePositionZero->m_Code == MuCode_Function) { m_CodeLine = MuLine_Function; } else if(f_Code->m_Code == MuCode_Function) { m_CodeLine = MuLine_Function; } } else if(f_CodeSize == 1) { throw; //add debug message impossible } else if(f_CodeSize == 4) { m_CodeLine = MuLine_Function; } } else if(f_Count == 2) { if(f_CodeSize == 2) { throw; //add debug message impossible } else if(f_CodeSize == 3) { std::shared_ptr<Code> f_CodePositionOne = m_vec_Code[1]; std::shared_ptr<Code> f_CodePositionZero = m_vec_Code[0]; if(f_CodePositionZero->m_Code == MuCode_Function) { m_CodeLine = MuLine_Function; } else if(f_CodePositionOne->m_Code == MuCode_Function) { m_CodeLine = MuLine_Function; } } else if(f_CodeSize == 1) { throw; //add debug message impossible } else if(f_CodeSize == 4) { m_CodeLine = MuLine_Function; } } else if(f_Count == 3) { if(f_CodeSize == 2) { throw; //add debug message impossible } else if(f_CodeSize == 3) { throw; //add debug message } else if(f_CodeSize == 1) { throw; //add debug message impossible } else if(f_CodeSize == 4) { m_CodeLine = MuLine_Function; } } //pass no vars...? }break; case MuCode_Function: { m_CodeLine = MuLine_Function; if(f_Code->m_Type[0]->m_VarType == MuFunc_Custom) { ////////////////////// // Custom Function m_CodeLine = MuLine_Function_Custom; } else if (f_Code->m_Type[0]->m_VarType == MuFunc_Frame) { m_CodeLine = MuLine_Function_Frame; } else ////////////////////////////////////////////// { // Math and System and Other (already storage) Function Calls m_CodeLine = MuLine_Function; } }break; case MuCode_FunctionStart: { m_CodeLine = MuLine_Function_Custom; if(f_Code->m_Type[0]->m_VarType == MuFunc_Custom) { ////////////////////// // Custom Function m_CodeLine = MuLine_Function_Custom; } else if (f_Code->m_Type[0]->m_VarType == MuFunc_Frame) { m_CodeLine = MuLine_Function_Frame; } else ////////////////////////////////////////////// { // Math and System and Other (already storage) Function Calls m_CodeLine = MuLine_Function; } }break; case MuCode_ClassDef: { m_CodeLine = MuLine_ClassDef; }break; case MuCode_System: { if(f_Count > 0) { if((m_CodeLine != MuLine_Init_ClassVar) && (m_CodeLine != MuLine_Assign_Opr) && (m_CodeLine != MuLine_Function) && (m_CodeLine != MuLine_Function_Frame) && (m_CodeLine != MuLine_Function_Custom) && (m_CodeLine != MuLine_Condition_Ajax) && (m_CodeLine != MuCode_For_Loop)) { m_CodeLine = MuLine_Assign; } std::shared_ptr<Variable> f_Var = m_System->av_Var(f_Code->m_Name[0]->m_MxName); m_vec_Variable.push_back(f_Var); if(f_Code->m_Number.size() == 1 && f_CodeSize == 1) { if((m_CodeLine != MuLine_Init_ClassVar) && (m_CodeLine != MuLine_Assign_Opr) && (m_CodeLine != MuLine_Function) && (m_CodeLine != MuLine_Function_Frame) && (m_CodeLine != MuLine_Function_Custom) && (m_CodeLine != MuLine_Condition_Ajax) && (m_CodeLine != MuCode_For_Loop)) { m_CodeLine = MuLine_Init_Var; } m_vec_Variable.push_back(f_Code->m_Number[0]->m_MxVar); } } else { if((m_CodeLine != MuLine_Init_ClassVar) && (m_CodeLine != MuLine_Assign_Opr) && (m_CodeLine != MuLine_Function) && (m_CodeLine != MuLine_Function_Frame) && (m_CodeLine != MuLine_Function_Custom) && (m_CodeLine != MuLine_Condition_Ajax) && (m_CodeLine != MuCode_For_Loop)) { m_CodeLine = MuLine_Init_Var; } std::shared_ptr<Variable> f_Var = m_System->av_Var(f_Code->m_Name[0]->m_MxName); m_vec_Variable.push_back(f_Var); } }break; case MuCode_Constant: { if((m_CodeLine != MuLine_Init_ClassVar) && (m_CodeLine != MuLine_Assign_Opr) && (m_CodeLine != MuLine_Function) && (m_CodeLine != MuLine_Function_Frame) && (m_CodeLine != MuLine_Function_Custom) && (m_CodeLine != MuLine_Condition_Ajax) && (m_CodeLine != MuCode_For_Loop)) { m_CodeLine = MuLine_Init_Var; } std::shared_ptr<Variable> f_Var = std::make_shared<Variable>(f_Code->m_Name[0]->m_MxName, MuCode_Constant); m_vec_Variable.push_back(f_Var); if(f_Code->m_Number.size() == 1 && f_CodeSize == 1) { if((m_CodeLine != MuLine_Init_ClassVar) && (m_CodeLine != MuLine_Assign_Opr) && (m_CodeLine != MuLine_Function) && (m_CodeLine != MuLine_Function_Frame) && (m_CodeLine != MuLine_Function_Custom) && (m_CodeLine != MuLine_Condition_Ajax) && (m_CodeLine != MuCode_For_Loop)) { m_CodeLine = MuLine_Init_Var; } f_Var->CloneVar(f_Code->m_Number[0]->m_MxVar); } else if(f_Code->m_Number.size() > 1) { #ifdef ECOIN_SECURE throw; #endif } }break; case MuCode_For_Loop: { m_CodeLine = MuLine_For_Loop; if(f_Code->m_Param.size() > 0) { std::shared_ptr<Variable> f_VarFRT = std::make_shared<Variable>(f_Code->m_Param[0]->m_MxName, MuCode_Var); *(f_VarFRT) = *(f_Code->m_Param[0]->m_MxVar); m_vec_Variable.push_back(f_VarFRT); } if(f_Code->m_Param.size() > 1) { std::shared_ptr<Variable> f_VarFRT = std::make_shared<Variable>(f_Code->m_Param[1]->m_MxName, MuCode_Var); *(f_VarFRT) = *(f_Code->m_Param[0]->m_MxVar); m_vec_Variable.push_back(f_VarFRT); } }break; case MuCode_Operator: { m_CodeLine = MuLine_Assign_Opr; std::shared_ptr<Code> f_LtCode = m_vec_Code[f_Code->m_Index - 1]; std::shared_ptr<Code> f_OpCode = m_vec_Code[f_Code->m_Index]; std::shared_ptr<Code> f_RtCode = m_vec_Code[f_Code->m_Index + 1]; std::shared_ptr<Operator> f_Operator = std::make_shared<Operator>(f_OpCode->m_MxName); f_Operator->m_Operator = f_OpCode->m_Type[0]->m_VarType; std::string f_L_StrCode = f_LtCode->m_MxName; std::string f_R_StrCode = f_RtCode->m_MxName; std::string f_L_StrCodeName = f_LtCode->m_Name[0]->m_MxName; std::string f_R_StrCodeName = f_RtCode->m_Name[0]->m_MxName; if(f_LtCode->m_vec_NameCall.size() == 1) { if(f_L_StrCode.compare("Sys") == 0) { if(f_L_StrCodeName.compare("Pos") == 0) { f_Operator->leftHand = m_System->Pos; m_vec_Variable.push_back(m_System->Pos); } if(f_L_StrCodeName.compare("Posx") == 0) { f_Operator->leftHand = m_System->Posx; m_vec_Variable.push_back(m_System->Posx); } if(f_L_StrCodeName.compare("Posy") == 0) { f_Operator->leftHand = m_System->Posy; m_vec_Variable.push_back(m_System->Posy); } if(f_L_StrCodeName.compare("Posz") == 0) { f_Operator->leftHand = m_System->Posz; m_vec_Variable.push_back(m_System->Posz); } else if(f_L_StrCodeName.compare("Color") == 0) { f_Operator->leftHand = m_System->Color; m_vec_Variable.push_back(m_System->Color); } } else if(f_L_StrCode.compare("Var") == 0) { f_Operator->leftHand = std::make_shared<Variable>(f_LtCode->m_Name[0]->m_MxName, f_LtCode->m_Code); m_vec_Variable.push_back(f_Operator->leftHand); } else { #ifdef ECOIN_SECURE throw; #endif } } else if(f_LtCode->m_vec_NameCall.size() == 2) //assign to classvar var { if(f_L_StrCode.compare("Var") == 0) { f_Operator->leftHand = std::make_shared<Variable>(f_LtCode->m_Name[0]->m_MxName, f_LtCode->m_Code); for(int f_Jet = 0; f_Jet < f_LtCode->m_vec_NameCall.size(); f_Jet++) { f_Operator->leftHand->m_vec_NameCall.push_back(f_LtCode->m_vec_NameCall[f_Jet]); } m_vec_Variable.push_back(f_Operator->leftHand); } else { #ifdef ECOIN_SECURE throw; #endif } } else { #ifdef ECOIN_SECURE throw; #endif } if(f_RtCode->m_vec_NameCall.size() == 1) { if(f_R_StrCode.compare("Sys") == 0) { if(f_R_StrCodeName.compare("Pos") == 0) { f_Operator->rightHand = f_RtCode->m_Number[0]->m_MxVar; m_vec_Variable.push_back(f_Operator->rightHand); #if 0 f_Operator->rightHand = std::make_shared<Variable>(f_RtCode->m_Name[0]->m_MxName, f_RtCode->m_Code); #endif } else if(f_R_StrCodeName.compare("Posx") == 0) { #if 0 f_Operator->rightHand = std::make_shared<Variable>(f_RtCode->m_Name[0]->m_MxName, f_RtCode->m_Code); #endif f_Operator->rightHand = f_RtCode->m_Number[0]->m_MxVar; m_vec_Variable.push_back(f_Operator->rightHand); } else if(f_R_StrCodeName.compare("Posy") == 0) { #if 0 f_Operator->rightHand = std::make_shared<Variable>(f_RtCode->m_Name[0]->m_MxName, f_RtCode->m_Code); #endif f_Operator->rightHand = f_RtCode->m_Number[0]->m_MxVar; m_vec_Variable.push_back(f_Operator->rightHand); } else if(f_R_StrCodeName.compare("Posz") == 0) { #if 0 f_Operator->rightHand = std::make_shared<Variable>(f_RtCode->m_Name[0]->m_MxName, f_RtCode->m_Code); #endif f_Operator->rightHand = f_RtCode->m_Number[0]->m_MxVar; m_vec_Variable.push_back(f_Operator->rightHand); } else if(f_R_StrCodeName.compare("Color") == 0) { #if 0 f_Operator->rightHand = std::make_shared<Variable>(f_RtCode->m_Name[0]->m_MxName, f_RtCode->m_Code); #endif f_Operator->rightHand = f_RtCode->m_MxVar; m_vec_Variable.push_back(f_Operator->rightHand); } else { throw; //add system not found } } else if(f_R_StrCode.compare("Var") == 0) { if(f_RtCode->m_Number.size() >= 1) { f_Operator->rightHand = f_RtCode->m_Number[0]->m_MxVar; m_vec_Variable.push_back(f_Operator->rightHand); } else { f_Operator->rightHand = std::make_shared<Variable>(f_RtCode->m_Name[0]->m_MxName, f_RtCode->m_Code); m_vec_Variable.push_back(f_Operator->rightHand); } } else { #ifdef ECOIN_SECURE throw; // #endif } } else if(f_RtCode->m_vec_NameCall.size() == 2) //assign to classvar var { if(f_R_StrCode.compare("Var") == 0) { f_Operator->leftHand = std::make_shared<Variable>(f_RtCode->m_Name[0]->m_MxName, f_LtCode->m_Code); for(int f_Jet = 0; f_Jet < f_RtCode->m_vec_NameCall.size(); f_Jet++) { f_Operator->leftHand->m_vec_NameCall.push_back(f_RtCode->m_vec_NameCall[f_Jet]); } m_vec_Variable.push_back(f_Operator->leftHand); } else { #ifdef ECOIN_SECURE throw; #endif } } else { #ifdef ECOIN_SECURE throw; #endif } m_vec_Operator.push_back(f_Operator); }break; case MuCode_Condition: { m_CodeLine = MuLine_Condition_Ajax; }break; case MuCode_Override: { ///////////// /// Pause /// ///////////// }break; } } f_Count++; } } CodeLine::~CodeLine() { m_vec_Code.clear(); m_vec_Variable.clear(); m_vec_Operator.clear(); } int CodeLine::acSearch_CodeType(uint f_TYPE) { for(uint f_CT = 0; f_CT < m_vec_Code.size(); f_CT++) { std::shared_ptr<Code> f_Code = m_vec_Code[f_CT]; if(f_Code->m_Code == f_TYPE) { return f_CT; } } return -5; } void CodeLine::ac_Variable_Align(void) { uint f_VarSize = m_vec_Variable.size(); switch(m_CodeLine) { #if 0 case MuLine_Assign: case MuLine_Assign_Opr: case MuLine_Init_Var: { if(f_VarSize == 1) { m_vec_Code[0]->m_MxVar = m_vec_Variable[0]; } else if(f_VarSize == 2) { m_vec_Code[0]->m_MxVar = m_vec_Variable[0]; m_vec_Code[1]->m_MxVar = m_vec_Variable[1]; } else { throw; } }break; #endif case MuLine_Condition_Ajax: { if(f_VarSize == 5) { if(m_vec_Variable[2]->m_MxName.compare("Con") == 0) { m_vec_Code[0]->m_MxVar = m_vec_Variable[0]; m_vec_Code[2]->m_MxVar = m_vec_Variable[2]; m_vec_Code[1]->m_Condition[0]->leftHand = m_vec_Variable[3]; m_vec_Code[1]->m_Condition[0]->rightHand = m_vec_Variable[4]; } else { throw; } } else if(f_VarSize == 2) { m_vec_Code[0]->m_MxVar = m_vec_Variable[0]; m_vec_Code[2]->m_MxVar = m_vec_Variable[1]; m_vec_Code[1]->m_Condition[0]->leftHand = m_vec_Variable[0]; m_vec_Code[1]->m_Condition[0]->rightHand = m_vec_Variable[1]; } else if(f_VarSize == 4) { m_vec_Code[0]->m_MxVar = m_vec_Variable[0]; m_vec_Code[2]->m_MxVar = m_vec_Variable[1]; m_vec_Code[1]->m_Condition[0]->leftHand = m_vec_Variable[2]; m_vec_Code[1]->m_Condition[0]->rightHand = m_vec_Variable[3]; } else { throw; } }break; case MuLine_Function: { if(f_VarSize >= 1) { if(g_Function[m_vec_Code[1]->m_ContractID]->m_Return_V != nullptr) { g_Function[m_vec_Code[1]->m_ContractID]->m_Return_V = m_Result_V; for(int f_XY = 0; f_XY < g_Function[m_vec_Code[1]->m_ContractID]->m_vec_Variable.size(); f_XY++) { g_Function[m_vec_Code[1]->m_ContractID]->m_vec_Variable[f_XY] = m_vec_Variable[f_XY]; } } else if(g_Function[m_vec_Code[1]->m_ContractID]->m_Return_CV != nullptr) { g_Function[m_vec_Code[1]->m_ContractID]->m_Return_CV = m_Result_CV; for(int f_XY = 0; f_XY < g_Function[m_vec_Code[1]->m_ContractID]->m_vec_Variable.size(); f_XY++) { g_Function[m_vec_Code[1]->m_ContractID]->m_vec_Variable[f_XY] = m_vec_Variable[f_XY]; } } else //no return { for(int f_XY = 0; f_XY < g_Function[m_vec_Code[0]->m_ContractID]->m_vec_Variable.size(); f_XY++) { g_Function[m_vec_Code[0]->m_ContractID]->m_vec_Variable[f_XY] = m_vec_Variable[f_XY]; } } } }break; case MuLine_Function_Custom: { for(int f_XY = 0; f_XY < g_Function[m_vec_Code[0]->m_ContractID]->m_vec_Variable.size(); f_XY++) { g_Function[m_vec_Code[0]->m_ContractID]->m_vec_Variable[f_XY] = m_vec_Variable[f_XY]; } }break; } } std::shared_ptr<Variable> Code::acCodeCall_Var(int f_Index, int f_MaxIndex, std::shared_ptr<Function> f_Function, int f_FindIndexInt) { switch(m_vec_NameCallType[f_Index]) { case MuNameCall_Type_VarVar: { if(f_FindIndexInt == 0) { std::shared_ptr<Variable> f_Var = f_Function->acFind_Var(m_vec_NameCall[f_Index]); if(f_Var == nullptr) { f_Var = ag_Find_Var(m_vec_NameCall[f_Index]); } if(f_Var == nullptr) { throw; //add debug message var not found } else { return f_Var; //win! } } else //is array index varint check for integer { throw; } }break; case MuNameCall_Type_VarIndexInt: { if(f_FindIndexInt == 0) { throw; //add debug message integer index var out of position } else if(f_FindIndexInt == 1) //is array index varint check for integer { std::shared_ptr<Variable> f_VarIndexInt = f_Function->acFind_Var(m_vec_NameCall[f_Index]); if(f_VarIndexInt == nullptr) { f_VarIndexInt = ag_Find_Var(m_vec_NameCall[f_Index]); } if(f_VarIndexInt == nullptr) { throw; //add debug message var not found } else { f_FindIndexInt--; if(f_Index >= f_MaxIndex) //win conditions! { int f_Ind = ag_any_cast<int>(f_VarIndexInt->m_Var); if((f_Ind < 0) || (f_Ind >= g_vec_BaseNode[g_vec_BaseNode.size() - 1]->m_Class->m_vec_Variable.size())) { throw; //add debug message array index out of bounds } return g_vec_BaseNode[g_vec_BaseNode.size() - 1]->m_Class->m_vec_Variable[f_Ind]; } else { int f_Ind = ag_any_cast<int>(f_VarIndexInt->m_Var); if((f_Ind < 0) || (f_Ind >= g_BaseNode->m_Class->m_vec_ClassVar.size())) { throw; //add debug message classvar array index out of bounds } g_BaseNode = g_BaseNode->m_Class->m_vec_ClassVar[ag_any_cast<int>(f_VarIndexInt->m_Var)]; g_vec_BaseNode.push_back(g_BaseNode); return acCodeCall_Var(f_Index + 1, f_MaxIndex, f_Function, f_FindIndexInt + 1); } return f_VarIndexInt; } } else { throw; //no native vector error } }break; case MuNameCall_Type_MemberVar: { if(f_Index == 0) //1 place classvar { throw; //add debug message membervar not found } if(f_Index >= f_MaxIndex) //win conditions race winner { std::shared_ptr<Variable> f_Var = g_BaseNode->m_Class->acFindVar(m_vec_NameCall[f_Index]); if(f_Var == nullptr) { f_Var = ag_Find_Var(m_vec_NameCall[f_Index]); if(f_Var == nullptr) { throw; //add debug message variable member not found } else { return f_Var; } } else { return f_Var; } } else //'assume' evector calculate number of indices { g_BaseNode = g_BaseNode->m_Class->acFindClassVar(m_vec_NameCall[f_Index]); g_vec_BaseNode.push_back(g_BaseNode); return acCodeCall_Var(f_Index + 1, f_MaxIndex, f_Function, f_FindIndexInt + 1); } }break; case MuNameCall_Type_MemberIndexInt: { if(f_FindIndexInt == 0) { throw; //add debug message integer index var out of position } else if(f_FindIndexInt == 1) //is array index varint check for integer member var { std::shared_ptr<Variable> f_MemberVarIndexInt = g_BaseNode->m_Class->acFindVar(m_vec_NameCall[f_Index]); if(f_MemberVarIndexInt == nullptr) { throw; //add debug message var not found } else { f_FindIndexInt--; if(f_Index >= f_MaxIndex) //win conditions! { return g_vec_BaseNode[g_vec_BaseNode.size() - 1]->m_Class->m_vec_Variable[ag_any_cast<int>(f_MemberVarIndexInt->m_Var)]; } else { g_BaseNode = g_BaseNode->m_Class->acFindClassVar(m_vec_NameCall[f_Index]); g_vec_BaseNode.push_back(g_BaseNode); return acCodeCall_Var(f_Index + 1, f_MaxIndex, f_Function, f_FindIndexInt); } } } else //findindexint runaway vector assignment error { throw; //add debug message no native array } }break; case MuNameCall_Type_ClassVar: { if(f_Index == 0) //1 place classvar { std::shared_ptr<ClassVar> f_ClassVar = f_Function->acFind_ClassVar(m_vec_NameCall[f_Index]); if(f_ClassVar == nullptr) { f_ClassVar = ag_Find_ClassVar(m_vec_NameCall[f_Index]); } if(f_ClassVar == nullptr) { throw; //add debug message classvar not found } else { g_BaseNode = f_ClassVar; } } if(f_Index >= f_MaxIndex) //!!!win conditions! { if(f_FindIndexInt == 1) { throw; //add debuging message currently classvar at var socket syntax error } else if(f_FindIndexInt > 1) { throw; //add debuging message currently classvar at var socket syntax error } } else { if(f_FindIndexInt == 0) { g_BaseNode = g_BaseNode->m_Class->acFindClassVar(m_vec_NameCall[f_Index]); return acCodeCall_Var(f_Index + 1, f_MaxIndex, f_Function, f_FindIndexInt); } if(f_FindIndexInt == 1) { g_BaseNode = g_BaseNode->m_Class->acFindClassVar(m_vec_NameCall[f_Index]); return acCodeCall_Var(f_Index + 1, f_MaxIndex, f_Function, f_FindIndexInt); } else { throw; //add debuging message find index int above 1 } } }break; } } std::shared_ptr<ClassVar> CodeLine::ac_Execute(std::shared_ptr<Function> f_Function) { ////////////////////// ////////////// // Setup // // uint f_VarSize = m_vec_Code.size(); #if 0 if(f_VarSize == 0 || f_VarSize == 1) { #ifdef ECOIN_SECURE #if 0 throw; #else return nullptr; #endif #endif } #endif #if 0 printf("ESL_EXEC-f_VarSize %i m_CodeLine %i\n", f_VarSize, m_CodeLine); #endif std::shared_ptr<Code> f_CodeL = m_vec_Code[0]; std::shared_ptr<Code> f_CodeR = m_vec_Code[m_vec_Code.size() - 1]; ////////////////// // Operator // if(m_CodeLine == MuLine_Assign_Opr) { if(m_vec_Operator.size() > 0) { std::shared_ptr<Variable> f_LeftHandSide = nullptr; std::shared_ptr<Variable> f_RightHandSide = nullptr; if(f_VarSize == 2) { uint f_OpSize = m_vec_Operator.size(); uint f_Count = 0; while(f_Count < f_OpSize) { std::shared_ptr<Operator> f_Operator = m_vec_Operator[f_Count]; std::shared_ptr<Variable> f_VarCall_L = f_CodeL->acCodeCall_Var(0, f_CodeL->m_vec_NameCall.size(), f_Function); std::shared_ptr<Variable> f_VarCall_R = f_CodeR->acCodeCall_Var(0, f_CodeR->m_vec_NameCall.size(), f_Function); if(f_VarCall_L == nullptr) { throw; //add debuging message variable assignation left hand variable not found } else { f_Operator->leftHand = f_VarCall_L; } if(f_VarCall_R == nullptr) { throw; //add debuging message variable assignation result hand variable not found } else { f_Operator->rightHand = f_VarCall_R; } f_Operator->ac_Execute(); f_Count++; } } else { throw; //add debug message variable assignation var count out of range } } else { #ifdef ECOIN_SECURE throw; #endif } } // Assign else if(m_CodeLine == MuLine_Assign) { if(f_VarSize == 0 || f_VarSize == 1) { #ifdef ECOIN_SECURE throw; #endif } else { if(f_VarSize == 2) { std::shared_ptr<Variable> f_VarA = m_vec_Variable[0]; std::shared_ptr<Variable> f_VarB = m_vec_Variable[1]; std::shared_ptr<Variable> f_VarCall_L = f_CodeL->acCodeCall_Var(0, f_CodeL->m_vec_NameCall.size(), f_Function); std::shared_ptr<Variable> f_VarCall_R = f_CodeR->acCodeCall_Var(0, f_CodeR->m_vec_NameCall.size(), f_Function); if(f_VarCall_L == nullptr) { throw; //add debuging message variable assignation left hand variable not found } if(f_VarCall_R == nullptr) { throw; //add debuging message variable assignation result hand variable not found } f_VarCall_L->CloneVar(f_VarCall_R); } else { if(f_VarSize == 3) { std::shared_ptr<Variable> f_VarA = m_vec_Variable[0]; std::shared_ptr<Variable> f_VarB = m_vec_Variable[1]; std::shared_ptr<Variable> f_VarC = m_vec_Variable[2]; std::shared_ptr<Variable> f_VarCall_A = m_vec_Code[0]->acCodeCall_Var(0, m_vec_Code[0]->m_vec_NameCall.size(), f_Function); std::shared_ptr<Variable> f_VarCall_B = m_vec_Code[1]->acCodeCall_Var(0, m_vec_Code[1]->m_vec_NameCall.size(), f_Function); std::shared_ptr<Variable> f_VarCall_C = m_vec_Code[2]->acCodeCall_Var(0, m_vec_Code[2]->m_vec_NameCall.size(), f_Function); if(f_VarCall_A == nullptr) { throw; //add debuging message variable assignation left hand variable not found } if(f_VarCall_B == nullptr) { throw; //add debuging message variable assignation mid hand variable not found } if(f_VarCall_C == nullptr) { throw; //add debuging message variable assignation result hand variable not found } f_VarCall_A->CloneVar(f_VarCall_B); f_VarCall_B->CloneVar(f_VarCall_C); } else { #ifdef ECOIN_SECURE throw; #endif } } } } else if(m_CodeLine == MuLine_Condition_Ajax) { std::shared_ptr<Condition> f_Condition = m_vec_Code[1]->m_Condition[0]; f_Condition->ac_Execute(); } else if(m_CodeLine == MuLine_Init_Var) { if(f_VarSize == 0 || f_VarSize == 1) { #ifdef ECOIN_SECURE throw; #endif } else { if(f_VarSize == 2) { std::shared_ptr<Variable> f_VarRes = m_vec_Variable[0]; std::shared_ptr<Variable> f_VarB = m_vec_Variable[1]; std::shared_ptr<Variable> f_VarCall_L = f_CodeL->acCodeCall_Var(0, f_CodeL->m_vec_NameCall.size(), f_Function); std::shared_ptr<Variable> f_VarCall_R = f_CodeR->acCodeCall_Var(0, f_CodeR->m_vec_NameCall.size(), f_Function); if(f_VarCall_L == nullptr) { throw; //add debuging message variable assignation left hand variable not found } if(f_VarCall_R == nullptr) { throw; //add debuging message variable assignation result hand variable not found } f_VarCall_L->CloneVar(f_VarCall_R); } else { if(f_VarSize == 3) { std::shared_ptr<Variable> f_VarRes = m_vec_Variable[0]; std::shared_ptr<Variable> f_VarB = m_vec_Variable[1]; std::shared_ptr<Variable> f_VarC = m_vec_Variable[2]; std::shared_ptr<Variable> f_VarCall_A = m_vec_Code[0]->acCodeCall_Var(0, m_vec_Code[0]->m_vec_NameCall.size(), f_Function); std::shared_ptr<Variable> f_VarCall_B = m_vec_Code[1]->acCodeCall_Var(0, m_vec_Code[1]->m_vec_NameCall.size(), f_Function); std::shared_ptr<Variable> f_VarCall_C = m_vec_Code[2]->acCodeCall_Var(0, m_vec_Code[2]->m_vec_NameCall.size(), f_Function); if(f_VarCall_A == nullptr) { throw; //add debuging message variable assignation left hand variable not found } if(f_VarCall_B == nullptr) { throw; //add debuging message variable assignation mid hand variable not found } if(f_VarCall_C == nullptr) { throw; //add debuging message variable assignation result hand variable not found } f_VarCall_A->CloneVar(f_VarCall_B); f_VarCall_B->CloneVar(f_VarCall_C); } else { #ifdef ECOIN_SECURE throw; #endif } } } } else if(m_CodeLine == MuLine_Function) { if(m_vec_Code[0]->m_Code == MuCode_Function) { if((m_vec_Code[0]->m_Type[0]->m_VarType >= MuFunc_Custom) && (m_vec_Code[0]->m_Type[0]->m_VarType < MuSetGLOBAL_)) { std::shared_ptr<Function> f_Function = m_vec_Code[0]->m_FunctionLink; f_Function->acExecute(); m_Result_V = f_Function->m_Return_V; m_Result_CV = f_Function->m_Return_CV; } else { throw; //add debug message functype out of range } } else if(m_vec_Code[1]->m_Code == MuCode_Function) { if((m_vec_Code[1]->m_Type[0]->m_VarType >= MuFunc_Custom) && (m_vec_Code[1]->m_Type[1]->m_VarType < MuSetGLOBAL_)) { std::shared_ptr<Function> f_Function = m_vec_Code[1]->m_FunctionLink; std::shared_ptr<Variable> f_Var = f_Function->acExecute(); m_Result_V = f_Function->m_Return_V; m_Result_CV = f_Function->m_Return_CV; } else { throw; //add debug message functype out of range } } } else if(m_CodeLine == MuLine_Function_Return) { std::shared_ptr<Variable> f_VariableReturn = m_vec_Variable[0]; if(f_VariableReturn != nullptr) { std::shared_ptr<Variable> f_Return = f_VariableReturn; } } else if(m_CodeLine == MuLine_For_Loop) { int f_ParamCount = m_vec_Code[0]->m_Param.size(); if(f_ParamCount == 1) { std::shared_ptr<Variable> f_VarCount = m_vec_Variable[0]; int f_Count = 0; if(f_VarCount->m_Var.type() == typeid(int)) { f_Count = ag_any_cast<int>(f_VarCount->m_Var); } else { #ifdef ECOIN_SECURE throw; #endif } if(f_Count < 0) { #ifdef ECOIN_SECURE throw; #endif } std::shared_ptr<Function> f_Function = g_Function[m_vec_Code[0]->m_ContractID]; for(int f_XY = 0; f_XY < f_Count; f_XY++) { f_Function->acExecute(); } } else if(f_ParamCount == 2) { std::shared_ptr<Variable> f_VarCountVar = m_vec_Variable[0]; std::shared_ptr<Variable> f_VarCount = m_vec_Variable[1]; int f_Count = 0; if(f_VarCount->m_Var.type() == typeid(int)) { f_Count = ag_any_cast<int>(f_VarCount->m_Var); } else { #ifdef ECOIN_SECURE throw; #endif } if(f_Count < 0) { #ifdef ECOIN_SECURE throw; #endif } std::shared_ptr<Function> f_Function = g_Function[m_vec_Code[0]->m_ContractID]; for(int f_XY = 0; f_XY < f_Count; f_XY++) { f_VarCountVar->set_Value(f_XY); f_Function->acExecute(); } } else if(f_ParamCount == 3) { std::shared_ptr<Variable> f_VarStart = m_vec_Variable[0]; std::shared_ptr<Variable> f_VarCount = m_vec_Variable[1]; std::shared_ptr<Variable> f_VarMax = m_vec_Variable[2]; int f_CountStart = 0; if(f_VarCount->m_Var.type() == typeid(int)) { f_CountStart = ag_any_cast<int>(f_VarCount->m_Var); } else { #ifdef ECOIN_SECURE throw; #endif } if(f_CountStart < 0) { #ifdef ECOIN_SECURE throw; #endif } int f_Count = 0; if(f_VarCount->m_Var.type() == typeid(int)) { f_Count = ag_any_cast<int>(f_VarCount->m_Var); } else { #ifdef ECOIN_SECURE throw; #endif } if(f_Count < 0) { #ifdef ECOIN_SECURE throw; #endif } int f_CountMax = 0; if(f_VarCount->m_Var.type() == typeid(int)) { f_CountMax = ag_any_cast<int>(f_VarCount->m_Var); } else { #ifdef ECOIN_SECURE throw; #endif } if(f_CountMax < 0) { #ifdef ECOIN_SECURE throw; #endif } std::shared_ptr<Function> f_Function = g_Function[m_vec_Code[0]->m_ContractID]; for(int f_XY = f_CountStart; f_XY < f_Count; f_XY += f_CountMax) { f_VarStart->set_Value(f_XY); f_Function->acExecute(); } } else { #ifdef ECOIN_SECURE throw; #endif } } else if(m_CodeLine == MuLine_Init_ClassVar) { std::shared_ptr<Code> f_CodeZero = m_vec_Code[0]; std::shared_ptr<Class> f_Class = nullptr; for(int f_Jet = 0; f_Jet < g_Class.size(); f_Jet++) { std::shared_ptr<Class> f_TestClass = g_Class[f_Jet]; #pragma message("Warning add debugability messages according to m_Type = result") if(f_TestClass->m_MxName.compare(m_vec_Code[0]->m_MxName) == 0) { f_Class = f_TestClass; } } if(!f_Class) { throw; //class not found } std::shared_ptr<ClassVar> f_ClassVar = std::make_shared<ClassVar>(f_Class); f_ClassVar->acCall_Constructor(); return f_ClassVar; } return nullptr; } std::string CodeLine::ac_Print(void) { return m_CodeString; } };
26.125708
134
0.570874
[ "vector" ]
7bd286773549f8940df75ae5d9f87038df315f94
989
cpp
C++
test/unit/math/mix/fun/atanh_test.cpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
1
2020-06-14T14:33:37.000Z
2020-06-14T14:33:37.000Z
test/unit/math/mix/fun/atanh_test.cpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
null
null
null
test/unit/math/mix/fun/atanh_test.cpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
1
2020-05-10T12:55:07.000Z
2020-05-10T12:55:07.000Z
#include <test/unit/math/test_ad.hpp> #include <vector> TEST(mathMixMatFun, atanh) { auto f = [](const auto& x1) { using stan::math::atanh; return atanh(x1); }; stan::test::expect_common_unary_vectorized(f); stan::test::expect_unary_vectorized(f, -0.9, 0.5); for (double re : std::vector<double>{-0.2, 0, 0.3}) { for (double im : std::vector<double>{-0.3, 0, 0.2}) { stan::test::expect_ad(f, std::complex<double>{re, im}); } } } TEST(mathMixMatFun, atanh_varmat) { using stan::math::vec_concat; using stan::test::expect_ad_vector_matvar; using stan::test::internal::common_args; auto f = [](const auto& x1) { using stan::math::atanh; return atanh(x1); }; std::vector<double> com_args = common_args(); std::vector<double> args{-0.9, 0.5}; auto all_args = vec_concat(com_args, args); Eigen::VectorXd A(all_args.size()); for (int i = 0; i < all_args.size(); ++i) { A(i) = all_args[i]; } expect_ad_vector_matvar(f, A); }
28.257143
61
0.634985
[ "vector" ]
7bdc4add29810b7736fa2cb9ad49d03c472dbb77
1,183
cpp
C++
level-editor/Driver.cpp
lukas-vaiciunas/haterminator
7f42e5a4ed4c5dee21368859989b74ba6c80898b
[ "MIT" ]
null
null
null
level-editor/Driver.cpp
lukas-vaiciunas/haterminator
7f42e5a4ed4c5dee21368859989b74ba6c80898b
[ "MIT" ]
null
null
null
level-editor/Driver.cpp
lukas-vaiciunas/haterminator
7f42e5a4ed4c5dee21368859989b74ba6c80898b
[ "MIT" ]
null
null
null
#include "Driver.h" #include "Keyboard.h" Driver::Driver() : camera_(0.0f, 0.0f, 4.0f), level_("data/maps/level-1.dat", "data/maps/map-1.dat", 20, 20), painter_(), imagesUI_(Key::T, "img/tilesheet.png"), statusUI_(0.0f, 0.0f) {} void Driver::updateOnTick(const Keyboard &keyboard) { camera_.updateOnTick(keyboard); } void Driver::updateOnKeyPress(const Keyboard &keyboard) { imagesUI_.updateOnKeyPress(keyboard); if (keyboard.isPressed(Key::NUM_0)) { painter_.setImageId(0); } else if (keyboard.isPressed(Key::C)) { painter_.setIsCollidable(!painter_.isCollidable()); } else if (keyboard.isPressed(Key::P)) { painter_.setIsPlacingSpawn(!painter_.isPlacingSpawn()); } else if (keyboard.isPressed(Key::F)) { level_.save(); } } void Driver::updateOnMousePress(const Mouse &mouse) { if (imagesUI_.isActive()) { imagesUI_.updateOnMousePress(mouse, painter_); } else { painter_.updateOnMousePress(mouse, level_, camera_); } } void Driver::render(const Mouse &mouse) const { level_.render(camera_); if (imagesUI_.isActive()) { imagesUI_.render(mouse); } else { painter_.render(mouse, level_, camera_); statusUI_.render(painter_); } }
18.484375
64
0.702451
[ "render" ]
7beefcdde8371e6c4f42fc63bed73cb590fbd97d
4,534
cpp
C++
L1/src/test.cpp
SqrtMinusOne/SEM7_Software_Design
a3d4828ad3aba5d7f266ee7eb598d1078d04450a
[ "Apache-2.0" ]
null
null
null
L1/src/test.cpp
SqrtMinusOne/SEM7_Software_Design
a3d4828ad3aba5d7f266ee7eb598d1078d04450a
[ "Apache-2.0" ]
null
null
null
L1/src/test.cpp
SqrtMinusOne/SEM7_Software_Design
a3d4828ad3aba5d7f266ee7eb598d1078d04450a
[ "Apache-2.0" ]
null
null
null
#pragma clang diagnostic push #pragma ide diagnostic ignored "cert-msc32-c" #pragma ide diagnostic ignored "cert-err58-cpp" #include <ctime> #include <iostream> #include <random> #include "gtest/gtest.h" #include "point.h" #include "pentagram.h" #include "text.h" #include "atanSegment.h" #include "pentagramText.h" #include "hashMap.h" TEST(PointTest, BasicPointTest) { std::mt19937 gen(time(nullptr)); std::uniform_real_distribution<> urd(-10, 10); auto x = urd(gen); auto y = urd(gen); Point p1 {x, y}; ASSERT_EQ(p1.getX(), x); ASSERT_EQ(p1.getY(), y); ASSERT_GE(p1.getR(), 0); ASSERT_NEAR(p1.getPhi(), 0, M_PI); p1.setX(y); p1.setY(x); ASSERT_EQ(p1.getX(), y); ASSERT_EQ(p1.getY(), x); } TEST(PointTest, CopyPaste) { Point p1 {2, 3}; auto p2 = p1; auto p3(p2); ASSERT_EQ(p1.getX(), p2.getX()); ASSERT_EQ(p2.getX(), p3.getX()); ASSERT_EQ(p1.getPhi(), p2.getPhi()); ASSERT_EQ(p1.getR(), p3.getR()); ASSERT_TRUE(p1 == p2); auto p4 = p2 + p3; auto p5 = p3 * 2; ASSERT_TRUE(p4 == p5); ASSERT_GT(p4.getR(), p1.getR()); ASSERT_GT(p5.getR(), p1.getR()); ASSERT_EQ(p3.getPhi(), p5.getPhi()); } void checkBorders(Shape& figure) { auto [p2, p1] = figure.getBorders(); for (Point& point : figure.getPath()) { ASSERT_LE(point.getX(), p1.getX()); ASSERT_LE(point.getY(), p1.getY()); ASSERT_GE(point.getX(),p2.getX()); ASSERT_GE(point.getY(),p2.getY()); } } void standartMoveSequence(Shape& figure) { ASSERT_NO_FATAL_FAILURE(checkBorders(figure)); figure.move(Point(99, -200)); ASSERT_NO_FATAL_FAILURE(checkBorders(figure)); figure.rotate(M_PI / 3); figure.scale(14); ASSERT_NO_FATAL_FAILURE(checkBorders(figure)); figure.scale(0.0001); ASSERT_NO_FATAL_FAILURE(checkBorders(figure)); } TEST(ShapeTest, PentagramTest) { auto center = Point{2, 3}; auto fig = Pentagram(center, 10); ASSERT_NO_FATAL_FAILURE(checkBorders(fig)); auto [ap1, ap2] = fig.getBorders(); fig.move(Point {2, 5}); auto [bp1, bp2] = fig.getBorders(); ASSERT_LT(ap1.getX(), bp1.getX()); ASSERT_LT(ap2.getY(), bp2.getY()); fig.rotate(M_PI * 0.42); fig.scale(13.4); auto [cp2, cp1] = fig.getBorders(); ASSERT_NO_FATAL_FAILURE(checkBorders(fig)); ASSERT_EQ(fig.getAngle(), M_PI*0.42); ASSERT_LT(cp2.getX(), bp2.getX()); ASSERT_GT(cp1.getY(), bp1.getY()); ASSERT_EQ(fig.getCenter(), center + Point(2, 5)); } TEST(ShapeTest, TextTest){ auto text = Text("Hello", Point(0, 0), Point(10, 10)); ASSERT_EQ(text.getString(), "Hello"); ASSERT_NO_FATAL_FAILURE(checkBorders(text)); text.setString("Goodbye"); ASSERT_EQ(text.getString(), "Goodbye"); ASSERT_NO_FATAL_FAILURE(standartMoveSequence(text)); } TEST(ShapeTest, AtanSegmentTest) { auto seg = AtanSegment(Point{0, 0}, Point{10, 10}, 0); ASSERT_NO_FATAL_FAILURE(checkBorders(seg)); ASSERT_NO_FATAL_FAILURE(standartMoveSequence(seg)); seg.setPrecision(20000); ASSERT_NO_FATAL_FAILURE(checkBorders(seg)); ASSERT_EQ(seg.getPrecision(), 20000); seg.setPrecision(2); ASSERT_NO_FATAL_FAILURE(checkBorders(seg)); } TEST(ContainerTest, InitTest) { auto m = HashMap<int, int>(); m.create(15, 20); m.create(20, 30); m.create(30, 40); ASSERT_EQ(m.at(15), 20); ASSERT_EQ(m.at(20), 30); ASSERT_EQ(m.at(30), 40); int val; ASSERT_FALSE(m.get(16, val)); ASSERT_TRUE(m.get(15, val)); m.update(15, 25); ASSERT_EQ(m.at(15), 25); m.remove(15); ASSERT_FALSE(m.get(15, val)); } TEST(ContainerTest, IteratorTest1) { auto m = HashMap<int, double>(); m.create(1, 2); m.create(2, 3); auto iter = HashMapIterator<int, double>(m); while (!iter.end()) { ASSERT_NE(iter.value(), 0); ASSERT_NE(iter.key(), 0); ++iter; } } TEST(ContainerTest, IteratorTest2) { auto m = HashMap<int, double>(); m.create(1, 2); m.create(2, 3); m.create(10, 4); m.create(20, 40); m.create(25, 45); auto it1 = m.begin(); auto it2 = m.end(); bool cmp = it1 == it2; ASSERT_FALSE(cmp); for (auto it = m.begin(); it != m.end(); it++) { ASSERT_NE(it.value(), 0); ASSERT_NE(it.key(), 0); } } int main(int argc, char *argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } #pragma clang diagnostic pop
24.376344
58
0.611381
[ "shape" ]
7bf6db46048c11427e7ea4c6d6b4a098b647d5c8
20,811
cc
C++
src/Enclave/ecallSrc/ecallIndex/ecallExtreme.cc
debe-sgx/debe
641f2b6473fec8ebea301c533d5aab563e53bcbb
[ "MIT" ]
null
null
null
src/Enclave/ecallSrc/ecallIndex/ecallExtreme.cc
debe-sgx/debe
641f2b6473fec8ebea301c533d5aab563e53bcbb
[ "MIT" ]
null
null
null
src/Enclave/ecallSrc/ecallIndex/ecallExtreme.cc
debe-sgx/debe
641f2b6473fec8ebea301c533d5aab563e53bcbb
[ "MIT" ]
null
null
null
/** * @file ecallExtreme.cc * @author * @brief implement the interface defined in the extreme index inside the enclave * @version 0.1 * @date 2020-12-30 * * @copyright Copyright (c) 2020 * */ #include "../../include/ecallExtreme.h" /** * @brief Construct a new Ecall Simple Index object * * @param maxRecvChunkNum the maximum number of received chunks * @param recipeBufferChunkNum the maximum number of chunk in recipe buffer */ EcallExtremeIndex::EcallExtremeIndex(uint64_t maxRecvChunkNum) : EnclaveBase(maxRecvChunkNum) { primaryIndex_ = new unordered_map<string, string>(); if (ENABLE_SEALING) { if (!this->LoadPrimaryIndex()) { EnclaveCommon::printf("ExtremeIndex: do not need to load the primary index.\n"); } } EnclaveCommon::printf("ExtremeIndex: Initial the extreme binning index.\n"); } /** * @brief Destroy the Ecall Extreme Index object * */ EcallExtremeIndex::~EcallExtremeIndex() { if (ENABLE_SEALING) { if (primaryIndex_->size() != 0) { this->PersistPrimaryIndex(); } } delete primaryIndex_; EnclaveCommon::printf("=================Destory ExtremeBinning Index=============\n"); #if SGX_BREAKDOWN==1 EnclaveCommon::printf("compute the segment hash time: %lf\n", computeSegmentHashTime_); EnclaveCommon::printf("find the min-hash chunk: %lf\n", findMinHashTime_); EnclaveCommon::printf("bin store query time: %lf\n", queryBinStoryTime_); EnclaveCommon::printf("bin store update time: %lf\n", updateBinStoreTime_); EnclaveCommon::printf("encryption time: %lf\n", encryptionTime_); EnclaveCommon::printf("primary index query time: %lf\n", queryPrimaryIndexTime_); EnclaveCommon::printf("primary index update time: %lf\n", updatePrimaryIndexTime_); EnclaveCommon::printf("key gen time: %lf\n", keyGenTime_); #endif EnclaveCommon::printf("logical chunk num: %lu\n", logicalChunkNum_); EnclaveCommon::printf("logical data size: %lu\n", logicalDataSize_); EnclaveCommon::printf("unique chunk num: %lu\n", uniqueChunkNum_); EnclaveCommon::printf("unique data size: %lu\n", uniqueDataSize_); EnclaveCommon::printf("compressed data size: %lu\n", compressedDataSize_); EnclaveCommon::printf("total segment num: %lu\n", totalSegmentNum_); EnclaveCommon::printf("unique segment num: %lu\n", uniqueSegmentNum_); EnclaveCommon::printf("different segment num: %lu\n", differentSegmentNum_); EnclaveCommon::printf("duplicate segment num: %lu\n", duplicateSegmentNum_); EnclaveCommon::printf("=================================================\n"); } /** * @brief process one batch * * @param buffer the input buffer * @param payloadSize the payload size * @param uploadOutSGXPtr the pointer to enclave-related var */ void EcallExtremeIndex::ProcessOneBatch(uint8_t* buffer, uint64_t payloadSize, UploadOutSGX_t* uploadOutSGXPtr) { // get the client out-enclave buffer int clientID = uploadOutSGXPtr->clientID; // get the client in-enclave buffer EnclaveClient* currentClient = EnclaveCommon::clientIndex_[clientID]; EVP_CIPHER_CTX* cipherCtx = currentClient->GetCipherCTX(); EVP_MD_CTX* mdCtx = currentClient->GetMdCTX(); uint8_t* recvBuffer = currentClient->GetRecvBuffer(); uint8_t* sessionKey = currentClient->GetSessionKey(); Segment_t* segment = currentClient->GetSegment(); // step-1: decrypt the received data with the session key cryptoObj_->SessionKeyDec(cipherCtx, buffer, payloadSize, sessionKey, recvBuffer); // get the chunk num uint64_t chunkNum = 0; memcpy(&chunkNum, recvBuffer, sizeof(uint64_t)); // start to process each chunk uint32_t tmpChunkSize = 0; string tmpHashStr; tmpHashStr.resize(CHUNK_HASH_SIZE, 0); size_t currentOffset = sizeof(uint64_t); // jump the chunk num uint32_t chunkHashVal = 0; SegmentMeta_t* currentSegmentMetaPtr; for (size_t i = 0; i < chunkNum; i++) { // step-2: compute the hash over the plaintext chunk // read the chunk size memcpy(&tmpChunkSize, recvBuffer + currentOffset, sizeof(tmpChunkSize)); currentOffset += sizeof(tmpChunkSize); cryptoObj_->GenerateHash(mdCtx, recvBuffer + currentOffset, tmpChunkSize, (uint8_t*)&tmpHashStr[0]); chunkHashVal = this->ConvertHashToValue((uint8_t*)&tmpHashStr[0]); if (this->IsEndOfSegment(chunkHashVal, tmpChunkSize, segment)) { // this is the end of the segment this->ProcessOneSegment(segment, uploadOutSGXPtr); this->ResetCurrentSegment(segment); } // add this chunk to current segment buffer memcpy(segment->insideBuffer + segment->currentSegmentSize, recvBuffer + currentOffset, tmpChunkSize); currentSegmentMetaPtr = segment->metaDataBuffer + segment->currentChunkNum; memcpy(currentSegmentMetaPtr->chunkHash, &tmpHashStr[0], CHUNK_HASH_SIZE); currentSegmentMetaPtr->chunkSize = tmpChunkSize; // update the corresponding metadata segment->currentSegmentSize += tmpChunkSize; segment->currentChunkNum++; if (chunkHashVal < segment->currentMinHashVal) { segment->currentMinHashVal = chunkHashVal; memcpy(segment->minHash, &tmpHashStr[0], CHUNK_HASH_SIZE); } // update the recv buffer offset currentOffset += tmpChunkSize; // update the statistic logicalDataSize_ += tmpChunkSize; logicalChunkNum_++; } return ; } /** * @brief start to process one batch * * @param currentSegment the pointer to current segment * @param uploadOutSGXPtr the pointer to enclave var */ void EcallExtremeIndex::ProcessOneSegment(Segment_t* currentSegment, UploadOutSGX_t* uploadOutSGXPtr) { // get the client out-enclave buffer int clientID = uploadOutSGXPtr->clientID; // get the client in-enclave buffer EnclaveClient* currentClient = EnclaveCommon::clientIndex_[clientID]; EVP_MD_CTX* mdCtx = currentClient->GetMdCTX(); RecipeBuffer_t* recipe = currentClient->GetRecipeBuffer(); // start to process the segment string tmpSegmentHash; tmpSegmentHash.resize(CHUNK_HASH_SIZE, 0); string tmpSegmentMinHash; tmpSegmentMinHash.resize(CHUNK_HASH_SIZE, 0); string binPointerStr; binPointerStr.resize(SEGMENT_ID_LENGTH, 0); unordered_map<string, string> tmpDedupIndex; // step-1: compute the hash of the segment uint32_t currentChunkNum = currentSegment->currentChunkNum; cryptoObj_->GenerateHash(mdCtx, (uint8_t*)currentSegment->metaDataBuffer, currentChunkNum * sizeof(SegmentMeta_t), (uint8_t*)&tmpSegmentHash[0]); // step-2: find the min-hash of the segment tmpSegmentMinHash.assign((char*)currentSegment->minHash, CHUNK_HASH_SIZE); // step-3: check the primary index via the min-hash of the segment auto findResult = primaryIndex_->find(tmpSegmentMinHash); PrimaryValue_t* primaryValuePtr; string primaryValueStr; primaryValueStr.resize(sizeof(PrimaryValue_t), 0); SegmentMeta_t* metaDataPtr = currentSegment->metaDataBuffer; size_t currentOffset = 0; string tmpChunkFp; tmpChunkFp.resize(CHUNK_HASH_SIZE, 0); string tmpChunkAddressStr; tmpChunkAddressStr.resize(sizeof(KeyForChunkHashDB_t), 0); if (findResult != primaryIndex_->end()) { // step-4: find this min-hash in the primary index, further compare the segment hash primaryValuePtr = (PrimaryValue_t*)&findResult->second[0]; // step-5: fetch the bin from the bin store binPointerStr.assign((char*)primaryValuePtr->binID_, SEGMENT_ID_LENGTH); if (!this->FetchBin(binPointerStr, tmpDedupIndex, uploadOutSGXPtr)) { Ocall_SGX_Exit_Error("ExtreneIndex: cannot find the bin."); } // step-6: compare this hash with current segment hash if (tmpSegmentHash.compare(string((char*)primaryValuePtr->segmentHash, CHUNK_HASH_SIZE)) != 0) { // this segment is different from the previous segment // conduct deduplication of the current segment for (size_t i = 0; i < currentChunkNum; i++) { tmpChunkFp.assign((char*)metaDataPtr->chunkHash, CHUNK_HASH_SIZE); auto tmpFindResult = tmpDedupIndex.find(tmpChunkFp); if (tmpFindResult != tmpDedupIndex.end()) { // this chunk is duplicate this->UpdateFileRecipe(tmpFindResult->second, *recipe, currentClient); } else { // this chunk is unique uniqueChunkNum_++; uniqueDataSize_ += metaDataPtr->chunkSize; // process one unique chunk this->ProcessUniqueChunk((KeyForChunkHashDB_t*)&tmpChunkAddressStr[0], currentSegment->insideBuffer + currentOffset, metaDataPtr->chunkSize, uploadOutSGXPtr, currentClient); // update the chunk to the tmp deduplication index tmpDedupIndex.insert(make_pair(tmpChunkFp, tmpChunkAddressStr)); this->UpdateFileRecipe(tmpChunkAddressStr, *recipe, currentClient); } currentOffset += metaDataPtr->chunkSize; metaDataPtr++; } // step: update the bin store if (!this->UpdateBinStore(binPointerStr, tmpDedupIndex, uploadOutSGXPtr)) { Ocall_SGX_Exit_Error("ExtremeIndex: cannot update the bin store."); } differentSegmentNum_++; } else { // this segment is same as previous segment, directly get the address from the bin store for (size_t i = 0; i < currentChunkNum; i++) { // chunk hash tmpChunkFp.assign((char*)metaDataPtr->chunkHash, CHUNK_HASH_SIZE); auto tmpFindResult = tmpDedupIndex.find(tmpChunkFp); if (tmpFindResult != tmpDedupIndex.end()) { // parse the chunk address this->UpdateFileRecipe(tmpFindResult->second, *recipe, currentClient); } else { // error Ocall_SGX_Exit_Error("ExtremeIndex: cannot find the chunk address of tmp deduplication index."); } metaDataPtr++; } // do not need to update the index bin store duplicateSegmentNum_++; } } else { // cannot find the min-hash of this segment in the primary index for (size_t i = 0; i < currentChunkNum; i++) { // chunk hash tmpChunkFp.assign((char*)metaDataPtr->chunkHash, CHUNK_HASH_SIZE); auto tmpFindResult = tmpDedupIndex.find(tmpChunkFp); if (tmpFindResult != tmpDedupIndex.end()) { // this chunk is duplicate this->UpdateFileRecipe(tmpFindResult->second, *recipe, currentClient); } else { // this chunk is unique uniqueDataSize_ += metaDataPtr->chunkSize; uniqueChunkNum_++; // process one unique chunk this->ProcessUniqueChunk((KeyForChunkHashDB_t*)&tmpChunkAddressStr[0], currentSegment->insideBuffer + currentOffset, metaDataPtr->chunkSize, uploadOutSGXPtr, currentClient); // step: add this chunk to the tmp deduplication index tmpDedupIndex.insert(make_pair(tmpChunkFp, tmpChunkAddressStr)); this->UpdateFileRecipe(tmpChunkAddressStr, *recipe, currentClient); } currentOffset += metaDataPtr->chunkSize; metaDataPtr++; } // step: update the bin store binPointerStr = storageCoreObj_->CreateUUID(SEGMENT_ID_LENGTH); primaryValuePtr = (PrimaryValue_t*)&primaryValueStr[0]; memcpy(primaryValuePtr->segmentHash, &tmpSegmentHash[0], CHUNK_HASH_SIZE); memcpy(primaryValuePtr->binID_, &binPointerStr[0], SEGMENT_ID_LENGTH); primaryIndex_->insert(make_pair(tmpSegmentMinHash, primaryValueStr)); // step: update the bin store here if (!this->UpdateBinStore(binPointerStr, tmpDedupIndex, uploadOutSGXPtr)) { Ocall_SGX_Exit_Error("ExtremeIndex: cannot update the bin store."); } uniqueSegmentNum_++; } totalSegmentNum_++; return ; } /** * @brief fetch the bin value in to the dedup index * * @param binAddress the bin address * @param tmpDedupIndex the reference to the tmp dedup index * @param uploadOutSGXPtr the pointer to the enclave var * @return true successes * @return false fails */ bool EcallExtremeIndex::FetchBin(string& binAddress, unordered_map<string, string>& tmpDedupIndex, UploadOutSGX_t* uploadOutSGXPtr) { // get the client out-enclave buffer int clientID = uploadOutSGXPtr->clientID; // get the client in-enclave buffer EnclaveClient* currentClient = EnclaveCommon::clientIndex_[clientID]; EVP_CIPHER_CTX* cipherCtx = currentClient->GetCipherCTX(); string binValue; string cipherBinValue; string tmpChunkFp; string tmpChunkAddressStr; BinValue_t* tmpBinValue; // step: query the index store tmpChunkFp.resize(CHUNK_HASH_SIZE, 0); tmpChunkAddressStr.resize(sizeof(KeyForChunkHashDB_t), 0); bool status = this->ReadIndexStore(binAddress, cipherBinValue, clientID); if (status == false) { EnclaveCommon::printf("ExtremeIndex: cannot find the bin from the bin store.\n"); return false; } // do decryption binValue.resize(cipherBinValue.size(), 0); cryptoObj_->DecryptWithKey(cipherCtx, (uint8_t*)&cipherBinValue[0], cipherBinValue.size(), EnclaveCommon::indexQueryKey_, (uint8_t*)&binValue[0]); // step: load those entries into the tmp deduplication index size_t chunkNum = binValue.length() / sizeof(BinValue_t); for (size_t i = 0; i < chunkNum; i++) { // add each chunk to the tmp deduplication index tmpBinValue = (BinValue_t*)(&binValue[0] + i * sizeof(BinValue_t)); tmpChunkFp.assign((const char*)tmpBinValue->chunkFp, CHUNK_HASH_SIZE); memcpy(&tmpChunkAddressStr[0], &tmpBinValue->address, sizeof(KeyForChunkHashDB_t)); tmpDedupIndex.insert(make_pair(tmpChunkFp, tmpChunkAddressStr)); } return true; } /** * @brief update the bin value to the store * * @param binAddress the bin address * @param tmpDedupIndex the reference to the tmp dedup index * @param uploadOutSGXPtr the pointer to the enclcave var * @return true successes * @return false fails */ bool EcallExtremeIndex::UpdateBinStore(string& binAddress, unordered_map<string, string>& tmpDedupIndex, UploadOutSGX_t* uploadOutSGXPtr) { // get the client out-enclave buffer int clientID = uploadOutSGXPtr->clientID; // get the client in-enclave buffer EnclaveClient* currentClient = EnclaveCommon::clientIndex_[clientID]; EVP_CIPHER_CTX* cipherCtx = currentClient->GetCipherCTX(); vector<BinValue_t> binValueBuffer; #if SGX_BREAKDOWN==1 Ocall_GetCurrentTime(&sTimeIndex_); #endif // update the bin store <binAddress, binValue> size_t entryNum = tmpDedupIndex.size(); BinValue_t tmpBinValue; // step: serialize the index into the bin value buffer for (auto it = tmpDedupIndex.begin(); it != tmpDedupIndex.end(); it++) { // <chunk fp, chunk address> memcpy(tmpBinValue.chunkFp, it->first.c_str(), CHUNK_HASH_SIZE); memcpy(&tmpBinValue.address, it->second.c_str(), sizeof(KeyForChunkHashDB_t)); binValueBuffer.push_back(tmpBinValue); } // step: encryption the binValue; string cipherBinValue; cipherBinValue.resize(entryNum * sizeof(BinValue_t), 0); cryptoObj_->EncryptWithKey(cipherCtx, (uint8_t*)&binValueBuffer[0], entryNum*sizeof(BinValue_t), EnclaveCommon::indexQueryKey_, (uint8_t*)&cipherBinValue[0]); // step: write the bin value buffer to the index store if (!this->UpdateIndexStore(binAddress, (const char*)&cipherBinValue[0], entryNum * sizeof(BinValue_t))) { EnclaveCommon::printf("ExtremeIndex: cannot update the bin store.\n"); return false; } #if SGX_BREAKDOWN==1 Ocall_GetCurrentTime(&eTimeIndex_); updateBinStoreTime_ += GetTimeDiffer(sTimeIndex_, eTimeIndex_); #endif return true; } /** * @brief process the tailed batch when received the end of the recipe flag * * @param buffer the input buffer * @param payloadSize the payload size * @param uploadOutSGXPtr the pointer to enclave-related var */ void EcallExtremeIndex::ProcessTailBatch(uint8_t* buffer, uint64_t payloadSize, UploadOutSGX_t* uploadOutSGXPtr) { // get the client out-enclave buffer int clientID = uploadOutSGXPtr->clientID; // get the client in-enclave buffer EnclaveClient* currentClient = EnclaveCommon::clientIndex_[clientID]; Segment_t* segment = currentClient->GetSegment(); RecipeBuffer_t* recipe = currentClient->GetRecipeBuffer(); uint8_t* masterKey = currentClient->GetMasterKey(); // check the tail segment first if (segment->currentChunkNum != 0) { this->ProcessOneSegment(segment, uploadOutSGXPtr); this->ResetCurrentSegment(segment); } if (recipe->recipeNum != 0) { uint8_t cipherRecipe[maxRecvChunkNum_ * sizeof(RecipeEntry_t)]; cryptoObj_->EncryptWithKey(currentClient->GetCipherCTX(), (uint8_t*)(recipe->recipeBuffer), recipe->recipeNum * sizeof(RecipeEntry_t), masterKey, cipherRecipe); Ocall_UpdateFileRecipe((RecipeEntry_t*)cipherRecipe, recipe->recipeNum, clientID); } // reset the recipe struct recipe->recipeNum = 0; // update the header of the file recipe this->FinalizeFileRecipeHeader(buffer, payloadSize, currentClient); return ; } /** * @brief read the primary index from the sealed data * * @return true success * @return false fail */ bool EcallExtremeIndex::LoadPrimaryIndex() { // step: compute the sealed file size size_t sealedDataSize; Ocall_InitReadSealedFile(&sealedDataSize, SEALED_PRIMAR_INDEX); if (sealedDataSize == 0) { return false; } // step: prepare the buffer uint8_t* sealedDataBuffer = (uint8_t*) malloc(sizeof(uint8_t) * sealedDataSize); EnclaveCommon::ReadFileToBuffer(sealedDataBuffer, static_cast<size_t>(sealedDataSize), SEALED_PRIMAR_INDEX); Ocall_CloseReadSealedFile(SEALED_PRIMAR_INDEX); // step: parse the buffer to the index size_t entryNum = sealedDataSize / (CHUNK_HASH_SIZE + sizeof(PrimaryValue_t)); string minHashStr; minHashStr.resize(CHUNK_HASH_SIZE, 0); string primaryValueStr; primaryValueStr.resize(sizeof(PrimaryValue_t), 0); for (size_t i = 0; i < entryNum; i++) { memcpy(&minHashStr[0], sealedDataBuffer + i * (CHUNK_HASH_SIZE + sizeof(PrimaryValue_t)), CHUNK_HASH_SIZE); memcpy(&primaryValueStr[0], sealedDataBuffer + i * (CHUNK_HASH_SIZE + sizeof(PrimaryValue_t)) + CHUNK_HASH_SIZE, sizeof(PrimaryValue_t)); primaryIndex_->insert(make_pair(minHashStr, primaryValueStr)); } free(sealedDataBuffer); return true; } /** * @brief seal the primary index to the disk * * @return true success * @return false fail */ bool EcallExtremeIndex::PersistPrimaryIndex() { // step: compute the deduplication index size uint32_t primaryIndexSize = primaryIndex_->size() * (CHUNK_HASH_SIZE + sizeof(PrimaryValue_t)); // step: prepare the buffer, serialize the index to the buffer uint8_t* tmpIndexBuffer = (uint8_t*) malloc(sizeof(uint8_t) * primaryIndexSize); size_t offset = 0; for (auto it = primaryIndex_->begin(); it != primaryIndex_->end(); it++) { memcpy(tmpIndexBuffer + offset * (CHUNK_HASH_SIZE + sizeof(PrimaryValue_t)), it->first.c_str(), CHUNK_HASH_SIZE); memcpy(tmpIndexBuffer + offset * (CHUNK_HASH_SIZE + sizeof(PrimaryValue_t)) + CHUNK_HASH_SIZE, it->second.c_str(), sizeof(PrimaryValue_t)); offset++; } // step: write the buffer to the file bool persistenceStatus; Ocall_InitWriteSealedFile(&persistenceStatus, SEALED_PRIMAR_INDEX); if (persistenceStatus == false) { Ocall_SGX_Exit_Error("ExtremeIndex: cannot init the sealed file."); } EnclaveCommon::WriteBufferToFile(tmpIndexBuffer, primaryIndexSize, SEALED_PRIMAR_INDEX); Ocall_CloseWriteSealedFile(SEALED_PRIMAR_INDEX); free(tmpIndexBuffer); return true; }
39.266038
120
0.673922
[ "object", "vector" ]
d002873313e3a459d7be500db429857e1ed77b59
324,136
cc
C++
third-party/webscalesqlclient/mysql-5.6/sql/rpl_slave.cc
hkirsman/hhvm_centos7_builds
2a1fd6de0d2d289c1575f43f10018f3bec23bb13
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
third-party/webscalesqlclient/mysql-5.6/sql/rpl_slave.cc
hkirsman/hhvm_centos7_builds
2a1fd6de0d2d289c1575f43f10018f3bec23bb13
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
third-party/webscalesqlclient/mysql-5.6/sql/rpl_slave.cc
hkirsman/hhvm_centos7_builds
2a1fd6de0d2d289c1575f43f10018f3bec23bb13
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
/* Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved. 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; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ /** @addtogroup Replication @{ @file @brief Code to run the io thread and the sql thread on the replication slave. */ #include "sql_priv.h" #include "my_global.h" #include "rpl_slave.h" #include "sql_parse.h" // execute_init_command #include "sql_table.h" // mysql_rm_table #include "rpl_mi.h" #include "rpl_rli.h" #include "rpl_filter.h" #include "rpl_info_factory.h" #include "transaction.h" #include <thr_alarm.h> #include <my_dir.h> #include <sql_common.h> #include <errmsg.h> #include <mysqld_error.h> #include <mysys_err.h> #include "rpl_handler.h" #include "rpl_info_dummy.h" #include <signal.h> #include <mysql.h> #include <myisam.h> #include "sql_base.h" // close_thread_tables #include "tztime.h" // struct Time_zone #include "log_event.h" // Rotate_log_event, // Create_file_log_event, // Format_description_log_event #include "dynamic_ids.h" #include "rpl_rli_pdb.h" #include "global_threads.h" #ifdef HAVE_REPLICATION #include "rpl_tblmap.h" #include "debug_sync.h" using std::min; using std::max; #define FLAGSTR(V,F) ((V)&(F)?#F" ":"") #define MAX_SLAVE_RETRY_PAUSE 5 /* a parameter of sql_slave_killed() to defer the killed status */ #define SLAVE_WAIT_GROUP_DONE 60 bool use_slave_mask = 0; MY_BITMAP slave_error_mask; char slave_skip_error_names[SHOW_VAR_FUNC_BUFF_SIZE]; static unsigned long stop_wait_timeout; char* slave_load_tmpdir = 0; Master_info *active_mi= 0; my_bool replicate_same_server_id; ulonglong relay_log_space_limit = 0; uint rpl_receive_buffer_size = 0; my_bool reset_seconds_behind_master = TRUE; const char *relay_log_index= 0; const char *relay_log_basename= 0; /* MTS load-ballancing parameter. Max length of one MTS Worker queue. The value also determines the size of Relay_log_info::gaq (see @c slave_start_workers()). It can be set to any value in [1, ULONG_MAX - 1] range. */ const ulong mts_slave_worker_queue_len_max= 16384; /* Statistics go to the error log every # of seconds when --log-warnings > 1 */ const long mts_online_stat_period= 60 * 2; /* MTS load-ballancing parameter. Time unit in microsecs to sleep by MTS Coordinator to avoid extra thread signalling in the case of Worker queues are close to be filled up. */ const ulong mts_coordinator_basic_nap= 5; /* MTS load-ballancing parameter. Percent of Worker queue size at which Worker is considered to become hungry. C enqueues --+ . underrun level V " +----------+-+------------------+--------------+ | empty |.|::::::::::::::::::|xxxxxxxxxxxxxx| ---> Worker dequeues +----------+-+------------------+--------------+ Like in the above diagram enqueuing to the x-d area would indicate actual underrruning by Worker. */ const ulong mts_worker_underrun_level= 10; Slave_job_item * de_queue(Slave_jobs_queue *jobs, Slave_job_item *ret); bool append_item_to_jobs(slave_job_item *job_item, Slave_worker *w, Relay_log_info *rli); /** Thread state for the SQL slave thread. */ class THD_SQL_slave : public THD { private: char *m_buffer; size_t m_buffer_size; public: /** Constructor, used to represent slave thread state. @param buffer Statically-allocated buffer. @param size Size of the passed buffer. */ THD_SQL_slave(char *buffer, size_t size) : m_buffer(buffer), m_buffer_size(size) { DBUG_ASSERT(buffer && size); memset(m_buffer, 0, m_buffer_size); } virtual ~THD_SQL_slave() { m_buffer[0]= '\0'; } void print_proc_info(const char *fmt, ...); }; /** Print an information (state) string for this slave thread. @param fmt Specifies how subsequent arguments are converted for output. @param ... Variable number of arguments. */ void THD_SQL_slave::print_proc_info(const char *fmt, ...) { va_list args; va_start(args, fmt); my_vsnprintf(m_buffer, m_buffer_size - 1, fmt, args); va_end(args); /* Set field directly, profiling is not useful in a slave thread anyway. */ proc_info= m_buffer; } /* When slave thread exits, we need to remember the temporary tables so we can re-use them on slave start. TODO: move the vars below under Master_info */ int disconnect_slave_event_count = 0, abort_slave_event_count = 0; static pthread_key(Master_info*, RPL_MASTER_INFO); /* Count binlog events by type processed by the SQL slave */ ulonglong repl_event_counts[ENUM_END_EVENT] = { 0 }; ulonglong repl_event_count_other= 0; /* Time binlog events by type processed by the SQL slave */ ulonglong repl_event_times[ENUM_END_EVENT] = { 0 }; ulonglong repl_event_time_other= 0; enum enum_slave_reconnect_actions { SLAVE_RECON_ACT_REG= 0, SLAVE_RECON_ACT_DUMP= 1, SLAVE_RECON_ACT_EVENT= 2, SLAVE_RECON_ACT_MAX }; enum enum_slave_reconnect_messages { SLAVE_RECON_MSG_WAIT= 0, SLAVE_RECON_MSG_KILLED_WAITING= 1, SLAVE_RECON_MSG_AFTER= 2, SLAVE_RECON_MSG_FAILED= 3, SLAVE_RECON_MSG_COMMAND= 4, SLAVE_RECON_MSG_KILLED_AFTER= 5, SLAVE_RECON_MSG_MAX }; static const char *reconnect_messages[SLAVE_RECON_ACT_MAX][SLAVE_RECON_MSG_MAX]= { { "Waiting to reconnect after a failed registration on master", "Slave I/O thread killed while waitnig to reconnect after a failed \ registration on master", "Reconnecting after a failed registration on master", "failed registering on master, reconnecting to try again, \ log '%s' at position %s", "COM_REGISTER_SLAVE", "Slave I/O thread killed during or after reconnect" }, { "Waiting to reconnect after a failed binlog dump request", "Slave I/O thread killed while retrying master dump", "Reconnecting after a failed binlog dump request", "failed dump request, reconnecting to try again, log '%s' at position %s", "COM_BINLOG_DUMP", "Slave I/O thread killed during or after reconnect" }, { "Waiting to reconnect after a failed master event read", "Slave I/O thread killed while waiting to reconnect after a failed read", "Reconnecting after a failed master event read", "Slave I/O thread: Failed reading log event, reconnecting to retry, \ log '%s' at position %s", "", "Slave I/O thread killed during or after a reconnect done to recover from \ failed read" } }; enum enum_slave_apply_event_and_update_pos_retval { SLAVE_APPLY_EVENT_AND_UPDATE_POS_OK= 0, SLAVE_APPLY_EVENT_AND_UPDATE_POS_APPLY_ERROR= 1, SLAVE_APPLY_EVENT_AND_UPDATE_POS_UPDATE_POS_ERROR= 2, SLAVE_APPLY_EVENT_AND_UPDATE_POS_APPEND_JOB_ERROR= 3, SLAVE_APPLY_EVENT_AND_UPDATE_POS_MAX }; static int process_io_rotate(Master_info* mi, Rotate_log_event* rev); static int process_io_create_file(Master_info* mi, Create_file_log_event* cev); static bool wait_for_relay_log_space(Relay_log_info* rli); static inline bool io_slave_killed(THD* thd,Master_info* mi); static inline bool sql_slave_killed(THD* thd,Relay_log_info* rli); static int init_slave_thread(THD* thd, SLAVE_THD_TYPE thd_type); static void print_slave_skip_errors(void); static int safe_connect(THD* thd, MYSQL* mysql, Master_info* mi); static int safe_reconnect(THD* thd, MYSQL* mysql, Master_info* mi, bool suppress_warnings); static int connect_to_master(THD* thd, MYSQL* mysql, Master_info* mi, bool reconnect, bool suppress_warnings); static int get_master_version_and_clock(MYSQL* mysql, Master_info* mi); static int get_master_uuid(MYSQL *mysql, Master_info *mi); int io_thread_init_commands(MYSQL *mysql, Master_info *mi); static Log_event* next_event(Relay_log_info* rli); static int queue_event(Master_info* mi,const char* buf,ulong event_len); static void set_stop_slave_wait_timeout(unsigned long wait_timeout); static int terminate_slave_thread(THD *thd, mysql_mutex_t *term_lock, mysql_cond_t *term_cond, volatile uint *slave_running, bool need_lock_term); static bool check_io_slave_killed(THD *thd, Master_info *mi, const char *info); int slave_worker_exec_job(Slave_worker * w, Relay_log_info *rli); static int mts_event_coord_cmp(LOG_POS_COORD *id1, LOG_POS_COORD *id2); /* Function to set the slave's max_allowed_packet based on the value of slave_max_allowed_packet. @in_param thd Thread handler for slave @in_param mysql MySQL connection handle */ static void set_slave_max_allowed_packet(THD *thd, MYSQL *mysql) { DBUG_ENTER("set_slave_max_allowed_packet"); // thd and mysql must be valid DBUG_ASSERT(thd && mysql); thd->variables.max_allowed_packet= slave_max_allowed_packet; thd->net.max_packet_size= slave_max_allowed_packet; /* Adding MAX_LOG_EVENT_HEADER_LEN to the max_packet_size on the I/O thread and the mysql->option max_allowed_packet, since a replication event can become this much larger than the corresponding packet (query) sent from client to master. */ thd->net.max_packet_size+= MAX_LOG_EVENT_HEADER; /* Skipping the setting of mysql->net.max_packet size to slave max_allowed_packet since this is done during mysql_real_connect. */ mysql->options.max_allowed_packet= slave_max_allowed_packet+MAX_LOG_EVENT_HEADER; DBUG_VOID_RETURN; } /* Find out which replications threads are running SYNOPSIS init_thread_mask() mask Return value here mi master_info for slave inverse If set, returns which threads are not running IMPLEMENTATION Get a bit mask for which threads are running so that we can later restart these threads. RETURN mask If inverse == 0, running threads If inverse == 1, stopped threads */ void init_thread_mask(int* mask, Master_info* mi, bool inverse) { bool set_io = mi->slave_running, set_sql = mi->rli->slave_running; register int tmp_mask=0; DBUG_ENTER("init_thread_mask"); if (set_io) tmp_mask |= SLAVE_IO; if (set_sql) tmp_mask |= SLAVE_SQL; if (inverse) tmp_mask^= (SLAVE_IO | SLAVE_SQL); *mask = tmp_mask; DBUG_VOID_RETURN; } /* lock_slave_threads() */ void lock_slave_threads(Master_info* mi) { DBUG_ENTER("lock_slave_threads"); //TODO: see if we can do this without dual mutex mysql_mutex_lock(&mi->run_lock); mysql_mutex_lock(&mi->rli->run_lock); DBUG_VOID_RETURN; } /* unlock_slave_threads() */ void unlock_slave_threads(Master_info* mi) { DBUG_ENTER("unlock_slave_threads"); //TODO: see if we can do this without dual mutex mysql_mutex_unlock(&mi->rli->run_lock); mysql_mutex_unlock(&mi->run_lock); DBUG_VOID_RETURN; } #ifdef HAVE_PSI_INTERFACE static PSI_thread_key key_thread_slave_io, key_thread_slave_sql, key_thread_slave_worker; static PSI_thread_info all_slave_threads[]= { { &key_thread_slave_io, "slave_io", PSI_FLAG_GLOBAL}, { &key_thread_slave_sql, "slave_sql", PSI_FLAG_GLOBAL}, { &key_thread_slave_worker, "slave_worker", PSI_FLAG_GLOBAL} }; static void init_slave_psi_keys(void) { const char* category= "sql"; int count; count= array_elements(all_slave_threads); mysql_thread_register(category, all_slave_threads, count); } #endif /* HAVE_PSI_INTERFACE */ /* Initialize slave structures */ int init_slave() { DBUG_ENTER("init_slave"); int error= 0; int thread_mask= SLAVE_SQL | SLAVE_IO; Relay_log_info* rli= NULL; #ifdef HAVE_PSI_INTERFACE init_slave_psi_keys(); #endif /* This is called when mysqld starts. Before client connections are accepted. However bootstrap may conflict with us if it does START SLAVE. So it's safer to take the lock. */ mysql_mutex_lock(&LOCK_active_mi); if (pthread_key_create(&RPL_MASTER_INFO, NULL)) DBUG_RETURN(1); if ((error= Rpl_info_factory::create_coordinators(opt_mi_repository_id, &active_mi, opt_rli_repository_id, &rli))) { sql_print_error("Failed to create or recover replication info repository."); error= 1; goto err; } /* This is the startup routine and as such we try to configure both the SLAVE_SQL and SLAVE_IO. */ if (global_init_info(active_mi, true, thread_mask)) { sql_print_error("Failed to initialize the master info structure"); error= 1; goto err; } is_slave = active_mi->host[0]; DBUG_PRINT("info", ("init group master %s %lu group relay %s %lu event %s %lu\n", rli->get_group_master_log_name(), (ulong) rli->get_group_master_log_pos(), rli->get_group_relay_log_name(), (ulong) rli->get_group_relay_log_pos(), rli->get_event_relay_log_name(), (ulong) rli->get_event_relay_log_pos())); if (active_mi->host[0] && mysql_bin_log.engine_binlog_pos != ULONGLONG_MAX && mysql_bin_log.engine_binlog_file[0] && gtid_mode > 0) { /* With less durable settins (sync_binlog !=1 and innodb_flush_log_at_trx_commit !=1), a slave with GTIDs/MTS may be inconsistent due to the two possible scenarios below 1) slave's binary log is behind innodb transaction log. 2) slave's binlary log is ahead of innodb transaction log. The slave_gtid_info transaction table consistently stores gtid information and handles scenario 1. But in case of scenario 2, even though the slave_gtid_info is consistent with innodb, slave will skip executing some transactions if it's GTID is logged in the binlog even though it is not commiited in innodb. Scenario 2 is handled by changing gtid_executed when a slave is initialized based on the binlog file and binlog position which are logged inside innodb trx log. When gtid_executed is set to an old value which is consistent with innodb, slave doesn't miss any transactions. */ mysql_mutex_t *log_lock = mysql_bin_log.get_log_lock(); mysql_mutex_lock(log_lock); global_sid_lock->wrlock(); char file_name[FN_REFLEN + 1]; mysql_bin_log.make_log_name(file_name, mysql_bin_log.engine_binlog_file); const_cast<Gtid_set *>(gtid_state->get_logged_gtids())->clear(); MYSQL_BIN_LOG::enum_read_gtids_from_binlog_status ret = mysql_bin_log.read_gtids_from_binlog(file_name, const_cast<Gtid_set *>( gtid_state->get_logged_gtids()), NULL, NULL, NULL, global_sid_map, opt_master_verify_checksum, mysql_bin_log.engine_binlog_pos); global_sid_lock->unlock(); // rotate writes the consistent gtid_executed as previous_gtid_log_event // in next binlog. This is done to avoid situations where there is a // slave crash immediately after executing some relay log events. // Those slave crashes are not safe if binlog is not rotated since the // gtid_executed set after crash recovery will be inconsistent with InnoDB. // A crash before this rotate is safe because of valid binlog file and // position values inside innodb trx header which will not be updated // until sql_thread is ready. bool check_purge; mysql_bin_log.rotate(true, &check_purge); mysql_mutex_unlock(log_lock); if (ret == MYSQL_BIN_LOG::ERROR || ret == MYSQL_BIN_LOG::TRUNCATED) { sql_print_error("Failed to read log %s up to pos %llu " "to find out crash safe gtid_executed " "Replication will not be setup due to " "possible data inconsistency with master. ", mysql_bin_log.engine_binlog_file, mysql_bin_log.engine_binlog_pos); error = 1; goto err; } } /* If server id is not set, start_slave_thread() will say it */ if (active_mi->host[0] && !opt_skip_slave_start) { /* same as in start_slave() cache the global var values into rli's members */ active_mi->rli->opt_slave_parallel_workers= opt_mts_slave_parallel_workers; active_mi->rli->checkpoint_group= opt_mts_checkpoint_group; if (start_slave_threads(true/*need_lock_slave=true*/, false/*wait_for_start=false*/, active_mi, thread_mask)) { sql_print_error("Failed to create slave threads"); error= 1; goto err; } } err: mysql_mutex_unlock(&LOCK_active_mi); if (error) sql_print_information("Check error log for additional messages. " "You will not be able to start replication until " "the issue is resolved and the server restarted."); DBUG_RETURN(error); } /** Parse the given relay log and identify the rotate event from the master. Ignore the Format description event, Previous_gtid log event and ignorable events within the relay log. When a rotate event is found check if it is a rotate that is originated from the master or not based on the server_id. If the rotate is from slave or if it is a fake rotate event ignore the event. If any other events are encountered apart from the above events generate an error. From the rotate event extract the master's binary log name and position. @param filename Relay log name which needs to be parsed. @param[OUT] master_log_file Set the master_log_file to the log file name that is extracted from rotate event. The master_log_file should contain string of len FN_REFLEN. @param[OUT] master_log_pos Set the master_log_pos to the log position extracted from rotate event. @retval FOUND_ROTATE: When rotate event is found in the relay log @retval NOT_FOUND_ROTATE: When rotate event is not found in the relay log @retval ERROR: On error */ enum enum_read_rotate_from_relay_log_status { FOUND_ROTATE, NOT_FOUND_ROTATE, ERROR }; static enum_read_rotate_from_relay_log_status read_rotate_from_relay_log(char *filename, char *master_log_file, my_off_t *master_log_pos) { DBUG_ENTER("read_rotate_from_relay_log"); /* Create a Format_description_log_event that is used to read the first event of the log. */ Format_description_log_event fd_ev(BINLOG_VERSION), *fd_ev_p= &fd_ev; DBUG_ASSERT(fd_ev.is_valid()); IO_CACHE log; const char *errmsg= NULL; File file= open_binlog_file(&log, filename, &errmsg); if (file < 0) { sql_print_error("Error during --relay-log-recovery: %s", errmsg); DBUG_RETURN(ERROR); } my_b_seek(&log, BIN_LOG_HEADER_SIZE); Log_event *ev= NULL; bool done= false; enum_read_rotate_from_relay_log_status ret= NOT_FOUND_ROTATE; while (!done && (ev= Log_event::read_log_event(&log, 0, fd_ev_p, opt_slave_sql_verify_checksum, NULL)) != NULL) { DBUG_PRINT("info", ("Read event of type %s", ev->get_type_str())); switch (ev->get_type_code()) { case FORMAT_DESCRIPTION_EVENT: if (fd_ev_p != &fd_ev) delete fd_ev_p; fd_ev_p= (Format_description_log_event *)ev; break; case ROTATE_EVENT: /* Check for rotate event from the master. Ignore the ROTATE event if it is a fake rotate event with server_id=0. */ if (ev->server_id && ev->server_id != ::server_id) { Rotate_log_event *rotate_ev= (Rotate_log_event *)ev; DBUG_ASSERT(FN_REFLEN >= rotate_ev->ident_len + 1); memcpy(master_log_file, rotate_ev->new_log_ident, rotate_ev->ident_len + 1); *master_log_pos= rotate_ev->pos; ret= FOUND_ROTATE; done= true; } break; case PREVIOUS_GTIDS_LOG_EVENT: break; case IGNORABLE_LOG_EVENT: break; default: sql_print_error("Error during --relay-log-recovery: Could not locate " "rotate event from the master."); ret= ERROR; done= true; break; } if (ev != fd_ev_p) delete ev; } if (log.error < 0) { sql_print_error("Error during --relay-log-recovery: Error reading events from relay log: %d", log.error); DBUG_RETURN(ERROR); } if (fd_ev_p != &fd_ev) { delete fd_ev_p; fd_ev_p= &fd_ev; } if (mysql_file_close(file, MYF(MY_WME))) DBUG_RETURN(ERROR); if (end_io_cache(&log)) { sql_print_error("Error during --relay-log-recovery: Error while freeing " "IO_CACHE object"); DBUG_RETURN(ERROR); } DBUG_RETURN(ret); } /** Reads relay logs one by one starting from the first relay log. Looks for the first rotate event from the master. If rotate is not found in the relay log search continues to next relay log. If rotate event from master is found then the extracted master_log_file and master_log_pos are used to set rli->group_master_log_name and rli->group_master_log_pos. If an error has occurred the error code is retuned back. @param rli Relay_log_info object to read relay log files and to set group_master_log_name and group_master_log_pos. @retval 0 On success @retval 1 On failure */ static int find_first_relay_log_with_rotate_from_master(Relay_log_info* rli) { DBUG_ENTER("find_first_relay_log_with_rotate_from_master"); int error= 0; LOG_INFO linfo; bool got_rotate_from_master= false; int pos; char master_log_file[FN_REFLEN]; my_off_t master_log_pos= 0; for (pos= rli->relay_log.find_log_pos(&linfo, NULL, true); !pos; pos= rli->relay_log.find_next_log(&linfo, true)) { switch (read_rotate_from_relay_log(linfo.log_file_name, master_log_file, &master_log_pos)) { case ERROR: error= 1; break; case FOUND_ROTATE: got_rotate_from_master= true; break; case NOT_FOUND_ROTATE: break; } if (error || got_rotate_from_master) break; } if (pos== LOG_INFO_IO) { error= 1; sql_print_error("Error during --relay-log-recovery: Could not read " "relay log index file due to an IO error."); goto err; } if (pos== LOG_INFO_EOF) { error= 1; sql_print_error("Error during --relay-log-recovery: Could not locate " "rotate event from master in relay log file."); goto err; } if (!error && got_rotate_from_master) { rli->set_group_master_log_name(master_log_file); rli->set_group_master_log_pos(master_log_pos); } err: DBUG_RETURN(error); } /* Updates the master info based on the information stored in the relay info and ignores relay logs previously retrieved by the IO thread, which thus starts fetching again based on to the master_log_pos and master_log_name. Eventually, the old relay logs will be purged by the normal purge mechanism. There can be a special case where rli->group_master_log_name and rli->group_master_log_pos are not intialized, as the sql thread was never started at all. In those cases all the existing relay logs are parsed starting from the first one and the initial rotate event that was received from the master is identified. From the rotate event master_log_name and master_log_pos are extracted and they are set to rli->group_master_log_name and rli->group_master_log_pos. In the feature, we should improve this routine in order to avoid throwing away logs that are safely stored in the disk. Note also that this recovery routine relies on the correctness of the relay-log.info and only tolerates coordinate problems in master.info. In this function, there is no need for a mutex as the caller (i.e. init_slave) already has one acquired. Specifically, the following structures are updated: 1 - mi->master_log_pos <-- rli->group_master_log_pos 2 - mi->master_log_name <-- rli->group_master_log_name 3 - It moves the relay log to the new relay log file, by rli->group_relay_log_pos <-- BIN_LOG_HEADER_SIZE; rli->event_relay_log_pos <-- BIN_LOG_HEADER_SIZE; rli->group_relay_log_name <-- rli->relay_log.get_log_fname(); rli->event_relay_log_name <-- rli->relay_log.get_log_fname(); If there is an error, it returns (1), otherwise returns (0). */ int init_recovery(Master_info* mi, const char** errmsg) { DBUG_ENTER("init_recovery"); int error= 0; Relay_log_info *rli= mi->rli; char *group_master_log_name= NULL; /** Avoid mts_recovery_groups if gtid_mode is ON. */ if (rli->recovery_parallel_workers && gtid_mode == 0) { /* This is not idempotent and a crash after this function and before the recovery is actually done may lead the system to an inconsistent state. This may happen because the gap is not persitent stored anywhere and eventually old relay log files will be removed and further calculations on the gaps will be impossible. We need to improve this. /Alfranio. */ error= mts_recovery_groups(rli); if (rli->mts_recovery_group_cnt) { error= 1; sql_print_error("--relay-log-recovery cannot be executed when the slave " "was stopped with an error or killed in MTS mode; " "consider using RESET SLAVE or restart the server " "with --relay-log-recovery = 0 followed by " "START SLAVE UNTIL SQL_AFTER_MTS_GAPS"); } } group_master_log_name= const_cast<char *>(rli->get_group_master_log_name()); if (!error) { if (!group_master_log_name[0]) { if (rli->replicate_same_server_id) { error= 1; sql_print_error("Error during --relay-log-recovery: " "replicate_same_server_id is in use and sql thread's " "positions are not initialized, hence relay log " "recovery cannot happen."); DBUG_RETURN(error); } error= find_first_relay_log_with_rotate_from_master(rli); if (error) DBUG_RETURN(error); } mi->set_master_log_pos(max<ulonglong>(BIN_LOG_HEADER_SIZE, rli->get_group_master_log_pos())); mi->set_master_log_name(rli->get_group_master_log_name()); sql_print_warning("Recovery from master pos %ld and file %s.", (ulong) mi->get_master_log_pos(), mi->get_master_log_name()); rli->set_group_relay_log_name(rli->relay_log.get_log_fname()); rli->set_event_relay_log_name(rli->relay_log.get_log_fname()); rli->set_group_relay_log_pos(BIN_LOG_HEADER_SIZE); rli->set_event_relay_log_pos(BIN_LOG_HEADER_SIZE); } /* Clear the retrieved GTID set so that events that are written partially will be fetched again. */ global_sid_lock->wrlock(); (const_cast<Gtid_set *>(rli->get_gtid_set()))->clear(); global_sid_lock->unlock(); DBUG_RETURN(error); } int global_init_info(Master_info* mi, bool ignore_if_no_info, int thread_mask) { DBUG_ENTER("init_info"); DBUG_ASSERT(mi != NULL && mi->rli != NULL); int init_error= 0; enum_return_check check_return= ERROR_CHECKING_REPOSITORY; THD *thd= current_thd; /* We need a mutex while we are changing master info parameters to keep other threads from reading bogus info */ mysql_mutex_lock(&mi->data_lock); mysql_mutex_lock(&mi->rli->data_lock); /* When info tables are used and autocommit= 0 we force a new transaction start to avoid table access deadlocks when START SLAVE is executed after RESET SLAVE. */ if (thd && thd->in_multi_stmt_transaction_mode() && (opt_mi_repository_id == INFO_REPOSITORY_TABLE || opt_rli_repository_id == INFO_REPOSITORY_TABLE)) if (trans_begin(thd)) { init_error= 1; goto end; } /* This takes care of the startup dependency between the master_info and relay_info. It initializes the master info if the SLAVE_IO thread is being started and the relay log info if either the SLAVE_SQL thread is being started or was not initialized as it is required by the SLAVE_IO thread. */ check_return= mi->check_info(); if (check_return == ERROR_CHECKING_REPOSITORY) goto end; if (!(ignore_if_no_info && check_return == REPOSITORY_DOES_NOT_EXIST)) { if ((thread_mask & SLAVE_IO) != 0 && mi->mi_init_info()) init_error= 1; } check_return= mi->rli->check_info(); if (check_return == ERROR_CHECKING_REPOSITORY) goto end; if (!(ignore_if_no_info && check_return == REPOSITORY_DOES_NOT_EXIST)) { if (((thread_mask & SLAVE_SQL) != 0 || !(mi->rli->inited)) && mi->rli->rli_init_info()) init_error= 1; } end: /* When info tables are used and autocommit= 0 we force transaction commit to avoid table access deadlocks when START SLAVE is executed after RESET SLAVE. */ if (thd && thd->in_multi_stmt_transaction_mode() && (opt_mi_repository_id == INFO_REPOSITORY_TABLE || opt_rli_repository_id == INFO_REPOSITORY_TABLE)) if (trans_commit(thd)) init_error= 1; mysql_mutex_unlock(&mi->rli->data_lock); mysql_mutex_unlock(&mi->data_lock); DBUG_RETURN(check_return == ERROR_CHECKING_REPOSITORY || init_error); } void end_info(Master_info* mi) { DBUG_ENTER("end_info"); DBUG_ASSERT(mi != NULL && mi->rli != NULL); /* The previous implementation was not acquiring locks. We do the same here. However, this is quite strange. */ mi->end_info(); mi->rli->end_info(); DBUG_VOID_RETURN; } int remove_info(Master_info* mi) { int error= 1; DBUG_ENTER("remove_info"); DBUG_ASSERT(mi != NULL && mi->rli != NULL); /* The previous implementation was not acquiring locks. We do the same here. However, this is quite strange. */ /* Reset errors (the idea is that we forget about the old master). */ mi->clear_error(); mi->rli->clear_error(); mi->rli->clear_until_condition(); mi->rli->clear_sql_delay(); mi->end_info(); mi->rli->end_info(); if (mi->remove_info() || Rpl_info_factory::reset_workers(mi->rli) || Rpl_info_factory::reset_gtid_infos(mi->rli) || mi->rli->remove_info()) goto err; error= 0; err: DBUG_RETURN(error); } int flush_master_info(Master_info* mi, bool force) { DBUG_ENTER("flush_master_info"); DBUG_ASSERT(mi != NULL && mi->rli != NULL); /* The previous implementation was not acquiring locks. We do the same here. However, this is quite strange. */ /* With the appropriate recovery process, we will not need to flush the content of the current log. For now, we flush the relay log BEFORE the master.info file, because if we crash, we will get a duplicate event in the relay log at restart. If we change the order, there might be missing events. If we don't do this and the slave server dies when the relay log has some parts (its last kilobytes) in memory only, with, say, from master's position 100 to 150 in memory only (not on disk), and with position 150 in master.info, there will be missing information. When the slave restarts, the I/O thread will fetch binlogs from 150, so in the relay log we will have "[0, 100] U [150, infinity[" and nobody will notice it, so the SQL thread will jump from 100 to 150, and replication will silently break. */ mysql_mutex_t *log_lock= mi->rli->relay_log.get_log_lock(); mysql_mutex_lock(log_lock); int err= (mi->rli->flush_current_log() || mi->flush_info(force)); mysql_mutex_unlock(log_lock); DBUG_RETURN (err); } /** Convert slave skip errors bitmap into a printable string. */ static void print_slave_skip_errors(void) { /* To be safe, we want 10 characters of room in the buffer for a number plus terminators. Also, we need some space for constant strings. 10 characters must be sufficient for a number plus {',' | '...'} plus a NUL terminator. That is a max 6 digit number. */ const size_t MIN_ROOM= 10; DBUG_ENTER("print_slave_skip_errors"); DBUG_ASSERT(sizeof(slave_skip_error_names) > MIN_ROOM); DBUG_ASSERT(MAX_SLAVE_ERROR <= 999999); // 6 digits if (!use_slave_mask || bitmap_is_clear_all(&slave_error_mask)) { /* purecov: begin tested */ memcpy(slave_skip_error_names, STRING_WITH_LEN("OFF")); /* purecov: end */ } else if (bitmap_is_set_all(&slave_error_mask)) { /* purecov: begin tested */ memcpy(slave_skip_error_names, STRING_WITH_LEN("ALL")); /* purecov: end */ } else { char *buff= slave_skip_error_names; char *bend= buff + sizeof(slave_skip_error_names); int errnum; for (errnum= 0; errnum < MAX_SLAVE_ERROR; errnum++) { if (bitmap_is_set(&slave_error_mask, errnum)) { if (buff + MIN_ROOM >= bend) break; /* purecov: tested */ buff= int10_to_str(errnum, buff, 10); *buff++= ','; } } if (buff != slave_skip_error_names) buff--; // Remove last ',' if (errnum < MAX_SLAVE_ERROR) { /* Couldn't show all errors */ buff= strmov(buff, "..."); /* purecov: tested */ } *buff=0; } DBUG_PRINT("init", ("error_names: '%s'", slave_skip_error_names)); DBUG_VOID_RETURN; } static void set_stop_slave_wait_timeout(unsigned long wait_timeout) { stop_wait_timeout = wait_timeout; } /** Change arg to the string with the nice, human-readable skip error values. @param slave_skip_errors_ptr The pointer to be changed */ void set_slave_skip_errors(char** slave_skip_errors_ptr) { DBUG_ENTER("set_slave_skip_errors"); print_slave_skip_errors(); *slave_skip_errors_ptr= slave_skip_error_names; DBUG_VOID_RETURN; } /** Init function to set up array for errors that should be skipped for slave */ static void init_slave_skip_errors() { DBUG_ENTER("init_slave_skip_errors"); DBUG_ASSERT(!use_slave_mask); // not already initialized if (bitmap_init(&slave_error_mask,0,MAX_SLAVE_ERROR,0)) { fprintf(stderr, "Badly out of memory, please check your system status\n"); exit(1); } use_slave_mask = 1; DBUG_VOID_RETURN; } static void add_slave_skip_errors(const uint* errors, uint n_errors) { DBUG_ENTER("add_slave_skip_errors"); DBUG_ASSERT(errors); DBUG_ASSERT(use_slave_mask); for (uint i = 0; i < n_errors; i++) { const uint err_code = errors[i]; if (err_code < MAX_SLAVE_ERROR) bitmap_set_bit(&slave_error_mask, err_code); } DBUG_VOID_RETURN; } /* Add errors that should be skipped for slave SYNOPSIS add_slave_skip_errors() arg List of errors numbers to be added to skip, separated with ',' NOTES Called from get_options() in mysqld.cc on start-up */ void add_slave_skip_errors(const char* arg) { const char *p= NULL; /* ALL is only valid when nothing else is provided. */ const uchar SKIP_ALL[]= "all"; size_t SIZE_SKIP_ALL= strlen((const char *) SKIP_ALL) + 1; /* IGNORE_DDL_ERRORS can be combined with other parameters but must be the first one provided. */ const uchar SKIP_DDL_ERRORS[]= "ddl_exist_errors"; size_t SIZE_SKIP_DDL_ERRORS= strlen((const char *) SKIP_DDL_ERRORS); DBUG_ENTER("add_slave_skip_errors"); // initialize mask if not done yet if (!use_slave_mask) init_slave_skip_errors(); for (; my_isspace(system_charset_info,*arg); ++arg) /* empty */; if (!my_strnncoll(system_charset_info, (uchar*)arg, SIZE_SKIP_ALL, SKIP_ALL, SIZE_SKIP_ALL)) { bitmap_set_all(&slave_error_mask); DBUG_VOID_RETURN; } if (!my_strnncoll(system_charset_info, (uchar*)arg, SIZE_SKIP_DDL_ERRORS, SKIP_DDL_ERRORS, SIZE_SKIP_DDL_ERRORS)) { // DDL errors to be skipped for relaxed 'exist' handling const uint ddl_errors[] = { // error codes with create/add <schema object> ER_DB_CREATE_EXISTS, ER_TABLE_EXISTS_ERROR, ER_DUP_KEYNAME, ER_MULTIPLE_PRI_KEY, // error codes with change/rename <schema object> ER_BAD_FIELD_ERROR, ER_NO_SUCH_TABLE, ER_DUP_FIELDNAME, // error codes with drop <schema object> ER_DB_DROP_EXISTS, ER_BAD_TABLE_ERROR, ER_CANT_DROP_FIELD_OR_KEY }; add_slave_skip_errors(ddl_errors, sizeof(ddl_errors)/sizeof(ddl_errors[0])); /* After processing the SKIP_DDL_ERRORS, the pointer is increased to the position after the comma. */ if (strlen(arg) > SIZE_SKIP_DDL_ERRORS + 1) arg+= SIZE_SKIP_DDL_ERRORS + 1; } for (p= arg ; *p; ) { long err_code; if (!(p= str2int(p, 10, 0, LONG_MAX, &err_code))) break; if (err_code < MAX_SLAVE_ERROR) bitmap_set_bit(&slave_error_mask,(uint)err_code); while (!my_isdigit(system_charset_info,*p) && *p) p++; } DBUG_VOID_RETURN; } static void set_thd_in_use_temporary_tables(Relay_log_info *rli) { TABLE *table; for (table= rli->save_temporary_tables ; table ; table= table->next) { table->in_use= rli->info_thd; if (table->file != NULL) { /* Since we are stealing opened temporary tables from one thread to another, we need to let the performance schema know that, for aggregates per thread to work properly. */ table->file->unbind_psi(); table->file->rebind_psi(); } } } int terminate_slave_threads(Master_info* mi,int thread_mask,bool need_lock_term) { DBUG_ENTER("terminate_slave_threads"); if (!mi->inited) DBUG_RETURN(0); /* successfully do nothing */ int error,force_all = (thread_mask & SLAVE_FORCE_ALL); mysql_mutex_t *sql_lock = &mi->rli->run_lock, *io_lock = &mi->run_lock; mysql_mutex_t *log_lock= mi->rli->relay_log.get_log_lock(); set_stop_slave_wait_timeout(rpl_stop_slave_timeout); if (thread_mask & (SLAVE_SQL|SLAVE_FORCE_ALL)) { DBUG_PRINT("info",("Terminating SQL thread")); mi->rli->abort_slave= 1; if ((error=terminate_slave_thread(mi->rli->info_thd, sql_lock, &mi->rli->stop_cond, &mi->rli->slave_running, need_lock_term)) && !force_all) { if (error == 1) { DBUG_RETURN(ER_STOP_SLAVE_SQL_THREAD_TIMEOUT); } DBUG_RETURN(error); } mysql_mutex_lock(log_lock); DBUG_PRINT("info",("Flushing relay-log info file.")); if (current_thd) THD_STAGE_INFO(current_thd, stage_flushing_relay_log_info_file); /* Flushes the relay log info regardles of the sync_relay_log_info option. */ if (mi->rli->flush_info(TRUE)) { mysql_mutex_unlock(log_lock); DBUG_RETURN(ER_ERROR_DURING_FLUSH_LOGS); } mysql_mutex_unlock(log_lock); } if (thread_mask & (SLAVE_IO|SLAVE_FORCE_ALL)) { DBUG_PRINT("info",("Terminating IO thread")); mi->abort_slave=1; if ((error=terminate_slave_thread(mi->info_thd,io_lock, &mi->stop_cond, &mi->slave_running, need_lock_term)) && !force_all) { if (error == 1) { DBUG_RETURN(ER_STOP_SLAVE_IO_THREAD_TIMEOUT); } DBUG_RETURN(error); } mysql_mutex_lock(log_lock); DBUG_PRINT("info",("Flushing relay log and master info repository.")); if (current_thd) THD_STAGE_INFO(current_thd, stage_flushing_relay_log_and_master_info_repository); /* Flushes the master info regardles of the sync_master_info option. */ if (mi->flush_info(TRUE)) { mysql_mutex_unlock(log_lock); DBUG_RETURN(ER_ERROR_DURING_FLUSH_LOGS); } /* Flushes the relay log regardles of the sync_relay_log option. */ if (mi->rli->relay_log.is_open() && mi->rli->relay_log.flush_and_sync(false, true)) { mysql_mutex_unlock(log_lock); DBUG_RETURN(ER_ERROR_DURING_FLUSH_LOGS); } mysql_mutex_unlock(log_lock); } DBUG_RETURN(0); } /** Wait for a slave thread to terminate. This function is called after requesting the thread to terminate (by setting @c abort_slave member of @c Relay_log_info or @c Master_info structure to 1). Termination of the thread is controlled with the the predicate <code>*slave_running</code>. Function will acquire @c term_lock before waiting on the condition unless @c need_lock_term is false in which case the mutex should be owned by the caller of this function and will remain acquired after return from the function. @param term_lock Associated lock to use when waiting for @c term_cond @param term_cond Condition that is signalled when the thread has terminated @param slave_running Pointer to predicate to check for slave thread termination @param need_lock_term If @c false the lock will not be acquired before waiting on the condition. In this case, it is assumed that the calling function acquires the lock before calling this function. @retval 0 All OK, 1 on "STOP SLAVE" command timeout, ER_SLAVE_NOT_RUNNING otherwise. @note If the executing thread has to acquire term_lock (need_lock_term is true, the negative running status does not represent any issue therefore no error is reported. */ static int terminate_slave_thread(THD *thd, mysql_mutex_t *term_lock, mysql_cond_t *term_cond, volatile uint *slave_running, bool need_lock_term) { DBUG_ENTER("terminate_slave_thread"); if (need_lock_term) { mysql_mutex_lock(term_lock); } else { mysql_mutex_assert_owner(term_lock); } if (!*slave_running) { if (need_lock_term) { /* if run_lock (term_lock) is acquired locally then either slave_running status is fine */ mysql_mutex_unlock(term_lock); DBUG_RETURN(0); } else { DBUG_RETURN(ER_SLAVE_NOT_RUNNING); } } DBUG_ASSERT(thd != 0); THD_CHECK_SENTRY(thd); /* Is is critical to test if the slave is running. Otherwise, we might be referening freed memory trying to kick it */ while (*slave_running) // Should always be true { int error __attribute__((unused)); DBUG_PRINT("loop", ("killing slave thread")); mysql_mutex_lock(&thd->LOCK_thd_data); #ifndef DONT_USE_THR_ALARM /* Error codes from pthread_kill are: EINVAL: invalid signal number (can't happen) ESRCH: thread already killed (can happen, should be ignored) */ int err __attribute__((unused))= pthread_kill(thd->real_id, thr_client_alarm); DBUG_ASSERT(err != EINVAL); #endif thd->awake(THD::NOT_KILLED); mysql_mutex_unlock(&thd->LOCK_thd_data); /* There is a small chance that slave thread might miss the first alarm. To protect againts it, resend the signal until it reacts */ struct timespec abstime; set_timespec(abstime,2); error= mysql_cond_timedwait(term_cond, term_lock, &abstime); if (stop_wait_timeout >= 2) stop_wait_timeout= stop_wait_timeout - 2; else if (*slave_running) { if (need_lock_term) mysql_mutex_unlock(term_lock); DBUG_RETURN (1); } DBUG_ASSERT(error == ETIMEDOUT || error == 0); } DBUG_ASSERT(*slave_running == 0); if (need_lock_term) mysql_mutex_unlock(term_lock); DBUG_RETURN(0); } int start_slave_thread( #ifdef HAVE_PSI_INTERFACE PSI_thread_key thread_key, #endif pthread_handler h_func, mysql_mutex_t *start_lock, mysql_mutex_t *cond_lock, mysql_cond_t *start_cond, volatile uint *slave_running, volatile ulong *slave_run_id, Master_info* mi) { pthread_t th; ulong start_id; int error; DBUG_ENTER("start_slave_thread"); if (start_lock) mysql_mutex_lock(start_lock); if (!server_id) { if (start_cond) mysql_cond_broadcast(start_cond); if (start_lock) mysql_mutex_unlock(start_lock); sql_print_error("Server id not set, will not start slave"); DBUG_RETURN(ER_BAD_SLAVE); } if (*slave_running) { if (start_cond) mysql_cond_broadcast(start_cond); if (start_lock) mysql_mutex_unlock(start_lock); DBUG_RETURN(ER_SLAVE_MUST_STOP); } start_id= *slave_run_id; DBUG_PRINT("info",("Creating new slave thread")); if ((error= mysql_thread_create(thread_key, &th, &connection_attrib, h_func, (void*)mi))) { sql_print_error("Can't create slave thread (errno= %d).", error); if (start_lock) mysql_mutex_unlock(start_lock); DBUG_RETURN(ER_SLAVE_THREAD); } if (start_cond && cond_lock) // caller has cond_lock { THD* thd = current_thd; while (start_id == *slave_run_id && thd != NULL) { DBUG_PRINT("sleep",("Waiting for slave thread to start")); PSI_stage_info saved_stage= {0, "", 0}; thd->ENTER_COND(start_cond, cond_lock, & stage_waiting_for_slave_thread_to_start, & saved_stage); /* It is not sufficient to test this at loop bottom. We must test it after registering the mutex in enter_cond(). If the kill happens after testing of thd->killed and before the mutex is registered, we could otherwise go waiting though thd->killed is set. */ if (!thd->killed) mysql_cond_wait(start_cond, cond_lock); thd->EXIT_COND(& saved_stage); mysql_mutex_lock(cond_lock); // re-acquire it as exit_cond() released if (thd->killed) { if (start_lock) mysql_mutex_unlock(start_lock); DBUG_RETURN(thd->killed_errno()); } } } if (start_lock) mysql_mutex_unlock(start_lock); DBUG_RETURN(0); } /* start_slave_threads() NOTES SLAVE_FORCE_ALL is not implemented here on purpose since it does not make sense to do that for starting a slave--we always care if it actually started the threads that were not previously running */ int start_slave_threads(bool need_lock_slave, bool wait_for_start, Master_info* mi, int thread_mask) { mysql_mutex_t *lock_io=0, *lock_sql=0, *lock_cond_io=0, *lock_cond_sql=0; mysql_cond_t* cond_io=0, *cond_sql=0; int error=0; DBUG_ENTER("start_slave_threads"); DBUG_EXECUTE_IF("uninitialized_master-info_structure", mi->inited= FALSE;); if (!mi->inited || !mi->rli->inited) { error= !mi->inited ? ER_SLAVE_MI_INIT_REPOSITORY : ER_SLAVE_RLI_INIT_REPOSITORY; Rpl_info *info= (!mi->inited ? mi : static_cast<Rpl_info *>(mi->rli)); const char* prefix= current_thd ? ER(error) : ER_DEFAULT(error); info->report(ERROR_LEVEL, error, prefix, NULL); DBUG_RETURN(error); } if (need_lock_slave) { lock_io = &mi->run_lock; lock_sql = &mi->rli->run_lock; } if (wait_for_start) { cond_io = &mi->start_cond; cond_sql = &mi->rli->start_cond; lock_cond_io = &mi->run_lock; lock_cond_sql = &mi->rli->run_lock; } if (thread_mask & SLAVE_IO) error= start_slave_thread( #ifdef HAVE_PSI_INTERFACE key_thread_slave_io, #endif handle_slave_io, lock_io, lock_cond_io, cond_io, &mi->slave_running, &mi->slave_run_id, mi); if (!error && (thread_mask & SLAVE_SQL)) { /* MTS-recovery gaps gathering is placed onto common execution path for either START-SLAVE and --skip-start-slave= 0 */ if (mi->rli->recovery_parallel_workers != 0 && gtid_mode == 0) error= mts_recovery_groups(mi->rli); if (!error) error= start_slave_thread( #ifdef HAVE_PSI_INTERFACE key_thread_slave_sql, #endif handle_slave_sql, lock_sql, lock_cond_sql, cond_sql, &mi->rli->slave_running, &mi->rli->slave_run_id, mi); if (error) terminate_slave_threads(mi, thread_mask & SLAVE_IO, need_lock_slave); } DBUG_RETURN(error); } /* Release slave threads at time of executing shutdown. SYNOPSIS end_slave() */ void end_slave() { DBUG_ENTER("end_slave"); /* This is called when the server terminates, in close_connections(). It terminates slave threads. However, some CHANGE MASTER etc may still be running presently. If a START SLAVE was in progress, the mutex lock below will make us wait until slave threads have started, and START SLAVE returns, then we terminate them here. */ mysql_mutex_lock(&LOCK_active_mi); if (active_mi) { /* TODO: replace the line below with list_walk(&master_list, (list_walk_action)end_slave_on_walk,0); once multi-master code is ready. */ terminate_slave_threads(active_mi,SLAVE_FORCE_ALL); } mysql_mutex_unlock(&LOCK_active_mi); DBUG_VOID_RETURN; } /** Free all resources used by slave threads at time of executing shutdown. The routine must be called after all possible users of @c active_mi have left. SYNOPSIS close_active_mi() */ void close_active_mi() { mysql_mutex_lock(&LOCK_active_mi); if (active_mi) { end_info(active_mi); if (active_mi->rli) delete active_mi->rli; delete active_mi; active_mi= 0; } mysql_mutex_unlock(&LOCK_active_mi); } static bool io_slave_killed(THD* thd, Master_info* mi) { DBUG_ENTER("io_slave_killed"); DBUG_ASSERT(mi->info_thd == thd); DBUG_ASSERT(mi->slave_running); // tracking buffer overrun DBUG_RETURN(mi->abort_slave || abort_loop || thd->killed); } /** The function analyzes a possible killed status and makes a decision whether to accept it or not. Normally upon accepting the sql thread goes to shutdown. In the event of deferring decision @rli->last_event_start_time waiting timer is set to force the killed status be accepted upon its expiration. Notice Multi-Threaded-Slave behaves similarly in that when it's being stopped and the current group of assigned events has not yet scheduled completely, Coordinator defers to accept to leave its read-distribute state. The above timeout ensures waiting won't last endlessly, and in such case an error is reported. @param thd pointer to a THD instance @param rli pointer to Relay_log_info instance @return TRUE the killed status is recognized, FALSE a possible killed status is deferred. */ static bool sql_slave_killed(THD* thd, Relay_log_info* rli) { bool ret= FALSE; bool is_parallel_warn= FALSE; DBUG_ENTER("sql_slave_killed"); DBUG_ASSERT(rli->info_thd == thd); DBUG_ASSERT(rli->slave_running == 1); if (abort_loop || thd->killed || rli->abort_slave) { is_parallel_warn= (rli->is_parallel_exec() && (rli->is_mts_in_group() || thd->killed)); /* Slave can execute stop being in one of two MTS or Single-Threaded mode. The modes define different criteria to accept the stop. In particular that relates to the concept of groupping. Killed Coordinator thread expects the worst so it warns on possible consistency issue. */ if (is_parallel_warn || (!rli->is_parallel_exec() && thd->transaction.all.cannot_safely_rollback() && rli->is_in_group())) { char msg_stopped[]= "... Slave SQL Thread stopped with incomplete event group " "having non-transactional changes. " "If the group consists solely of row-based events, you can try " "to restart the slave with --slave-exec-mode=IDEMPOTENT, which " "ignores duplicate key, key not found, and similar errors (see " "documentation for details)."; char msg_stopped_mts[]= "... The slave coordinator and worker threads are stopped, possibly " "leaving data in inconsistent state. A restart should " "restore consistency automatically, although using non-transactional " "storage for data or info tables or DDL queries could lead to problems. " "In such cases you have to examine your data (see documentation for " "details)."; ret= TRUE; if (rli->abort_slave) { DBUG_PRINT("info", ("Request to stop slave SQL Thread received while " "applying an MTS group or a group that " "has non-transactional " "changes; waiting for completion of the group ... ")); /* Slave sql thread shutdown in face of unfinished group modified Non-trans table is handled via a timer. The slave may eventually give out to complete the current group and in that case there might be issues at consequent slave restart, see the error message. WL#2975 offers a robust solution requiring to store the last exectuted event's coordinates along with the group's coordianates instead of waiting with @c last_event_start_time the timer. */ if (rli->last_event_start_time == 0) rli->last_event_start_time= my_time(0); ret= difftime(my_time(0), rli->last_event_start_time) <= SLAVE_WAIT_GROUP_DONE ? FALSE : TRUE; DBUG_EXECUTE_IF("stop_slave_middle_group", DBUG_EXECUTE_IF("incomplete_group_in_relay_log", ret= TRUE;);); // time is over if (!ret && !rli->reported_unsafe_warning) { rli->report(WARNING_LEVEL, 0, !is_parallel_warn ? "Request to stop slave SQL Thread received while " "applying a group that has non-transactional " "changes; waiting for completion of the group ... " : "Coordinator thread of multi-threaded slave is being " "stopped in the middle of assigning a group of events; " "deferring to exit until the group completion ... "); rli->reported_unsafe_warning= true; } } if (ret) { if (is_parallel_warn) rli->report(!rli->is_error() ? ERROR_LEVEL : WARNING_LEVEL, // an error was reported by Worker ER_MTS_INCONSISTENT_DATA, ER(ER_MTS_INCONSISTENT_DATA), msg_stopped_mts); else rli->report(ERROR_LEVEL, ER_SLAVE_FATAL_ERROR, ER(ER_SLAVE_FATAL_ERROR), msg_stopped); } } else { ret= TRUE; } } if (ret) { rli->last_event_start_time= 0; if (rli->mts_group_status == Relay_log_info::MTS_IN_GROUP) { rli->mts_group_status= Relay_log_info::MTS_KILLED_GROUP; } } DBUG_RETURN(ret); } /* skip_load_data_infile() NOTES This is used to tell a 3.23 master to break send_file() */ void skip_load_data_infile(NET *net) { DBUG_ENTER("skip_load_data_infile"); (void)net_request_file(net, "/dev/null"); (void)my_net_read(net); // discard response (void)net_write_command(net, 0, (uchar*) "", 0, (uchar*) "", 0); // ok DBUG_VOID_RETURN; } bool net_request_file(NET* net, const char* fname) { DBUG_ENTER("net_request_file"); DBUG_RETURN(net_write_command(net, 251, (uchar*) fname, strlen(fname), (uchar*) "", 0)); } /* From other comments and tests in code, it looks like sometimes Query_log_event and Load_log_event can have db == 0 (see rewrite_db() above for example) (cases where this happens are unclear; it may be when the master is 3.23). */ const char *print_slave_db_safe(const char* db) { DBUG_ENTER("*print_slave_db_safe"); DBUG_RETURN((db ? db : "")); } /* Check if the error is caused by network. @param[in] errorno Number of the error. RETURNS: TRUE network error FALSE not network error */ bool is_network_error(uint errorno) { if (errorno == CR_CONNECTION_ERROR || errorno == CR_CONN_HOST_ERROR || errorno == CR_SERVER_GONE_ERROR || errorno == CR_SERVER_LOST || errorno == ER_CON_COUNT_ERROR || errorno == ER_SERVER_SHUTDOWN || errorno == ER_NET_READ_INTERRUPTED) return TRUE; return FALSE; } /** Execute an initialization query for the IO thread. If there is an error, then this function calls mysql_free_result; otherwise the MYSQL object holds the result after this call. If there is an error other than allowed_error, then this function prints a message and returns -1. @param mysql MYSQL object. @param query Query string. @param allowed_error Allowed error code, or 0 if no errors are allowed. @param[out] master_res If this is not NULL and there is no error, then mysql_store_result() will be called and the result stored in this pointer. @param[out] master_row If this is not NULL and there is no error, then mysql_fetch_row() will be called and the result stored in this pointer. @retval COMMAND_STATUS_OK No error. @retval COMMAND_STATUS_ALLOWED_ERROR There was an error and the error code was 'allowed_error'. @retval COMMAND_STATUS_ERROR There was an error and the error code was not 'allowed_error'. */ enum enum_command_status { COMMAND_STATUS_OK, COMMAND_STATUS_ERROR, COMMAND_STATUS_ALLOWED_ERROR }; static enum_command_status io_thread_init_command(Master_info *mi, const char *query, int allowed_error, MYSQL_RES **master_res= NULL, MYSQL_ROW *master_row= NULL) { DBUG_ENTER("io_thread_init_command"); DBUG_PRINT("info", ("IO thread initialization command: '%s'", query)); MYSQL *mysql= mi->mysql; int ret= mysql_real_query(mysql, query, strlen(query)); if (io_slave_killed(mi->info_thd, mi)) { sql_print_information("The slave IO thread was killed while executing " "initialization query '%s'", query); mysql_free_result(mysql_store_result(mysql)); DBUG_RETURN(COMMAND_STATUS_ERROR); } if (ret != 0) { int err= mysql_errno(mysql); mysql_free_result(mysql_store_result(mysql)); if (!err || err != allowed_error) { mi->report(is_network_error(err) ? WARNING_LEVEL : ERROR_LEVEL, err, "The slave IO thread stops because the initialization query " "'%s' failed with error '%s'.", query, mysql_error(mysql)); DBUG_RETURN(COMMAND_STATUS_ERROR); } DBUG_RETURN(COMMAND_STATUS_ALLOWED_ERROR); } if (master_res != NULL) { if ((*master_res= mysql_store_result(mysql)) == NULL) { mi->report(WARNING_LEVEL, mysql_errno(mysql), "The slave IO thread stops because the initialization query " "'%s' did not return any result.", query); DBUG_RETURN(COMMAND_STATUS_ERROR); } if (master_row != NULL) { if ((*master_row= mysql_fetch_row(*master_res)) == NULL) { mysql_free_result(*master_res); mi->report(WARNING_LEVEL, mysql_errno(mysql), "The slave IO thread stops because the initialization query " "'%s' did not return any row.", query); DBUG_RETURN(COMMAND_STATUS_ERROR); } } } else DBUG_ASSERT(master_row == NULL); DBUG_RETURN(COMMAND_STATUS_OK); } /** Set user variables after connecting to the master. @param mysql MYSQL to request uuid from master. @param mi Master_info to set master_uuid @return 0: Success, 1: Fatal error, 2: Network error. */ int io_thread_init_commands(MYSQL *mysql, Master_info *mi) { char query[256]; int ret= 0; sprintf(query, "SET @slave_uuid= '%s'", server_uuid); if (mysql_real_query(mysql, query, strlen(query)) && !check_io_slave_killed(mi->info_thd, mi, NULL)) goto err; mysql_free_result(mysql_store_result(mysql)); return ret; err: if (mysql_errno(mysql) && is_network_error(mysql_errno(mysql))) { mi->report(WARNING_LEVEL, mysql_errno(mysql), "The initialization command '%s' failed with the following" " error: '%s'.", query, mysql_error(mysql)); ret= 2; } else { char errmsg[512]; const char *errmsg_fmt= "The slave I/O thread stops because a fatal error is encountered " "when it tries to send query to master(query: %s)."; sprintf(errmsg, errmsg_fmt, query); mi->report(ERROR_LEVEL, ER_SLAVE_FATAL_ERROR, ER(ER_SLAVE_FATAL_ERROR), errmsg); ret= 1; } mysql_free_result(mysql_store_result(mysql)); return ret; } /** Get master's uuid on connecting. @param mysql MYSQL to request uuid from master. @param mi Master_info to set master_uuid @return 0: Success, 1: Fatal error, 2: Network error. */ static int get_master_uuid(MYSQL *mysql, Master_info *mi) { const char *errmsg; MYSQL_RES *master_res= NULL; MYSQL_ROW master_row= NULL; int ret= 0; DBUG_EXECUTE_IF("dbug.before_get_MASTER_UUID", { const char act[]= "now wait_for signal.get_master_uuid"; DBUG_ASSERT(opt_debug_sync_timeout > 0); DBUG_ASSERT(!debug_sync_set_action(current_thd, STRING_WITH_LEN(act))); };); DBUG_EXECUTE_IF("dbug.simulate_busy_io", { const char act[]= "now signal Reached wait_for signal.got_stop_slave"; DBUG_ASSERT(opt_debug_sync_timeout > 0); DBUG_ASSERT(!debug_sync_set_action(current_thd, STRING_WITH_LEN(act))); };); if (!mysql_real_query(mysql, STRING_WITH_LEN("SHOW VARIABLES LIKE 'SERVER_UUID'")) && (master_res= mysql_store_result(mysql)) && (master_row= mysql_fetch_row(master_res))) { if (!strcmp(::server_uuid, master_row[1]) && !mi->rli->replicate_same_server_id) { errmsg= "The slave I/O thread stops because master and slave have equal " "MySQL server UUIDs; these UUIDs must be different for " "replication to work."; mi->report(ERROR_LEVEL, ER_SLAVE_FATAL_ERROR, ER(ER_SLAVE_FATAL_ERROR), errmsg); // Fatal error ret= 1; } else { if (mi->master_uuid[0] != 0 && strcmp(mi->master_uuid, master_row[1])) sql_print_warning("The master's UUID has changed, although this should" " not happen unless you have changed it manually." " The old UUID was %s.", mi->master_uuid); strncpy(mi->master_uuid, master_row[1], UUID_LENGTH); mi->master_uuid[UUID_LENGTH]= 0; } } else if (mysql_errno(mysql)) { if (is_network_error(mysql_errno(mysql))) { mi->report(WARNING_LEVEL, mysql_errno(mysql), "Get master SERVER_UUID failed with error: %s", mysql_error(mysql)); ret= 2; } else { /* Fatal error */ errmsg= "The slave I/O thread stops because a fatal error is encountered " "when it tries to get the value of SERVER_UUID variable from master."; mi->report(ERROR_LEVEL, ER_SLAVE_FATAL_ERROR, ER(ER_SLAVE_FATAL_ERROR), errmsg); ret= 1; } } else if (!master_row && master_res) { mi->report(WARNING_LEVEL, ER_UNKNOWN_SYSTEM_VARIABLE, "Unknown system variable 'SERVER_UUID' on master. " "A probable cause is that the variable is not supported on the " "master (version: %s), even though it is on the slave (version: %s)", mysql->server_version, server_version); } if (master_res) mysql_free_result(master_res); return ret; } /* Note that we rely on the master's version (3.23, 4.0.14 etc) instead of relying on the binlog's version. This is not perfect: imagine an upgrade of the master without waiting that all slaves are in sync with the master; then a slave could be fooled about the binlog's format. This is what happens when people upgrade a 3.23 master to 4.0 without doing RESET MASTER: 4.0 slaves are fooled. So we do this only to distinguish between 3.23 and more recent masters (it's too late to change things for 3.23). RETURNS 0 ok 1 error 2 transient network problem, the caller should try to reconnect */ static int get_master_version_and_clock(MYSQL* mysql, Master_info* mi) { char err_buff[MAX_SLAVE_ERRMSG]; const char* errmsg= 0; int err_code= 0; int version_number=0; version_number= atoi(mysql->server_version); const char query_global_attr_version_four[] = "SELECT @@global.server_id, @@global.collation_server, @@global.time_zone"; const char query_global_attr_older_versions[] = "SELECT @@global.server_id"; const char* global_server_id = NULL; const char* global_collation_server = NULL; const char* global_time_zone = NULL; mi->ignore_checksum_alg = false; MYSQL_RES *master_res= 0; MYSQL_ROW master_row; DBUG_ENTER("get_master_version_and_clock"); /* Free old mi_description_event (that is needed if we are in a reconnection). */ DBUG_EXECUTE_IF("unrecognized_master_version", { version_number= 1; };); mysql_mutex_lock(&mi->data_lock); mi->set_mi_description_event(NULL); if (!my_isdigit(&my_charset_bin,*mysql->server_version)) { errmsg = "Master reported unrecognized MySQL version"; err_code= ER_SLAVE_FATAL_ERROR; sprintf(err_buff, ER(err_code), errmsg); } else { /* Note the following switch will bug when we have MySQL branch 30 ;) */ switch (version_number) { case 0: case 1: case 2: errmsg = "Master reported unrecognized MySQL version"; err_code= ER_SLAVE_FATAL_ERROR; sprintf(err_buff, ER(err_code), errmsg); break; case 3: mi->set_mi_description_event(new Format_description_log_event(1, mysql->server_version)); break; case 4: mi->set_mi_description_event(new Format_description_log_event(3, mysql->server_version)); break; default: /* Master is MySQL >=5.0. Give a default Format_desc event, so that we can take the early steps (like tests for "is this a 3.23 master") which we have to take before we receive the real master's Format_desc which will override this one. Note that the Format_desc we create below is garbage (it has the format of the *slave*); it's only good to help know if the master is 3.23, 4.0, etc. */ mi->set_mi_description_event(new Format_description_log_event(4, mysql->server_version)); break; } } /* This does not mean that a 5.0 slave will be able to read a 5.5 master; but as we don't know yet, we don't want to forbid this for now. If a 5.0 slave can't read a 5.5 master, this will show up when the slave can't read some events sent by the master, and there will be error messages. */ if (errmsg) { /* unlock the mutex on master info structure */ mysql_mutex_unlock(&mi->data_lock); goto err; } /* as we are here, we tried to allocate the event */ if (mi->get_mi_description_event() == NULL) { mysql_mutex_unlock(&mi->data_lock); errmsg= "default Format_description_log_event"; err_code= ER_SLAVE_CREATE_EVENT_FAILURE; sprintf(err_buff, ER(err_code), errmsg); goto err; } if (mi->get_mi_description_event()->binlog_version < 4 && opt_slave_sql_verify_checksum) { sql_print_warning("Found a master with MySQL server version older than " "5.0. With checksums enabled on the slave, replication " "might not work correctly. To ensure correct " "replication, restart the slave server with " "--slave_sql_verify_checksum=0."); } /* FD_q's (A) is set initially from RL's (A): FD_q.(A) := RL.(A). It's necessary to adjust FD_q.(A) at this point because in the following course FD_q is going to be dumped to RL. Generally FD_q is derived from a received FD_m (roughly FD_q := FD_m) in queue_event and the master's (A) is installed. At one step with the assignment the Relay-Log's checksum alg is set to a new value: RL.(A) := FD_q.(A). If the slave service is stopped the last time assigned RL.(A) will be passed over to the restarting service (to the current execution point). RL.A is a "codec" to verify checksum in queue_event() almost all the time the first fake Rotate event. Starting from this point IO thread will executes the following checksum warmup sequence of actions: FD_q.A := RL.A, A_m^0 := master.@@global.binlog_checksum, {queue_event(R_f): verifies(R_f, A_m^0)}, {queue_event(FD_m): verifies(FD_m, FD_m.A), dump(FD_q), rotate(RL), FD_q := FD_m, RL.A := FD_q.A)} See legends definition on MYSQL_BIN_LOG::relay_log_checksum_alg docs lines (binlog.h). In above A_m^0 - the value of master's @@binlog_checksum determined in the upcoming handshake (stored in mi->checksum_alg_before_fd). After the warm-up sequence IO gets to "normal" checksum verification mode to use RL.A in {queue_event(E_m): verifies(E_m, RL.A)} until it has received a new FD_m. */ mi->get_mi_description_event()->checksum_alg= mi->rli->relay_log.relay_log_checksum_alg; DBUG_ASSERT(mi->get_mi_description_event()->checksum_alg != BINLOG_CHECKSUM_ALG_UNDEF); DBUG_ASSERT(mi->rli->relay_log.relay_log_checksum_alg != BINLOG_CHECKSUM_ALG_UNDEF); mi->clock_diff_with_master= 0; /* The "most sensible" value */ mysql_mutex_unlock(&mi->data_lock); /* Check that the master's server id and ours are different. Because if they are equal (which can result from a simple copy of master's datadir to slave, thus copying some my.cnf), replication will work but all events will be skipped. Do not die if SHOW VARIABLES LIKE 'SERVER_ID' fails on master (very old master?). Note: we could have put a @@SERVER_ID in the previous SELECT UNIX_TIMESTAMP() instead, but this would not have worked on 3.23 masters. */ DBUG_EXECUTE_IF("dbug.before_get_SERVER_ID", { const char act[]= "now " "wait_for signal.get_server_id"; DBUG_ASSERT(opt_debug_sync_timeout > 0); DBUG_ASSERT(!debug_sync_set_action(current_thd, STRING_WITH_LEN(act))); };); master_res= NULL; master_row= NULL; if (*mysql->server_version == '4') { if (!mysql_real_query(mysql, STRING_WITH_LEN(query_global_attr_version_four)) && (master_res= mysql_store_result(mysql)) && (master_row= mysql_fetch_row(master_res))) { global_server_id = master_row[0]; global_collation_server = master_row[1]; global_time_zone = master_row[2]; } else if (mysql_errno(mysql)) { if (check_io_slave_killed(mi->info_thd, mi, NULL)) goto slave_killed_err; else if (is_network_error(mysql_errno(mysql))) { mi->report(WARNING_LEVEL, mysql_errno(mysql), "Get master SERVER_ID, COLLATION_SERVER and TIME_ZONE " "failed with error: %s", mysql_error(mysql)); goto network_err; } else if (mysql_errno(mysql) != ER_UNKNOWN_SYSTEM_VARIABLE) { /* Fatal error */ errmsg = "The slave I/O thread stops because a fatal error is " "encountered when it try to get the value of SERVER_ID, " "COLLATION_SERVER and TIME_ZONE global variable from master."; err_code = mysql_errno(mysql); sprintf(err_buff, "%s Error: %s", errmsg, mysql_error(mysql)); goto err; } else { mi->report(WARNING_LEVEL, ER_UNKNOWN_SYSTEM_VARIABLE, "Unknown system variable 'SERVER_ID', 'COLLATION_SERVER' or " "'TIME_ZONE' on master, maybe it is a *VERY OLD MASTER*. " "*NOTE*: slave may experience inconsistency if replicated " "data deals with collation."); } } } else { if (!mysql_real_query(mysql, STRING_WITH_LEN(query_global_attr_older_versions)) && (master_res = mysql_store_result(mysql)) && (master_row = mysql_fetch_row(master_res))) { global_server_id = master_row[0]; } else if (mysql_errno(mysql)) { if (check_io_slave_killed(mi->info_thd, mi, NULL)) { goto slave_killed_err; } else if (is_network_error(mysql_errno(mysql))) { mi->report(WARNING_LEVEL, mysql_errno(mysql), "Get master SERVER_ID failed with error: %s", mysql_error(mysql)); goto network_err; } else if (mysql_errno(mysql) != ER_UNKNOWN_SYSTEM_VARIABLE) { /* Fatal error */ errmsg = "The slave I/O thread stops because a fatal error is " "encountered when it try to get the value of SERVER_ID global " "variable from master."; err_code = mysql_errno(mysql); sprintf(err_buff, "%s Error: %s", errmsg, mysql_error(mysql)); goto err; } else { mi->report(WARNING_LEVEL, ER_UNKNOWN_SYSTEM_VARIABLE, "Unknown system variable 'SERVER_ID' on master, " "maybe it is a *VERY OLD MASTER*. *NOTE*: slave may " "experience inconsistency if replicated data deals " "with collation."); } } } if (global_server_id != NULL && (::server_id == (mi->master_id= strtoul(global_server_id, 0, 10))) && !mi->rli->replicate_same_server_id) { errmsg = "The slave I/O thread stops because master and slave have equal " "MySQL server ids; these ids must be different for replication " "to work (or the --replicate-same-server-id option must be used " "on slave but this does not always make sense; please check the " "manual before using it)."; err_code= ER_SLAVE_FATAL_ERROR; sprintf(err_buff, ER(err_code), errmsg); goto err; } if (mi->master_id == 0 && mi->ignore_server_ids->dynamic_ids.elements > 0) { errmsg = "Slave configured with server id filtering could not detect the " "master server id."; err_code= ER_SLAVE_FATAL_ERROR; sprintf(err_buff, ER(err_code), errmsg); goto err; } /* Check that the master's global character_set_server and ours are the same. Not fatal if query fails (old master?). Note that we don't check for equality of global character_set_client and collation_connection (neither do we prevent their setting in set_var.cc). That's because from what I (Guilhem) have tested, the global values of these 2 are never used (new connections don't use them). We don't test equality of global collation_database either as it's is going to be deprecated (made read-only) in 4.1 very soon. The test is only relevant if master < 5.0.3 (we'll test only if it's older than the 5 branch; < 5.0.3 was alpha...), as >= 5.0.3 master stores charset info in each binlog event. We don't do it for 3.23 because masters <3.23.50 hang on SELECT @@unknown_var (BUG#7965 - see changelog of 3.23.50). So finally we test only if master is 4.x. */ /* redundant with rest of code but safer against later additions */ if (*mysql->server_version == '3') goto err; if (*mysql->server_version == '4' && global_collation_server != NULL && strcmp(global_collation_server, global_system_variables.collation_server->name)) { errmsg = "The slave I/O thread stops because master and slave have " "different values for the COLLATION_SERVER global variable. " "The values must be equal for the Statement-format " "replication to work"; err_code = ER_SLAVE_FATAL_ERROR; sprintf(err_buff, ER(err_code), errmsg); goto err; } /* Perform analogous check for time zone. Theoretically we also should perform check here to verify that SYSTEM time zones are the same on slave and master, but we can't rely on value of @@system_time_zone variable (it is time zone abbreviation) since it determined at start time and so could differ for slave and master even if they are really in the same system time zone. So we are omiting this check and just relying on documentation. Also according to Monty there are many users who are using replication between servers in various time zones. Hence such check will broke everything for them. (And now everything will work for them because by default both their master and slave will have 'SYSTEM' time zone). This check is only necessary for 4.x masters (and < 5.0.4 masters but those were alpha). */ if (*mysql->server_version == '4' && global_time_zone != NULL && strcmp(global_time_zone, global_system_variables.time_zone->get_name()->ptr())) { errmsg= "The slave I/O thread stops because master and slave have \ different values for the TIME_ZONE global variable. The values must \ be equal for the Statement-format replication to work"; err_code= ER_SLAVE_FATAL_ERROR; sprintf(err_buff, ER(err_code), errmsg); goto err; } /* Cleans the queries for UNIX_TIMESTAMP, server_id, collation_server and time_zone Dont free the memory before, this will free the strings too. */ if (master_res) { mysql_free_result(master_res); master_res = NULL; } if (mi->heartbeat_period != 0.0) { char llbuf[22]; const char query_format[]= "SET @master_heartbeat_period= %s"; char query[sizeof(query_format) - 2 + sizeof(llbuf)]; /* the period is an ulonglong of nano-secs. */ llstr((ulonglong) (mi->heartbeat_period*1000000000UL), llbuf); sprintf(query, query_format, llbuf); if (mysql_real_query(mysql, query, strlen(query))) { if (check_io_slave_killed(mi->info_thd, mi, NULL)) goto slave_killed_err; if (is_network_error(mysql_errno(mysql))) { mi->report(WARNING_LEVEL, mysql_errno(mysql), "SET @master_heartbeat_period to master failed with error: %s", mysql_error(mysql)); mysql_free_result(mysql_store_result(mysql)); goto network_err; } else { /* Fatal error */ errmsg= "The slave I/O thread stops because a fatal error is encountered " " when it tries to SET @master_heartbeat_period on master."; err_code= ER_SLAVE_FATAL_ERROR; sprintf(err_buff, "%s Error: %s", errmsg, mysql_error(mysql)); mysql_free_result(mysql_store_result(mysql)); goto err; } } mysql_free_result(mysql_store_result(mysql)); } /* Querying if master is capable to checksum and notifying it about own CRC-awareness. The master's side instant value of @@global.binlog_checksum is stored in the dump thread's uservar area as well as cached locally to become known in consensus by master and slave. */ if (DBUG_EVALUATE_IF("simulate_slave_unaware_checksum", 0, 1)) { int rc; const char query[]= "SET @master_binlog_checksum= @@global.binlog_checksum"; master_res= NULL; mi->checksum_alg_before_fd= BINLOG_CHECKSUM_ALG_UNDEF; //initially undefined /* @c checksum_alg_before_fd is queried from master in this block. If master is old checksum-unaware the value stays undefined. Once the first FD will be received its alg descriptor will replace the being queried one. */ rc= mysql_real_query(mysql, query, strlen(query)); if (rc != 0) { mi->checksum_alg_before_fd= BINLOG_CHECKSUM_ALG_OFF; if (check_io_slave_killed(mi->info_thd, mi, NULL)) goto slave_killed_err; if (mysql_errno(mysql) == ER_UNKNOWN_SYSTEM_VARIABLE) { // this is tolerable as OM -> NS is supported mi->ignore_checksum_alg = true; mi->report(WARNING_LEVEL, mysql_errno(mysql), "Notifying master by %s failed with " "error: %s", query, mysql_error(mysql)); } else { if (is_network_error(mysql_errno(mysql))) { mi->report(WARNING_LEVEL, mysql_errno(mysql), "Notifying master by %s failed with " "error: %s", query, mysql_error(mysql)); mysql_free_result(mysql_store_result(mysql)); goto network_err; } else { errmsg= "The slave I/O thread stops because a fatal error is encountered " "when it tried to SET @master_binlog_checksum on master."; err_code= ER_SLAVE_FATAL_ERROR; sprintf(err_buff, "%s Error: %s", errmsg, mysql_error(mysql)); mysql_free_result(mysql_store_result(mysql)); goto err; } } } else { mysql_free_result(mysql_store_result(mysql)); if (!mysql_real_query(mysql, STRING_WITH_LEN("SELECT @master_binlog_checksum")) && (master_res= mysql_store_result(mysql)) && (master_row= mysql_fetch_row(master_res)) && (master_row[0] != NULL)) { mi->checksum_alg_before_fd= (uint8) find_type(master_row[0], &binlog_checksum_typelib, 1) - 1; DBUG_EXECUTE_IF("undefined_algorithm_on_slave", mi->checksum_alg_before_fd = BINLOG_CHECKSUM_ALG_UNDEF;); if(mi->checksum_alg_before_fd == BINLOG_CHECKSUM_ALG_UNDEF) { errmsg= "The slave I/O thread was stopped because a fatal error is encountered " "The checksum algorithm used by master is unknown to slave."; err_code= ER_SLAVE_FATAL_ERROR; sprintf(err_buff, "%s Error: %s", errmsg, mysql_error(mysql)); mysql_free_result(mysql_store_result(mysql)); goto err; } // valid outcome is either of DBUG_ASSERT(mi->checksum_alg_before_fd == BINLOG_CHECKSUM_ALG_OFF || mi->checksum_alg_before_fd == BINLOG_CHECKSUM_ALG_CRC32); } else if (check_io_slave_killed(mi->info_thd, mi, NULL)) goto slave_killed_err; else if (is_network_error(mysql_errno(mysql))) { mi->report(WARNING_LEVEL, mysql_errno(mysql), "Get master BINLOG_CHECKSUM failed with error: %s", mysql_error(mysql)); goto network_err; } else { errmsg= "The slave I/O thread stops because a fatal error is encountered " "when it tried to SELECT @master_binlog_checksum."; err_code= ER_SLAVE_FATAL_ERROR; sprintf(err_buff, "%s Error: %s", errmsg, mysql_error(mysql)); mysql_free_result(mysql_store_result(mysql)); goto err; } } if (master_res) { mysql_free_result(master_res); master_res= NULL; } } else mi->checksum_alg_before_fd= BINLOG_CHECKSUM_ALG_OFF; if (DBUG_EVALUATE_IF("simulate_slave_unaware_gtid", 0, 1)) { switch (io_thread_init_command(mi, "SELECT @@GLOBAL.GTID_MODE", ER_UNKNOWN_SYSTEM_VARIABLE, &master_res, &master_row)) { case COMMAND_STATUS_ERROR: DBUG_RETURN(2); case COMMAND_STATUS_ALLOWED_ERROR: // master is old and does not have @@GLOBAL.GTID_MODE mi->master_gtid_mode= 0; break; case COMMAND_STATUS_OK: int typelib_index= find_type(master_row[0], &gtid_mode_typelib, 1); mysql_free_result(master_res); if (typelib_index == 0) { mi->report(ERROR_LEVEL, ER_SLAVE_FATAL_ERROR, "The slave IO thread stops because the master has " "an unknown @@GLOBAL.GTID_MODE."); DBUG_RETURN(1); } mi->master_gtid_mode= typelib_index - 1; break; } if ((mi->master_gtid_mode > gtid_mode + 1 || gtid_mode > mi->master_gtid_mode + 1) && !enable_gtid_mode_on_new_slave_with_old_master && !read_only) { mi->report(ERROR_LEVEL, ER_SLAVE_FATAL_ERROR, "The slave IO thread stops because the master has " "@@GLOBAL.GTID_MODE %s and this server has " "@@GLOBAL.GTID_MODE %s", gtid_mode_names[mi->master_gtid_mode], gtid_mode_names[gtid_mode]); DBUG_RETURN(1); } if (mi->is_auto_position() && mi->master_gtid_mode != 3) { mi->report(ERROR_LEVEL, ER_SLAVE_FATAL_ERROR, "The slave IO thread stops because the master has " "@@GLOBAL.GTID_MODE %s and we are trying to connect " "using MASTER_AUTO_POSITION.", gtid_mode_names[mi->master_gtid_mode]); DBUG_RETURN(1); } } err: if (errmsg) { if (master_res) mysql_free_result(master_res); DBUG_ASSERT(err_code != 0); mi->report(ERROR_LEVEL, err_code, "%s", err_buff); DBUG_RETURN(1); } DBUG_RETURN(0); network_err: if (master_res) mysql_free_result(master_res); DBUG_RETURN(2); slave_killed_err: if (master_res) mysql_free_result(master_res); DBUG_RETURN(2); } static bool wait_for_relay_log_space(Relay_log_info* rli) { bool slave_killed=0; Master_info* mi = rli->mi; PSI_stage_info old_stage; THD* thd = mi->info_thd; DBUG_ENTER("wait_for_relay_log_space"); mysql_mutex_lock(&rli->log_space_lock); thd->ENTER_COND(&rli->log_space_cond, &rli->log_space_lock, &stage_waiting_for_relay_log_space, &old_stage); while (rli->log_space_limit < rli->log_space_total && !(slave_killed=io_slave_killed(thd,mi)) && !rli->ignore_log_space_limit) mysql_cond_wait(&rli->log_space_cond, &rli->log_space_lock); /* Makes the IO thread read only one event at a time until the SQL thread is able to purge the relay logs, freeing some space. Therefore, once the SQL thread processes this next event, it goes to sleep (no more events in the queue), sets ignore_log_space_limit=true and wakes the IO thread. However, this event may have been enough already for the SQL thread to purge some log files, freeing rli->log_space_total . This guarantees that the SQL and IO thread move forward only one event at a time (to avoid deadlocks), when the relay space limit is reached. It also guarantees that when the SQL thread is prepared to rotate (to be able to purge some logs), the IO thread will know about it and will rotate. NOTE: The ignore_log_space_limit is only set when the SQL thread sleeps waiting for events. */ if (rli->ignore_log_space_limit) { #ifndef DBUG_OFF { char llbuf1[22], llbuf2[22]; DBUG_PRINT("info", ("log_space_limit=%s " "log_space_total=%s " "ignore_log_space_limit=%d " "sql_force_rotate_relay=%d", llstr(rli->log_space_limit,llbuf1), llstr(rli->log_space_total,llbuf2), (int) rli->ignore_log_space_limit, (int) rli->sql_force_rotate_relay)); } #endif if (rli->sql_force_rotate_relay) { mysql_mutex_lock(&mi->data_lock); rotate_relay_log(mi); mysql_mutex_unlock(&mi->data_lock); rli->sql_force_rotate_relay= false; } rli->ignore_log_space_limit= false; } thd->EXIT_COND(&old_stage); DBUG_RETURN(slave_killed); } /* Builds a Rotate from the ignored events' info and writes it to relay log. The caller must hold mi->data_lock before invoking this function. @param thd pointer to I/O Thread's Thd. @param mi point to I/O Thread metadata class. @return 0 if everything went fine, 1 otherwise. */ static int write_ignored_events_info_to_relay_log(THD *thd, Master_info *mi) { Relay_log_info *rli= mi->rli; mysql_mutex_t *log_lock= rli->relay_log.get_log_lock(); int error= 0; DBUG_ENTER("write_ignored_events_info_to_relay_log"); DBUG_ASSERT(thd == mi->info_thd); mysql_mutex_assert_owner(&mi->data_lock); mysql_mutex_lock(log_lock); if (rli->ign_master_log_name_end[0]) { DBUG_PRINT("info",("writing a Rotate event to track down ignored events")); Rotate_log_event *ev= new Rotate_log_event(rli->ign_master_log_name_end, 0, rli->ign_master_log_pos_end, Rotate_log_event::DUP_NAME); if (mi->get_mi_description_event() != NULL) ev->checksum_alg= mi->get_mi_description_event()->checksum_alg; rli->ign_master_log_name_end[0]= 0; /* can unlock before writing as slave SQL thd will soon see our Rotate */ mysql_mutex_unlock(log_lock); if (likely((bool)ev)) { ev->server_id= 0; // don't be ignored by slave SQL thread if (unlikely(rli->relay_log.append_event(ev, mi) != 0)) mi->report(ERROR_LEVEL, ER_SLAVE_RELAY_LOG_WRITE_FAILURE, ER(ER_SLAVE_RELAY_LOG_WRITE_FAILURE), "failed to write a Rotate event" " to the relay log, SHOW SLAVE STATUS may be" " inaccurate"); rli->relay_log.harvest_bytes_written(&rli->log_space_total); if (flush_master_info(mi, TRUE)) { error= 1; sql_print_error("Failed to flush master info file."); } delete ev; } else { error= 1; mi->report(ERROR_LEVEL, ER_SLAVE_CREATE_EVENT_FAILURE, ER(ER_SLAVE_CREATE_EVENT_FAILURE), "Rotate_event (out of memory?)," " SHOW SLAVE STATUS may be inaccurate"); } } else mysql_mutex_unlock(log_lock); DBUG_RETURN(error); } int register_slave_on_master(MYSQL* mysql, Master_info *mi, bool *suppress_warnings) { uchar buf[1024], *pos= buf; uint report_host_len=0, report_user_len=0, report_password_len=0; DBUG_ENTER("register_slave_on_master"); *suppress_warnings= FALSE; if (report_host) report_host_len= strlen(report_host); if (report_host_len > HOSTNAME_LENGTH) { sql_print_warning("The length of report_host is %d. " "It is larger than the max length(%d), so this " "slave cannot be registered to the master.", report_host_len, HOSTNAME_LENGTH); DBUG_RETURN(0); } if (report_user) report_user_len= strlen(report_user); if (report_user_len > USERNAME_LENGTH) { sql_print_warning("The length of report_user is %d. " "It is larger than the max length(%d), so this " "slave cannot be registered to the master.", report_user_len, USERNAME_LENGTH); DBUG_RETURN(0); } if (report_password) report_password_len= strlen(report_password); if (report_password_len > MAX_PASSWORD_LENGTH) { sql_print_warning("The length of report_password is %d. " "It is larger than the max length(%d), so this " "slave cannot be registered to the master.", report_password_len, MAX_PASSWORD_LENGTH); DBUG_RETURN(0); } int4store(pos, server_id); pos+= 4; pos= net_store_data(pos, (uchar*) report_host, report_host_len); pos= net_store_data(pos, (uchar*) report_user, report_user_len); pos= net_store_data(pos, (uchar*) report_password, report_password_len); int2store(pos, (uint16) report_port); pos+= 2; /* Fake rpl_recovery_rank, which was removed in BUG#13963, so that this server can register itself on old servers, see BUG#49259. */ int4store(pos, /* rpl_recovery_rank */ 0); pos+= 4; /* The master will fill in master_id */ int4store(pos, 0); pos+= 4; if (simple_command(mysql, COM_REGISTER_SLAVE, buf, (size_t) (pos- buf), 0)) { if (mysql_errno(mysql) == ER_NET_READ_INTERRUPTED) { *suppress_warnings= TRUE; // Suppress reconnect warning } else if (!check_io_slave_killed(mi->info_thd, mi, NULL)) { char buf[256]; my_snprintf(buf, sizeof(buf), "%s (Errno: %d)", mysql_error(mysql), mysql_errno(mysql)); mi->report(ERROR_LEVEL, ER_SLAVE_MASTER_COM_FAILURE, ER(ER_SLAVE_MASTER_COM_FAILURE), "COM_REGISTER_SLAVE", buf); } DBUG_RETURN(1); } DBUG_RETURN(0); } /** Execute a SHOW SLAVE STATUS statement. @param thd Pointer to THD object for the client thread executing the statement. @param mi Pointer to Master_info object for the IO thread. @retval FALSE success @retval TRUE failure */ bool show_slave_status(THD* thd, Master_info* mi) { // TODO: fix this for multi-master List<Item> field_list; Protocol *protocol= thd->protocol; char *slave_sql_running_state= NULL; char *sql_gtid_set_buffer= NULL, *io_gtid_set_buffer= NULL; int sql_gtid_set_size= 0, io_gtid_set_size= 0; DBUG_ENTER("show_slave_status"); if (mi != NULL) { global_sid_lock->wrlock(); const Gtid_set* sql_gtid_set= gtid_state->get_logged_gtids(); const Gtid_set* io_gtid_set= mi->rli->get_gtid_set(); if ((sql_gtid_set_size= sql_gtid_set->to_string(&sql_gtid_set_buffer)) < 0 || (io_gtid_set_size= io_gtid_set->to_string(&io_gtid_set_buffer)) < 0) { my_eof(thd); my_free(sql_gtid_set_buffer); my_free(io_gtid_set_buffer); global_sid_lock->unlock(); DBUG_RETURN(true); } global_sid_lock->unlock(); } field_list.push_back(new Item_empty_string("Slave_IO_State", 14)); field_list.push_back(new Item_empty_string("Master_Host", mi != NULL ? sizeof(mi->host) : 0)); field_list.push_back(new Item_empty_string("Master_User", mi != NULL ? mi->get_user_size() : 0)); field_list.push_back(new Item_return_int("Master_Port", 7, MYSQL_TYPE_LONG)); field_list.push_back(new Item_return_int("Connect_Retry", 10, MYSQL_TYPE_LONG)); field_list.push_back(new Item_empty_string("Master_Log_File", FN_REFLEN)); field_list.push_back(new Item_return_int("Read_Master_Log_Pos", 10, MYSQL_TYPE_LONGLONG)); field_list.push_back(new Item_empty_string("Relay_Log_File", FN_REFLEN)); field_list.push_back(new Item_return_int("Relay_Log_Pos", 10, MYSQL_TYPE_LONGLONG)); field_list.push_back(new Item_empty_string("Relay_Master_Log_File", FN_REFLEN)); field_list.push_back(new Item_empty_string("Slave_IO_Running", 3)); field_list.push_back(new Item_empty_string("Slave_SQL_Running", 3)); field_list.push_back(new Item_empty_string("Replicate_Do_DB", 20)); field_list.push_back(new Item_empty_string("Replicate_Ignore_DB", 20)); field_list.push_back(new Item_empty_string("Replicate_Do_Table", 20)); field_list.push_back(new Item_empty_string("Replicate_Ignore_Table", 23)); field_list.push_back(new Item_empty_string("Replicate_Wild_Do_Table", 24)); field_list.push_back(new Item_empty_string("Replicate_Wild_Ignore_Table", 28)); field_list.push_back(new Item_return_int("Last_Errno", 4, MYSQL_TYPE_LONG)); field_list.push_back(new Item_empty_string("Last_Error", 20)); field_list.push_back(new Item_return_int("Skip_Counter", 10, MYSQL_TYPE_LONG)); field_list.push_back(new Item_return_int("Exec_Master_Log_Pos", 10, MYSQL_TYPE_LONGLONG)); field_list.push_back(new Item_return_int("Relay_Log_Space", 10, MYSQL_TYPE_LONGLONG)); field_list.push_back(new Item_empty_string("Until_Condition", 6)); field_list.push_back(new Item_empty_string("Until_Log_File", FN_REFLEN)); field_list.push_back(new Item_return_int("Until_Log_Pos", 10, MYSQL_TYPE_LONGLONG)); field_list.push_back(new Item_empty_string("Master_SSL_Allowed", 7)); field_list.push_back(new Item_empty_string("Master_SSL_CA_File", mi != NULL ? sizeof(mi->ssl_ca) : 0)); field_list.push_back(new Item_empty_string("Master_SSL_CA_Path", mi != NULL ? sizeof(mi->ssl_capath) : 0)); field_list.push_back(new Item_empty_string("Master_SSL_Cert", mi != NULL ? sizeof(mi->ssl_cert) : 0)); field_list.push_back(new Item_empty_string("Master_SSL_Cipher", mi != NULL ? sizeof(mi->ssl_cipher) : 0)); field_list.push_back(new Item_empty_string("Master_SSL_Key", mi != NULL ? sizeof(mi->ssl_key) : 0)); field_list.push_back(new Item_return_int("Seconds_Behind_Master", 10, MYSQL_TYPE_LONGLONG)); field_list.push_back(new Item_return_int("Lag_Peak_Over_Last_Period", 10, MYSQL_TYPE_LONGLONG)); field_list.push_back(new Item_empty_string("Master_SSL_Verify_Server_Cert", 3)); field_list.push_back(new Item_return_int("Last_IO_Errno", 4, MYSQL_TYPE_LONG)); field_list.push_back(new Item_empty_string("Last_IO_Error", 20)); field_list.push_back(new Item_return_int("Last_SQL_Errno", 4, MYSQL_TYPE_LONG)); field_list.push_back(new Item_empty_string("Last_SQL_Error", 20)); field_list.push_back(new Item_empty_string("Replicate_Ignore_Server_Ids", FN_REFLEN)); field_list.push_back(new Item_return_int("Master_Server_Id", sizeof(ulong), MYSQL_TYPE_LONG)); field_list.push_back(new Item_empty_string("Master_UUID", UUID_LENGTH)); field_list.push_back(new Item_empty_string("Master_Info_File", 2 * FN_REFLEN)); field_list.push_back(new Item_return_int("SQL_Delay", 10, MYSQL_TYPE_LONG)); field_list.push_back(new Item_return_int("SQL_Remaining_Delay", 8, MYSQL_TYPE_LONG)); field_list.push_back(new Item_empty_string("Slave_SQL_Running_State", 20)); field_list.push_back(new Item_return_int("Master_Retry_Count", 10, MYSQL_TYPE_LONGLONG)); field_list.push_back(new Item_empty_string("Master_Bind", mi != NULL ? sizeof(mi->bind_addr) : 0)); field_list.push_back(new Item_empty_string("Last_IO_Error_Timestamp", 20)); field_list.push_back(new Item_empty_string("Last_SQL_Error_Timestamp", 20)); field_list.push_back(new Item_empty_string("Master_SSL_Crl", mi != NULL ? sizeof(mi->ssl_crl) : 0)); field_list.push_back(new Item_empty_string("Master_SSL_Crlpath", mi != NULL ? sizeof(mi->ssl_crlpath) : 0)); field_list.push_back(new Item_empty_string("Retrieved_Gtid_Set", io_gtid_set_size)); field_list.push_back(new Item_empty_string("Executed_Gtid_Set", sql_gtid_set_size)); field_list.push_back(new Item_return_int("Auto_Position", sizeof(ulong), MYSQL_TYPE_LONG)); field_list.push_back(new Item_empty_string("Master_SSL_Actual_Cipher", mi != NULL ? sizeof(mi->ssl_actual_cipher) : 0)); field_list.push_back(new Item_empty_string("Master_SSL_Subject", mi != NULL ? sizeof(mi->ssl_master_subject) : 0)); field_list.push_back(new Item_empty_string("Master_SSL_Issuer", mi != NULL ? sizeof(mi->ssl_master_issuer) : 0)); if (protocol->send_result_set_metadata(&field_list, Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF)) { my_free(sql_gtid_set_buffer); my_free(io_gtid_set_buffer); DBUG_RETURN(true); } if (mi != NULL && mi->host[0]) { DBUG_PRINT("info",("host is set: '%s'", mi->host)); String *packet= &thd->packet; protocol->prepare_for_resend(); /* slave_running can be accessed without run_lock but not other non-volotile members like mi->info_thd or rli->info_thd, for them either info_thd_lock or run_lock hold is required. */ mysql_mutex_lock(&mi->info_thd_lock); protocol->store(mi->info_thd ? mi->info_thd->get_proc_info() : "", &my_charset_bin); mysql_mutex_unlock(&mi->info_thd_lock); mysql_mutex_lock(&mi->rli->info_thd_lock); slave_sql_running_state= const_cast<char *>(mi->rli->info_thd ? mi->rli->info_thd->get_proc_info() : ""); mysql_mutex_unlock(&mi->rli->info_thd_lock); mysql_mutex_lock(&mi->data_lock); mysql_mutex_lock(&mi->rli->data_lock); mysql_mutex_lock(&mi->err_lock); mysql_mutex_lock(&mi->rli->err_lock); DEBUG_SYNC(thd, "wait_after_lock_active_mi_and_rli_data_lock_is_acquired"); protocol->store(mi->host, &my_charset_bin); protocol->store(mi->get_user(), &my_charset_bin); protocol->store((uint32) mi->port); protocol->store((uint32) mi->connect_retry); protocol->store(mi->get_master_log_name(), &my_charset_bin); protocol->store((ulonglong) mi->get_master_log_pos()); protocol->store(mi->rli->get_group_relay_log_name() + dirname_length(mi->rli->get_group_relay_log_name()), &my_charset_bin); protocol->store((ulonglong) mi->rli->get_group_relay_log_pos()); protocol->store(mi->rli->get_group_master_log_name(), &my_charset_bin); protocol->store(mi->slave_running == MYSQL_SLAVE_RUN_CONNECT ? "Yes" : (mi->slave_running == MYSQL_SLAVE_RUN_NOT_CONNECT ? "Connecting" : "No"), &my_charset_bin); protocol->store(mi->rli->slave_running ? "Yes":"No", &my_charset_bin); protocol->store(rpl_filter->get_do_db()); protocol->store(rpl_filter->get_ignore_db()); char buf[256]; String tmp(buf, sizeof(buf), &my_charset_bin); rpl_filter->get_do_table(&tmp); protocol->store(&tmp); rpl_filter->get_ignore_table(&tmp); protocol->store(&tmp); rpl_filter->get_wild_do_table(&tmp); protocol->store(&tmp); rpl_filter->get_wild_ignore_table(&tmp); protocol->store(&tmp); protocol->store(mi->rli->last_error().number); protocol->store(mi->rli->last_error().message, &my_charset_bin); protocol->store((uint32) mi->rli->slave_skip_counter); protocol->store((ulonglong) mi->rli->get_group_master_log_pos()); protocol->store((ulonglong) mi->rli->log_space_total); const char *until_type= ""; switch (mi->rli->until_condition) { case Relay_log_info::UNTIL_NONE: until_type= "None"; break; case Relay_log_info::UNTIL_MASTER_POS: until_type= "Master"; break; case Relay_log_info::UNTIL_RELAY_POS: until_type= "Relay"; break; case Relay_log_info::UNTIL_SQL_BEFORE_GTIDS: until_type= "SQL_BEFORE_GTIDS"; break; case Relay_log_info::UNTIL_SQL_AFTER_GTIDS: until_type= "SQL_AFTER_GTIDS"; break; case Relay_log_info::UNTIL_SQL_AFTER_MTS_GAPS: until_type= "SQL_AFTER_MTS_GAPS"; #ifndef DBUG_OFF case Relay_log_info::UNTIL_DONE: until_type= "DONE"; break; #endif default: DBUG_ASSERT(0); } protocol->store(until_type, &my_charset_bin); protocol->store(mi->rli->until_log_name, &my_charset_bin); protocol->store((ulonglong) mi->rli->until_log_pos); #ifdef HAVE_OPENSSL protocol->store(mi->ssl? "Yes":"No", &my_charset_bin); #else protocol->store(mi->ssl? "Ignored":"No", &my_charset_bin); #endif protocol->store(mi->ssl_ca, &my_charset_bin); protocol->store(mi->ssl_capath, &my_charset_bin); protocol->store(mi->ssl_cert, &my_charset_bin); protocol->store(mi->ssl_cipher, &my_charset_bin); protocol->store(mi->ssl_key, &my_charset_bin); /* The pseudo code to compute Seconds_Behind_Master: if (SQL thread is running) { if (SQL thread processed all the available relay log) { if (IO thread is running) print 0; else print NULL; } else compute Seconds_Behind_Master; } else print NULL; */ if (mi->rli->slave_running) { time_t now = time(0); /* Check if SQL thread is at the end of relay log Checking should be done using two conditions condition1: compare the log positions and condition2: compare the file names (to handle rotation case) */ if (reset_seconds_behind_master && (mi->get_master_log_pos() == mi->rli->get_group_master_log_pos()) && (!strcmp(mi->get_master_log_name(), mi->rli->get_group_master_log_name()))) { if (mi->slave_running == MYSQL_SLAVE_RUN_CONNECT) protocol->store(0LL); else protocol->store_null(); } else { long time_diff= ((long)(now - mi->rli->last_master_timestamp) - mi->clock_diff_with_master); /* Apparently on some systems time_diff can be <0. Here are possible reasons related to MySQL: - the master is itself a slave of another master whose time is ahead. - somebody used an explicit SET TIMESTAMP on the master. Possible reason related to granularity-to-second of time functions (nothing to do with MySQL), which can explain a value of -1: assume the master's and slave's time are perfectly synchronized, and that at slave's connection time, when the master's timestamp is read, it is at the very end of second 1, and (a very short time later) when the slave's timestamp is read it is at the very beginning of second 2. Then the recorded value for master is 1 and the recorded value for slave is 2. At SHOW SLAVE STATUS time, assume that the difference between timestamp of slave and rli->last_master_timestamp is 0 (i.e. they are in the same second), then we get 0-(2-1)=-1 as a result. This confuses users, so we don't go below 0: hence the max(). last_master_timestamp == 0 (an "impossible" timestamp 1970) is a special marker to say "consider we have caught up". */ protocol->store((longlong)(mi->rli->last_master_timestamp ? max(0L, time_diff) : 0)); } protocol->store((longlong) (max(0L, mi->rli->peak_lag(now)))); } else { protocol->store_null(); protocol->store_null(); } protocol->store(mi->ssl_verify_server_cert? "Yes":"No", &my_charset_bin); // Last_IO_Errno protocol->store(mi->last_error().number); // Last_IO_Error protocol->store(mi->last_error().message, &my_charset_bin); // Last_SQL_Errno protocol->store(mi->rli->last_error().number); // Last_SQL_Error protocol->store(mi->rli->last_error().message, &my_charset_bin); // Replicate_Ignore_Server_Ids { char buff[FN_REFLEN]; ulong i, cur_len; for (i= 0, buff[0]= 0, cur_len= 0; i < mi->ignore_server_ids->dynamic_ids.elements; i++) { ulong s_id, slen; char sbuff[FN_REFLEN]; get_dynamic(&(mi->ignore_server_ids->dynamic_ids), (uchar*) &s_id, i); slen= sprintf(sbuff, (i == 0 ? "%lu" : ", %lu"), s_id); if (cur_len + slen + 4 > FN_REFLEN) { /* break the loop whenever remained space could not fit ellipses on the next cycle */ sprintf(buff + cur_len, "..."); break; } cur_len += sprintf(buff + cur_len, "%s", sbuff); } protocol->store(buff, &my_charset_bin); } // Master_Server_id protocol->store((uint32) mi->master_id); protocol->store(mi->master_uuid, &my_charset_bin); // Master_Info_File protocol->store(mi->get_description_info(), &my_charset_bin); // SQL_Delay protocol->store((uint32) mi->rli->get_sql_delay()); // SQL_Remaining_Delay if (slave_sql_running_state == stage_sql_thd_waiting_until_delay.m_name) { time_t t= my_time(0), sql_delay_end= mi->rli->get_sql_delay_end(); protocol->store((uint32)(t < sql_delay_end ? sql_delay_end - t : 0)); } else protocol->store_null(); // Slave_SQL_Running_State protocol->store(slave_sql_running_state, &my_charset_bin); // Master_Retry_Count protocol->store((ulonglong) mi->retry_count); // Master_Bind protocol->store(mi->bind_addr, &my_charset_bin); // Last_IO_Error_Timestamp protocol->store(mi->last_error().timestamp, &my_charset_bin); // Last_SQL_Error_Timestamp protocol->store(mi->rli->last_error().timestamp, &my_charset_bin); // Master_Ssl_Crl protocol->store(mi->ssl_crl, &my_charset_bin); // Master_Ssl_Crlpath protocol->store(mi->ssl_crlpath, &my_charset_bin); // Retrieved_Gtid_Set protocol->store(io_gtid_set_buffer, &my_charset_bin); // Executed_Gtid_Set protocol->store(sql_gtid_set_buffer, &my_charset_bin); // Auto_Position protocol->store(mi->is_auto_position() ? 1 : 0); // ssl xxx protocol->store(mi->ssl_actual_cipher, &my_charset_bin); protocol->store(mi->ssl_master_issuer, &my_charset_bin); protocol->store(mi->ssl_master_subject, &my_charset_bin); mysql_mutex_unlock(&mi->rli->err_lock); mysql_mutex_unlock(&mi->err_lock); mysql_mutex_unlock(&mi->rli->data_lock); mysql_mutex_unlock(&mi->data_lock); if (my_net_write(&thd->net, (uchar*) thd->packet.ptr(), packet->length())) { my_free(sql_gtid_set_buffer); my_free(io_gtid_set_buffer); DBUG_RETURN(true); } } my_eof(thd); my_free(sql_gtid_set_buffer); my_free(io_gtid_set_buffer); DBUG_RETURN(false); } void set_slave_thread_options(THD* thd) { DBUG_ENTER("set_slave_thread_options"); /* It's nonsense to constrain the slave threads with max_join_size; if a query succeeded on master, we HAVE to execute it. So set OPTION_BIG_SELECTS. Setting max_join_size to HA_POS_ERROR is not enough (and it's not needed if we have OPTION_BIG_SELECTS) because an INSERT SELECT examining more than 4 billion rows would still fail (yes, because when max_join_size is 4G, OPTION_BIG_SELECTS is automatically set, but only for client threads. */ ulonglong options= thd->variables.option_bits | OPTION_BIG_SELECTS; if (opt_log_slave_updates) options|= OPTION_BIN_LOG; else options&= ~OPTION_BIN_LOG; thd->variables.option_bits= options; thd->variables.completion_type= 0; /* Set autocommit= 1 when info tables are used and autocommit == 0 to avoid trigger asserts on mysql_execute_command(THD *thd) caused by info tables updates which do not commit, like Rotate, Stop and skipped events handling. */ if ((thd->variables.option_bits & OPTION_NOT_AUTOCOMMIT) && (opt_mi_repository_id == INFO_REPOSITORY_TABLE || opt_rli_repository_id == INFO_REPOSITORY_TABLE)) { thd->variables.option_bits|= OPTION_AUTOCOMMIT; thd->variables.option_bits&= ~OPTION_NOT_AUTOCOMMIT; thd->server_status|= SERVER_STATUS_AUTOCOMMIT; } DBUG_VOID_RETURN; } void set_slave_thread_default_charset(THD* thd, Relay_log_info const *rli) { DBUG_ENTER("set_slave_thread_default_charset"); thd->variables.character_set_client= global_system_variables.character_set_client; thd->variables.collation_connection= global_system_variables.collation_connection; thd->variables.collation_server= global_system_variables.collation_server; thd->update_charset(); /* We use a const cast here since the conceptual (and externally visible) behavior of the function is to set the default charset of the thread. That the cache has to be invalidated is a secondary effect. */ const_cast<Relay_log_info*>(rli)->cached_charset_invalidate(); DBUG_VOID_RETURN; } /* init_slave_thread() */ static int init_slave_thread(THD* thd, SLAVE_THD_TYPE thd_type) { DBUG_ENTER("init_slave_thread"); #if !defined(DBUG_OFF) int simulate_error= 0; #endif thd->system_thread= (thd_type == SLAVE_THD_WORKER) ? SYSTEM_THREAD_SLAVE_WORKER : (thd_type == SLAVE_THD_SQL) ? SYSTEM_THREAD_SLAVE_SQL : SYSTEM_THREAD_SLAVE_IO; thd->security_ctx->skip_grants(); my_net_init(&thd->net, 0); thd->slave_thread = 1; thd->enable_slow_log= opt_log_slow_slave_statements; set_slave_thread_options(thd); thd->client_capabilities = CLIENT_LOCAL_FILES; mysql_mutex_lock(&LOCK_thread_count); thd->thread_id= thd->variables.pseudo_thread_id= thread_id++; mysql_mutex_unlock(&LOCK_thread_count); DBUG_EXECUTE_IF("simulate_io_slave_error_on_init", simulate_error|= (1 << SLAVE_THD_IO);); DBUG_EXECUTE_IF("simulate_sql_slave_error_on_init", simulate_error|= (1 << SLAVE_THD_SQL);); #if !defined(DBUG_OFF) if (init_thr_lock() || thd->store_globals() || simulate_error & (1<< thd_type)) #else if (init_thr_lock() || thd->store_globals()) #endif { DBUG_RETURN(-1); } if (thd_type == SLAVE_THD_SQL) { THD_STAGE_INFO(thd, stage_waiting_for_the_next_event_in_relay_log); } else { THD_STAGE_INFO(thd, stage_waiting_for_master_update); } thd->set_time(); /* Do not use user-supplied timeout value for system threads. */ thd->variables.lock_wait_timeout= LONG_TIMEOUT; DBUG_RETURN(0); } /** Sleep for a given amount of time or until killed. @param thd Thread context of the current thread. @param seconds The number of seconds to sleep. @param func Function object to check if the thread has been killed. @param info The Rpl_info object associated with this sleep. @retval True if the thread has been killed, false otherwise. */ template <typename killed_func, typename rpl_info> static inline bool slave_sleep(THD *thd, time_t seconds, killed_func func, rpl_info info) { bool ret; struct timespec abstime; mysql_mutex_t *lock= &info->sleep_lock; mysql_cond_t *cond= &info->sleep_cond; /* Absolute system time at which the sleep time expires. */ set_timespec(abstime, seconds); mysql_mutex_lock(lock); thd->ENTER_COND(cond, lock, NULL, NULL); while (! (ret= func(thd, info))) { int error= mysql_cond_timedwait(cond, lock, &abstime); if (error == ETIMEDOUT || error == ETIME) break; } /* Implicitly unlocks the mutex. */ thd->EXIT_COND(NULL); return ret; } static int request_dump(THD *thd, MYSQL* mysql, Master_info* mi, bool *suppress_warnings) { DBUG_ENTER("request_dump"); const int BINLOG_NAME_INFO_SIZE= strlen(mi->get_master_log_name()); int error= 1; size_t command_size= 0; enum_server_command command= mi->is_auto_position() ? COM_BINLOG_DUMP_GTID : COM_BINLOG_DUMP; uchar* command_buffer= NULL; ushort binlog_flags= 0; if (RUN_HOOK(binlog_relay_io, before_request_transmit, (thd, mi, binlog_flags))) goto err; *suppress_warnings= false; if (command == COM_BINLOG_DUMP_GTID) { // get set of GTIDs Sid_map sid_map(NULL/*no lock needed*/); Gtid_set gtid_executed(&sid_map); global_sid_lock->wrlock(); gtid_state->dbug_print(); /* We are unsure whether I/O thread retrieved the last gtid transaction completely or not (before it is going down because of a crash/normal shutdown/normal stop slave io_thread). It is possible that I/O thread would have retrieved and written only partial transaction events. So We request Master to send the last gtid event once again. We do this by removing the last I/O thread retrieved gtid event from "Retrieved_gtid_set". Possible cases: 1) I/O thread would have retrieved full transaction already in the first time itself, but retrieving them again will not cause problem because GTID number is same, Hence SQL thread will not commit it again. 2) I/O thread would have retrieved full transaction already and SQL thread would have already executed it. In that case, We are not going remove last retrieved gtid from "Retrieved_gtid_set" otherwise we will see gaps in "Retrieved set". The same case is handled in the below code. Please note there will be paritial transactions written in relay log but they will not cause any problem incase of transactional tables. But incase of non-transaction tables, partial trx will create inconsistency between master and slave. In that case, users need to check manually. */ Gtid_set * retrieved_set= (const_cast<Gtid_set *>(mi->rli->get_gtid_set())); Gtid *last_retrieved_gtid= mi->rli->get_last_retrieved_gtid(); /* Remove last_retrieved_gtid only if it is not part of executed_gtid_set */ if (!last_retrieved_gtid->empty() && !gtid_state->get_logged_gtids()->contains_gtid(*last_retrieved_gtid)) { if (retrieved_set->_remove_gtid(*last_retrieved_gtid) != RETURN_STATUS_OK) { global_sid_lock->unlock(); goto err; } } if (gtid_executed.add_gtid_set(mi->rli->get_gtid_set()) != RETURN_STATUS_OK || gtid_executed.add_gtid_set(gtid_state->get_logged_gtids()) != RETURN_STATUS_OK) { global_sid_lock->unlock(); goto err; } global_sid_lock->unlock(); // allocate buffer size_t encoded_data_size= gtid_executed.get_encoded_length(); size_t allocation_size= ::BINLOG_FLAGS_INFO_SIZE + ::BINLOG_SERVER_ID_INFO_SIZE + ::BINLOG_NAME_SIZE_INFO_SIZE + BINLOG_NAME_INFO_SIZE + ::BINLOG_POS_INFO_SIZE + ::BINLOG_DATA_SIZE_INFO_SIZE + encoded_data_size + 1; if (!(command_buffer= (uchar *) my_malloc(allocation_size, MYF(MY_WME)))) goto err; uchar* ptr_buffer= command_buffer; DBUG_PRINT("info", ("Do I know something about the master? (binary log's name %s - auto position %d).", mi->get_master_log_name(), mi->is_auto_position())); /* Note: binlog_flags is always 0. However, in versions up to 5.6 RC, the master would check the lowest bit and do something unexpected if it was set; in early versions of 5.6 it would also use the two next bits. Therefore, for backward compatibility, if we ever start to use the flags, we should leave the three lowest bits unused. */ int2store(ptr_buffer, binlog_flags); ptr_buffer+= ::BINLOG_FLAGS_INFO_SIZE; int4store(ptr_buffer, server_id); ptr_buffer+= ::BINLOG_SERVER_ID_INFO_SIZE; int4store(ptr_buffer, BINLOG_NAME_INFO_SIZE); ptr_buffer+= ::BINLOG_NAME_SIZE_INFO_SIZE; memset(ptr_buffer, 0, BINLOG_NAME_INFO_SIZE); ptr_buffer+= BINLOG_NAME_INFO_SIZE; int8store(ptr_buffer, 4LL); ptr_buffer+= ::BINLOG_POS_INFO_SIZE; int4store(ptr_buffer, encoded_data_size); ptr_buffer+= ::BINLOG_DATA_SIZE_INFO_SIZE; gtid_executed.encode(ptr_buffer); ptr_buffer+= encoded_data_size; command_size= ptr_buffer - command_buffer; DBUG_ASSERT(command_size == (allocation_size - 1)); } else { size_t allocation_size= ::BINLOG_POS_OLD_INFO_SIZE + BINLOG_NAME_INFO_SIZE + ::BINLOG_FLAGS_INFO_SIZE + ::BINLOG_SERVER_ID_INFO_SIZE + 1; if (!(command_buffer= (uchar *) my_malloc(allocation_size, MYF(MY_WME)))) goto err; uchar* ptr_buffer= command_buffer; int4store(ptr_buffer, mi->get_master_log_pos()); ptr_buffer+= ::BINLOG_POS_OLD_INFO_SIZE; // See comment regarding binlog_flags above. int2store(ptr_buffer, binlog_flags); ptr_buffer+= ::BINLOG_FLAGS_INFO_SIZE; int4store(ptr_buffer, server_id); ptr_buffer+= ::BINLOG_SERVER_ID_INFO_SIZE; memcpy(ptr_buffer, mi->get_master_log_name(), BINLOG_NAME_INFO_SIZE); ptr_buffer+= BINLOG_NAME_INFO_SIZE; command_size= ptr_buffer - command_buffer; DBUG_ASSERT(command_size == (allocation_size - 1)); } if (simple_command(mysql, command, command_buffer, command_size, 1)) { /* Something went wrong, so we will just reconnect and retry later in the future, we should do a better error analysis, but for now we just fill up the error log :-) */ if (mysql_errno(mysql) == ER_NET_READ_INTERRUPTED) *suppress_warnings= true; // Suppress reconnect warning else sql_print_error("Error on %s: %d %s, will retry in %d secs", command_name[command].str, mysql_errno(mysql), mysql_error(mysql), mi->connect_retry); goto err; } error= 0; err: my_free(command_buffer); DBUG_RETURN(error); } /* Read one event from the master SYNOPSIS read_event() mysql MySQL connection mi Master connection information suppress_warnings TRUE when a normal net read timeout has caused us to try a reconnect. We do not want to print anything to the error log in this case because this a anormal event in an idle server. RETURN VALUES 'packet_error' Error number Length of packet */ static ulong read_event(MYSQL* mysql, Master_info *mi, bool* suppress_warnings) { ulong len; DBUG_ENTER("read_event"); *suppress_warnings= FALSE; /* my_real_read() will time us out We check if we were told to die, and if not, try reading again */ #ifndef DBUG_OFF if (disconnect_slave_event_count && !(mi->events_until_exit--)) DBUG_RETURN(packet_error); #endif len = cli_safe_read(mysql); if (len == packet_error || (long) len < 1) { if (mysql_errno(mysql) == ER_NET_READ_INTERRUPTED) { /* We are trying a normal reconnect after a read timeout; we suppress prints to .err file as long as the reconnect happens without problems */ *suppress_warnings= TRUE; } else sql_print_error("Error reading packet from server: %s ( server_errno=%d)", mysql_error(mysql), mysql_errno(mysql)); DBUG_RETURN(packet_error); } /* Check if eof packet */ if (len < 8 && mysql->net.read_pos[0] == 254) { sql_print_information("Slave: received end packet from server due to dump " "thread being killed on master. Dump threads are " "killed for example during master shutdown, " "explicitly by a user, or when the master receives " "a binlog send request from a duplicate server " "UUID <%s> : Error %s", ::server_uuid, mysql_error(mysql)); DBUG_RETURN(packet_error); } DBUG_PRINT("exit", ("len: %lu net->read_pos[4]: %d", len, mysql->net.read_pos[4])); DBUG_RETURN(len - 1); } /** If this is a lagging slave (specified with CHANGE MASTER TO MASTER_DELAY = X), delays accordingly. Also unlocks rli->data_lock. Design note: this is the place to unlock rli->data_lock. The lock must be held when reading delay info from rli, but it should not be held while sleeping. @param ev Event that is about to be executed. @param thd The sql thread's THD object. @param rli The sql thread's Relay_log_info structure. @retval 0 If the delay timed out and the event shall be executed. @retval nonzero If the delay was interrupted and the event shall be skipped. */ static int sql_delay_event(Log_event *ev, THD *thd, Relay_log_info *rli) { long sql_delay= rli->get_sql_delay(); DBUG_ENTER("sql_delay_event"); mysql_mutex_assert_owner(&rli->data_lock); DBUG_ASSERT(!rli->belongs_to_client()); int type= ev->get_type_code(); if (sql_delay && type != ROTATE_EVENT && type != FORMAT_DESCRIPTION_EVENT && type != START_EVENT_V3) { // The time when we should execute the event. time_t sql_delay_end= ev->when.tv_sec + rli->mi->clock_diff_with_master + sql_delay; // The current time. time_t now= my_time(0); // The time we will have to sleep before executing the event. unsigned long nap_time= 0; if (sql_delay_end > now) nap_time= sql_delay_end - now; DBUG_PRINT("info", ("sql_delay= %lu " "ev->when= %lu " "rli->mi->clock_diff_with_master= %lu " "now= %ld " "sql_delay_end= %ld " "nap_time= %ld", sql_delay, (long) ev->when.tv_sec, rli->mi->clock_diff_with_master, (long)now, (long)sql_delay_end, (long)nap_time)); if (sql_delay_end > now) { DBUG_PRINT("info", ("delaying replication event %lu secs", nap_time)); rli->start_sql_delay(sql_delay_end); mysql_mutex_unlock(&rli->data_lock); DBUG_RETURN(slave_sleep(thd, nap_time, sql_slave_killed, rli)); } } mysql_mutex_unlock(&rli->data_lock); DBUG_RETURN(0); } /** a sort_dynamic function on ulong type returns as specified by @c qsort_cmp */ int ulong_cmp(ulong *id1, ulong *id2) { return *id1 < *id2? -1 : (*id1 > *id2? 1 : 0); } /** Applies the given event and advances the relay log position. This is needed by the sql thread to execute events from the binlog, and by clients executing BINLOG statements. Conceptually, this function does: @code ev->apply_event(rli); ev->update_pos(rli); @endcode It also does the following maintainance: - Initializes the thread's server_id and time; and the event's thread. - If !rli->belongs_to_client() (i.e., if it belongs to the slave sql thread instead of being used for executing BINLOG statements), it does the following things: (1) skips events if it is needed according to the server id or slave_skip_counter; (2) unlocks rli->data_lock; (3) sleeps if required by 'CHANGE MASTER TO MASTER_DELAY=X'; (4) maintains the running state of the sql thread (rli->thread_state). - Reports errors as needed. @param ptr_ev a pointer to a reference to the event to apply. @param thd The client thread that executes the event (i.e., the slave sql thread if called from a replication slave, or the client thread if called to execute a BINLOG statement). @param rli The relay log info (i.e., the slave's rli if called from a replication slave, or the client's thd->rli_fake if called to execute a BINLOG statement). @note MTS can store NULL to @c ptr_ev location to indicate the event is taken over by a Worker. @retval SLAVE_APPLY_EVENT_AND_UPDATE_POS_OK OK. @retval SLAVE_APPLY_EVENT_AND_UPDATE_POS_APPLY_ERROR Error calling ev->apply_event(). @retval SLAVE_APPLY_EVENT_AND_UPDATE_POS_UPDATE_POS_ERROR No error calling ev->apply_event(), but error calling ev->update_pos(). @retval SLAVE_APPLY_EVENT_AND_UPDATE_POS_APPEND_JOB_ERROR append_item_to_jobs() failed, thread was killed while waiting for successful enqueue on worker. */ enum enum_slave_apply_event_and_update_pos_retval apply_event_and_update_pos(Log_event** ptr_ev, THD* thd, Relay_log_info* rli) { int exec_res= 0; bool skip_event= FALSE; Log_event *ev= *ptr_ev; Log_event::enum_skip_reason reason= Log_event::EVENT_SKIP_NOT; DBUG_ENTER("apply_event_and_update_pos"); DBUG_PRINT("exec_event",("%s(type_code: %d; server_id: %d)", ev->get_type_str(), ev->get_type_code(), ev->server_id)); DBUG_PRINT("info", ("thd->options: %s%s; rli->last_event_start_time: %lu", FLAGSTR(thd->variables.option_bits, OPTION_NOT_AUTOCOMMIT), FLAGSTR(thd->variables.option_bits, OPTION_BEGIN), (ulong) rli->last_event_start_time)); /* Execute the event to change the database and update the binary log coordinates, but first we set some data that is needed for the thread. The event will be executed unless it is supposed to be skipped. Queries originating from this server must be skipped. Low-level events (Format_description_log_event, Rotate_log_event, Stop_log_event) from this server must also be skipped. But for those we don't want to modify 'group_master_log_pos', because these events did not exist on the master. Format_description_log_event is not completely skipped. Skip queries specified by the user in 'slave_skip_counter'. We can't however skip events that has something to do with the log files themselves. Filtering on own server id is extremely important, to ignore execution of events created by the creation/rotation of the relay log (remember that now the relay log starts with its Format_desc, has a Rotate etc). */ /* Set the unmasked and actual server ids from the event */ thd->server_id = ev->server_id; // use the original server id for logging thd->unmasked_server_id = ev->unmasked_server_id; thd->set_time(); // time the query thd->lex->current_select= 0; if (!ev->when.tv_sec) my_micro_time_to_timeval(my_micro_time(), &ev->when); ev->thd = thd; // because up to this point, ev->thd == 0 if (!(rli->is_mts_recovery() && bitmap_is_set(&rli->recovery_groups, rli->mts_recovery_index))) { reason= ev->shall_skip(rli); } #ifndef DBUG_OFF if (rli->is_mts_recovery()) { DBUG_PRINT("mts", ("Mts is recovering %d, number of bits set %d, " "bitmap is set %d, index %lu.\n", rli->is_mts_recovery(), bitmap_bits_set(&rli->recovery_groups), bitmap_is_set(&rli->recovery_groups, rli->mts_recovery_index), rli->mts_recovery_index)); } #endif if (reason == Log_event::EVENT_SKIP_COUNT) { sql_slave_skip_counter= --rli->slave_skip_counter; skip_event= TRUE; } if (reason == Log_event::EVENT_SKIP_NOT) { my_io_perf_t start_perf_read, start_perf_read_blob, start_perf_read_primary, start_perf_read_secondary; ulonglong init_timer; /* Initialize for user_statistics, see dispatch_command */ thd->reset_user_stats_counters(); start_perf_read = thd->io_perf_read; start_perf_read_blob = thd->io_perf_read_blob; start_perf_read_primary = thd->io_perf_read_primary; start_perf_read_secondary = thd->io_perf_read_secondary; // Sleeps if needed, and unlocks rli->data_lock. if (sql_delay_event(ev, thd, rli)) DBUG_RETURN(SLAVE_APPLY_EVENT_AND_UPDATE_POS_OK); init_timer = my_timer_now(); exec_res= ev->apply_event(rli); if (!exec_res && (ev->worker != rli)) { if (ev->worker) { Slave_job_item item= {ev}, *job_item= &item; Slave_worker *w= (Slave_worker *) ev->worker; // specially marked group typically with OVER_MAX_DBS_IN_EVENT_MTS db:s bool need_sync= ev->is_mts_group_isolated(); // all events except BEGIN-query must be marked with a non-NULL Worker DBUG_ASSERT(((Slave_worker*) ev->worker) == rli->last_assigned_worker); DBUG_PRINT("Log_event::apply_event:", ("-> job item data %p to W_%lu", job_item->data, w->id)); // Reset mts in-group state if (rli->mts_group_status == Relay_log_info::MTS_END_GROUP) { // CGAP cleanup for (uint i= rli->curr_group_assigned_parts.elements; i > 0; i--) delete_dynamic_element(&rli-> curr_group_assigned_parts, i - 1); // reset the B-group and Gtid-group marker rli->curr_group_seen_begin= rli->curr_group_seen_gtid= false; rli->last_assigned_worker= NULL; } /* Stroring GAQ index of the group that the event belongs to in the event. Deferred events are handled similarly below. */ ev->mts_group_idx= rli->gaq->assigned_group_index; bool append_item_to_jobs_error= false; if (rli->curr_group_da.elements > 0) { /* the current event sorted out which partion the current group belongs to. It's time now to processed deferred array events. */ for (uint i= 0; i < rli->curr_group_da.elements; i++) { Slave_job_item da_item; get_dynamic(&rli->curr_group_da, (uchar*) &da_item.data, i); DBUG_PRINT("mts", ("Assigning job %llu to worker %lu", ((Log_event* )da_item.data)->log_pos, w->id)); static_cast<Log_event*>(da_item.data)->mts_group_idx= rli->gaq->assigned_group_index; // similarly to above if (!append_item_to_jobs_error) append_item_to_jobs_error= append_item_to_jobs(&da_item, w, rli); if (append_item_to_jobs_error) delete static_cast<Log_event*>(da_item.data); } if (rli->curr_group_da.elements > rli->curr_group_da.max_element) { // reallocate to less mem rli->curr_group_da.elements= rli->curr_group_da.max_element; rli->curr_group_da.max_element= 0; freeze_size(&rli->curr_group_da); // restores max_element } rli->curr_group_da.elements= 0; } if (append_item_to_jobs_error) DBUG_RETURN(SLAVE_APPLY_EVENT_AND_UPDATE_POS_APPEND_JOB_ERROR); DBUG_PRINT("mts", ("Assigning job %llu to worker %lu\n", ((Log_event* )job_item->data)->log_pos, w->id)); /* Notice `ev' instance can be destoyed after `append()' */ if (append_item_to_jobs(job_item, w, rli)) DBUG_RETURN(SLAVE_APPLY_EVENT_AND_UPDATE_POS_APPEND_JOB_ERROR); if (need_sync) { /* combination of over-max db:s and end of the current group forces to wait for the assigned groups completion by assigned to the event worker. Indeed MTS group status could be safely set to MTS_NOT_IN_GROUP after wait_() returns. No need to know a possible error out of synchronization call. */ (void) wait_for_workers_to_finish(rli); } } *ptr_ev= NULL; // announcing the event is passed to w-worker if (log_warnings > 1 && rli->is_parallel_exec() && rli->mts_events_assigned % 1024 == 1) { time_t my_now= my_time(0); if ((my_now - rli->mts_last_online_stat) >= mts_online_stat_period) { sql_print_information("Multi-threaded slave statistics: " "seconds elapsed = %lu; " "events assigned = %llu; " "worker queues filled over overrun level = %lu; " "waited due a Worker queue full = %lu; " "waited due the total size = %lu; " "slept when Workers occupied = %lu ", static_cast<unsigned long> (my_now - rli->mts_last_online_stat), rli->mts_events_assigned, rli->mts_wq_overrun_cnt, rli->mts_wq_overfill_cnt, rli->wq_size_waits_cnt, rli->mts_wq_no_underrun_cnt); rli->mts_last_online_stat= my_now; } } } else { ulonglong wall_time = my_timer_since(init_timer); /* Update counters for USER_STATS */ bool is_other= FALSE; bool is_xid= FALSE; bool update_slave_stats= FALSE; if (ev->get_type_code() < ENUM_END_EVENT) { repl_event_counts[ev->get_type_code()] += 1; repl_event_times[ev->get_type_code()] += wall_time; } else { repl_event_count_other += 1; repl_event_time_other += wall_time; } /* TODO: handle WRITE_ROWS_EVENT, UPDATE_ROWS_EVENT, DELETE_ROWS_EVENT */ switch (ev->get_type_code()) { case XID_EVENT: is_xid= TRUE; update_slave_stats= TRUE; break; case QUERY_EVENT: update_slave_stats= TRUE; break; default: break; } if (update_slave_stats) { if (exec_res == 0) { rli->update_peak_lag(ev->when.tv_sec); } USER_STATS *us= thd_get_user_stats(thd); update_user_stats_after_statement(us, thd, wall_time, is_other, is_xid, &start_perf_read, &start_perf_read_blob, &start_perf_read_primary, &start_perf_read_secondary); } } } else mysql_mutex_unlock(&rli->data_lock); DBUG_PRINT("info", ("apply_event error = %d", exec_res)); if (exec_res == 0) { /* Positions are not updated here when an XID is processed. To make a slave crash-safe, positions must be updated while processing a XID event and as such do not need to be updated here again. However, if the event needs to be skipped, this means that it will not be processed and then positions need to be updated here. See sql/rpl_rli.h for further details. */ int error= 0; if (*ptr_ev && (ev->get_type_code() != XID_EVENT || skip_event || (rli->is_mts_recovery() && !is_gtid_event(ev) && (ev->ends_group() || !rli->mts_recovery_group_seen_begin) && bitmap_is_set(&rli->recovery_groups, rli->mts_recovery_index)))) { #ifndef DBUG_OFF /* This only prints information to the debug trace. TODO: Print an informational message to the error log? */ static const char *const explain[] = { // EVENT_SKIP_NOT, "not skipped", // EVENT_SKIP_IGNORE, "skipped because event should be ignored", // EVENT_SKIP_COUNT "skipped because event skip counter was non-zero" }; DBUG_PRINT("info", ("OPTION_BEGIN: %d; IN_STMT: %d", MY_TEST(thd->variables.option_bits & OPTION_BEGIN), rli->get_flag(Relay_log_info::IN_STMT))); DBUG_PRINT("skip_event", ("%s event was %s", ev->get_type_str(), explain[reason])); #endif error= ev->update_pos(rli); #ifndef DBUG_OFF DBUG_PRINT("info", ("update_pos error = %d", error)); if (!rli->belongs_to_client()) { char buf[22]; DBUG_PRINT("info", ("group %s %s", llstr(rli->get_group_relay_log_pos(), buf), rli->get_group_relay_log_name())); DBUG_PRINT("info", ("event %s %s", llstr(rli->get_event_relay_log_pos(), buf), rli->get_event_relay_log_name())); } #endif } else { DBUG_ASSERT(*ptr_ev == ev || rli->is_parallel_exec() || (!ev->worker && (ev->get_type_code() == INTVAR_EVENT || ev->get_type_code() == RAND_EVENT || ev->get_type_code() == USER_VAR_EVENT))); rli->inc_event_relay_log_pos(); } if (!error && rli->is_mts_recovery() && ev->get_type_code() != ROTATE_EVENT && ev->get_type_code() != FORMAT_DESCRIPTION_EVENT && ev->get_type_code() != PREVIOUS_GTIDS_LOG_EVENT) { if (ev->starts_group()) { rli->mts_recovery_group_seen_begin= true; } else if ((ev->ends_group() || !rli->mts_recovery_group_seen_begin) && !is_gtid_event(ev)) { rli->mts_recovery_index++; if (--rli->mts_recovery_group_cnt == 0) { rli->mts_recovery_index= 0; sql_print_information("Slave: MTS Recovery has completed at " "relay log %s, position %llu " "master log %s, position %llu.", rli->get_group_relay_log_name(), rli->get_group_relay_log_pos(), rli->get_group_master_log_name(), rli->get_group_master_log_pos()); #ifndef DBUG_OFF /* Few tests wait for UNTIL_SQL_AFTER_MTS_GAPS completion. Due to exisiting convention the status won't change prior to slave restarts. So making of UNTIL_SQL_AFTER_MTS_GAPS completion isdone here, and only in the debug build to make the test to catch the change despite a faulty design of UNTIL checking before execution. */ if (rli->until_condition == Relay_log_info::UNTIL_SQL_AFTER_MTS_GAPS) { rli->until_condition= Relay_log_info::UNTIL_DONE; } #endif // reset the Worker tables to remove last slave session time info if ((error= rli->mts_finalize_recovery())) { (void) Rpl_info_factory::reset_workers(rli); } } rli->mts_recovery_group_seen_begin= false; if (!error) error= rli->flush_info(true); } } if (error) { /* The update should not fail, so print an error message and return an error code. TODO: Replace this with a decent error message when merged with BUG#24954 (which adds several new error message). */ char buf[22]; rli->report(ERROR_LEVEL, ER_UNKNOWN_ERROR, "It was not possible to update the positions" " of the relay log information: the slave may" " be in an inconsistent state." " Stopped in %s position %s", rli->get_group_relay_log_name(), llstr(rli->get_group_relay_log_pos(), buf)); DBUG_RETURN(SLAVE_APPLY_EVENT_AND_UPDATE_POS_UPDATE_POS_ERROR); } } DBUG_RETURN(exec_res ? SLAVE_APPLY_EVENT_AND_UPDATE_POS_APPLY_ERROR : SLAVE_APPLY_EVENT_AND_UPDATE_POS_OK); } /** Let the worker applying the current group to rollback and gracefully finish its work before. @param rli The slave's relay log info. @param ev a pointer to the event on hold before applying this rollback procedure. @retval false The rollback succeeded. @retval true There was an error while injecting events. */ static bool coord_handle_partial_binlogged_transaction(Relay_log_info *rli, const Log_event *ev) { DBUG_ENTER("coord_handle_partial_binlogged_transaction"); /* This function is called holding the rli->data_lock. We must return it still holding this lock, except in the case of returning error. */ mysql_mutex_assert_owner(&rli->data_lock); THD *thd= rli->info_thd; if (!rli->curr_group_seen_begin) { DBUG_PRINT("info",("Injecting QUERY(BEGIN) to rollback worker")); Log_event *begin_event= new Query_log_event(thd, STRING_WITH_LEN("BEGIN"), true, /* using_trans */ false, /* immediate */ true, /* suppress_use */ 0, /* error */ true /* ignore_command */); ((Query_log_event*) begin_event)->db= ""; begin_event->data_written= 0; begin_event->server_id= ev->server_id; /* We must be careful to avoid SQL thread increasing its position farther than the event that triggered this QUERY(BEGIN). */ begin_event->log_pos= ev->log_pos; begin_event->future_event_relay_log_pos= ev->future_event_relay_log_pos; if (apply_event_and_update_pos(&begin_event, thd, rli) != SLAVE_APPLY_EVENT_AND_UPDATE_POS_OK) { delete begin_event; DBUG_RETURN(true); } mysql_mutex_lock(&rli->data_lock); } DBUG_PRINT("info",("Injecting QUERY(ROLLBACK) to rollback worker")); Log_event *rollback_event= new Query_log_event(thd, STRING_WITH_LEN("ROLLBACK"), true, /* using_trans */ false, /* immediate */ true, /* suppress_use */ 0, /* error */ true /* ignore_command */); ((Query_log_event*) rollback_event)->db= ""; rollback_event->data_written= 0; rollback_event->server_id= ev->server_id; // Set a flag for this special ROLLBACK event so the slave worker // skips updating slave_gtid_info table. rollback_event->set_relay_log_event(); /* We must be careful to avoid SQL thread increasing its position farther than the event that triggered this QUERY(ROLLBACK). */ rollback_event->log_pos= ev->log_pos; rollback_event->future_event_relay_log_pos= ev->future_event_relay_log_pos; if (apply_event_and_update_pos(&rollback_event, thd, rli) != SLAVE_APPLY_EVENT_AND_UPDATE_POS_OK) { delete rollback_event; DBUG_RETURN(true); } mysql_mutex_lock(&rli->data_lock); DBUG_RETURN(false); } /** Top-level function for executing the next event in the relay log. This is called from the SQL thread. This function reads the event from the relay log, executes it, and advances the relay log position. It also handles errors, etc. This function may fail to apply the event for the following reasons: - The position specfied by the UNTIL condition of the START SLAVE command is reached. - It was not possible to read the event from the log. - The slave is killed. - An error occurred when applying the event, and the event has been tried slave_trans_retries times. If the event has been retried fewer times, 0 is returned. - init_info or init_relay_log_pos failed. (These are called if a failure occurs when applying the event.) - An error occurred when updating the binlog position. @retval 0 The event was applied. @retval 1 The event was not applied. */ static int exec_relay_log_event(THD* thd, Relay_log_info* rli) { DBUG_ENTER("exec_relay_log_event"); /* We acquire this mutex since we need it for all operations except event execution. But we will release it in places where we will wait for something for example inside of next_event(). */ mysql_mutex_lock(&rli->data_lock); /* UNTIL_SQL_AFTER_GTIDS requires special handling since we have to check whether the until_condition is satisfied *before* the SQL threads goes on a wait inside next_event() for the relay log to grow. This is reuired since if we have already applied the last event in the waiting set but since he check happens only at the start of the next event we may end up waiting forever the next event is not available or is delayed. */ if (rli->until_condition == Relay_log_info::UNTIL_SQL_AFTER_GTIDS && rli->is_until_satisfied(thd, NULL)) { rli->abort_slave= 1; mysql_mutex_unlock(&rli->data_lock); DBUG_RETURN(1); } Log_event *ev = next_event(rli), **ptr_ev; DBUG_ASSERT(rli->info_thd==thd); if (sql_slave_killed(thd,rli)) { mysql_mutex_unlock(&rli->data_lock); delete ev; DBUG_RETURN(1); } if (ev) { enum enum_slave_apply_event_and_update_pos_retval exec_res; ptr_ev= &ev; /* Even if we don't execute this event, we keep the master timestamp, so that seconds behind master shows correct delta (there are events that are not replayed, so we keep falling behind). If it is an artificial event, or a relay log event (IO thread generated event) or ev->when is set to 0, or a FD from master, or a heartbeat event with server_id '0' then we don't update the last_master_timestamp. */ if (!(rli->is_parallel_exec() || ev->is_artificial_event() || ev->is_relay_log_event() || ev->when.tv_sec == 0 || ev->get_type_code() == FORMAT_DESCRIPTION_EVENT || ev->server_id == 0 || ev->get_type_code() == ROTATE_EVENT || ev->get_type_code() == PREVIOUS_GTIDS_LOG_EVENT)) { DBUG_ASSERT(ev->get_type_code() != ROTATE_EVENT && ev->get_type_code() != PREVIOUS_GTIDS_LOG_EVENT); rli->last_master_timestamp= ev->when.tv_sec + (time_t) ev->exec_time; DBUG_ASSERT(rli->last_master_timestamp >= 0); } /* This tests if the position of the beginning of the current event hits the UNTIL barrier. MTS: since the master and the relay-group coordinates change asynchronously logics of rli->is_until_satisfied() can't apply. A special UNTIL_SQL_AFTER_MTS_GAPS is still deployed here temporarily (see is_until_satisfied todo). */ if (rli->until_condition != Relay_log_info::UNTIL_NONE && rli->until_condition != Relay_log_info::UNTIL_SQL_AFTER_GTIDS && rli->is_until_satisfied(thd, ev)) { /* Setting abort_slave flag because we do not want additional message about error in query execution to be printed. */ rli->abort_slave= 1; mysql_mutex_unlock(&rli->data_lock); delete ev; DBUG_RETURN(1); } { /** The following failure injecion works in cooperation with tests setting @@global.debug= 'd,incomplete_group_in_relay_log'. Xid or Commit events are not executed to force the slave sql read hanging if the realy log does not have any more events. */ DBUG_EXECUTE_IF("incomplete_group_in_relay_log", if ((ev->get_type_code() == XID_EVENT) || ((ev->get_type_code() == QUERY_EVENT) && strcmp("COMMIT", ((Query_log_event *) ev)->query) == 0)) { DBUG_ASSERT(thd->transaction.all.cannot_safely_rollback()); rli->abort_slave= 1; mysql_mutex_unlock(&rli->data_lock); delete ev; rli->inc_event_relay_log_pos(); DBUG_RETURN(0); };); } /* GTID protocol will put a FORMAT_DESCRIPTION_EVENT from the master with log_pos != 0 after each (re)connection if auto positioning is enabled. This means that the SQL thread might have already started to apply the current group but, as the IO thread had to reconnect, it left this group incomplete and will start it again from the beginning. So, before applying this FORMAT_DESCRIPTION_EVENT, we must let the worker roll back the current group and gracefully finish its work, before starting to apply the new (complete) copy of the group. */ if (ev->get_type_code() == FORMAT_DESCRIPTION_EVENT && ev->server_id != ::server_id && ev->log_pos != 0 && rli->is_parallel_exec() && rli->curr_group_seen_gtid) { if (coord_handle_partial_binlogged_transaction(rli, ev)) /* In the case of an error, coord_handle_partial_binlogged_transaction will not try to get the rli->data_lock again. */ DBUG_RETURN(1); } /* ptr_ev can change to NULL indicating MTS coorinator passed to a Worker */ exec_res= apply_event_and_update_pos(ptr_ev, thd, rli); /* Note: the above call to apply_event_and_update_pos executes mysql_mutex_unlock(&rli->data_lock); */ /* For deferred events, the ptr_ev is set to NULL in Deferred_log_events::add() function. Hence deferred events wont be deleted here. They will be deleted in Deferred_log_events::rewind() funciton. */ if (*ptr_ev) { DBUG_ASSERT(*ptr_ev == ev); // event remains to belong to Coordinator DBUG_EXECUTE_IF("dbug.calculate_sbm_after_previous_gtid_log_event", { if (ev->get_type_code() == PREVIOUS_GTIDS_LOG_EVENT) { const char act[]= "now signal signal.reached wait_for signal.done_sbm_calculation"; DBUG_ASSERT(opt_debug_sync_timeout > 0); DBUG_ASSERT(!debug_sync_set_action(thd, STRING_WITH_LEN(act))); } };); /* Format_description_log_event should not be deleted because it will be used to read info about the relay log's format; it will be deleted when the SQL thread does not need it, i.e. when this thread terminates. ROWS_QUERY_LOG_EVENT is destroyed at the end of the current statement clean-up routine. */ if (ev->get_type_code() != FORMAT_DESCRIPTION_EVENT && ev->get_type_code() != ROWS_QUERY_LOG_EVENT) { DBUG_PRINT("info", ("Deleting the event after it has been executed")); delete ev; ev= NULL; } } /* exec_res == SLAVE_APPLY_EVENT_AND_UPDATE_POS_UPDATE_POS_ERROR update_log_pos failed: this should not happen, so we don't retry. exec_res == SLAVE_APPLY_EVENT_AND_UPDATE_POS_APPEND_JOB_ERROR append_item_to_jobs() failed, this happened because thread was killed while waiting for enqueue on worker. */ if (exec_res >= SLAVE_APPLY_EVENT_AND_UPDATE_POS_UPDATE_POS_ERROR) { delete ev; DBUG_RETURN(1); } if (slave_trans_retries) { int UNINIT_VAR(temp_err); bool silent= false; if (exec_res && !is_mts_worker(thd) /* no reexecution in MTS mode */ && (temp_err= rli->has_temporary_error(thd, 0, &silent)) && !thd->transaction.all.cannot_safely_rollback()) { const char *errmsg; /* We were in a transaction which has been rolled back because of a temporary error; let's seek back to BEGIN log event and retry it all again. Note, if lock wait timeout (innodb_lock_wait_timeout exceeded) there is no rollback since 5.0.13 (ref: manual). We have to not only seek but also a) init_info(), to seek back to hot relay log's start for later (for when we will come back to this hot log after re-processing the possibly existing old logs where BEGIN is: check_binlog_magic() will then need the cache to be at position 0 (see comments at beginning of init_info()). b) init_relay_log_pos(), because the BEGIN may be an older relay log. */ if (rli->trans_retries < slave_trans_retries) { /* We need to figure out if there is a test case that covers this part. \Alfranio. */ if (global_init_info(rli->mi, false, SLAVE_SQL)) sql_print_error("Failed to initialize the master info structure"); else if (rli->init_relay_log_pos(rli->get_group_relay_log_name(), rli->get_group_relay_log_pos(), true/*need_data_lock=true*/, &errmsg, 1)) sql_print_error("Error initializing relay log position: %s", errmsg); else { exec_res= SLAVE_APPLY_EVENT_AND_UPDATE_POS_OK; rli->cleanup_context(thd, 1); /* chance for concurrent connection to get more locks */ slave_sleep(thd, min<ulong>(rli->trans_retries, MAX_SLAVE_RETRY_PAUSE), sql_slave_killed, rli); mysql_mutex_lock(&rli->data_lock); // because of SHOW STATUS if (!silent) rli->trans_retries++; rli->retried_trans++; mysql_mutex_unlock(&rli->data_lock); DBUG_PRINT("info", ("Slave retries transaction " "rli->trans_retries: %lu", rli->trans_retries)); } } else { thd->is_fatal_error= 1; rli->set_fatal_error(); rli->report(ERROR_LEVEL, thd->get_stmt_da()->sql_errno(), "Slave SQL thread retried transaction %lu time(s) " "in vain, giving up. Consider raising the value of " "the slave_transaction_retries variable.", rli->trans_retries); } } else if ((exec_res && !temp_err) || (opt_using_transactions && rli->get_group_relay_log_pos() == rli->get_event_relay_log_pos())) { /* Only reset the retry counter if the entire group succeeded or failed with a non-transient error. On a successful event, the execution will proceed as usual; in the case of a non-transient error, the slave will stop with an error. */ rli->trans_retries= 0; // restart from fresh DBUG_PRINT("info", ("Resetting retry counter, rli->trans_retries: %lu", rli->trans_retries)); } } if (exec_res) delete ev; DBUG_RETURN(exec_res); } mysql_mutex_unlock(&rli->data_lock); rli->report(ERROR_LEVEL, ER_SLAVE_RELAY_LOG_READ_FAILURE, ER(ER_SLAVE_RELAY_LOG_READ_FAILURE), "\ Could not parse relay log event entry. The possible reasons are: the master's \ binary log is corrupted (you can check this by running 'mysqlbinlog' on the \ binary log), the slave's relay log is corrupted (you can check this by running \ 'mysqlbinlog' on the relay log), a network problem, or a bug in the master's \ or slave's MySQL code. If you want to check the master's binary log or slave's \ relay log, you will be able to know their names by issuing 'SHOW SLAVE STATUS' \ on this slave.\ "); DBUG_RETURN(1); } static bool check_io_slave_killed(THD *thd, Master_info *mi, const char *info) { if (io_slave_killed(thd, mi)) { if (info && log_warnings) sql_print_information("%s", info); return TRUE; } return FALSE; } /** @brief Try to reconnect slave IO thread. @details Terminates current connection to master, sleeps for @c mi->connect_retry msecs and initiates new connection with @c safe_reconnect(). Variable pointed by @c retry_count is increased - if it exceeds @c mi->retry_count then connection is not re-established and function signals error. Unless @c suppres_warnings is TRUE, a warning is put in the server error log when reconnecting. The warning message and messages used to report errors are taken from @c messages array. In case @c mi->retry_count is exceeded, no messages are added to the log. @param[in] thd Thread context. @param[in] mysql MySQL connection. @param[in] mi Master connection information. @param[in,out] retry_count Number of attempts to reconnect. @param[in] suppress_warnings TRUE when a normal net read timeout has caused to reconnecting. @param[in] messages Messages to print/log, see reconnect_messages[] array. @retval 0 OK. @retval 1 There was an error. */ static int try_to_reconnect(THD *thd, MYSQL *mysql, Master_info *mi, uint *retry_count, bool suppress_warnings, const char *messages[SLAVE_RECON_MSG_MAX]) { mi->slave_running= MYSQL_SLAVE_RUN_NOT_CONNECT; thd->proc_info= messages[SLAVE_RECON_MSG_WAIT]; #ifdef SIGNAL_WITH_VIO_SHUTDOWN thd->clear_active_vio(); #endif end_server(mysql); if ((*retry_count)++) { if (*retry_count > mi->retry_count) return 1; // Don't retry forever slave_sleep(thd, mi->connect_retry, io_slave_killed, mi); } if (check_io_slave_killed(thd, mi, messages[SLAVE_RECON_MSG_KILLED_WAITING])) return 1; thd->proc_info = messages[SLAVE_RECON_MSG_AFTER]; if (!suppress_warnings) { char buf[256], llbuff[22]; my_snprintf(buf, sizeof(buf), messages[SLAVE_RECON_MSG_FAILED], mi->get_io_rpl_log_name(), llstr(mi->get_master_log_pos(), llbuff)); /* Raise a warining during registering on master/requesting dump. Log a message reading event. */ if (messages[SLAVE_RECON_MSG_COMMAND][0]) { mi->report(WARNING_LEVEL, ER_SLAVE_MASTER_COM_FAILURE, ER(ER_SLAVE_MASTER_COM_FAILURE), messages[SLAVE_RECON_MSG_COMMAND], buf); } else { sql_print_information("%s", buf); } } if (safe_reconnect(thd, mysql, mi, 1) || io_slave_killed(thd, mi)) { if (log_warnings) sql_print_information("%s", messages[SLAVE_RECON_MSG_KILLED_AFTER]); return 1; } return 0; } /** Slave IO thread entry point. @param arg Pointer to Master_info struct that holds information for the IO thread. @return Always 0. */ pthread_handler_t handle_slave_io(void *arg) { THD *thd= NULL; // needs to be first for thread_stack bool thd_added= false; MYSQL *mysql; Master_info *mi = (Master_info*)arg; Relay_log_info *rli= mi->rli; char llbuff[22]; uint retry_count; bool suppress_warnings; int ret; int binlog_version; #ifndef DBUG_OFF uint retry_count_reg= 0, retry_count_dump= 0, retry_count_event= 0; #endif // needs to call my_thread_init(), otherwise we get a coredump in DBUG_ stuff my_thread_init(); DBUG_ENTER("handle_slave_io"); DBUG_ASSERT(mi->inited); mysql= NULL ; retry_count= 0; mysql_mutex_lock(&mi->run_lock); /* Inform waiting threads that slave has started */ mi->slave_run_id++; #ifndef DBUG_OFF mi->events_until_exit = disconnect_slave_event_count; #endif thd= new THD; // note that contructor of THD uses DBUG_ ! THD_CHECK_SENTRY(thd); mysql_mutex_lock(&mi->info_thd_lock); mi->info_thd = thd; mysql_mutex_unlock(&mi->info_thd_lock); pthread_detach_this_thread(); thd->thread_stack= (char*) &thd; // remember where our stack is mi->clear_error(); if (init_slave_thread(thd, SLAVE_THD_IO)) { mysql_cond_broadcast(&mi->start_cond); mysql_mutex_unlock(&mi->run_lock); sql_print_error("Failed during slave I/O thread initialization"); goto err; } mysql_mutex_lock(&LOCK_thread_count); add_global_thread(thd); thd_added= true; mysql_mutex_unlock(&LOCK_thread_count); mi->slave_running = 1; mi->abort_slave = 0; mysql_mutex_unlock(&mi->run_lock); mysql_cond_broadcast(&mi->start_cond); DBUG_PRINT("master_info",("log_file_name: '%s' position: %s", mi->get_master_log_name(), llstr(mi->get_master_log_pos(), llbuff))); /* This must be called before run any binlog_relay_io hooks */ my_pthread_setspecific_ptr(RPL_MASTER_INFO, mi); if (RUN_HOOK(binlog_relay_io, thread_start, (thd, mi))) { mi->report(ERROR_LEVEL, ER_SLAVE_FATAL_ERROR, ER(ER_SLAVE_FATAL_ERROR), "Failed to run 'thread_start' hook"); goto err; } if (!(mi->mysql = mysql = mysql_init(NULL))) { mi->report(ERROR_LEVEL, ER_SLAVE_FATAL_ERROR, ER(ER_SLAVE_FATAL_ERROR), "error in mysql_init()"); goto err; } THD_STAGE_INFO(thd, stage_connecting_to_master); // we can get killed during safe_connect if (!safe_connect(thd, mysql, mi)) { sql_print_information("Slave I/O thread: connected to master '%s@%s:%d'," "replication started in log '%s' at position %s", mi->get_user(), mi->host, mi->port, mi->get_io_rpl_log_name(), llstr(mi->get_master_log_pos(), llbuff)); } else { sql_print_information("Slave I/O thread killed while connecting to master"); goto err; } connected: ++relay_io_connected; DBUG_EXECUTE_IF("dbug.before_get_running_status_yes", { const char act[]= "now " "wait_for signal.io_thread_let_running"; DBUG_ASSERT(opt_debug_sync_timeout > 0); DBUG_ASSERT(!debug_sync_set_action(thd, STRING_WITH_LEN(act))); };); DBUG_EXECUTE_IF("dbug.calculate_sbm_after_previous_gtid_log_event", { /* Fake that thread started 3 mints ago */ thd->start_time.tv_sec-=180; };); mysql_mutex_lock(&mi->run_lock); mi->slave_running= MYSQL_SLAVE_RUN_CONNECT; mysql_mutex_unlock(&mi->run_lock); thd->slave_net = &mysql->net; THD_STAGE_INFO(thd, stage_checking_master_version); ret= get_master_version_and_clock(mysql, mi); if (!ret) ret= get_master_uuid(mysql, mi); if (!ret) ret= io_thread_init_commands(mysql, mi); if (ret == 1) /* Fatal error */ goto err; if (ret == 2) { if (check_io_slave_killed(mi->info_thd, mi, "Slave I/O thread killed" "while calling get_master_version_and_clock(...)")) goto err; suppress_warnings= FALSE; /* Try to reconnect because the error was caused by a transient network problem */ if (try_to_reconnect(thd, mysql, mi, &retry_count, suppress_warnings, reconnect_messages[SLAVE_RECON_ACT_REG])) goto err; goto connected; } mysql_mutex_lock(&mi->data_lock); binlog_version= mi->get_mi_description_event()->binlog_version; mysql_mutex_unlock(&mi->data_lock); if (binlog_version > 1) { /* Register ourselves with the master. */ THD_STAGE_INFO(thd, stage_registering_slave_on_master); if (register_slave_on_master(mysql, mi, &suppress_warnings)) { if (!check_io_slave_killed(thd, mi, "Slave I/O thread killed " "while registering slave on master")) { sql_print_error("Slave I/O thread couldn't register on master"); if (try_to_reconnect(thd, mysql, mi, &retry_count, suppress_warnings, reconnect_messages[SLAVE_RECON_ACT_REG])) goto err; } else goto err; goto connected; } DBUG_EXECUTE_IF("FORCE_SLAVE_TO_RECONNECT_REG", if (!retry_count_reg) { retry_count_reg++; sql_print_information("Forcing to reconnect slave I/O thread"); if (try_to_reconnect(thd, mysql, mi, &retry_count, suppress_warnings, reconnect_messages[SLAVE_RECON_ACT_REG])) goto err; goto connected; }); } DBUG_PRINT("info",("Starting reading binary log from master")); while (!io_slave_killed(thd,mi)) { THD_STAGE_INFO(thd, stage_requesting_binlog_dump); if (request_dump(thd, mysql, mi, &suppress_warnings)) { sql_print_error("Failed on request_dump()"); if (check_io_slave_killed(thd, mi, "Slave I/O thread killed while \ requesting master dump") || try_to_reconnect(thd, mysql, mi, &retry_count, suppress_warnings, reconnect_messages[SLAVE_RECON_ACT_DUMP])) goto err; goto connected; } DBUG_EXECUTE_IF("FORCE_SLAVE_TO_RECONNECT_DUMP", if (!retry_count_dump) { retry_count_dump++; sql_print_information("Forcing to reconnect slave I/O thread"); if (try_to_reconnect(thd, mysql, mi, &retry_count, suppress_warnings, reconnect_messages[SLAVE_RECON_ACT_DUMP])) goto err; goto connected; }); const char *event_buf; DBUG_ASSERT(mi->last_error().number == 0); while (!io_slave_killed(thd,mi)) { ulong event_len; /* We say "waiting" because read_event() will wait if there's nothing to read. But if there's something to read, it will not wait. The important thing is to not confuse users by saying "reading" whereas we're in fact receiving nothing. */ THD_STAGE_INFO(thd, stage_waiting_for_master_to_send_event); event_len= read_event(mysql, mi, &suppress_warnings); if (check_io_slave_killed(thd, mi, "Slave I/O thread killed while \ reading event")) goto err; DBUG_EXECUTE_IF("FORCE_SLAVE_TO_RECONNECT_EVENT", if (!retry_count_event) { retry_count_event++; sql_print_information("Forcing to reconnect slave I/O thread"); if (try_to_reconnect(thd, mysql, mi, &retry_count, suppress_warnings, reconnect_messages[SLAVE_RECON_ACT_EVENT])) goto err; goto connected; }); if (event_len == packet_error) { uint mysql_error_number= mysql_errno(mysql); switch (mysql_error_number) { case CR_NET_PACKET_TOO_LARGE: sql_print_error("\ Log entry on master is longer than slave_max_allowed_packet (%lu) on \ slave. If the entry is correct, restart the server with a higher value of \ slave_max_allowed_packet", slave_max_allowed_packet); mi->report(ERROR_LEVEL, ER_NET_PACKET_TOO_LARGE, "%s", "Got a packet bigger than 'slave_max_allowed_packet' bytes"); goto err; case ER_MASTER_FATAL_ERROR_READING_BINLOG: mi->report(ERROR_LEVEL, ER_MASTER_FATAL_ERROR_READING_BINLOG, ER(ER_MASTER_FATAL_ERROR_READING_BINLOG), mysql_error_number, mysql_error(mysql)); goto err; case ER_OUT_OF_RESOURCES: sql_print_error("\ Stopping slave I/O thread due to out-of-memory error from master"); mi->report(ERROR_LEVEL, ER_OUT_OF_RESOURCES, "%s", ER(ER_OUT_OF_RESOURCES)); goto err; } if (try_to_reconnect(thd, mysql, mi, &retry_count, suppress_warnings, reconnect_messages[SLAVE_RECON_ACT_EVENT])) goto err; goto connected; } // if (event_len == packet_error) relay_io_events++; relay_io_bytes += event_len; retry_count=0; // ok event, reset retry counter THD_STAGE_INFO(thd, stage_queueing_master_event_to_the_relay_log); event_buf= (const char*)mysql->net.read_pos + 1; DBUG_PRINT("info", ("IO thread received event of type %s", Log_event::get_type_str((Log_event_type)event_buf[EVENT_TYPE_OFFSET]))); if (RUN_HOOK(binlog_relay_io, after_read_event, (thd, mi,(const char*)mysql->net.read_pos + 1, event_len, &event_buf, &event_len))) { mi->report(ERROR_LEVEL, ER_SLAVE_FATAL_ERROR, ER(ER_SLAVE_FATAL_ERROR), "Failed to run 'after_read_event' hook"); goto err; } /* XXX: 'synced' should be updated by queue_event to indicate whether event has been synced to disk */ bool synced= 0; if (queue_event(mi, event_buf, event_len)) { mi->report(ERROR_LEVEL, ER_SLAVE_RELAY_LOG_WRITE_FAILURE, ER(ER_SLAVE_RELAY_LOG_WRITE_FAILURE), "could not queue event from master"); goto err; } if (RUN_HOOK(binlog_relay_io, after_queue_event, (thd, mi, event_buf, event_len, synced))) { mi->report(ERROR_LEVEL, ER_SLAVE_FATAL_ERROR, ER(ER_SLAVE_FATAL_ERROR), "Failed to run 'after_queue_event' hook"); goto err; } mysql_mutex_lock(&mi->data_lock); if (flush_master_info(mi, FALSE)) { mi->report(ERROR_LEVEL, ER_SLAVE_FATAL_ERROR, ER(ER_SLAVE_FATAL_ERROR), "Failed to flush master info."); mysql_mutex_unlock(&mi->data_lock); goto err; } mysql_mutex_unlock(&mi->data_lock); /* See if the relay logs take too much space. We don't lock mi->rli->log_space_lock here; this dirty read saves time and does not introduce any problem: - if mi->rli->ignore_log_space_limit is 1 but becomes 0 just after (so the clean value is 0), then we are reading only one more event as we should, and we'll block only at the next event. No big deal. - if mi->rli->ignore_log_space_limit is 0 but becomes 1 just after (so the clean value is 1), then we are going into wait_for_relay_log_space() for no reason, but this function will do a clean read, notice the clean value and exit immediately. */ #ifndef DBUG_OFF { char llbuf1[22], llbuf2[22]; DBUG_PRINT("info", ("log_space_limit=%s log_space_total=%s \ ignore_log_space_limit=%d", llstr(rli->log_space_limit,llbuf1), llstr(rli->log_space_total,llbuf2), (int) rli->ignore_log_space_limit)); } #endif if (rli->log_space_limit && rli->log_space_limit < rli->log_space_total && !rli->ignore_log_space_limit) if (wait_for_relay_log_space(rli)) { sql_print_error("Slave I/O thread aborted while waiting for relay \ log space"); goto err; } DBUG_EXECUTE_IF("stop_io_after_reading_gtid_log_event", if (event_buf[EVENT_TYPE_OFFSET] == GTID_LOG_EVENT) thd->killed= THD::KILLED_NO_VALUE; ); DBUG_EXECUTE_IF("stop_io_after_reading_query_log_event", if (event_buf[EVENT_TYPE_OFFSET] == QUERY_EVENT) thd->killed= THD::KILLED_NO_VALUE; ); DBUG_EXECUTE_IF("stop_io_after_reading_user_var_log_event", if (event_buf[EVENT_TYPE_OFFSET] == USER_VAR_EVENT) thd->killed= THD::KILLED_NO_VALUE; ); DBUG_EXECUTE_IF("stop_io_after_reading_table_map_event", if (event_buf[EVENT_TYPE_OFFSET] == TABLE_MAP_EVENT) thd->killed= THD::KILLED_NO_VALUE; ); DBUG_EXECUTE_IF("stop_io_after_reading_xid_log_event", if (event_buf[EVENT_TYPE_OFFSET] == XID_EVENT) thd->killed= THD::KILLED_NO_VALUE; ); DBUG_EXECUTE_IF("stop_io_after_reading_write_rows_log_event", if (event_buf[EVENT_TYPE_OFFSET] == WRITE_ROWS_EVENT) thd->killed= THD::KILLED_NO_VALUE; ); } } // error = 0; err: // print the current replication position sql_print_information("Slave I/O thread exiting, read up to log '%s', position %s", mi->get_io_rpl_log_name(), llstr(mi->get_master_log_pos(), llbuff)); (void) RUN_HOOK(binlog_relay_io, thread_stop, (thd, mi)); thd->reset_query(); thd->reset_db(NULL, 0); if (mysql) { /* Here we need to clear the active VIO before closing the connection with the master. The reason is that THD::awake() might be called from terminate_slave_thread() because somebody issued a STOP SLAVE. If that happends, the shutdown_active_vio() can be called in the middle of closing the VIO associated with the 'mysql' object, causing a crash. */ #ifdef SIGNAL_WITH_VIO_SHUTDOWN thd->clear_active_vio(); #endif mysql_close(mysql); mi->mysql=0; } mysql_mutex_lock(&mi->data_lock); write_ignored_events_info_to_relay_log(thd, mi); mysql_mutex_unlock(&mi->data_lock); THD_STAGE_INFO(thd, stage_waiting_for_slave_mutex_on_exit); mysql_mutex_lock(&mi->run_lock); /* Clean information used to start slave in order to avoid security issues. */ mi->reset_start_info(); /* Forget the relay log's format */ mysql_mutex_lock(&mi->data_lock); mi->set_mi_description_event(NULL); mysql_mutex_unlock(&mi->data_lock); DBUG_ASSERT(thd->net.buff != 0); net_end(&thd->net); // destructor will not free it, because net.vio is 0 thd->release_resources(); THD_CHECK_SENTRY(thd); if (thd_added) remove_global_thread(thd); delete thd; mi->abort_slave= 0; mi->slave_running= 0; mysql_mutex_lock(&mi->info_thd_lock); mi->info_thd= 0; mysql_mutex_unlock(&mi->info_thd_lock); /* Note: the order of the two following calls (first broadcast, then unlock) is important. Otherwise a killer_thread can execute between the calls and delete the mi structure leading to a crash! (see BUG#25306 for details) */ mysql_cond_broadcast(&mi->stop_cond); // tell the world we are done DBUG_EXECUTE_IF("simulate_slave_delay_at_terminate_bug38694", sleep(5);); mysql_mutex_unlock(&mi->run_lock); DBUG_LEAVE; // Must match DBUG_ENTER() my_thread_end(); ERR_remove_state(0); pthread_exit(0); return(0); // Avoid compiler warnings } /* Check the temporary directory used by commands like LOAD DATA INFILE. */ static int check_temp_dir(char* tmp_file) { int fd; MY_DIR *dirp; char tmp_dir[FN_REFLEN]; size_t tmp_dir_size; DBUG_ENTER("check_temp_dir"); /* Get the directory from the temporary file. */ dirname_part(tmp_dir, tmp_file, &tmp_dir_size); /* Check if the directory exists. */ if (!(dirp=my_dir(tmp_dir,MYF(MY_WME)))) DBUG_RETURN(1); my_dirend(dirp); /* Check permissions to create a file. */ //append the server UUID to the temp file name. char *unique_tmp_file_name= (char*)my_malloc((FN_REFLEN+TEMP_FILE_MAX_LEN)*sizeof(char), MYF(0)); sprintf(unique_tmp_file_name, "%s%s", tmp_file, server_uuid); if ((fd= mysql_file_create(key_file_misc, unique_tmp_file_name, CREATE_MODE, O_WRONLY | O_BINARY | O_EXCL | O_NOFOLLOW, MYF(MY_WME))) < 0) DBUG_RETURN(1); /* Clean up. */ mysql_file_close(fd, MYF(0)); mysql_file_delete(key_file_misc, unique_tmp_file_name, MYF(0)); my_free(unique_tmp_file_name); DBUG_RETURN(0); } /* Worker thread for the parallel execution of the replication events. */ pthread_handler_t handle_slave_worker(void *arg) { THD *thd; /* needs to be first for thread_stack */ bool thd_added= false; int error= 0; Slave_worker *w= (Slave_worker *) arg; Relay_log_info* rli= w->c_rli; ulong purge_cnt= 0; ulonglong purge_size= 0; ulong current_event_index = 0; ulong i = 0; struct slave_job_item _item, *job_item= &_item; /* Buffer lifetime extends across the entire runtime of the THD handle. */ static char proc_info_buf[256]= {0}; my_thread_init(); DBUG_ENTER("handle_slave_worker"); thd = new THD_SQL_slave(proc_info_buf, sizeof(proc_info_buf)); if (!thd) { sql_print_error("Failed during slave worker initialization"); goto err; } mysql_mutex_lock(&w->info_thd_lock); w->info_thd= thd; thd->thread_stack = (char*)&thd; mysql_mutex_unlock(&w->info_thd_lock); pthread_detach_this_thread(); if (init_slave_thread(thd, SLAVE_THD_WORKER)) { // todo make SQL thread killed sql_print_error("Failed during slave worker initialization"); goto err; } thd->init_for_queries(w); mysql_mutex_lock(&LOCK_thread_count); add_global_thread(thd); thd_added= true; mysql_mutex_unlock(&LOCK_thread_count); if (w->update_is_transactional()) { rli->report(ERROR_LEVEL, ER_SLAVE_FATAL_ERROR, "Error checking if the worker repository is transactional."); goto err; } mysql_mutex_lock(&w->jobs_lock); w->running_status= Slave_worker::RUNNING; mysql_cond_signal(&w->jobs_cond); mysql_mutex_unlock(&w->jobs_lock); DBUG_ASSERT(thd->is_slave_error == 0); while (!error) { error= slave_worker_exec_job(w, rli); } // force the flush to the worker info repository. w->flush_info(true); /* Cleanup after an error requires clear_error() go first. Otherwise assert(!all) in binlog_rollback() */ thd->clear_error(); w->cleanup_context(thd, error); mysql_mutex_lock(&w->jobs_lock); current_event_index = max(w->last_current_event_index, w->current_event_index); while(de_queue(&w->jobs, job_item)) { i++; if (i > current_event_index) { purge_size += ((Log_event*) (job_item->data))->data_written; purge_cnt++; } DBUG_ASSERT(job_item->data); delete static_cast<Log_event*>(job_item->data); } DBUG_ASSERT(w->jobs.len == 0); mysql_mutex_unlock(&w->jobs_lock); mysql_mutex_lock(&rli->pending_jobs_lock); rli->pending_jobs -= purge_cnt; rli->mts_pending_jobs_size -= purge_size; DBUG_ASSERT(rli->mts_pending_jobs_size < rli->mts_pending_jobs_size_max); mysql_mutex_unlock(&rli->pending_jobs_lock); /* In MTS case cleanup_after_session() has be called explicitly. TODO: to make worker thd be deleted before Slave_worker instance. */ if (thd->rli_slave) { w->cleanup_after_session(); thd->rli_slave= NULL; } mysql_mutex_lock(&w->jobs_lock); w->running_status= Slave_worker::NOT_RUNNING; if (log_warnings > 1) sql_print_information("Worker %lu statistics: " "events processed = %lu " "hungry waits = %lu " "priv queue overfills = %llu ", w->id, w->events_done, w->wq_size_waits_cnt, w->jobs.waited_overfill); mysql_cond_signal(&w->jobs_cond); // famous last goodbye mysql_mutex_unlock(&w->jobs_lock); err: if (thd) { /* The slave code is very bad. Notice that it is missing several clean up calls here. I've just added what was necessary to avoid valgrind errors. /Alfranio */ DBUG_ASSERT(thd->net.buff != 0); net_end(&thd->net); /* to avoid close_temporary_tables() closing temp tables as those are Coordinator's burden. */ thd->system_thread= NON_SYSTEM_THREAD; thd->release_resources(); THD_CHECK_SENTRY(thd); if (thd_added) remove_global_thread(thd); delete thd; } my_thread_end(); ERR_remove_state(0); pthread_exit(0); DBUG_RETURN(0); } /** Orders jobs by comparing relay log information. */ int mts_event_coord_cmp(LOG_POS_COORD *id1, LOG_POS_COORD *id2) { longlong filecmp= strcmp(id1->file_name, id2->file_name); longlong poscmp= id1->pos - id2->pos; return (filecmp < 0 ? -1 : (filecmp > 0 ? 1 : (poscmp < 0 ? -1 : (poscmp > 0 ? 1 : 0)))); } int mts_recovery_groups(Relay_log_info *rli) { Log_event *ev= NULL; const char *errmsg= NULL; bool error= FALSE; bool flag_group_seen_begin= FALSE; uint recovery_group_cnt= 0; bool not_reached_commit= true; DYNAMIC_ARRAY above_lwm_jobs; Slave_job_group job_worker; IO_CACHE log; File file; LOG_INFO linfo; my_off_t offset= 0; MY_BITMAP *groups= &rli->recovery_groups; DBUG_ENTER("mts_recovery_groups"); DBUG_ASSERT(rli->slave_parallel_workers == 0); /* Although mts_recovery_groups() is reentrant it returns early if the previous invocation raised any bit in recovery_groups bitmap. */ if (rli->is_mts_recovery()) DBUG_RETURN(0); /* Save relay log position to compare with worker's position. */ LOG_POS_COORD cp= { (char *) rli->get_group_master_log_name(), rli->get_group_master_log_pos() }; Format_description_log_event fdle(BINLOG_VERSION), *p_fdle= &fdle; if (!p_fdle->is_valid()) DBUG_RETURN(TRUE); /* Gathers information on valuable workers and stores it in above_lwm_jobs in asc ordered by the master binlog coordinates. */ my_init_dynamic_array(&above_lwm_jobs, sizeof(Slave_job_group), rli->recovery_parallel_workers, rli->recovery_parallel_workers); for (uint id= 0; id < rli->recovery_parallel_workers; id++) { Slave_worker *worker= Rpl_info_factory::create_worker(opt_rli_repository_id, id, rli, true); if (!worker) { error= TRUE; goto err; } LOG_POS_COORD w_last= { const_cast<char*>(worker->get_group_master_log_name()), worker->get_group_master_log_pos() }; if (mts_event_coord_cmp(&w_last, &cp) > 0) { /* Inserts information into a dynamic array for further processing. The jobs/workers are ordered by the last checkpoint positions workers have seen. */ job_worker.worker= worker; job_worker.checkpoint_log_pos= worker->checkpoint_master_log_pos; job_worker.checkpoint_log_name= worker->checkpoint_master_log_name; insert_dynamic(&above_lwm_jobs, (uchar*) &job_worker); } else { /* Deletes the worker because its jobs are included in the latest checkpoint. */ delete worker; } } /* In what follows, the group Recovery Bitmap is constructed. seek(lwm); while(w= next(above_lwm_w)) do read G if G == w->last_comm w.B << group_cnt++; RB |= w.B; break; else group_cnt++; while(!eof); continue; */ DBUG_ASSERT(!rli->recovery_groups_inited); if (above_lwm_jobs.elements != 0) { bitmap_init(groups, NULL, MTS_MAX_BITS_IN_GROUP, FALSE); rli->recovery_groups_inited= true; bitmap_clear_all(groups); } rli->mts_recovery_group_cnt= 0; for (uint it_job= 0; it_job < above_lwm_jobs.elements; it_job++) { Slave_worker *w= ((Slave_job_group *) dynamic_array_ptr(&above_lwm_jobs, it_job))->worker; LOG_POS_COORD w_last= { const_cast<char*>(w->get_group_master_log_name()), w->get_group_master_log_pos() }; bool checksum_detected= FALSE; sql_print_information("Slave: MTS group recovery relay log info based on Worker-Id %lu, " "group_relay_log_name %s, group_relay_log_pos %llu " "group_master_log_name %s, group_master_log_pos %llu", w->id, w->get_group_relay_log_name(), w->get_group_relay_log_pos(), w->get_group_master_log_name(), w->get_group_master_log_pos()); recovery_group_cnt= 0; not_reached_commit= true; if (rli->relay_log.find_log_pos(&linfo, rli->get_group_relay_log_name(), 1)) { error= TRUE; sql_print_error("Error looking for %s.", rli->get_group_relay_log_name()); goto err; } offset= rli->get_group_relay_log_pos(); for (int checking= 0 ; not_reached_commit; checking++) { if ((file= open_binlog_file(&log, linfo.log_file_name, &errmsg)) < 0) { error= TRUE; sql_print_error("%s", errmsg); goto err; } /* Looking for the actual relay checksum algorithm that is present in a FD at head events of the relay log. */ if (!checksum_detected) { int i= 0; while (i < 4 && (ev= Log_event::read_log_event(&log, (mysql_mutex_t*) 0, p_fdle, 0, NULL))) { if (ev->get_type_code() == FORMAT_DESCRIPTION_EVENT) { p_fdle->checksum_alg= ev->checksum_alg; checksum_detected= TRUE; } delete ev; i++; } if (!checksum_detected) { error= TRUE; sql_print_error("%s", "malformed or very old relay log which " "does not have FormatDescriptor"); goto err; } } my_b_seek(&log, offset); while (not_reached_commit && (ev= Log_event::read_log_event(&log, 0, p_fdle, opt_slave_sql_verify_checksum, NULL))) { DBUG_ASSERT(ev->is_valid()); if (ev->get_type_code() == FORMAT_DESCRIPTION_EVENT) p_fdle->checksum_alg= ev->checksum_alg; if (ev->get_type_code() == ROTATE_EVENT || ev->get_type_code() == FORMAT_DESCRIPTION_EVENT || ev->get_type_code() == PREVIOUS_GTIDS_LOG_EVENT) { delete ev; ev= NULL; continue; } DBUG_PRINT("mts", ("Event Recoverying relay log info " "group_mster_log_name %s, event_master_log_pos %llu type code %u.", linfo.log_file_name, ev->log_pos, ev->get_type_code())); if (ev->starts_group()) { flag_group_seen_begin= true; } else if ((ev->ends_group() || !flag_group_seen_begin) && !is_gtid_event(ev)) { int ret= 0; LOG_POS_COORD ev_coord= { (char *) rli->get_group_master_log_name(), ev->log_pos }; flag_group_seen_begin= false; recovery_group_cnt++; sql_print_information("Slave: MTS group recovery relay log info " "group_master_log_name %s, " "event_master_log_pos %llu.", rli->get_group_master_log_name(), ev->log_pos); if ((ret= mts_event_coord_cmp(&ev_coord, &w_last)) == 0) { #ifndef DBUG_OFF for (uint i= 0; i <= w->checkpoint_seqno; i++) { if (bitmap_is_set(&w->group_executed, i)) DBUG_PRINT("mts", ("Bit %u is set.", i)); else DBUG_PRINT("mts", ("Bit %u is not set.", i)); } #endif DBUG_PRINT("mts", ("Doing a shift ini(%lu) end(%lu).", (w->checkpoint_seqno + 1) - recovery_group_cnt, w->checkpoint_seqno)); for (uint i= (w->checkpoint_seqno + 1) - recovery_group_cnt, j= 0; i <= w->checkpoint_seqno; i++, j++) { if (bitmap_is_set(&w->group_executed, i)) { DBUG_PRINT("mts", ("Setting bit %u.", j)); bitmap_fast_test_and_set(groups, j); } } not_reached_commit= false; } else DBUG_ASSERT(ret < 0); } delete ev; ev= NULL; } end_io_cache(&log); mysql_file_close(file, MYF(MY_WME)); offset= BIN_LOG_HEADER_SIZE; if (not_reached_commit && rli->relay_log.find_next_log(&linfo, 1)) { error= TRUE; sql_print_error("Error looking for file after %s.", linfo.log_file_name); goto err; } } rli->mts_recovery_group_cnt= (rli->mts_recovery_group_cnt < recovery_group_cnt ? recovery_group_cnt : rli->mts_recovery_group_cnt); } DBUG_ASSERT(!rli->recovery_groups_inited || rli->mts_recovery_group_cnt <= groups->n_bits); err: for (uint it_job= 0; it_job < above_lwm_jobs.elements; it_job++) { get_dynamic(&above_lwm_jobs, (uchar *) &job_worker, it_job); delete job_worker.worker; } delete_dynamic(&above_lwm_jobs); if (rli->recovery_groups_inited && rli->mts_recovery_group_cnt == 0) { bitmap_free(groups); rli->recovery_groups_inited= false; } DBUG_RETURN(error ? ER_MTS_RECOVERY_FAILURE : 0); } /** Processing rli->gaq to find out the low-water-mark (lwm) coordinates which is stored into the cental recovery table. @param rli pointer to Relay-log-info of Coordinator @param period period of processing GAQ, normally derived from @c mts_checkpoint_period @param force if TRUE then hang in a loop till some progress @param need_data_lock False if rli->data_lock mutex is aquired by the caller. @return FALSE success, TRUE otherwise */ bool mts_checkpoint_routine(Relay_log_info *rli, ulonglong period, bool force, bool need_data_lock) { ulong cnt; bool error= FALSE; struct timespec curr_clock; DBUG_ENTER("checkpoint_routine"); #ifndef DBUG_OFF if (DBUG_EVALUATE_IF("check_slave_debug_group", 1, 0)) { if (!rli->gaq->count_done(rli)) DBUG_RETURN(FALSE); } #endif /* rli->checkpoint_group can have two possible values due to two possible status of the last (being scheduled) group. */ DBUG_ASSERT(!rli->gaq->full() || ((rli->checkpoint_seqno == rli->checkpoint_group -1 && rli->mts_group_status == Relay_log_info::MTS_IN_GROUP) || rli->checkpoint_seqno == rli->checkpoint_group)); /* Currently, the checkpoint routine is being called by the SQL Thread. For that reason, this function is called call from appropriate points in the SQL Thread's execution path and the elapsed time is calculated here to check if it is time to execute it. */ set_timespec_nsec(curr_clock, 0); ulonglong diff= diff_timespec(curr_clock, rli->last_clock); if (!force && diff < period) { /* We do not need to execute the checkpoint now because the time elapsed is not enough. */ DBUG_RETURN(FALSE); } do { cnt= rli->gaq->move_queue_head(&rli->workers); #ifndef DBUG_OFF if (DBUG_EVALUATE_IF("check_slave_debug_group", 1, 0) && cnt != opt_mts_checkpoint_period) sql_print_error("This an error cnt != mts_checkpoint_period"); #endif } while (!sql_slave_killed(rli->info_thd, rli) && cnt == 0 && force && !DBUG_EVALUATE_IF("check_slave_debug_group", 1, 0) && (my_sleep(rli->mts_coordinator_basic_nap), 1)); /* This checks how many consecutive jobs where processed. If this value is different than zero the checkpoint routine can proceed. Otherwise, there is nothing to be done. */ if (cnt == 0) goto end; /* TODO: to turn the least occupied selection in terms of jobs pieces */ for (uint i= 0; i < rli->workers.elements; i++) { Slave_worker *w_i; get_dynamic(&rli->workers, (uchar *) &w_i, i); set_dynamic(&rli->least_occupied_workers, (uchar*) &w_i->jobs.len, w_i->id); }; sort_dynamic(&rli->least_occupied_workers, (qsort_cmp) ulong_cmp); if (need_data_lock) mysql_mutex_lock(&rli->data_lock); else mysql_mutex_assert_owner(&rli->data_lock); /* "Coordinator::commit_positions" { rli->gaq->lwm has been updated in move_queue_head() and to contain all but rli->group_master_log_name which is altered solely by Coordinator at special checkpoints. */ rli->set_group_master_log_pos(rli->gaq->lwm.group_master_log_pos); rli->set_group_relay_log_pos(rli->gaq->lwm.group_relay_log_pos); DBUG_PRINT("mts", ("New checkpoint %llu %llu %s", rli->gaq->lwm.group_master_log_pos, rli->gaq->lwm.group_relay_log_pos, rli->gaq->lwm.group_relay_log_name)); if (rli->gaq->lwm.group_relay_log_name[0] != 0) rli->set_group_relay_log_name(rli->gaq->lwm.group_relay_log_name); /* todo: uncomment notifies when UNTIL will be supported rli->notify_group_master_log_name_update(); rli->notify_group_relay_log_name_update(); Todo: optimize with if (wait_flag) broadcast waiter: set wait_flag; waits....; drops wait_flag; */ error= rli->flush_info(TRUE); mysql_cond_broadcast(&rli->data_cond); if (need_data_lock) mysql_mutex_unlock(&rli->data_lock); /* We need to ensure that this is never called at this point when cnt is zero. This value means that the checkpoint information will be completely reset. */ rli->reset_notified_checkpoint(cnt, rli->gaq->lwm.ts, need_data_lock); /* end-of "Coordinator::"commit_positions" */ end: #ifndef DBUG_OFF if (DBUG_EVALUATE_IF("check_slave_debug_group", 1, 0)) DBUG_SUICIDE(); #endif set_timespec_nsec(rli->last_clock, 0); DBUG_RETURN(error); } /** Instantiation of a Slave_worker and forking out a single Worker thread. @param rli Coordinator's Relay_log_info pointer @param i identifier of the Worker @return 0 suppress or 1 if fails */ int slave_start_single_worker(Relay_log_info *rli, ulong i) { int error= 0; pthread_t th; Slave_worker *w= NULL; mysql_mutex_assert_owner(&rli->run_lock); if (!(w= Rpl_info_factory::create_worker(opt_rli_repository_id, i, rli, false))) { sql_print_error("Failed during slave worker thread create"); error= 1; goto err; } if (w->init_worker(rli, i)) { sql_print_error("Failed during slave worker thread create"); error= 1; goto err; } set_dynamic(&rli->workers, (uchar*) &w, i); if (DBUG_EVALUATE_IF("mts_worker_thread_fails", i == 1, 0) || (error= mysql_thread_create(key_thread_slave_worker, &th, &connection_attrib, handle_slave_worker, (void*) w))) { sql_print_error("Failed during slave worker thread create (errno= %d)", error); error= 1; goto err; } mysql_mutex_lock(&w->jobs_lock); if (w->running_status == Slave_worker::NOT_RUNNING) mysql_cond_wait(&w->jobs_cond, &w->jobs_lock); mysql_mutex_unlock(&w->jobs_lock); // Least occupied inited with zero insert_dynamic(&rli->least_occupied_workers, (uchar*) &w->jobs.len); err: if (error && w) { delete w; /* Any failure after dynarray inserted must follow with deletion of just created item. */ if (rli->workers.elements == i + 1) delete_dynamic_element(&rli->workers, i); } return error; } /** Initialization of the central rli members for Coordinator's role, communication channels such as Assigned Partition Hash (APH), and starting the Worker pool. @param n Number of configured Workers in the upcoming session. @return 0 success non-zero as failure */ int slave_start_workers(Relay_log_info *rli, ulong n, bool *mts_inited) { uint i; int error= 0; mysql_mutex_assert_owner(&rli->run_lock); if (n == 0 && rli->mts_recovery_group_cnt == 0) { reset_dynamic(&rli->workers); goto end; } *mts_inited= true; /* The requested through argument number of Workers can be different from the previous time which ended with an error. Thereby the effective number of configured Workers is max of the two. */ rli->init_workers(max(n, rli->recovery_parallel_workers)); // CGAP dynarray holds id:s of partitions of the Current being executed Group my_init_dynamic_array(&rli->curr_group_assigned_parts, sizeof(db_worker_hash_entry*), SLAVE_INIT_DBS_IN_GROUP, 1); rli->last_assigned_worker= NULL; // associated with curr_group_assigned my_init_dynamic_array(&rli->curr_group_da, sizeof(Log_event*), 8, 2); // Least_occupied_workers array to hold items size of Slave_jobs_queue::len my_init_dynamic_array(&rli->least_occupied_workers, sizeof(ulong), n, 0); /* GAQ queue holds seqno:s of scheduled groups. C polls workers in @c opt_mts_checkpoint_period to update GAQ (see @c next_event()) The length of GAQ is set to be equal to checkpoint_group. Notice, the size matters for mts_checkpoint_routine's progress loop. */ rli->gaq= new Slave_committed_queue(rli->get_group_master_log_name(), sizeof(Slave_job_group), rli->checkpoint_group, n); if (!rli->gaq->inited) return 1; // length of WQ is actually constant though can be made configurable rli->mts_slave_worker_queue_len_max= mts_slave_worker_queue_len_max; rli->mts_pending_jobs_size= 0; rli->mts_pending_jobs_size_max= ::opt_mts_pending_jobs_size_max; rli->mts_wq_underrun_w_id= MTS_WORKER_UNDEF; rli->mts_wq_excess_cnt= 0; rli->mts_wq_overrun_cnt= 0; rli->mts_wq_oversize= FALSE; rli->mts_coordinator_basic_nap= mts_coordinator_basic_nap; rli->mts_worker_underrun_level= mts_worker_underrun_level; rli->curr_group_seen_begin= rli->curr_group_seen_gtid= false; rli->curr_group_isolated= FALSE; rli->checkpoint_seqno= 0; rli->mts_last_online_stat= my_time(0); rli->mts_group_status= Relay_log_info::MTS_NOT_IN_GROUP; if (init_hash_workers(n)) // MTS: mapping_db_to_worker { sql_print_error("Failed to init partitions hash"); error= 1; goto err; } for (i= 0; i < n; i++) { if ((error= slave_start_single_worker(rli, i))) goto err; } end: rli->slave_parallel_workers= n; // Effective end of the recovery right now when there is no gaps if (!error && rli->mts_recovery_group_cnt == 0) { if ((error= rli->mts_finalize_recovery())) (void) Rpl_info_factory::reset_workers(rli); if (!error) error= rli->flush_info(TRUE); } err: return error; } /* Ending Worker threads. Not in case Coordinator is killed itself, it first waits for Workers have finished their assignements, and then updates checkpoint. Workers are notified with setting KILLED status and waited for their acknowledgment as specified by worker's running_status. Coordinator finalizes with its MTS running status to reset few objects. */ void slave_stop_workers(Relay_log_info *rli, bool *mts_inited) { int i; THD *thd= rli->info_thd; if (!*mts_inited) return; else if (rli->slave_parallel_workers == 0) goto end; /* In case of the "soft" graceful stop Coordinator guaranteed Workers were assigned with full groups so waiting will be resultful. "Hard" stop with KILLing Coordinator or erroring out by a Worker can't wait for Workers' completion because those may not receive commit-events of last assigned groups. */ if (rli->mts_group_status != Relay_log_info::MTS_KILLED_GROUP && thd->killed == THD::NOT_KILLED) { DBUG_ASSERT(rli->mts_group_status != Relay_log_info::MTS_IN_GROUP || thd->is_error()); #ifndef DBUG_OFF if (DBUG_EVALUATE_IF("check_slave_debug_group", 1, 0)) { sql_print_error("This is not supposed to happen at this point..."); DBUG_SUICIDE(); } #endif // No need to know a possible error out of synchronization call. (void) wait_for_workers_to_finish(rli); /* At this point the coordinator has been stopped and the checkpoint routine is executed to eliminate possible gaps. */ (void) mts_checkpoint_routine(rli, 0, false, true/*need_data_lock=true*/); // TODO: ALFRANIO ERROR } for (i= rli->workers.elements - 1; i >= 0; i--) { Slave_worker *w; get_dynamic((DYNAMIC_ARRAY*)&rli->workers, (uchar*) &w, i); mysql_mutex_lock(&w->jobs_lock); if (w->running_status != Slave_worker::RUNNING) { mysql_mutex_unlock(&w->jobs_lock); continue; } w->running_status= Slave_worker::KILLED; mysql_cond_signal(&w->jobs_cond); mysql_mutex_unlock(&w->jobs_lock); if (log_warnings > 1) sql_print_information("Notifying Worker %lu to exit, thd %p", w->id, w->info_thd); } thd_proc_info(thd, "Waiting for workers to exit"); for (i= rli->workers.elements - 1; i >= 0; i--) { Slave_worker *w= NULL; get_dynamic((DYNAMIC_ARRAY*)&rli->workers, (uchar*) &w, i); mysql_mutex_lock(&w->jobs_lock); while (w->running_status != Slave_worker::NOT_RUNNING) { PSI_stage_info old_stage; DBUG_ASSERT(w->running_status == Slave_worker::KILLED || w->running_status == Slave_worker::ERROR_LEAVING); thd->ENTER_COND(&w->jobs_cond, &w->jobs_lock, &stage_slave_waiting_workers_to_exit, &old_stage); mysql_cond_wait(&w->jobs_cond, &w->jobs_lock); thd->EXIT_COND(&old_stage); mysql_mutex_lock(&w->jobs_lock); } mysql_mutex_unlock(&w->jobs_lock); delete_dynamic_element(&rli->workers, i); delete w; } if (log_warnings > 1) sql_print_information("Total MTS session statistics: " "events processed = %llu; " "worker queues filled over overrun level = %lu; " "waited due a Worker queue full = %lu; " "waited due the total size = %lu; " "slept when Workers occupied = %lu ", rli->mts_events_assigned, rli->mts_wq_overrun_cnt, rli->mts_wq_overfill_cnt, rli->wq_size_waits_cnt, rli->mts_wq_no_underrun_cnt); DBUG_ASSERT(rli->pending_jobs == 0); DBUG_ASSERT(rli->mts_pending_jobs_size == 0); end: rli->mts_group_status= Relay_log_info::MTS_NOT_IN_GROUP; destroy_hash_workers(rli); delete rli->gaq; delete_dynamic(&rli->least_occupied_workers); // least occupied // Destroy buffered events of the current group prior to exit. for (uint i= 0; i < rli->curr_group_da.elements; i++) delete *(Log_event**) dynamic_array_ptr(&rli->curr_group_da, i); delete_dynamic(&rli->curr_group_da); // GCDA delete_dynamic(&rli->curr_group_assigned_parts); // GCAP rli->deinit_workers(); rli->slave_parallel_workers= 0; *mts_inited= false; } /** Slave SQL thread entry point. @param arg Pointer to Relay_log_info object that holds information for the SQL thread. @return Always 0. */ pthread_handler_t handle_slave_sql(void *arg) { THD *thd; /* needs to be first for thread_stack */ bool thd_added= false; char llbuff[22],llbuff1[22]; char saved_log_name[FN_REFLEN]; char saved_master_log_name[FN_REFLEN]; my_off_t saved_log_pos= 0; my_off_t saved_master_log_pos= 0; my_off_t saved_skip= 0; Relay_log_info* rli = ((Master_info*)arg)->rli; const char *errmsg; bool mts_inited= false; /* Buffer lifetime extends across the entire runtime of the THD handle. */ static char proc_info_buf[256]= {0}; // needs to call my_thread_init(), otherwise we get a coredump in DBUG_ stuff my_thread_init(); DBUG_ENTER("handle_slave_sql"); DBUG_ASSERT(rli->inited); mysql_mutex_lock(&rli->run_lock); DBUG_ASSERT(!rli->slave_running); errmsg= 0; #ifndef DBUG_OFF rli->events_until_exit = abort_slave_event_count; #endif // note that contructor of THD uses DBUG_ ! thd = new THD_SQL_slave(proc_info_buf, sizeof(proc_info_buf)); thd->thread_stack = (char*)&thd; // remember where our stack is mysql_mutex_lock(&rli->info_thd_lock); rli->info_thd= thd; mysql_mutex_unlock(&rli->info_thd_lock); /* Inform waiting threads that slave has started */ rli->slave_run_id++; rli->slave_running = 1; rli->reported_unsafe_warning= false; pthread_detach_this_thread(); if (init_slave_thread(thd, SLAVE_THD_SQL)) { /* TODO: this is currently broken - slave start and change master will be stuck if we fail here */ mysql_cond_broadcast(&rli->start_cond); mysql_mutex_unlock(&rli->run_lock); rli->report(ERROR_LEVEL, ER_SLAVE_FATAL_ERROR, "Failed during slave thread initialization"); goto err; } thd->init_for_queries(rli); thd->temporary_tables = rli->save_temporary_tables; // restore temp tables set_thd_in_use_temporary_tables(rli); // (re)set sql_thd in use for saved temp tables mysql_mutex_lock(&LOCK_thread_count); add_global_thread(thd); thd_added= true; mysql_mutex_unlock(&LOCK_thread_count); /* MTS: starting the worker pool */ if (slave_start_workers(rli, rli->opt_slave_parallel_workers, &mts_inited) != 0) { mysql_cond_broadcast(&rli->start_cond); mysql_mutex_unlock(&rli->run_lock); rli->report(ERROR_LEVEL, ER_SLAVE_FATAL_ERROR, "Failed during slave workers initialization"); goto err; } if (Rpl_info_factory::init_gtid_info_repository(rli)) { mysql_cond_broadcast(&rli->start_cond); mysql_mutex_unlock(&rli->run_lock); rli->report(ERROR_LEVEL, ER_SLAVE_FATAL_ERROR, "Error creating gtid_info"); goto err; } /* We are going to set slave_running to 1. Assuming slave I/O thread is alive and connected, this is going to make Seconds_Behind_Master be 0 i.e. "caught up". Even if we're just at start of thread. Well it's ok, at the moment we start we can think we are caught up, and the next second we start receiving data so we realize we are not caught up and Seconds_Behind_Master grows. No big deal. */ rli->abort_slave = 0; /* Reset errors for a clean start (otherwise, if the master is idle, the SQL thread may execute no Query_log_event, so the error will remain even though there's no problem anymore). Do not reset the master timestamp (imagine the slave has caught everything, the STOP SLAVE and START SLAVE: as we are not sure that we are going to receive a query, we want to remember the last master timestamp (to say how many seconds behind we are now. But the master timestamp is reset by RESET SLAVE & CHANGE MASTER. */ rli->clear_error(); if (rli->update_is_transactional()) { mysql_cond_broadcast(&rli->start_cond); mysql_mutex_unlock(&rli->run_lock); rli->report(ERROR_LEVEL, ER_SLAVE_FATAL_ERROR, "Error checking if the relay log repository is transactional."); goto err; } if (!rli->is_transactional()) rli->report(WARNING_LEVEL, 0, "If a crash happens this configuration does not guarantee that the relay " "log info will be consistent"); mysql_mutex_unlock(&rli->run_lock); mysql_cond_broadcast(&rli->start_cond); DEBUG_SYNC(thd, "after_start_slave"); //tell the I/O thread to take relay_log_space_limit into account from now on mysql_mutex_lock(&rli->log_space_lock); rli->ignore_log_space_limit= 0; mysql_mutex_unlock(&rli->log_space_lock); rli->trans_retries= 0; // start from "no error" DBUG_PRINT("info", ("rli->trans_retries: %lu", rli->trans_retries)); if (rli->init_relay_log_pos(rli->get_group_relay_log_name(), rli->get_group_relay_log_pos(), true/*need_data_lock=true*/, &errmsg, 1 /*look for a description_event*/)) { rli->report(ERROR_LEVEL, ER_SLAVE_FATAL_ERROR, "Error initializing relay log position: %s", errmsg); goto err; } THD_CHECK_SENTRY(thd); #ifndef DBUG_OFF { char llbuf1[22], llbuf2[22]; DBUG_PRINT("info", ("my_b_tell(rli->cur_log)=%s rli->event_relay_log_pos=%s", llstr(my_b_tell(rli->cur_log),llbuf1), llstr(rli->get_event_relay_log_pos(),llbuf2))); DBUG_ASSERT(rli->get_event_relay_log_pos() >= BIN_LOG_HEADER_SIZE); /* Wonder if this is correct. I (Guilhem) wonder if my_b_tell() returns the correct position when it's called just after my_b_seek() (the questionable stuff is those "seek is done on next read" comments in the my_b_seek() source code). The crude reality is that this assertion randomly fails whereas replication seems to work fine. And there is no easy explanation why it fails (as we my_b_seek(rli->event_relay_log_pos) at the very end of init_relay_log_pos() called above). Maybe the assertion would be meaningful if we held rli->data_lock between the my_b_seek() and the DBUG_ASSERT(). */ #ifdef SHOULD_BE_CHECKED DBUG_ASSERT(my_b_tell(rli->cur_log) == rli->get_event_relay_log_pos()); #endif } #endif DBUG_ASSERT(rli->info_thd == thd); #ifdef WITH_NDBCLUSTER_STORAGE_ENGINE /* engine specific hook, to be made generic */ if (ndb_wait_setup_func && ndb_wait_setup_func(opt_ndb_wait_setup)) { sql_print_warning("Slave SQL thread : NDB : Tables not available after %lu" " seconds. Consider increasing --ndb-wait-setup value", opt_ndb_wait_setup); } #endif DBUG_PRINT("master_info",("log_file_name: %s position: %s", rli->get_group_master_log_name(), llstr(rli->get_group_master_log_pos(),llbuff))); if (log_warnings) sql_print_information("Slave SQL thread initialized, starting replication in \ log '%s' at position %s, relay log '%s' position: %s", rli->get_rpl_log_name(), llstr(rli->get_group_master_log_pos(),llbuff),rli->get_group_relay_log_name(), llstr(rli->get_group_relay_log_pos(),llbuff1)); if (check_temp_dir(rli->slave_patternload_file)) { rli->report(ERROR_LEVEL, thd->get_stmt_da()->sql_errno(), "Unable to use slave's temporary directory %s - %s", slave_load_tmpdir, thd->get_stmt_da()->message()); goto err; } /* execute init_slave variable */ if (opt_init_slave.length) { execute_init_command(thd, &opt_init_slave, &LOCK_sys_init_slave); if (thd->is_slave_error) { rli->report(ERROR_LEVEL, thd->get_stmt_da()->sql_errno(), "Slave SQL thread aborted. Can't execute init_slave query"); goto err; } } /* First check until condition - probably there is nothing to execute. We do not want to wait for next event in this case. */ mysql_mutex_lock(&rli->data_lock); if (rli->slave_skip_counter) { strmake(saved_log_name, rli->get_group_relay_log_name(), FN_REFLEN - 1); strmake(saved_master_log_name, rli->get_group_master_log_name(), FN_REFLEN - 1); saved_log_pos= rli->get_group_relay_log_pos(); saved_master_log_pos= rli->get_group_master_log_pos(); saved_skip= rli->slave_skip_counter; } if (rli->until_condition != Relay_log_info::UNTIL_NONE && rli->is_until_satisfied(thd, NULL)) { mysql_mutex_unlock(&rli->data_lock); goto err; } mysql_mutex_unlock(&rli->data_lock); /* Read queries from the IO/THREAD until this thread is killed */ while (!sql_slave_killed(thd,rli)) { THD_STAGE_INFO(thd, stage_reading_event_from_the_relay_log); DBUG_ASSERT(rli->info_thd == thd); THD_CHECK_SENTRY(thd); if (saved_skip && rli->slave_skip_counter == 0) { sql_print_information("'SQL_SLAVE_SKIP_COUNTER=%ld' executed at " "relay_log_file='%s', relay_log_pos='%ld', master_log_name='%s', " "master_log_pos='%ld' and new position at " "relay_log_file='%s', relay_log_pos='%ld', master_log_name='%s', " "master_log_pos='%ld' ", (ulong) saved_skip, saved_log_name, (ulong) saved_log_pos, saved_master_log_name, (ulong) saved_master_log_pos, rli->get_group_relay_log_name(), (ulong) rli->get_group_relay_log_pos(), rli->get_group_master_log_name(), (ulong) rli->get_group_master_log_pos()); saved_skip= 0; } if (exec_relay_log_event(thd,rli)) { DBUG_PRINT("info", ("exec_relay_log_event() failed")); // do not scare the user if SQL thread was simply killed or stopped if (!sql_slave_killed(thd,rli)) { /* retrieve as much info as possible from the thd and, error codes and warnings and print this to the error log as to allow the user to locate the error */ uint32 const last_errno= rli->last_error().number; if (thd->is_error()) { char const *const errmsg= thd->get_stmt_da()->message(); DBUG_PRINT("info", ("thd->get_stmt_da()->sql_errno()=%d; " "rli->last_error.number=%d", thd->get_stmt_da()->sql_errno(), last_errno)); if (last_errno == 0) { /* This function is reporting an error which was not reported while executing exec_relay_log_event(). */ rli->report(ERROR_LEVEL, thd->get_stmt_da()->sql_errno(), "%s", errmsg); } else if (last_errno != thd->get_stmt_da()->sql_errno()) { /* * An error was reported while executing exec_relay_log_event() * however the error code differs from what is in the thread. * This function prints out more information to help finding * what caused the problem. */ sql_print_error("Slave (additional info): %s Error_code: %d", errmsg, thd->get_stmt_da()->sql_errno()); } } /* Print any warnings issued */ Diagnostics_area::Sql_condition_iterator it= thd->get_stmt_da()->sql_conditions(); const Sql_condition *err; /* Added controlled slave thread cancel for replication of user-defined variables. */ bool udf_error = false; while ((err= it++)) { if (err->get_sql_errno() == ER_CANT_OPEN_LIBRARY) udf_error = true; sql_print_warning("Slave: %s Error_code: %d", err->get_message_text(), err->get_sql_errno()); } if (udf_error) sql_print_error("Error loading user-defined library, slave SQL " "thread aborted. Install the missing library, and restart the " "slave SQL thread with \"SLAVE START\". We stopped at log '%s' " "position %s", rli->get_rpl_log_name(), llstr(rli->get_group_master_log_pos(), llbuff)); else sql_print_error("\ Error running query, slave SQL thread aborted. Fix the problem, and restart \ the slave SQL thread with \"SLAVE START\". We stopped at log \ '%s' position %s", rli->get_rpl_log_name(), llstr(rli->get_group_master_log_pos(), llbuff)); } goto err; } } /* Thread stopped. Print the current replication position to the log */ sql_print_information("Slave SQL thread exiting, replication stopped in log " "'%s' at position %s", rli->get_rpl_log_name(), llstr(rli->get_group_master_log_pos(), llbuff)); err: slave_stop_workers(rli, &mts_inited); // stopping worker pool if (rli->recovery_groups_inited) { bitmap_free(&rli->recovery_groups); rli->mts_recovery_group_cnt= 0; rli->recovery_groups_inited= false; } /* Some events set some playgrounds, which won't be cleared because thread stops. Stopping of this thread may not be known to these events ("stop" request is detected only by the present function, not by events), so we must "proactively" clear playgrounds: */ thd->clear_error(); rli->cleanup_context(thd, 1); /* Some extra safety, which should not been needed (normally, event deletion should already have done these assignments (each event which sets these variables is supposed to set them to 0 before terminating)). */ thd->catalog= 0; thd->reset_query(); thd->reset_db(NULL, 0); THD_STAGE_INFO(thd, stage_waiting_for_slave_mutex_on_exit); mysql_mutex_lock(&rli->run_lock); /* We need data_lock, at least to wake up any waiting master_pos_wait() */ mysql_mutex_lock(&rli->data_lock); DBUG_ASSERT(rli->slave_running == 1); // tracking buffer overrun /* When master_pos_wait() wakes up it will check this and terminate */ rli->slave_running= 0; /* Forget the relay log's format */ rli->set_rli_description_event(NULL); /* Wake up master_pos_wait() */ mysql_mutex_unlock(&rli->data_lock); DBUG_PRINT("info",("Signaling possibly waiting master_pos_wait() functions")); mysql_cond_broadcast(&rli->data_cond); rli->ignore_log_space_limit= 0; /* don't need any lock */ /* we die so won't remember charset - re-update them on next thread start */ rli->cached_charset_invalidate(); rli->save_temporary_tables = thd->temporary_tables; /* TODO: see if we can do this conditionally in next_event() instead to avoid unneeded position re-init */ thd->temporary_tables = 0; // remove tempation from destructor to close them DBUG_ASSERT(thd->net.buff != 0); net_end(&thd->net); // destructor will not free it, because we are weird DBUG_ASSERT(rli->info_thd == thd); THD_CHECK_SENTRY(thd); mysql_mutex_lock(&rli->info_thd_lock); rli->info_thd= 0; mysql_mutex_unlock(&rli->info_thd_lock); set_thd_in_use_temporary_tables(rli); // (re)set info_thd in use for saved temp tables thd->release_resources(); THD_CHECK_SENTRY(thd); if (thd_added) remove_global_thread(thd); delete thd; /* Note: the order of the broadcast and unlock calls below (first broadcast, then unlock) is important. Otherwise a killer_thread can execute between the calls and delete the mi structure leading to a crash! (see BUG#25306 for details) */ mysql_cond_broadcast(&rli->stop_cond); DBUG_EXECUTE_IF("simulate_slave_delay_at_terminate_bug38694", sleep(5);); mysql_mutex_unlock(&rli->run_lock); // tell the world we are done DBUG_LEAVE; // Must match DBUG_ENTER() my_thread_end(); ERR_remove_state(0); pthread_exit(0); return 0; // Avoid compiler warnings } /* process_io_create_file() */ static int process_io_create_file(Master_info* mi, Create_file_log_event* cev) { int error = 1; ulong num_bytes; bool cev_not_written; THD *thd = mi->info_thd; NET *net = &mi->mysql->net; DBUG_ENTER("process_io_create_file"); mysql_mutex_assert_owner(&mi->data_lock); if (unlikely(!cev->is_valid())) DBUG_RETURN(1); if (!rpl_filter->db_ok(cev->db)) { skip_load_data_infile(net); DBUG_RETURN(0); } DBUG_ASSERT(cev->inited_from_old); thd->file_id = cev->file_id = mi->file_id++; thd->server_id = cev->server_id; cev_not_written = 1; if (unlikely(net_request_file(net,cev->fname))) { sql_print_error("Slave I/O: failed requesting download of '%s'", cev->fname); goto err; } /* This dummy block is so we could instantiate Append_block_log_event once and then modify it slightly instead of doing it multiple times in the loop */ { Append_block_log_event aev(thd,0,0,0,0); for (;;) { if (unlikely((num_bytes=my_net_read(net)) == packet_error)) { sql_print_error("Network read error downloading '%s' from master", cev->fname); goto err; } if (unlikely(!num_bytes)) /* eof */ { /* 3.23 master wants it */ net_write_command(net, 0, (uchar*) "", 0, (uchar*) "", 0); /* If we wrote Create_file_log_event, then we need to write Execute_load_log_event. If we did not write Create_file_log_event, then this is an empty file and we can just do as if the LOAD DATA INFILE had not existed, i.e. write nothing. */ if (unlikely(cev_not_written)) break; Execute_load_log_event xev(thd,0,0); xev.log_pos = cev->log_pos; if (unlikely(mi->rli->relay_log.append_event(&xev, mi) != 0)) { mi->report(ERROR_LEVEL, ER_SLAVE_RELAY_LOG_WRITE_FAILURE, ER(ER_SLAVE_RELAY_LOG_WRITE_FAILURE), "error writing Exec_load event to relay log"); goto err; } mi->rli->relay_log.harvest_bytes_written(&mi->rli->log_space_total); break; } if (unlikely(cev_not_written)) { cev->block = net->read_pos; cev->block_len = num_bytes; if (unlikely(mi->rli->relay_log.append_event(cev, mi) != 0)) { mi->report(ERROR_LEVEL, ER_SLAVE_RELAY_LOG_WRITE_FAILURE, ER(ER_SLAVE_RELAY_LOG_WRITE_FAILURE), "error writing Create_file event to relay log"); goto err; } cev_not_written=0; mi->rli->relay_log.harvest_bytes_written(&mi->rli->log_space_total); } else { aev.block = net->read_pos; aev.block_len = num_bytes; aev.log_pos = cev->log_pos; if (unlikely(mi->rli->relay_log.append_event(&aev, mi) != 0)) { mi->report(ERROR_LEVEL, ER_SLAVE_RELAY_LOG_WRITE_FAILURE, ER(ER_SLAVE_RELAY_LOG_WRITE_FAILURE), "error writing Append_block event to relay log"); goto err; } mi->rli->relay_log.harvest_bytes_written(&mi->rli->log_space_total); } } } error=0; err: DBUG_RETURN(error); } /** Used by the slave IO thread when it receives a rotate event from the master. Updates the master info with the place in the next binary log where we should start reading. Rotate the relay log to avoid mixed-format relay logs. @param mi master_info for the slave @param rev The rotate log event read from the master @note The caller must hold mi->data_lock before invoking this function. @retval 0 ok @retval 1 error */ static int process_io_rotate(Master_info *mi, Rotate_log_event *rev) { DBUG_ENTER("process_io_rotate"); mysql_mutex_assert_owner(&mi->data_lock); if (unlikely(!rev->is_valid())) DBUG_RETURN(1); /* Safe copy as 'rev' has been "sanitized" in Rotate_log_event's ctor */ memcpy(const_cast<char *>(mi->get_master_log_name()), rev->new_log_ident, rev->ident_len + 1); mi->set_master_log_pos(rev->pos); DBUG_PRINT("info", ("new (master_log_name, master_log_pos): ('%s', %lu)", mi->get_master_log_name(), (ulong) mi->get_master_log_pos())); #ifndef DBUG_OFF /* If we do not do this, we will be getting the first rotate event forever, so we need to not disconnect after one. */ if (disconnect_slave_event_count) mi->events_until_exit++; #endif /* If mi_description_event is format <4, there is conversion in the relay log to the slave's format (4). And Rotate can mean upgrade or nothing. If upgrade, it's to 5.0 or newer, so we will get a Format_desc, so no need to reset mi_description_event now. And if it's nothing (same master version as before), no need (still using the slave's format). */ Format_description_log_event *old_fdle= mi->get_mi_description_event(); if (old_fdle->binlog_version >= 4) { DBUG_ASSERT(old_fdle->checksum_alg == mi->rli->relay_log.relay_log_checksum_alg); Format_description_log_event *new_fdle= new Format_description_log_event(3); new_fdle->checksum_alg= mi->rli->relay_log.relay_log_checksum_alg; mi->set_mi_description_event(new_fdle); } /* Rotate the relay log makes binlog format detection easier (at next slave start or mysqlbinlog) */ int ret= rotate_relay_log(mi); DBUG_RETURN(ret); } /** Reads a 3.23 event and converts it to the slave's format. This code was copied from MySQL 4.0. @note The caller must hold mi->data_lock before invoking this function. */ static int queue_binlog_ver_1_event(Master_info *mi, const char *buf, ulong event_len) { const char *errmsg = 0; ulong inc_pos; bool ignore_event= 0; char *tmp_buf = 0; Relay_log_info *rli= mi->rli; DBUG_ENTER("queue_binlog_ver_1_event"); mysql_mutex_assert_owner(&mi->data_lock); /* If we get Load event, we need to pass a non-reusable buffer to read_log_event, so we do a trick */ if (buf[EVENT_TYPE_OFFSET] == LOAD_EVENT) { if (unlikely(!(tmp_buf=(char*)my_malloc(event_len+1,MYF(MY_WME))))) { mi->report(ERROR_LEVEL, ER_SLAVE_FATAL_ERROR, ER(ER_SLAVE_FATAL_ERROR), "Memory allocation failed"); DBUG_RETURN(1); } memcpy(tmp_buf,buf,event_len); /* Create_file constructor wants a 0 as last char of buffer, this 0 will serve as the string-termination char for the file's name (which is at the end of the buffer) We must increment event_len, otherwise the event constructor will not see this end 0, which leads to segfault. */ tmp_buf[event_len++]=0; int4store(tmp_buf+EVENT_LEN_OFFSET, event_len); buf = (const char*)tmp_buf; } /* This will transform LOAD_EVENT into CREATE_FILE_EVENT, ask the master to send the loaded file, and write it to the relay log in the form of Append_block/Exec_load (the SQL thread needs the data, as that thread is not connected to the master). */ Log_event *ev= Log_event::read_log_event(buf, event_len, &errmsg, mi->get_mi_description_event(), 0); if (unlikely(!ev)) { sql_print_error("Read invalid event from master: '%s',\ master could be corrupt but a more likely cause of this is a bug", errmsg); my_free((char*) tmp_buf); DBUG_RETURN(1); } mi->set_master_log_pos(ev->log_pos); /* 3.23 events don't contain log_pos */ switch (ev->get_type_code()) { case STOP_EVENT: ignore_event= 1; inc_pos= event_len; break; case ROTATE_EVENT: if (unlikely(process_io_rotate(mi,(Rotate_log_event*)ev))) { delete ev; DBUG_RETURN(1); } inc_pos= 0; break; case CREATE_FILE_EVENT: /* Yes it's possible to have CREATE_FILE_EVENT here, even if we're in queue_old_event() which is for 3.23 events which don't comprise CREATE_FILE_EVENT. This is because read_log_event() above has just transformed LOAD_EVENT into CREATE_FILE_EVENT. */ { /* We come here when and only when tmp_buf != 0 */ DBUG_ASSERT(tmp_buf != 0); inc_pos=event_len; ev->log_pos+= inc_pos; int error = process_io_create_file(mi,(Create_file_log_event*)ev); delete ev; mi->set_master_log_pos(mi->get_master_log_pos() + inc_pos); DBUG_PRINT("info", ("master_log_pos: %lu", (ulong) mi->get_master_log_pos())); my_free((char*)tmp_buf); DBUG_RETURN(error); } default: inc_pos= event_len; break; } if (likely(!ignore_event)) { if (ev->log_pos) /* Don't do it for fake Rotate events (see comment in Log_event::Log_event(const char* buf...) in log_event.cc). */ ev->log_pos+= event_len; /* make log_pos be the pos of the end of the event */ if (unlikely(rli->relay_log.append_event(ev, mi) != 0)) { delete ev; DBUG_RETURN(1); } rli->relay_log.harvest_bytes_written(&rli->log_space_total); } delete ev; mi->set_master_log_pos(mi->get_master_log_pos() + inc_pos); DBUG_PRINT("info", ("master_log_pos: %lu", (ulong) mi->get_master_log_pos())); DBUG_RETURN(0); } /** Reads a 4.0 event and converts it to the slave's format. This code was copied from queue_binlog_ver_1_event(), with some affordable simplifications. @note The caller must hold mi->data_lock before invoking this function. */ static int queue_binlog_ver_3_event(Master_info *mi, const char *buf, ulong event_len) { const char *errmsg = 0; ulong inc_pos; char *tmp_buf = 0; Relay_log_info *rli= mi->rli; DBUG_ENTER("queue_binlog_ver_3_event"); mysql_mutex_assert_owner(&mi->data_lock); /* read_log_event() will adjust log_pos to be end_log_pos */ Log_event *ev= Log_event::read_log_event(buf, event_len, &errmsg, mi->get_mi_description_event(), 0); if (unlikely(!ev)) { sql_print_error("Read invalid event from master: '%s',\ master could be corrupt but a more likely cause of this is a bug", errmsg); my_free((char*) tmp_buf); DBUG_RETURN(1); } switch (ev->get_type_code()) { case STOP_EVENT: goto err; case ROTATE_EVENT: if (unlikely(process_io_rotate(mi,(Rotate_log_event*)ev))) { delete ev; DBUG_RETURN(1); } inc_pos= 0; break; default: inc_pos= event_len; break; } if (unlikely(rli->relay_log.append_event(ev, mi) != 0)) { delete ev; DBUG_RETURN(1); } rli->relay_log.harvest_bytes_written(&rli->log_space_total); delete ev; mi->set_master_log_pos(mi->get_master_log_pos() + inc_pos); err: DBUG_PRINT("info", ("master_log_pos: %lu", (ulong) mi->get_master_log_pos())); DBUG_RETURN(0); } /* queue_old_event() Writes a 3.23 or 4.0 event to the relay log, after converting it to the 5.0 (exactly, slave's) format. To do the conversion, we create a 5.0 event from the 3.23/4.0 bytes, then write this event to the relay log. TODO: Test this code before release - it has to be tested on a separate setup with 3.23 master or 4.0 master */ static int queue_old_event(Master_info *mi, const char *buf, ulong event_len) { DBUG_ENTER("queue_old_event"); mysql_mutex_assert_owner(&mi->data_lock); switch (mi->get_mi_description_event()->binlog_version) { case 1: DBUG_RETURN(queue_binlog_ver_1_event(mi,buf,event_len)); case 3: DBUG_RETURN(queue_binlog_ver_3_event(mi,buf,event_len)); default: /* unsupported format; eg version 2 */ DBUG_PRINT("info",("unsupported binlog format %d in queue_old_event()", mi->get_mi_description_event()->binlog_version)); DBUG_RETURN(1); } } /* queue_event() If the event is 3.23/4.0, passes it to queue_old_event() which will convert it. Otherwise, writes a 5.0 (or newer) event to the relay log. Then there is no format conversion, it's pure read/write of bytes. So a 5.0.0 slave's relay log can contain events in the slave's format or in any >=5.0.0 format. */ static int queue_event(Master_info* mi,const char* buf, ulong event_len) { int error= 0; String error_msg; ulong inc_pos= 0; Relay_log_info *rli= mi->rli; mysql_mutex_t *log_lock= rli->relay_log.get_log_lock(); ulong s_id; bool unlock_data_lock= TRUE; /* FD_q must have been prepared for the first R_a event inside get_master_version_and_clock() Show-up of FD:s affects checksum_alg at once because that changes FD_queue. */ uint8 checksum_alg= mi->checksum_alg_before_fd != BINLOG_CHECKSUM_ALG_UNDEF ? mi->checksum_alg_before_fd : mi->rli->relay_log.relay_log_checksum_alg; char *save_buf= NULL; // needed for checksumming the fake Rotate event char rot_buf[LOG_EVENT_HEADER_LEN + ROTATE_HEADER_LEN + FN_REFLEN]; char fde_buf[LOG_EVENT_MINIMAL_HEADER_LEN + FORMAT_DESCRIPTION_HEADER_LEN + BINLOG_CHECKSUM_ALG_DESC_LEN + BINLOG_CHECKSUM_LEN]; Gtid gtid= { 0, 0 }; Log_event_type event_type= (Log_event_type)buf[EVENT_TYPE_OFFSET]; DBUG_ASSERT(checksum_alg == BINLOG_CHECKSUM_ALG_OFF || checksum_alg == BINLOG_CHECKSUM_ALG_UNDEF || checksum_alg == BINLOG_CHECKSUM_ALG_CRC32); DBUG_ENTER("queue_event"); /* FD_queue checksum alg description does not apply in a case of FD itself. The one carries both parts of the checksum data. */ if (event_type == FORMAT_DESCRIPTION_EVENT) { checksum_alg= get_checksum_alg(buf, event_len); } else if (event_type == START_EVENT_V3) { // checksum behaviour is similar to the pre-checksum FD handling mi->checksum_alg_before_fd= BINLOG_CHECKSUM_ALG_UNDEF; mysql_mutex_lock(&mi->data_lock); mi->get_mi_description_event()->checksum_alg= mi->rli->relay_log.relay_log_checksum_alg= checksum_alg= BINLOG_CHECKSUM_ALG_OFF; mysql_mutex_unlock(&mi->data_lock); } // does not hold always because of old binlog can work with NM // DBUG_ASSERT(checksum_alg != BINLOG_CHECKSUM_ALG_UNDEF); // should hold unless manipulations with RL. Tests that do that // will have to refine the clause. DBUG_ASSERT(mi->rli->relay_log.relay_log_checksum_alg != BINLOG_CHECKSUM_ALG_UNDEF); // Emulate the network corruption DBUG_EXECUTE_IF("corrupt_queue_event", if (event_type != FORMAT_DESCRIPTION_EVENT) { char *debug_event_buf_c = (char*) buf; int debug_cor_pos = rand() % (event_len - BINLOG_CHECKSUM_LEN); debug_event_buf_c[debug_cor_pos] =~ debug_event_buf_c[debug_cor_pos]; DBUG_PRINT("info", ("Corrupt the event at queue_event: byte on position %d", debug_cor_pos)); DBUG_SET(""); } ); if (!(mi->ignore_checksum_alg && (event_type == FORMAT_DESCRIPTION_EVENT || event_type == ROTATE_EVENT)) && event_checksum_test((uchar *) buf, event_len, checksum_alg)) { error= ER_NETWORK_READ_EVENT_CHECKSUM_FAILURE; unlock_data_lock= FALSE; goto err; } mysql_mutex_lock(&mi->data_lock); if (mi->get_mi_description_event()->binlog_version < 4 && event_type != FORMAT_DESCRIPTION_EVENT /* a way to escape */) { // Old FDE doesn't have description of the heartbeat events. Skip them. if (event_type == HEARTBEAT_LOG_EVENT) goto skip_relay_logging; int ret= queue_old_event(mi,buf,event_len); mysql_mutex_unlock(&mi->data_lock); DBUG_RETURN(ret); } switch (event_type) { case STOP_EVENT: /* We needn't write this event to the relay log. Indeed, it just indicates a master server shutdown. The only thing this does is cleaning. But cleaning is already done on a per-master-thread basis (as the master server is shutting down cleanly, it has written all DROP TEMPORARY TABLE prepared statements' deletion are TODO only when we binlog prep stmts). We don't even increment mi->get_master_log_pos(), because we may be just after a Rotate event. Btw, in a few milliseconds we are going to have a Start event from the next binlog (unless the master is presently running without --log-bin). */ goto err; case ROTATE_EVENT: { Rotate_log_event rev(buf, checksum_alg != BINLOG_CHECKSUM_ALG_OFF ? event_len - BINLOG_CHECKSUM_LEN : event_len, mi->get_mi_description_event()); if (unlikely(process_io_rotate(mi, &rev))) { error= ER_SLAVE_RELAY_LOG_WRITE_FAILURE; goto err; } /* Checksum special cases for the fake Rotate (R_f) event caused by the protocol of events generation and serialization in RL where Rotate of master is queued right next to FD of slave. Since it's only FD that carries the alg desc of FD_s has to apply to R_m. Two special rules apply only to the first R_f which comes in before any FD_m. The 2nd R_f should be compatible with the FD_s that must have taken over the last seen FD_m's (A). RSC_1: If OM \and fake Rotate \and slave is configured to to compute checksum for its first FD event for RL the fake Rotate gets checksummed here. */ if (uint4korr(&buf[0]) == 0 && checksum_alg == BINLOG_CHECKSUM_ALG_OFF && mi->rli->relay_log.relay_log_checksum_alg != BINLOG_CHECKSUM_ALG_OFF) { ha_checksum rot_crc= my_checksum(0L, NULL, 0); event_len += BINLOG_CHECKSUM_LEN; memcpy(rot_buf, buf, event_len - BINLOG_CHECKSUM_LEN); int4store(&rot_buf[EVENT_LEN_OFFSET], uint4korr(rot_buf + EVENT_LEN_OFFSET) + BINLOG_CHECKSUM_LEN); rot_crc= my_checksum(rot_crc, (const uchar *) rot_buf, event_len - BINLOG_CHECKSUM_LEN); int4store(&rot_buf[event_len - BINLOG_CHECKSUM_LEN], rot_crc); DBUG_ASSERT(event_len == uint4korr(&rot_buf[EVENT_LEN_OFFSET])); DBUG_ASSERT(mi->get_mi_description_event()->checksum_alg == mi->rli->relay_log.relay_log_checksum_alg); /* the first one */ DBUG_ASSERT(mi->checksum_alg_before_fd != BINLOG_CHECKSUM_ALG_UNDEF); save_buf= (char *) buf; buf= rot_buf; } else /* RSC_2: If NM \and fake Rotate \and slave does not compute checksum the fake Rotate's checksum is stripped off before relay-logging. */ if (uint4korr(&buf[0]) == 0 && checksum_alg != BINLOG_CHECKSUM_ALG_OFF && mi->rli->relay_log.relay_log_checksum_alg == BINLOG_CHECKSUM_ALG_OFF) { event_len -= BINLOG_CHECKSUM_LEN; memcpy(rot_buf, buf, event_len); int4store(&rot_buf[EVENT_LEN_OFFSET], uint4korr(rot_buf + EVENT_LEN_OFFSET) - BINLOG_CHECKSUM_LEN); DBUG_ASSERT(event_len == uint4korr(&rot_buf[EVENT_LEN_OFFSET])); DBUG_ASSERT(mi->get_mi_description_event()->checksum_alg == mi->rli->relay_log.relay_log_checksum_alg); /* the first one */ DBUG_ASSERT(mi->checksum_alg_before_fd != BINLOG_CHECKSUM_ALG_UNDEF); save_buf= (char *) buf; buf= rot_buf; } /* Now the I/O thread has just changed its mi->get_master_log_name(), so incrementing mi->get_master_log_pos() is nonsense. */ inc_pos= 0; break; } case FORMAT_DESCRIPTION_EVENT: { /* Create an event, and save it (when we rotate the relay log, we will have to write this event again). */ /* We are the only thread which reads/writes mi_description_event. The relay_log struct does not move (though some members of it can change), so we needn't any lock (no rli->data_lock, no log lock). */ const char* errmsg; // mark it as undefined that is irrelevant anymore mi->checksum_alg_before_fd= BINLOG_CHECKSUM_ALG_UNDEF; /* Turn off checksum in FDE here, since the event was modified by 5.1 master before sending to the slave. Otherwise, event_checksum_test fails causing slave I/O and SQL threads to stop. */ if (mi->ignore_checksum_alg && checksum_alg != BINLOG_CHECKSUM_ALG_OFF && checksum_alg != BINLOG_CHECKSUM_ALG_UNDEF) { DBUG_ASSERT(event_len == sizeof(fde_buf)); memcpy(fde_buf, buf, event_len); fde_buf[event_len - BINLOG_CHECKSUM_LEN - BINLOG_CHECKSUM_ALG_DESC_LEN] = BINLOG_CHECKSUM_ALG_OFF; save_buf= (char *)buf; buf= fde_buf; } Format_description_log_event *new_fdle= (Format_description_log_event*) Log_event::read_log_event(buf, event_len, &errmsg, mi->get_mi_description_event(), 1); if (new_fdle == NULL) { error= ER_SLAVE_RELAY_LOG_WRITE_FAILURE; goto err; } if (new_fdle->checksum_alg == BINLOG_CHECKSUM_ALG_UNDEF) new_fdle->checksum_alg= BINLOG_CHECKSUM_ALG_OFF; mi->set_mi_description_event(new_fdle); /* installing new value of checksum Alg for relay log */ mi->rli->relay_log.relay_log_checksum_alg= new_fdle->checksum_alg; /* Though this does some conversion to the slave's format, this will preserve the master's binlog format version, and number of event types. */ /* If the event was not requested by the slave (the slave did not ask for it), i.e. has end_log_pos=0, we do not increment mi->get_master_log_pos() */ inc_pos= uint4korr(buf+LOG_POS_OFFSET) ? event_len : 0; DBUG_PRINT("info",("binlog format is now %d", mi->get_mi_description_event()->binlog_version)); } break; case HEARTBEAT_LOG_EVENT: { /* HB (heartbeat) cannot come before RL (Relay) */ char llbuf[22]; Heartbeat_log_event hb(buf, mi->rli->relay_log.relay_log_checksum_alg != BINLOG_CHECKSUM_ALG_OFF ? event_len - BINLOG_CHECKSUM_LEN : event_len, mi->get_mi_description_event()); if (!hb.is_valid()) { error= ER_SLAVE_HEARTBEAT_FAILURE; error_msg.append(STRING_WITH_LEN("inconsistent heartbeat event content;")); error_msg.append(STRING_WITH_LEN("the event's data: log_file_name ")); error_msg.append(hb.get_log_ident(), (uint) strlen(hb.get_log_ident())); error_msg.append(STRING_WITH_LEN(" log_pos ")); llstr(hb.log_pos, llbuf); error_msg.append(llbuf, strlen(llbuf)); goto err; } mi->received_heartbeats++; mi->last_heartbeat= my_time(0); /* During GTID protocol, if the master skips transactions, a heartbeat event is sent to the slave at the end of last skipped transaction to update coordinates. I/O thread receives the heartbeat event and updates mi only if the received heartbeat position is greater than mi->get_master_log_pos(). This event is written to the relay log as an ignored Rotate event. SQL thread reads the rotate event only to update the coordinates corresponding to the last skipped transaction. Note that, we update only the positions and not the file names, as a ROTATE EVENT from the master prior to this will update the file name. */ if (mi->is_auto_position() && mi->get_master_log_pos() < hb.log_pos && mi->get_master_log_name() != NULL) { DBUG_ASSERT(memcmp(const_cast<char*>(mi->get_master_log_name()), hb.get_log_ident(), hb.get_ident_len()) == 0); mi->set_master_log_pos(hb.log_pos); /* Put this heartbeat event in the relay log as a Rotate Event. */ inc_pos= 0; memcpy(rli->ign_master_log_name_end, mi->get_master_log_name(), FN_REFLEN); rli->ign_master_log_pos_end = mi->get_master_log_pos(); if (write_ignored_events_info_to_relay_log(mi->info_thd, mi)) goto err; } /* compare local and event's versions of log_file, log_pos. Heartbeat is sent only after an event corresponding to the corrdinates the heartbeat carries. Slave can not have a difference in coordinates except in the only special case when mi->get_master_log_name(), mi->get_master_log_pos() have never been updated by Rotate event i.e when slave does not have any history with the master (and thereafter mi->get_master_log_pos() is NULL). TODO: handling `when' for SHOW SLAVE STATUS' snds behind */ if ((memcmp(const_cast<char *>(mi->get_master_log_name()), hb.get_log_ident(), hb.get_ident_len()) && mi->get_master_log_name() != NULL) || ((mi->get_master_log_pos() != hb.log_pos && gtid_mode == 0) || /* When Gtid mode is on only monotocity can be claimed. Todo: enhance HB event with the skipped events size and to convert HB.pos == MI.pos to HB.pos - HB.skip_size == MI.pos */ (mi->get_master_log_pos() > hb.log_pos))) { /* missed events of heartbeat from the past */ error= ER_SLAVE_HEARTBEAT_FAILURE; error_msg.append(STRING_WITH_LEN("heartbeat is not compatible with local info;")); error_msg.append(STRING_WITH_LEN("the event's data: log_file_name ")); error_msg.append(hb.get_log_ident(), (uint) strlen(hb.get_log_ident())); error_msg.append(STRING_WITH_LEN(" log_pos ")); llstr(hb.log_pos, llbuf); error_msg.append(llbuf, strlen(llbuf)); goto err; } goto skip_relay_logging; } break; case PREVIOUS_GTIDS_LOG_EVENT: { /* This event does not have any meaning for the slave and was just sent to show the slave the master is making progress and avoid possible deadlocks. So at this point, the event is replaced by a rotate event what will make the slave to update what it knows about the master's coordinates. */ inc_pos= 0; mi->set_master_log_pos(mi->get_master_log_pos() + event_len); memcpy(rli->ign_master_log_name_end, mi->get_master_log_name(), FN_REFLEN); rli->ign_master_log_pos_end= mi->get_master_log_pos(); if (write_ignored_events_info_to_relay_log(mi->info_thd, mi)) goto err; goto skip_relay_logging; } break; case GTID_LOG_EVENT: { if (gtid_mode == 0) { error= ER_FOUND_GTID_EVENT_WHEN_GTID_MODE_IS_OFF; goto err; } global_sid_lock->rdlock(); Gtid_log_event gtid_ev(buf, checksum_alg != BINLOG_CHECKSUM_ALG_OFF ? event_len - BINLOG_CHECKSUM_LEN : event_len, mi->get_mi_description_event()); gtid.sidno= gtid_ev.get_sidno(false); global_sid_lock->unlock(); if (gtid.sidno < 0) goto err; gtid.gno= gtid_ev.get_gno(); inc_pos= event_len; } break; case ANONYMOUS_GTID_LOG_EVENT: default: inc_pos= event_len; break; } /* Simulate an unknown ignorable log event by rewriting the write_rows log event and previous_gtids log event before writing them in relay log. */ DBUG_EXECUTE_IF("simulate_unknown_ignorable_log_event", if (event_type == WRITE_ROWS_EVENT || event_type == PREVIOUS_GTIDS_LOG_EVENT) { char *event_buf= const_cast<char*>(buf); /* Overwrite the log event type with an unknown type. */ event_buf[EVENT_TYPE_OFFSET]= ENUM_END_EVENT + 1; /* Set LOG_EVENT_IGNORABLE_F for the log event. */ int2store(event_buf + FLAGS_OFFSET, uint2korr(event_buf + FLAGS_OFFSET) | LOG_EVENT_IGNORABLE_F); } ); /* If this event is originating from this server, don't queue it. We don't check this for 3.23 events because it's simpler like this; 3.23 will be filtered anyway by the SQL slave thread which also tests the server id (we must also keep this test in the SQL thread, in case somebody upgrades a 4.0 slave which has a not-filtered relay log). ANY event coming from ourselves can be ignored: it is obvious for queries; for STOP_EVENT/ROTATE_EVENT/START_EVENT: these cannot come from ourselves (--log-slave-updates would not log that) unless this slave is also its direct master (an unsupported, useless setup!). */ mysql_mutex_lock(log_lock); s_id= uint4korr(buf + SERVER_ID_OFFSET); /* If server_id_bits option is set we need to mask out irrelevant bits when checking server_id, but we still put the full unmasked server_id into the Relay log so that it can be accessed when applying the event */ s_id&= opt_server_id_mask; if ((s_id == ::server_id && !mi->rli->replicate_same_server_id) || /* the following conjunction deals with IGNORE_SERVER_IDS, if set If the master is on the ignore list, execution of format description log events and rotate events is necessary. */ (mi->ignore_server_ids->dynamic_ids.elements > 0 && mi->shall_ignore_server_id(s_id) && /* everything is filtered out from non-master */ (s_id != mi->master_id || /* for the master meta information is necessary */ (event_type != FORMAT_DESCRIPTION_EVENT && event_type != ROTATE_EVENT)))) { /* Do not write it to the relay log. a) We still want to increment mi->get_master_log_pos(), so that we won't re-read this event from the master if the slave IO thread is now stopped/restarted (more efficient if the events we are ignoring are big LOAD DATA INFILE). b) We want to record that we are skipping events, for the information of the slave SQL thread, otherwise that thread may let rli->group_relay_log_pos stay too small if the last binlog's event is ignored. But events which were generated by this slave and which do not exist in the master's binlog (i.e. Format_desc, Rotate & Stop) should not increment mi->get_master_log_pos(). If the event is originated remotely and is being filtered out by IGNORE_SERVER_IDS it increments mi->get_master_log_pos() as well as rli->group_relay_log_pos. */ if (!(s_id == ::server_id && !mi->rli->replicate_same_server_id) || (event_type != FORMAT_DESCRIPTION_EVENT && event_type != ROTATE_EVENT && event_type != STOP_EVENT)) { mi->set_master_log_pos(mi->get_master_log_pos() + inc_pos); memcpy(rli->ign_master_log_name_end, mi->get_master_log_name(), FN_REFLEN); DBUG_ASSERT(rli->ign_master_log_name_end[0]); rli->ign_master_log_pos_end= mi->get_master_log_pos(); } rli->relay_log.signal_update(); // the slave SQL thread needs to re-check DBUG_PRINT("info", ("master_log_pos: %lu, event originating from %u server, ignored", (ulong) mi->get_master_log_pos(), uint4korr(buf + SERVER_ID_OFFSET))); } else { /* write the event to the relay log */ if (likely(rli->relay_log.append_buffer(buf, event_len, mi) == 0)) { mi->set_master_log_pos(mi->get_master_log_pos() + inc_pos); DBUG_PRINT("info", ("master_log_pos: %lu", (ulong) mi->get_master_log_pos())); rli->relay_log.harvest_bytes_written(&rli->log_space_total); if (event_type == GTID_LOG_EVENT) { global_sid_lock->rdlock(); int ret= rli->add_logged_gtid(gtid.sidno, gtid.gno); if (!ret) rli->set_last_retrieved_gtid(gtid); global_sid_lock->unlock(); if (ret != 0) goto err; } } else { error= ER_SLAVE_RELAY_LOG_WRITE_FAILURE; } rli->ign_master_log_name_end[0]= 0; // last event is not ignored if (save_buf != NULL) buf= save_buf; } mysql_mutex_unlock(log_lock); skip_relay_logging: err: if (unlock_data_lock) mysql_mutex_unlock(&mi->data_lock); DBUG_PRINT("info", ("error: %d", error)); if (error) mi->report(ERROR_LEVEL, error, ER(error), (error == ER_SLAVE_RELAY_LOG_WRITE_FAILURE)? "could not queue event from master" : error_msg.ptr()); DBUG_RETURN(error); } /** Hook to detach the active VIO before closing a connection handle. The client API might close the connection (and associated data) in case it encounters a unrecoverable (network) error. This hook is called from the client code before the VIO handle is deleted allows the thread to detach the active vio so it does not point to freed memory. Other calls to THD::clear_active_vio throughout this module are redundant due to the hook but are left in place for illustrative purposes. */ extern "C" void slave_io_thread_detach_vio() { #ifdef SIGNAL_WITH_VIO_SHUTDOWN THD *thd= current_thd; if (thd && thd->slave_thread) thd->clear_active_vio(); #endif } /* Try to connect until successful or slave killed SYNPOSIS safe_connect() thd Thread handler for slave mysql MySQL connection handle mi Replication handle RETURN 0 ok # Error */ static int safe_connect(THD* thd, MYSQL* mysql, Master_info* mi) { DBUG_ENTER("safe_connect"); DBUG_RETURN(connect_to_master(thd, mysql, mi, 0, 0)); } /* SYNPOSIS connect_to_master() IMPLEMENTATION Try to connect until successful or slave killed or we have retried mi->retry_count times */ static int connect_to_master(THD* thd, MYSQL* mysql, Master_info* mi, bool reconnect, bool suppress_warnings) { int slave_was_killed= 0; int last_errno= -2; // impossible error ulong err_count=0; char llbuff[22]; char password[MAX_PASSWORD_LENGTH + 1]; int password_size= sizeof(password); DBUG_ENTER("connect_to_master"); set_slave_max_allowed_packet(thd, mysql); #ifndef DBUG_OFF mi->events_until_exit = disconnect_slave_event_count; #endif ulong client_flag= CLIENT_REMEMBER_OPTIONS; if (opt_slave_compressed_protocol) client_flag|= CLIENT_COMPRESS; /* We will use compression */ mysql_options(mysql, MYSQL_OPT_CONNECT_TIMEOUT, (char *) &slave_net_timeout); mysql_options(mysql, MYSQL_OPT_READ_TIMEOUT, (char *) &slave_net_timeout); if (mi->bind_addr[0]) { DBUG_PRINT("info",("bind_addr: %s", mi->bind_addr)); mysql_options(mysql, MYSQL_OPT_BIND, mi->bind_addr); } #ifdef HAVE_OPENSSL if (mi->ssl) { mysql_ssl_set(mysql, mi->ssl_key[0]?mi->ssl_key:0, mi->ssl_cert[0]?mi->ssl_cert:0, mi->ssl_ca[0]?mi->ssl_ca:0, mi->ssl_capath[0]?mi->ssl_capath:0, mi->ssl_cipher[0]?mi->ssl_cipher:0); #ifdef HAVE_YASSL mi->ssl_crl[0]= '\0'; mi->ssl_crlpath[0]= '\0'; #endif mysql_options(mysql, MYSQL_OPT_SSL_CRL, mi->ssl_crl[0] ? mi->ssl_crl : 0); mysql_options(mysql, MYSQL_OPT_SSL_CRLPATH, mi->ssl_crlpath[0] ? mi->ssl_crlpath : 0); mysql_options(mysql, MYSQL_OPT_SSL_VERIFY_SERVER_CERT, &mi->ssl_verify_server_cert); } #endif /* If server's default charset is not supported (like utf16, utf32) as client charset, then set client charset to 'latin1' (default client charset). */ if (is_supported_parser_charset(default_charset_info)) mysql_options(mysql, MYSQL_SET_CHARSET_NAME, default_charset_info->csname); else { sql_print_information("'%s' can not be used as client character set. " "'%s' will be used as default client character set " "while connecting to master.", default_charset_info->csname, default_client_charset_info->csname); mysql_options(mysql, MYSQL_SET_CHARSET_NAME, default_client_charset_info->csname); } /* This one is not strictly needed but we have it here for completeness */ mysql_options(mysql, MYSQL_SET_CHARSET_DIR, (char *) charsets_dir); if (mi->is_start_plugin_auth_configured()) { DBUG_PRINT("info", ("Slaving is using MYSQL_DEFAULT_AUTH %s", mi->get_start_plugin_auth())); mysql_options(mysql, MYSQL_DEFAULT_AUTH, mi->get_start_plugin_auth()); } if (mi->is_start_plugin_dir_configured()) { DBUG_PRINT("info", ("Slaving is using MYSQL_PLUGIN_DIR %s", mi->get_start_plugin_dir())); mysql_options(mysql, MYSQL_PLUGIN_DIR, mi->get_start_plugin_dir()); } /* Set MYSQL_PLUGIN_DIR in case master asks for an external authentication plugin */ else if (opt_plugin_dir_ptr && *opt_plugin_dir_ptr) mysql_options(mysql, MYSQL_PLUGIN_DIR, opt_plugin_dir_ptr); if (!mi->is_start_user_configured()) sql_print_warning("%s", ER(ER_INSECURE_CHANGE_MASTER)); if (mi->get_password(password, &password_size)) { mi->report(ERROR_LEVEL, ER_SLAVE_FATAL_ERROR, ER(ER_SLAVE_FATAL_ERROR), "Unable to configure password when attempting to " "connect to the master server. Connection attempt " "terminated."); DBUG_RETURN(1); } const char* user= mi->get_user(); if (user == NULL || user[0] == 0) { mi->report(ERROR_LEVEL, ER_SLAVE_FATAL_ERROR, ER(ER_SLAVE_FATAL_ERROR), "Invalid (empty) username when attempting to " "connect to the master server. Connection attempt " "terminated."); DBUG_RETURN(1); } mysql_options(mysql, MYSQL_OPT_NET_RECEIVE_BUFFER_SIZE, &rpl_receive_buffer_size); while (!(slave_was_killed = io_slave_killed(thd,mi)) && (reconnect ? mysql_reconnect(mysql) != 0 : mysql_real_connect(mysql, mi->host, user, password, 0, mi->port, 0, client_flag) == 0)) { /* SHOW SLAVE STATUS will display the number of retries which would be real retry counts instead of mi->retry_count for each connection attempt by 'Last_IO_Error' entry. */ last_errno=mysql_errno(mysql); suppress_warnings= 0; mi->report(ERROR_LEVEL, last_errno, "error %s to master '%s@%s:%d'" " - retry-time: %d retries: %lu", (reconnect ? "reconnecting" : "connecting"), mi->get_user(), mi->host, mi->port, mi->connect_retry, err_count + 1); /* By default we try forever. The reason is that failure will trigger master election, so if the user did not set mi->retry_count we do not want to have election triggered on the first failure to connect */ if (++err_count == mi->retry_count) { slave_was_killed=1; break; } slave_sleep(thd, mi->connect_retry, io_slave_killed, mi); } if (!slave_was_killed) { mi->clear_error(); // clear possible left over reconnect error if (reconnect) { if (!suppress_warnings && log_warnings) sql_print_information("Slave: connected to master '%s@%s:%d',\ replication resumed in log '%s' at position %s", mi->get_user(), mi->host, mi->port, mi->get_io_rpl_log_name(), llstr(mi->get_master_log_pos(),llbuff)); } else { general_log_print(thd, COM_CONNECT_OUT, "%s@%s:%d", mi->get_user(), mi->host, mi->port); } #ifdef SIGNAL_WITH_VIO_SHUTDOWN thd->set_active_vio(mysql->net.vio); #endif } if (mysql_get_ssl_cipher(mysql)) { strncpy(mi->ssl_actual_cipher, mysql_get_ssl_cipher(mysql), sizeof(mi->ssl_actual_cipher)); mi->ssl_actual_cipher[sizeof(mi->ssl_actual_cipher) - 1] = 0; mysql_get_ssl_server_cerfificate_info( mysql, mi->ssl_master_issuer, sizeof(mi->ssl_master_issuer), mi->ssl_master_subject, sizeof(mi->ssl_master_subject)); } mysql->reconnect= 1; DBUG_PRINT("exit",("slave_was_killed: %d", slave_was_killed)); DBUG_RETURN(slave_was_killed); } /* safe_reconnect() IMPLEMENTATION Try to connect until successful or slave killed or we have retried mi->retry_count times */ static int safe_reconnect(THD* thd, MYSQL* mysql, Master_info* mi, bool suppress_warnings) { DBUG_ENTER("safe_reconnect"); DBUG_RETURN(connect_to_master(thd, mysql, mi, 1, suppress_warnings)); } /* Called when we notice that the current "hot" log got rotated under our feet. */ static IO_CACHE *reopen_relay_log(Relay_log_info *rli, const char **errmsg) { DBUG_ENTER("reopen_relay_log"); DBUG_ASSERT(rli->cur_log != &rli->cache_buf); DBUG_ASSERT(rli->cur_log_fd == -1); IO_CACHE *cur_log = rli->cur_log=&rli->cache_buf; if ((rli->cur_log_fd=open_binlog_file(cur_log,rli->get_event_relay_log_name(), errmsg)) <0) DBUG_RETURN(0); /* We want to start exactly where we was before: relay_log_pos Current log pos pending Number of bytes already processed from the event */ rli->set_event_relay_log_pos(max<ulonglong>(rli->get_event_relay_log_pos(), BIN_LOG_HEADER_SIZE)); my_b_seek(cur_log,rli->get_event_relay_log_pos()); DBUG_RETURN(cur_log); } /** Reads next event from the relay log. Should be called from the slave IO thread. @param rli Relay_log_info structure for the slave IO thread. @return The event read, or NULL on error. If an error occurs, the error is reported through the sql_print_information() or sql_print_error() functions. */ static Log_event* next_event(Relay_log_info* rli) { Log_event* ev; IO_CACHE* cur_log = rli->cur_log; mysql_mutex_t *log_lock = rli->relay_log.get_log_lock(); const char* errmsg=0; THD* thd = rli->info_thd; int read_length; /* length of event read from relay log */ DBUG_ENTER("next_event"); DBUG_ASSERT(thd != 0); #ifndef DBUG_OFF if (abort_slave_event_count && !rli->events_until_exit--) DBUG_RETURN(0); #endif /* For most operations we need to protect rli members with data_lock, so we assume calling function acquired this mutex for us and we will hold it for the most of the loop below However, we will release it whenever it is worth the hassle, and in the cases when we go into a mysql_cond_wait() with the non-data_lock mutex */ mysql_mutex_assert_owner(&rli->data_lock); while (!sql_slave_killed(thd,rli)) { /* We can have two kinds of log reading: hot_log: rli->cur_log points at the IO_CACHE of relay_log, which is actively being updated by the I/O thread. We need to be careful in this case and make sure that we are not looking at a stale log that has already been rotated. If it has been, we reopen the log. The other case is much simpler: We just have a read only log that nobody else will be updating. */ bool hot_log; if ((hot_log = (cur_log != &rli->cache_buf))) { DBUG_ASSERT(rli->cur_log_fd == -1); // foreign descriptor mysql_mutex_lock(log_lock); /* Reading xxx_file_id is safe because the log will only be rotated when we hold relay_log.LOCK_log */ if (rli->relay_log.get_open_count() != rli->cur_log_old_open_count) { // The master has switched to a new log file; Reopen the old log file cur_log=reopen_relay_log(rli, &errmsg); mysql_mutex_unlock(log_lock); if (!cur_log) // No more log files goto err; hot_log=0; // Using old binary log } } /* As there is no guarantee that the relay is open (for example, an I/O error during a write by the slave I/O thread may have closed it), we have to test it. */ if (!my_b_inited(cur_log)) goto err; #ifndef DBUG_OFF { DBUG_PRINT("info", ("assertion skip %lu file pos %lu event relay log pos %lu file %s\n", (ulong) rli->slave_skip_counter, (ulong) my_b_tell(cur_log), (ulong) rli->get_event_relay_log_pos(), rli->get_event_relay_log_name())); /* This is an assertion which sometimes fails, let's try to track it */ char llbuf1[22], llbuf2[22]; DBUG_PRINT("info", ("my_b_tell(cur_log)=%s rli->event_relay_log_pos=%s", llstr(my_b_tell(cur_log),llbuf1), llstr(rli->get_event_relay_log_pos(),llbuf2))); DBUG_ASSERT(my_b_tell(cur_log) >= BIN_LOG_HEADER_SIZE); DBUG_ASSERT(my_b_tell(cur_log) == rli->get_event_relay_log_pos() || rli->is_parallel_exec()); DBUG_PRINT("info", ("next_event group master %s %lu group relay %s %lu event %s %lu\n", rli->get_group_master_log_name(), (ulong) rli->get_group_master_log_pos(), rli->get_group_relay_log_name(), (ulong) rli->get_group_relay_log_pos(), rli->get_event_relay_log_name(), (ulong) rli->get_event_relay_log_pos())); } #endif /* Relay log is always in new format - if the master is 3.23, the I/O thread will convert the format for us. A problem: the description event may be in a previous relay log. So if the slave has been shutdown meanwhile, we would have to look in old relay logs, which may even have been deleted. So we need to write this description event at the beginning of the relay log. When the relay log is created when the I/O thread starts, easy: the master will send the description event and we will queue it. But if the relay log is created by new_file(): then the solution is: MYSQL_BIN_LOG::open() will write the buffered description event. */ if ((ev= Log_event::read_log_event(cur_log, 0, rli->get_rli_description_event(), opt_slave_sql_verify_checksum, &read_length))) { DBUG_ASSERT(thd==rli->info_thd); /* read it while we have a lock, to avoid a mutex lock in inc_event_relay_log_pos() */ rli->set_future_event_relay_log_pos(my_b_tell(cur_log)); ev->future_event_relay_log_pos= rli->get_future_event_relay_log_pos(); if (hot_log) mysql_mutex_unlock(log_lock); relay_sql_events++; relay_sql_bytes += read_length; /* MTS checkpoint in the successful read branch */ bool force= (rli->checkpoint_seqno > (rli->checkpoint_group - 1)); if (rli->is_parallel_exec() && (opt_mts_checkpoint_period != 0 || force)) { ulonglong period= static_cast<ulonglong>(opt_mts_checkpoint_period * 1000000ULL); mysql_mutex_unlock(&rli->data_lock); /* At this point the coordinator has is delegating jobs to workers and the checkpoint routine must be periodically invoked. */ (void) mts_checkpoint_routine(rli, period, force, true/*need_data_lock=true*/); // TODO: ALFRANIO ERROR DBUG_ASSERT(!force || (force && (rli->checkpoint_seqno <= (rli->checkpoint_group - 1))) || sql_slave_killed(thd, rli)); mysql_mutex_lock(&rli->data_lock); } DBUG_RETURN(ev); } DBUG_ASSERT(thd==rli->info_thd); if (opt_reckless_slave) // For mysql-test cur_log->error = 0; if (cur_log->error < 0) { errmsg = "slave SQL thread aborted because of I/O error"; if (rli->mts_group_status == Relay_log_info::MTS_IN_GROUP) /* MTS group status is set to MTS_KILLED_GROUP, whenever a read event error happens and there was already a non-terminal event scheduled. */ rli->mts_group_status= Relay_log_info::MTS_KILLED_GROUP; if (hot_log) mysql_mutex_unlock(log_lock); goto err; } if (!cur_log->error) /* EOF */ { ulonglong wait_timer; /* time wait for more data in binlog */ /* On a hot log, EOF means that there are no more updates to process and we must block until I/O thread adds some and signals us to continue */ if (hot_log) { /* We say in Seconds_Behind_Master that we have "caught up". Note that for example if network link is broken but I/O slave thread hasn't noticed it (slave_net_timeout not elapsed), then we'll say "caught up" whereas we're not really caught up. Fixing that would require internally cutting timeout in smaller pieces in network read, no thanks. Another example: SQL has caught up on I/O, now I/O has read a new event and is queuing it; the false "0" will exist until SQL finishes executing the new event; it will be look abnormal only if the events have old timestamps (then you get "many", 0, "many"). Transient phases like this can be fixed with implemeting Heartbeat event which provides the slave the status of the master at time the master does not have any new update to send. Seconds_Behind_Master would be zero only when master has no more updates in binlog for slave. The heartbeat can be sent in a (small) fraction of slave_net_timeout. Until it's done rli->last_master_timestamp is temporarely (for time of waiting for the following event) reset whenever EOF is reached. */ /* shows zero while it is sleeping (and until the next event is about to be executed). Note, in MTS case Seconds_Behind_Master resetting follows slightly different schema where reaching EOF is not enough. The status parameter is updated per some number of processed group of events. The number can't be greater than @@global.slave_checkpoint_group and anyway SBM updating rate does not exceed @@global.slave_checkpoint_period. Notice that SBM is set to a new value after processing the terminal event (e.g Commit) of a group. Coordinator resets SBM when notices no more groups left neither to read from Relay-log nor to process by Workers. */ if (!rli->is_parallel_exec() && reset_seconds_behind_master) rli->last_master_timestamp= 0; DBUG_ASSERT(rli->relay_log.get_open_count() == rli->cur_log_old_open_count); if (rli->ign_master_log_name_end[0]) { /* We generate and return a Rotate, to make our positions advance */ DBUG_PRINT("info",("seeing an ignored end segment")); ev= new Rotate_log_event(rli->ign_master_log_name_end, 0, rli->ign_master_log_pos_end, Rotate_log_event::DUP_NAME); rli->ign_master_log_name_end[0]= 0; mysql_mutex_unlock(log_lock); if (unlikely(!ev)) { errmsg= "Slave SQL thread failed to create a Rotate event " "(out of memory?), SHOW SLAVE STATUS may be inaccurate"; goto err; } ev->server_id= 0; // don't be ignored by slave SQL thread DBUG_RETURN(ev); } wait_timer = my_timer_now(); /* We can, and should release data_lock while we are waiting for update. If we do not, show slave status will block */ mysql_mutex_unlock(&rli->data_lock); /* Possible deadlock : - the I/O thread has reached log_space_limit - the SQL thread has read all relay logs, but cannot purge for some reason: * it has already purged all logs except the current one * there are other logs than the current one but they're involved in a transaction that finishes in the current one (or is not finished) Solution : Wake up the possibly waiting I/O thread, and set a boolean asking the I/O thread to temporarily ignore the log_space_limit constraint, because we do not want the I/O thread to block because of space (it's ok if it blocks for any other reason (e.g. because the master does not send anything). Then the I/O thread stops waiting and reads one more event and starts honoring log_space_limit again. If the SQL thread needs more events to be able to rotate the log (it might need to finish the current group first), then it can ask for one more at a time. Thus we don't outgrow the relay log indefinitely, but rather in a controlled manner, until the next rotate. When the SQL thread starts it sets ignore_log_space_limit to false. We should also reset ignore_log_space_limit to 0 when the user does RESET SLAVE, but in fact, no need as RESET SLAVE requires that the slave be stopped, and the SQL thread sets ignore_log_space_limit to 0 when it stops. */ mysql_mutex_lock(&rli->log_space_lock); /* If we have reached the limit of the relay space and we are going to sleep, waiting for more events: 1. If outside a group, SQL thread asks the IO thread to force a rotation so that the SQL thread purges logs next time it processes an event (thus space is freed). 2. If in a group, SQL thread asks the IO thread to ignore the limit and queues yet one more event so that the SQL thread finishes the group and is are able to rotate and purge sometime soon. */ if (rli->log_space_limit && rli->log_space_limit < rli->log_space_total) { /* force rotation if not in an unfinished group */ if (!rli->is_parallel_exec()) { rli->sql_force_rotate_relay= !rli->is_in_group(); } else { rli->sql_force_rotate_relay= (rli->mts_group_status != Relay_log_info::MTS_IN_GROUP); } /* ask for one more event */ rli->ignore_log_space_limit= true; } /* If the I/O thread is blocked, unblock it. Ok to broadcast after unlock, because the mutex is only destroyed in ~Relay_log_info(), i.e. when rli is destroyed, and rli will not be destroyed before we exit the present function. */ mysql_mutex_unlock(&rli->log_space_lock); mysql_cond_broadcast(&rli->log_space_cond); // Note that wait_for_update_relay_log unlocks lock_log ! if (rli->is_parallel_exec() && (opt_mts_checkpoint_period != 0 || DBUG_EVALUATE_IF("check_slave_debug_group", 1, 0))) { int ret= 0; struct timespec waittime; ulonglong period= static_cast<ulonglong>(opt_mts_checkpoint_period * 1000000ULL); ulong signal_cnt= rli->relay_log.signal_cnt; mysql_mutex_unlock(log_lock); do { /* At this point the coordinator has no job to delegate to workers. However, workers are executing their assigned jobs and as such the checkpoint routine must be periodically invoked. */ (void) mts_checkpoint_routine(rli, period, false, true/*need_data_lock=true*/); // TODO: ALFRANIO ERROR mysql_mutex_lock(log_lock); // More to the empty relay-log all assigned events done so reset it. if (rli->gaq->empty() && reset_seconds_behind_master) rli->last_master_timestamp= 0; if (DBUG_EVALUATE_IF("check_slave_debug_group", 1, 0)) period= 10000000ULL; set_timespec_nsec(waittime, period); ret= rli->relay_log.wait_for_update_relay_log(thd, &waittime); } while ((ret == ETIMEDOUT || ret == ETIME) /* todo:remove */ && signal_cnt == rli->relay_log.signal_cnt && !thd->killed); } else { rli->relay_log.wait_for_update_relay_log(thd, NULL); } // re-acquire data lock since we released it earlier mysql_mutex_lock(&rli->data_lock); relay_sql_wait_time += my_timer_since_and_update(&wait_timer); continue; } /* If the log was not hot, we need to move to the next log in sequence. The next log could be hot or cold, we deal with both cases separately after doing some common initialization */ end_io_cache(cur_log); DBUG_ASSERT(rli->cur_log_fd >= 0); mysql_file_close(rli->cur_log_fd, MYF(MY_WME)); rli->cur_log_fd = -1; if (relay_log_purge) { /* purge_first_log will properly set up relay log coordinates in rli. If the group's coordinates are equal to the event's coordinates (i.e. the relay log was not rotated in the middle of a group), we can purge this relay log too. We do ulonglong and string comparisons, this may be slow but - purging the last relay log is nice (it can save 1GB of disk), so we like to detect the case where we can do it, and given this, - I see no better detection method - purge_first_log is not called that often */ if (rli->relay_log.purge_first_log (rli, rli->get_group_relay_log_pos() == rli->get_event_relay_log_pos() && !strcmp(rli->get_group_relay_log_name(),rli->get_event_relay_log_name()))) { errmsg = "Error purging processed logs"; goto err; } DBUG_PRINT("info", ("next_event group master %s %lu group relay %s %lu event %s %lu\n", rli->get_group_master_log_name(), (ulong) rli->get_group_master_log_pos(), rli->get_group_relay_log_name(), (ulong) rli->get_group_relay_log_pos(), rli->get_event_relay_log_name(), (ulong) rli->get_event_relay_log_pos())); } else { /* If hot_log is set, then we already have a lock on LOCK_log. If not, we have to get the lock. According to Sasha, the only time this code will ever be executed is if we are recovering from a bug. */ if (rli->relay_log.find_next_log(&rli->linfo, !hot_log)) { errmsg = "error switching to the next log"; goto err; } rli->set_event_relay_log_pos(BIN_LOG_HEADER_SIZE); rli->set_event_relay_log_name(rli->linfo.log_file_name); /* We may update the worker here but this is not extremlly necessary. /Alfranio */ rli->flush_info(); } /* Reset the relay-log-change-notified status of Slave Workers */ if (rli->is_parallel_exec()) { DBUG_PRINT("info", ("next_event: MTS group relay log changes to %s %lu\n", rli->get_group_relay_log_name(), (ulong) rli->get_group_relay_log_pos())); rli->reset_notified_relay_log_change(); } /* Now we want to open this next log. To know if it's a hot log (the one being written by the I/O thread now) or a cold log, we can use is_active(); if it is hot, we use the I/O cache; if it's cold we open the file normally. But if is_active() reports that the log is hot, this may change between the test and the consequence of the test. So we may open the I/O cache whereas the log is now cold, which is nonsense. To guard against this, we need to have LOCK_log. */ DBUG_PRINT("info",("hot_log: %d",hot_log)); if (!hot_log) /* if hot_log, we already have this mutex */ mysql_mutex_lock(log_lock); if (rli->relay_log.is_active(rli->linfo.log_file_name)) { #ifdef EXTRA_DEBUG if (log_warnings) sql_print_information("next log '%s' is currently active", rli->linfo.log_file_name); #endif rli->cur_log= cur_log= rli->relay_log.get_log_file(); rli->cur_log_old_open_count= rli->relay_log.get_open_count(); DBUG_ASSERT(rli->cur_log_fd == -1); /* When the SQL thread is [stopped and] (re)started the following may happen: 1. Log was hot at stop time and remains hot at restart SQL thread reads again from hot_log (SQL thread was reading from the active log when it was stopped and the very same log is still active on SQL thread restart). In this case, my_b_seek is performed on cur_log, while cur_log points to relay_log.get_log_file(); 2. Log was hot at stop time but got cold before restart The log was hot when SQL thread stopped, but it is not anymore when the SQL thread restarts. In this case, the SQL thread reopens the log, using cache_buf, ie, cur_log points to &cache_buf, and thence its coordinates are reset. 3. Log was already cold at stop time The log was not hot when the SQL thread stopped, and, of course, it will not be hot when it restarts. In this case, the SQL thread opens the cold log again, using cache_buf, ie, cur_log points to &cache_buf, and thence its coordinates are reset. 4. Log was hot at stop time, DBA changes to previous cold log and restarts SQL thread The log was hot when the SQL thread was stopped, but the user changed the coordinates of the SQL thread to restart from a previous cold log. In this case, at start time, cur_log points to a cold log, opened using &cache_buf as cache, and coordinates are reset. However, as it moves on to the next logs, it will eventually reach the hot log. If the hot log is the same at the time the SQL thread was stopped, then coordinates were not reset - the cur_log will point to relay_log.get_log_file(), and not a freshly opened IO_CACHE through cache_buf. For this reason we need to deploy a my_b_seek before calling check_binlog_magic at this point of the code (see: BUG#55263 for more details). NOTES: - We must keep the LOCK_log to read the 4 first bytes, as this is a hot log (same as when we call read_log_event() above: for a hot log we take the mutex). - Because of scenario #4 above, we need to have a my_b_seek here. Otherwise, we might hit the assertion inside check_binlog_magic. */ my_b_seek(cur_log, (my_off_t) 0); if (check_binlog_magic(cur_log,&errmsg)) { if (!hot_log) mysql_mutex_unlock(log_lock); goto err; } if (!hot_log) mysql_mutex_unlock(log_lock); continue; } if (!hot_log) mysql_mutex_unlock(log_lock); /* if we get here, the log was not hot, so we will have to open it ourselves. We are sure that the log is still not hot now (a log can get from hot to cold, but not from cold to hot). No need for LOCK_log. */ #ifdef EXTRA_DEBUG if (log_warnings) sql_print_information("next log '%s' is not active", rli->linfo.log_file_name); #endif // open_binlog_file() will check the magic header if ((rli->cur_log_fd=open_binlog_file(cur_log,rli->linfo.log_file_name, &errmsg)) <0) goto err; } else { /* Read failed with a non-EOF error. TODO: come up with something better to handle this error */ if (hot_log) mysql_mutex_unlock(log_lock); sql_print_error("Slave SQL thread: I/O error reading \ event(errno: %d cur_log->error: %d)", my_errno,cur_log->error); // set read position to the beginning of the event my_b_seek(cur_log,rli->get_event_relay_log_pos()); /* otherwise, we have had a partial read */ errmsg = "Aborting slave SQL thread because of partial event read"; break; // To end of function } } if (!errmsg && log_warnings) { sql_print_information("Error reading relay log event: %s", "slave SQL thread was killed"); DBUG_RETURN(0); } err: if (errmsg) sql_print_error("Error reading relay log event: %s", errmsg); DBUG_RETURN(0); } /* Rotate a relay log (this is used only by FLUSH LOGS; the automatic rotation because of size is simpler because when we do it we already have all relevant locks; here we don't, so this function is mainly taking locks). Returns nothing as we cannot catch any error (MYSQL_BIN_LOG::new_file() is void). */ int rotate_relay_log(Master_info* mi) { DBUG_ENTER("rotate_relay_log"); mysql_mutex_assert_owner(&mi->data_lock); DBUG_EXECUTE_IF("crash_before_rotate_relaylog", DBUG_SUICIDE();); Relay_log_info* rli= mi->rli; int error= 0; /* We need to test inited because otherwise, new_file() will attempt to lock LOCK_log, which may not be inited (if we're not a slave). */ if (!rli->inited) { DBUG_PRINT("info", ("rli->inited == 0")); goto end; } /* If the relay log is closed, new_file() will do nothing. */ error= rli->relay_log.new_file(mi->get_mi_description_event()); if (error != 0) goto end; /* We harvest now, because otherwise BIN_LOG_HEADER_SIZE will not immediately be counted, so imagine a succession of FLUSH LOGS and assume the slave threads are started: relay_log_space decreases by the size of the deleted relay log, but does not increase, so flush-after-flush we may become negative, which is wrong. Even if this will be corrected as soon as a query is replicated on the slave (because the I/O thread will then call harvest_bytes_written() which will harvest all these BIN_LOG_HEADER_SIZE we forgot), it may give strange output in SHOW SLAVE STATUS meanwhile. So we harvest now. If the log is closed, then this will just harvest the last writes, probably 0 as they probably have been harvested. */ rli->relay_log.harvest_bytes_written(&rli->log_space_total); end: DBUG_RETURN(error); } /** Detects, based on master's version (as found in the relay log), if master has a certain bug. @param rli Relay_log_info which tells the master's version @param bug_id Number of the bug as found in bugs.mysql.com @param report bool report error message, default TRUE @param pred Predicate function that will be called with @c param to check for the bug. If the function return @c true, the bug is present, otherwise, it is not. @param param State passed to @c pred function. @return TRUE if master has the bug, FALSE if it does not. */ bool rpl_master_has_bug(const Relay_log_info *rli, uint bug_id, bool report, bool (*pred)(const void *), const void *param) { struct st_version_range_for_one_bug { uint bug_id; const uchar introduced_in[3]; // first version with bug const uchar fixed_in[3]; // first version with fix }; static struct st_version_range_for_one_bug versions_for_all_bugs[]= { {24432, { 5, 0, 24 }, { 5, 0, 38 } }, {24432, { 5, 1, 12 }, { 5, 1, 17 } }, {33029, { 5, 0, 0 }, { 5, 0, 58 } }, {33029, { 5, 1, 0 }, { 5, 1, 12 } }, {37426, { 5, 1, 0 }, { 5, 1, 26 } }, }; const uchar *master_ver= rli->get_rli_description_event()->server_version_split; DBUG_ASSERT(sizeof(rli->get_rli_description_event()->server_version_split) == 3); for (uint i= 0; i < sizeof(versions_for_all_bugs)/sizeof(*versions_for_all_bugs);i++) { const uchar *introduced_in= versions_for_all_bugs[i].introduced_in, *fixed_in= versions_for_all_bugs[i].fixed_in; if ((versions_for_all_bugs[i].bug_id == bug_id) && (memcmp(introduced_in, master_ver, 3) <= 0) && (memcmp(fixed_in, master_ver, 3) > 0) && (pred == NULL || (*pred)(param))) { if (!report) return TRUE; // a short message for SHOW SLAVE STATUS (message length constraints) my_printf_error(ER_UNKNOWN_ERROR, "master may suffer from" " http://bugs.mysql.com/bug.php?id=%u" " so slave stops; check error log on slave" " for more info", MYF(0), bug_id); // a verbose message for the error log rli->report(ERROR_LEVEL, ER_UNKNOWN_ERROR, "According to the master's version ('%s')," " it is probable that master suffers from this bug:" " http://bugs.mysql.com/bug.php?id=%u" " and thus replicating the current binary log event" " may make the slave's data become different from the" " master's data." " To take no risk, slave refuses to replicate" " this event and stops." " We recommend that all updates be stopped on the" " master and slave, that the data of both be" " manually synchronized," " that master's binary logs be deleted," " that master be upgraded to a version at least" " equal to '%d.%d.%d'. Then replication can be" " restarted.", rli->get_rli_description_event()->server_version, bug_id, fixed_in[0], fixed_in[1], fixed_in[2]); return TRUE; } } return FALSE; } /** BUG#33029, For all 5.0 up to 5.0.58 exclusive, and 5.1 up to 5.1.12 exclusive, if one statement in a SP generated AUTO_INCREMENT value by the top statement, all statements after it would be considered generated AUTO_INCREMENT value by the top statement, and a erroneous INSERT_ID value might be associated with these statement, which could cause duplicate entry error and stop the slave. Detect buggy master to work around. */ bool rpl_master_erroneous_autoinc(THD *thd) { if (active_mi != NULL && active_mi->rli->info_thd == thd) { Relay_log_info *rli= active_mi->rli; DBUG_EXECUTE_IF("simulate_bug33029", return TRUE;); return rpl_master_has_bug(rli, 33029, FALSE, NULL, NULL); } return FALSE; } /** a copy of active_mi->rli->slave_skip_counter, for showing in SHOW VARIABLES, INFORMATION_SCHEMA.GLOBAL_VARIABLES and @@sql_slave_skip_counter without taking all the mutexes needed to access active_mi->rli->slave_skip_counter properly. */ uint sql_slave_skip_counter; /** Execute a START SLAVE statement. @param thd Pointer to THD object for the client thread executing the statement. @param mi Pointer to Master_info object for the slave's IO thread. @param net_report If true, saves the exit status into Diagnostics_area. @retval 0 success @retval 1 error */ int start_slave(THD* thd , Master_info* mi, bool net_report) { int slave_errno= 0; int thread_mask; DBUG_ENTER("start_slave"); if (check_access(thd, SUPER_ACL, any_db, NULL, NULL, 0, 0)) DBUG_RETURN(1); if (thd->lex->slave_connection.user || thd->lex->slave_connection.password) { #if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY) if (thd->vio_ok() && !thd->net.vio->ssl_arg) push_warning(thd, Sql_condition::WARN_LEVEL_NOTE, ER_INSECURE_PLAIN_TEXT, ER(ER_INSECURE_PLAIN_TEXT)); #endif #if !defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY) push_warning(thd, Sql_condition::WARN_LEVEL_NOTE, ER_INSECURE_PLAIN_TEXT, ER(ER_INSECURE_PLAIN_TEXT)); #endif } lock_slave_threads(mi); // this allows us to cleanly read slave_running // Get a mask of _stopped_ threads init_thread_mask(&thread_mask,mi,1 /* inverse */); /* Below we will start all stopped threads. But if the user wants to start only one thread, do as if the other thread was running (as we don't wan't to touch the other thread), so set the bit to 0 for the other thread */ if (thd->lex->slave_thd_opt) thread_mask&= thd->lex->slave_thd_opt; if (thread_mask) //some threads are stopped, start them { if (global_init_info(mi, false, thread_mask)) slave_errno=ER_MASTER_INFO; else if (server_id_supplied && *mi->host) { /* If we will start IO thread we need to take care of possible options provided through the START SLAVE if there is any. */ if (thread_mask & SLAVE_IO) { if (thd->lex->slave_connection.user) { mi->set_start_user_configured(true); mi->set_user(thd->lex->slave_connection.user); } if (thd->lex->slave_connection.password) { mi->set_start_user_configured(true); mi->set_password(thd->lex->slave_connection.password, strlen(thd->lex->slave_connection.password)); } if (thd->lex->slave_connection.plugin_auth) mi->set_plugin_auth(thd->lex->slave_connection.plugin_auth); if (thd->lex->slave_connection.plugin_dir) mi->set_plugin_dir(thd->lex->slave_connection.plugin_dir); } /* If we will start SQL thread we will care about UNTIL options If not and they are specified we will ignore them and warn user about this fact. */ if (thread_mask & SLAVE_SQL) { /* To cache the MTS system var values and used them in the following runtime. The system var:s can change meanwhile but having no other effects. */ mi->rli->opt_slave_parallel_workers= opt_mts_slave_parallel_workers; #ifndef DBUG_OFF if (!DBUG_EVALUATE_IF("check_slave_debug_group", 1, 0)) #endif mi->rli->checkpoint_group= opt_mts_checkpoint_group; mysql_mutex_lock(&mi->rli->data_lock); if (thd->lex->mi.pos) { if (thd->lex->mi.relay_log_pos) slave_errno= ER_BAD_SLAVE_UNTIL_COND; mi->rli->until_condition= Relay_log_info::UNTIL_MASTER_POS; mi->rli->until_log_pos= thd->lex->mi.pos; /* We don't check thd->lex->mi.log_file_name for NULL here since it is checked in sql_yacc.yy */ strmake(mi->rli->until_log_name, thd->lex->mi.log_file_name, sizeof(mi->rli->until_log_name)-1); } else if (thd->lex->mi.relay_log_pos) { if (thd->lex->mi.pos) slave_errno= ER_BAD_SLAVE_UNTIL_COND; mi->rli->until_condition= Relay_log_info::UNTIL_RELAY_POS; mi->rli->until_log_pos= thd->lex->mi.relay_log_pos; strmake(mi->rli->until_log_name, thd->lex->mi.relay_log_name, sizeof(mi->rli->until_log_name)-1); } else if (thd->lex->mi.gtid) { global_sid_lock->wrlock(); mi->rli->clear_until_condition(); if (mi->rli->until_sql_gtids.add_gtid_text(thd->lex->mi.gtid) != RETURN_STATUS_OK) slave_errno= ER_BAD_SLAVE_UNTIL_COND; else { mi->rli->until_condition= LEX_MASTER_INFO::UNTIL_SQL_BEFORE_GTIDS == thd->lex->mi.gtid_until_condition ? Relay_log_info::UNTIL_SQL_BEFORE_GTIDS : Relay_log_info::UNTIL_SQL_AFTER_GTIDS; if ((mi->rli->until_condition == Relay_log_info::UNTIL_SQL_AFTER_GTIDS) && mi->rli->opt_slave_parallel_workers != 0) { mi->rli->opt_slave_parallel_workers= 0; push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE, ER_MTS_FEATURE_IS_NOT_SUPPORTED, ER(ER_MTS_FEATURE_IS_NOT_SUPPORTED), "UNTIL condtion", "Slave is started in the sequential execution mode."); } } global_sid_lock->unlock(); } else if (thd->lex->mi.until_after_gaps) { mi->rli->until_condition= Relay_log_info::UNTIL_SQL_AFTER_MTS_GAPS; mi->rli->opt_slave_parallel_workers= mi->rli->recovery_parallel_workers; } else mi->rli->clear_until_condition(); if (mi->rli->until_condition == Relay_log_info::UNTIL_MASTER_POS || mi->rli->until_condition == Relay_log_info::UNTIL_RELAY_POS) { /* Preparing members for effective until condition checking */ const char *p= fn_ext(mi->rli->until_log_name); char *p_end; if (*p) { //p points to '.' mi->rli->until_log_name_extension= strtoul(++p,&p_end, 10); /* p_end points to the first invalid character. If it equals to p, no digits were found, error. If it contains '\0' it means conversion went ok. */ if (p_end==p || *p_end) slave_errno=ER_BAD_SLAVE_UNTIL_COND; } else slave_errno=ER_BAD_SLAVE_UNTIL_COND; /* mark the cached result of the UNTIL comparison as "undefined" */ mi->rli->until_log_names_cmp_result= Relay_log_info::UNTIL_LOG_NAMES_CMP_UNKNOWN; /* Issuing warning then started without --skip-slave-start */ if (!opt_skip_slave_start) push_warning(thd, Sql_condition::WARN_LEVEL_NOTE, ER_MISSING_SKIP_SLAVE, ER(ER_MISSING_SKIP_SLAVE)); if (mi->rli->opt_slave_parallel_workers != 0) { mi->rli->opt_slave_parallel_workers= 0; push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE, ER_MTS_FEATURE_IS_NOT_SUPPORTED, ER(ER_MTS_FEATURE_IS_NOT_SUPPORTED), "UNTIL condtion", "Slave is started in the sequential execution mode."); } } mysql_mutex_unlock(&mi->rli->data_lock); } else if (thd->lex->mi.pos || thd->lex->mi.relay_log_pos || thd->lex->mi.gtid) push_warning(thd, Sql_condition::WARN_LEVEL_NOTE, ER_UNTIL_COND_IGNORED, ER(ER_UNTIL_COND_IGNORED)); if (!slave_errno) slave_errno = start_slave_threads(false/*need_lock_slave=false*/, true/*wait_for_start=true*/, mi, thread_mask); } else slave_errno = ER_BAD_SLAVE; } else { /* no error if all threads are already started, only a warning */ push_warning(thd, Sql_condition::WARN_LEVEL_NOTE, ER_SLAVE_WAS_RUNNING, ER(ER_SLAVE_WAS_RUNNING)); } /* Clean up start information if there was an attempt to start the IO thread to avoid any security issue. */ if (slave_errno && (thread_mask & SLAVE_IO) == SLAVE_IO) mi->reset_start_info(); unlock_slave_threads(mi); if (slave_errno) { if (net_report) my_message(slave_errno, ER(slave_errno), MYF(0)); DBUG_RETURN(1); } else if (net_report) my_ok(thd); DBUG_RETURN(0); } /** Execute a STOP SLAVE statement. @param thd Pointer to THD object for the client thread executing the statement. @param mi Pointer to Master_info object for the slave's IO thread. @param net_report If true, saves the exit status into Diagnostics_area. @retval 0 success @retval 1 error */ int stop_slave(THD* thd, Master_info* mi, bool net_report ) { DBUG_ENTER("stop_slave"); int slave_errno; if (!thd) thd = current_thd; if (check_access(thd, SUPER_ACL, any_db, NULL, NULL, 0, 0)) DBUG_RETURN(1); THD_STAGE_INFO(thd, stage_killing_slave); int thread_mask; lock_slave_threads(mi); // Get a mask of _running_ threads init_thread_mask(&thread_mask,mi,0 /* not inverse*/); /* Below we will stop all running threads. But if the user wants to stop only one thread, do as if the other thread was stopped (as we don't wan't to touch the other thread), so set the bit to 0 for the other thread */ if (thd->lex->slave_thd_opt) thread_mask &= thd->lex->slave_thd_opt; if (thread_mask) { slave_errno= terminate_slave_threads(mi,thread_mask, false/*need_lock_term=false*/); } else { //no error if both threads are already stopped, only a warning slave_errno= 0; push_warning(thd, Sql_condition::WARN_LEVEL_NOTE, ER_SLAVE_WAS_NOT_RUNNING, ER(ER_SLAVE_WAS_NOT_RUNNING)); } unlock_slave_threads(mi); if (slave_errno) { if ((slave_errno == ER_STOP_SLAVE_SQL_THREAD_TIMEOUT) || (slave_errno == ER_STOP_SLAVE_IO_THREAD_TIMEOUT)) { push_warning(thd, Sql_condition::WARN_LEVEL_NOTE, slave_errno, ER(slave_errno)); sql_print_warning("%s",ER(slave_errno)); } if (net_report) my_message(slave_errno, ER(slave_errno), MYF(0)); DBUG_RETURN(1); } else if (net_report) my_ok(thd); DBUG_RETURN(0); } /** Execute a RESET SLAVE statement. @param thd Pointer to THD object of the client thread executing the statement. @param mi Pointer to Master_info object for the slave. @retval 0 success @retval 1 error */ int reset_slave(THD *thd, Master_info* mi) { int thread_mask= 0, error= 0; uint sql_errno=ER_UNKNOWN_ERROR; const char* errmsg= "Unknown error occured while reseting slave"; DBUG_ENTER("reset_slave"); lock_slave_threads(mi); init_thread_mask(&thread_mask,mi,0 /* not inverse */); if (thread_mask) // We refuse if any slave thread is running { sql_errno= ER_SLAVE_MUST_STOP; error=1; goto err; } ha_reset_slave(thd); // delete relay logs, clear relay log coordinates if ((error= mi->rli->purge_relay_logs(thd, 1 /* just reset */, &errmsg))) { sql_errno= ER_RELAY_LOG_FAIL; goto err; } /* Clear master's log coordinates and associated information */ DBUG_ASSERT(!mi->rli || !mi->rli->slave_running); // none writes in rli table mi->clear_in_memory_info(thd->lex->reset_slave_info.all); if (remove_info(mi)) { error= 1; goto err; } is_slave = mi->host[0]; (void) RUN_HOOK(binlog_relay_io, after_reset_slave, (thd, mi)); err: unlock_slave_threads(mi); if (error) my_error(sql_errno, MYF(0), errmsg); DBUG_RETURN(error); } /** Execute a CHANGE MASTER statement. MTS workers info tables data are removed in the successful branch (i.e. there are no gaps in the execution history). @param thd Pointer to THD object for the client thread executing the statement. @param mi Pointer to Master_info object belonging to the slave's IO thread. @retval FALSE success @retval TRUE error */ bool change_master(THD* thd, Master_info* mi) { int thread_mask; const char* errmsg= 0; bool need_relay_log_purge= 1; char *var_master_log_name= NULL, *var_group_master_log_name= NULL; bool ret= false; char saved_host[HOSTNAME_LENGTH + 1], saved_bind_addr[HOSTNAME_LENGTH + 1]; uint saved_port= 0; char saved_log_name[FN_REFLEN]; my_off_t saved_log_pos= 0; my_bool save_relay_log_purge= relay_log_purge; bool mts_remove_workers= false; DBUG_ENTER("change_master"); lock_slave_threads(mi); init_thread_mask(&thread_mask,mi,0 /*not inverse*/); LEX_MASTER_INFO* lex_mi= &thd->lex->mi; if (thread_mask) // We refuse if any slave thread is running { my_message(ER_SLAVE_MUST_STOP, ER(ER_SLAVE_MUST_STOP), MYF(0)); ret= true; goto err; } thread_mask= SLAVE_IO | SLAVE_SQL; THD_STAGE_INFO(thd, stage_changing_master); /* We need to check if there is an empty master_host. Otherwise change master succeeds, a master.info file is created containing empty master_host string and when issuing: start slave; an error is thrown stating that the server is not configured as slave. (See BUG#28796). */ if(lex_mi->host && !*lex_mi->host) { my_error(ER_WRONG_ARGUMENTS, MYF(0), "MASTER_HOST"); unlock_slave_threads(mi); DBUG_RETURN(TRUE); } if (global_init_info(mi, false, thread_mask)) { my_message(ER_MASTER_INFO, ER(ER_MASTER_INFO), MYF(0)); ret= true; goto err; } if (mi->rli->mts_recovery_group_cnt) { /* Change-Master can't be done if there is a mts group gap. That requires mts-recovery which START SLAVE provides. */ DBUG_ASSERT(mi->rli->recovery_parallel_workers); my_message(ER_MTS_CHANGE_MASTER_CANT_RUN_WITH_GAPS, ER(ER_MTS_CHANGE_MASTER_CANT_RUN_WITH_GAPS), MYF(0)); ret= true; goto err; } else { /* Lack of mts group gaps makes Workers info stale regardless of need_relay_log_purge computation. */ if (mi->rli->recovery_parallel_workers) mts_remove_workers= true; } /* We cannot specify auto position and set either the coordinates on master or slave. If we try to do so, an error message is printed out. */ if (lex_mi->log_file_name != NULL || lex_mi->pos != 0 || lex_mi->relay_log_name != NULL || lex_mi->relay_log_pos != 0) { /* Disable auto-position when master_auto_position is not specified in CHANGE MASTER TO command but coordinates are specified. */ if (lex_mi->auto_position == LEX_MASTER_INFO::LEX_MI_UNCHANGED) { mi->set_auto_position(false); } else if (lex_mi->auto_position == LEX_MASTER_INFO::LEX_MI_ENABLE || (lex_mi->auto_position != LEX_MASTER_INFO::LEX_MI_DISABLE && mi->is_auto_position())) { my_message(ER_BAD_SLAVE_AUTO_POSITION, ER(ER_BAD_SLAVE_AUTO_POSITION), MYF(0)); ret= true; goto err; } } // CHANGE MASTER TO MASTER_AUTO_POSITION = 1 requires GTID_MODE = ON if (lex_mi->auto_position == LEX_MASTER_INFO::LEX_MI_ENABLE && gtid_mode != 3) { my_message(ER_AUTO_POSITION_REQUIRES_GTID_MODE_ON, ER(ER_AUTO_POSITION_REQUIRES_GTID_MODE_ON), MYF(0)); ret= true; goto err; } /* Data lock not needed since we have already stopped the running threads, and we have the hold on the run locks which will keep all threads that could possibly modify the data structures from running */ /* Before processing the command, save the previous state. */ strmake(saved_host, mi->host, HOSTNAME_LENGTH); strmake(saved_bind_addr, mi->bind_addr, HOSTNAME_LENGTH); saved_port= mi->port; strmake(saved_log_name, mi->get_master_log_name(), FN_REFLEN - 1); saved_log_pos= mi->get_master_log_pos(); /* If the user specified host or port without binlog or position, reset binlog's name to FIRST and position to 4. */ if ((lex_mi->host && strcmp(lex_mi->host, mi->host)) || (lex_mi->port && lex_mi->port != mi->port)) { /* This is necessary because the primary key, i.e. host or port, has changed. The repository does not support direct changes on the primary key, so the row is dropped and re-inserted with a new primary key. If we don't do that, the master info repository we will end up with several rows. */ if (mi->clean_info()) { ret= true; goto err; } mi->master_uuid[0]= 0; mi->master_id= 0; } if ((lex_mi->host || lex_mi->port) && !lex_mi->log_file_name && !lex_mi->pos) { var_master_log_name= const_cast<char*>(mi->get_master_log_name()); var_master_log_name[0]= '\0'; mi->set_master_log_pos(BIN_LOG_HEADER_SIZE); } if (lex_mi->log_file_name) mi->set_master_log_name(lex_mi->log_file_name); if (lex_mi->pos) { mi->set_master_log_pos(lex_mi->pos); } DBUG_PRINT("info", ("master_log_pos: %lu", (ulong) mi->get_master_log_pos())); if (lex_mi->user || lex_mi->password) { #if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY) if (thd->vio_ok() && !thd->net.vio->ssl_arg) push_warning(thd, Sql_condition::WARN_LEVEL_NOTE, ER_INSECURE_PLAIN_TEXT, ER(ER_INSECURE_PLAIN_TEXT)); #endif #if !defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY) push_warning(thd, Sql_condition::WARN_LEVEL_NOTE, ER_INSECURE_PLAIN_TEXT, ER(ER_INSECURE_PLAIN_TEXT)); #endif push_warning(thd, Sql_condition::WARN_LEVEL_NOTE, ER_INSECURE_CHANGE_MASTER, ER(ER_INSECURE_CHANGE_MASTER)); } if (lex_mi->user) mi->set_user(lex_mi->user); if (lex_mi->password) { if (mi->set_password(lex_mi->password, strlen(lex_mi->password))) { /* After implementing WL#5769, we should create a better error message to denote that the call may have failed due to an error while trying to encrypt/store the password in a secure key store. */ my_message(ER_MASTER_INFO, ER(ER_MASTER_INFO), MYF(0)); ret= false; goto err; } } if (lex_mi->host) strmake(mi->host, lex_mi->host, sizeof(mi->host)-1); if (lex_mi->bind_addr) strmake(mi->bind_addr, lex_mi->bind_addr, sizeof(mi->bind_addr)-1); if (lex_mi->port) mi->port = lex_mi->port; if (lex_mi->connect_retry) mi->connect_retry = lex_mi->connect_retry; if (lex_mi->retry_count_opt != LEX_MASTER_INFO::LEX_MI_UNCHANGED) mi->retry_count = lex_mi->retry_count; if (lex_mi->heartbeat_opt != LEX_MASTER_INFO::LEX_MI_UNCHANGED) mi->heartbeat_period = lex_mi->heartbeat_period; else mi->heartbeat_period= min<float>(SLAVE_MAX_HEARTBEAT_PERIOD, (slave_net_timeout/2.0)); mi->received_heartbeats= LL(0); // counter lives until master is CHANGEd /* reset the last time server_id list if the current CHANGE MASTER is mentioning IGNORE_SERVER_IDS= (...) */ if (lex_mi->repl_ignore_server_ids_opt == LEX_MASTER_INFO::LEX_MI_ENABLE) reset_dynamic(&(mi->ignore_server_ids->dynamic_ids)); for (uint i= 0; i < lex_mi->repl_ignore_server_ids.elements; i++) { ulong s_id; get_dynamic(&lex_mi->repl_ignore_server_ids, (uchar*) &s_id, i); if (s_id == ::server_id && replicate_same_server_id) { my_error(ER_SLAVE_IGNORE_SERVER_IDS, MYF(0), static_cast<int>(s_id)); ret= TRUE; goto err; } else { if (bsearch((const ulong *) &s_id, mi->ignore_server_ids->dynamic_ids.buffer, mi->ignore_server_ids->dynamic_ids.elements, sizeof(ulong), (int (*) (const void*, const void*)) change_master_server_id_cmp) == NULL) insert_dynamic(&(mi->ignore_server_ids->dynamic_ids), (uchar*) &s_id); } } sort_dynamic(&(mi->ignore_server_ids->dynamic_ids), (qsort_cmp) change_master_server_id_cmp); if (lex_mi->ssl != LEX_MASTER_INFO::LEX_MI_UNCHANGED) mi->ssl= (lex_mi->ssl == LEX_MASTER_INFO::LEX_MI_ENABLE); if (lex_mi->sql_delay != -1) mi->rli->set_sql_delay(lex_mi->sql_delay); if (lex_mi->ssl_verify_server_cert != LEX_MASTER_INFO::LEX_MI_UNCHANGED) mi->ssl_verify_server_cert= (lex_mi->ssl_verify_server_cert == LEX_MASTER_INFO::LEX_MI_ENABLE); if (lex_mi->ssl_ca) strmake(mi->ssl_ca, lex_mi->ssl_ca, sizeof(mi->ssl_ca)-1); if (lex_mi->ssl_capath) strmake(mi->ssl_capath, lex_mi->ssl_capath, sizeof(mi->ssl_capath)-1); if (lex_mi->ssl_cert) strmake(mi->ssl_cert, lex_mi->ssl_cert, sizeof(mi->ssl_cert)-1); if (lex_mi->ssl_cipher) strmake(mi->ssl_cipher, lex_mi->ssl_cipher, sizeof(mi->ssl_cipher)-1); if (lex_mi->ssl_key) strmake(mi->ssl_key, lex_mi->ssl_key, sizeof(mi->ssl_key)-1); if (lex_mi->ssl_crl) strmake(mi->ssl_crl, lex_mi->ssl_crl, sizeof(mi->ssl_crl)-1); if (lex_mi->ssl_crlpath) strmake(mi->ssl_crlpath, lex_mi->ssl_crlpath, sizeof(mi->ssl_crlpath)-1); #ifndef HAVE_OPENSSL if (lex_mi->ssl || lex_mi->ssl_ca || lex_mi->ssl_capath || lex_mi->ssl_cert || lex_mi->ssl_cipher || lex_mi->ssl_key || lex_mi->ssl_verify_server_cert || lex_mi->ssl_crl || lex_mi->ssl_crlpath) push_warning(thd, Sql_condition::WARN_LEVEL_NOTE, ER_SLAVE_IGNORED_SSL_PARAMS, ER(ER_SLAVE_IGNORED_SSL_PARAMS)); #endif if (lex_mi->relay_log_name) { need_relay_log_purge= 0; char relay_log_name[FN_REFLEN]; mi->rli->relay_log.make_log_name(relay_log_name, lex_mi->relay_log_name); mi->rli->set_group_relay_log_name(relay_log_name); mi->rli->set_event_relay_log_name(relay_log_name); } if (lex_mi->relay_log_pos) { need_relay_log_purge= 0; mi->rli->set_group_relay_log_pos(lex_mi->relay_log_pos); mi->rli->set_event_relay_log_pos(lex_mi->relay_log_pos); } /* If user did specify neither host nor port nor any log name nor any log pos, i.e. he specified only user/password/master_connect_retry, he probably wants replication to resume from where it had left, i.e. from the coordinates of the **SQL** thread (imagine the case where the I/O is ahead of the SQL; restarting from the coordinates of the I/O would lose some events which is probably unwanted when you are just doing minor changes like changing master_connect_retry). A side-effect is that if only the I/O thread was started, this thread may restart from ''/4 after the CHANGE MASTER. That's a minor problem (it is a much more unlikely situation than the one we are fixing here). Note: coordinates of the SQL thread must be read here, before the 'if (need_relay_log_purge)' block which resets them. */ if (!lex_mi->host && !lex_mi->port && !lex_mi->log_file_name && !lex_mi->pos && need_relay_log_purge) { /* Sometimes mi->rli->master_log_pos == 0 (it happens when the SQL thread is not initialized), so we use a max(). What happens to mi->rli->master_log_pos during the initialization stages of replication is not 100% clear, so we guard against problems using max(). */ mi->set_master_log_pos(max<ulonglong>(BIN_LOG_HEADER_SIZE, mi->rli->get_group_master_log_pos())); mi->set_master_log_name(mi->rli->get_group_master_log_name()); } /* Sets if the slave should connect to the master and look for GTIDs. */ if (lex_mi->auto_position != LEX_MASTER_INFO::LEX_MI_UNCHANGED) mi->set_auto_position( (lex_mi->auto_position == LEX_MASTER_INFO::LEX_MI_ENABLE)); /* Relay log's IO_CACHE may not be inited, if rli->inited==0 (server was never a slave before). */ if (flush_master_info(mi, true)) { my_error(ER_RELAY_LOG_INIT, MYF(0), "Failed to flush master info file"); ret= TRUE; goto err; } if (need_relay_log_purge) { relay_log_purge= 1; THD_STAGE_INFO(thd, stage_purging_old_relay_logs); if (mi->rli->purge_relay_logs(thd, 0 /* not only reset, but also reinit */, &errmsg)) { my_error(ER_RELAY_LOG_FAIL, MYF(0), errmsg); ret= TRUE; goto err; } } else { const char* msg; relay_log_purge= 0; /* Relay log is already initialized */ if (mi->rli->init_relay_log_pos(mi->rli->get_group_relay_log_name(), mi->rli->get_group_relay_log_pos(), true/*need_data_lock=true*/, &msg, 0)) { my_error(ER_RELAY_LOG_INIT, MYF(0), msg); ret= TRUE; goto err; } } relay_log_purge= save_relay_log_purge; /* Coordinates in rli were spoilt by the 'if (need_relay_log_purge)' block, so restore them to good values. If we left them to ''/0, that would work; but that would fail in the case of 2 successive CHANGE MASTER (without a START SLAVE in between): because first one would set the coords in mi to the good values of those in rli, the set those in rli to ''/0, then second CHANGE MASTER would set the coords in mi to those of rli, i.e. to ''/0: we have lost all copies of the original good coordinates. That's why we always save good coords in rli. */ if (need_relay_log_purge) { mi->rli->set_group_master_log_pos(mi->get_master_log_pos()); DBUG_PRINT("info", ("master_log_pos: %lu", (ulong) mi->get_master_log_pos())); mi->rli->set_group_master_log_name(mi->get_master_log_name()); } var_group_master_log_name= const_cast<char *>(mi->rli->get_group_master_log_name()); if (!var_group_master_log_name[0]) // uninitialized case mi->rli->set_group_master_log_pos(0); mysql_mutex_lock(&mi->rli->data_lock); mi->rli->abort_pos_wait++; /* for MASTER_POS_WAIT() to abort */ /* Clear the errors, for a clean start */ mi->rli->clear_error(); mi->rli->clear_until_condition(); sql_print_information("'CHANGE MASTER TO executed'. " "Previous state master_host='%s', master_port= %u, master_log_file='%s', " "master_log_pos= %ld, master_bind='%s'. " "New state master_host='%s', master_port= %u, master_log_file='%s', " "master_log_pos= %ld, master_bind='%s'.", saved_host, saved_port, saved_log_name, (ulong) saved_log_pos, saved_bind_addr, mi->host, mi->port, mi->get_master_log_name(), (ulong) mi->get_master_log_pos(), mi->bind_addr); is_slave = mi->host[0]; /* If we don't write new coordinates to disk now, then old will remain in relay-log.info until START SLAVE is issued; but if mysqld is shutdown before START SLAVE, then old will remain in relay-log.info, and will be the in-memory value at restart (thus causing errors, as the old relay log does not exist anymore). Notice that the rli table is available exclusively as slave is not running. */ DBUG_ASSERT(!mi->rli->slave_running); if ((ret= mi->rli->flush_info(true))) my_error(ER_RELAY_LOG_INIT, MYF(0), "Failed to flush relay info file."); mysql_cond_broadcast(&mi->data_cond); mysql_mutex_unlock(&mi->rli->data_lock); err: unlock_slave_threads(mi); if (ret == FALSE) { if (!mts_remove_workers) my_ok(thd); else if (!Rpl_info_factory::reset_workers(mi->rli)) my_ok(thd); else my_error(ER_MTS_RESET_WORKERS, MYF(0)); } DBUG_RETURN(ret); } /** @} (end of group Replication) */ #endif /* HAVE_REPLICATION */
35.328174
137
0.644267
[ "object", "transform" ]
d005b9a6e9a23d413c0e574b613f55fa684b40e0
2,386
cpp
C++
src/ngraph/frontend/onnx_import/op/unsqueeze.cpp
bergtholdt/ngraph
55ca8bb15488ac7a567bb420ca32fcee25e60fe6
[ "Apache-2.0" ]
null
null
null
src/ngraph/frontend/onnx_import/op/unsqueeze.cpp
bergtholdt/ngraph
55ca8bb15488ac7a567bb420ca32fcee25e60fe6
[ "Apache-2.0" ]
null
null
null
src/ngraph/frontend/onnx_import/op/unsqueeze.cpp
bergtholdt/ngraph
55ca8bb15488ac7a567bb420ca32fcee25e60fe6
[ "Apache-2.0" ]
null
null
null
//***************************************************************************** // Copyright 2018 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** #include <numeric> #include "unsqueeze.hpp" #include "ngraph/op/reshape.hpp" #include "exceptions.hpp" namespace ngraph { namespace onnx_import { namespace op { NodeVector unsqueeze(const Node& node) { NodeVector inputs{node.get_ng_inputs()}; auto data = inputs.at(0); auto data_shape = data->get_shape(); auto axes = node.get_attribute_value<std::vector<int64_t>>("axes"); if (axes.empty()) { throw error::parameter::Value( "Unsqueeze", node.get_name(), "axes attribute is mandatory."); } std::sort(std::begin(axes), std::end(axes), std::greater<int64_t>()); // Generate an increasing sequence (0,1,2,3..) as input_order for Reshape AxisVector input_order(data_shape.size()); std::iota(std::begin(input_order), std::end(input_order), 0); for (auto axis : axes) { if ((axis < 0) || (axis > data_shape.size())) { throw error::parameter::Value( "Unsqueeze", node.get_name(), "provided axes attribute is not valid."); } data_shape.insert(std::next(std::begin(data_shape), axis), 1); } return {std::make_shared<ngraph::op::Reshape>(data, input_order, data_shape)}; } } // namespace op } // namespace onnx_import } // namespace ngraph
36.151515
99
0.526823
[ "vector" ]
d00cbf6a4cde92c74b50e2390040d8a4781e2e7c
1,323
cc
C++
tesseract4android/src/main/cpp/tesseract/src/unittest/params_model_test.cc
letin97/Tesseract4
9b798d6864bfc70933e6ea641a70435e2d5b9c2d
[ "Apache-2.0" ]
null
null
null
tesseract4android/src/main/cpp/tesseract/src/unittest/params_model_test.cc
letin97/Tesseract4
9b798d6864bfc70933e6ea641a70435e2d5b9c2d
[ "Apache-2.0" ]
null
null
null
tesseract4android/src/main/cpp/tesseract/src/unittest/params_model_test.cc
letin97/Tesseract4
9b798d6864bfc70933e6ea641a70435e2d5b9c2d
[ "Apache-2.0" ]
null
null
null
#include <vector> #include "tesseract/wordrec/params_model.h" namespace { // Test some basic I/O of params model files (automated learning of language // model weights). class ParamsModelTest : public testing::Test { protected: string TestDataNameToPath(const string& name) const { return file::JoinPath(FLAGS_test_srcdir, "testdata/" + name); } string OutputNameToPath(const string& name) const { return file::JoinPath(FLAGS_test_tmpdir, name); } // Test that we are able to load a params model, save it, reload it, // and verify that the re-serialized version is the same as the original. void TestParamsModelRoundTrip(const string& params_model_filename) const { tesseract::ParamsModel orig_model; tesseract::ParamsModel duplicate_model; string orig_file = TestDataNameToPath(params_model_filename); string out_file = OutputNameToPath(params_model_filename); EXPECT_TRUE(orig_model.LoadFromFile("eng", orig_file.c_str())); EXPECT_TRUE(orig_model.SaveToFile(out_file.c_str())); EXPECT_TRUE(duplicate_model.LoadFromFile("eng", out_file.c_str())); EXPECT_TRUE(orig_model.Equivalent(duplicate_model)); } }; TEST_F(ParamsModelTest, TestEngParamsModelIO) { TestParamsModelRoundTrip("eng.params_model"); } } // namespace
33.923077
77
0.734694
[ "vector", "model" ]
d00dfd7cb70e3e7229aba1df6c5a3a0c2e82220f
3,919
cpp
C++
GridWorld.cpp
Aakarshan-Chauhan/RL-GridWorld_CPlusPlus
dcdba048aa0b620412ac9c4ef8c558b214f885da
[ "MIT" ]
1
2021-04-23T09:23:45.000Z
2021-04-23T09:23:45.000Z
GridWorld.cpp
Aakarshan-Chauhan/RL-GridWorld_CPlusPlus
dcdba048aa0b620412ac9c4ef8c558b214f885da
[ "MIT" ]
null
null
null
GridWorld.cpp
Aakarshan-Chauhan/RL-GridWorld_CPlusPlus
dcdba048aa0b620412ac9c4ef8c558b214f885da
[ "MIT" ]
null
null
null
#include<iostream> #include<map> #include<vector> #include<set> using namespace std; // Class to interact and form our gameboard class Grid { public: //i and j are coordinates of the agent in the grid, y axis is i and x axis is j. Top left corner is (0, 0). int rows, cols, i, j; //rewards is a ditionary with set of coordinates mapped with numerical rewards for that state. std::map<std::vector<int>, float> rewards; //actions is a dictionary with set of coordinates mapped to the list of possible actions in that state. std::map<std::vector<int>, std::vector<char>> actions; Grid(int num_rows, int num_cols, std::vector<int> start_coord) { rows = num_rows; cols = num_cols; i = start_coord[0]; j = start_coord[1]; } void set(std::map<std::vector<int>, float> reward, std::map<std::vector<int>, std::vector<char>> action) { rewards = reward; actions = action; } // Set the state of the agent by assigning the coordinates to the agent. void set_state(std::vector<int> s) { i = s[0]; j = s[1]; } // Return the immidiate coordinates at the time of call. std::vector<int> current_state() { return { i, j }; } // Return a boolean if agent is in terminal state or not. bool is_terminal(std::vector<int> s) { for (const auto x : actions) if (s == x.first) return false; return true; } // Move the agent by changing its coordinate if the assigned action is a possible action in that state. int move(char action) { for (auto x : actions[{i, j}]) { if (action == x) { if (action == 'U') i--; else if (action == 'D') i++; else if (action == 'L') j--; else if (action == 'R') j++; break; } } return rewards[{i, j}]; } void undo_move(char action) { if (action == ' U') i++; else if (action == 'D') i--; else if (action == 'L') j++; else if (action == 'R') j--; } //Return False if the agent has reached a terminal state or an invalid state. bool game_over() { std::vector<int> temp = { i, j }; for (const auto x : actions) if (temp == x.first) return false; return true; } // Return all possible states. std::vector<std::vector<int>> all_states() { std::vector<std::vector<int>> all_states; std::set<std::vector<int>> set_states; for (const auto x : actions) set_states.insert(x.first); for (const auto y : rewards) set_states.insert(y.first); for (const auto z : set_states) all_states.push_back(z); return all_states; } }; Grid standard_grid() { /* Define a grid that shows the board and reward of each file with possible actions at each state. Our current board is a 3 x 4 board. Example: . . . W . X . L S . . . W = Win, X = wall, L = loss, S = start position. */ Grid g = { 3, 4, {2, 0} }; std::map<std::vector<int>, float> rewards; rewards[{0, 3}] = 1; rewards[{1, 3}] = -1; std::map<std::vector<int>, std::vector<char>> actions; std::vector<std::vector<int>> blocks = { {1,1}, {0,3}, {1,3} }; for (int i = 0; i < 3; i++) { for (int j = 0; j < 4; j++) { std::vector<int> pos = { i, j }; std::vector<char> list; if (std::find(blocks.begin(), blocks.end(), pos) == blocks.end()) { if (i + 1 != 1 && i + 1 < 3) list.push_back('D'); if (i - 1 != 1 && i - 1 > 0) list.push_back('U'); if (j + 1 != 1 && j + 1 < 4) list.push_back('R'); if (j - 1 != 1 && j - 1 > 0) list.push_back('L'); } actions[{i, j}]= list; } } g.set(rewards, actions); return g; } // This will be a grid with each move or action resulting in a small penalty. // This would encourage shorter paths over longer ones. Grid negative_grid(float step_cost = -0.1) { Grid g = standard_grid(); for (const auto x : g.rewards) { g.rewards[x.first] = step_cost; } return g; }
23.052941
109
0.58765
[ "vector" ]
d00fd269d82830d1dcb9dc89100bb3118dbd363b
4,476
cpp
C++
Firmware/Marlin/src/lcd/extui/mks_ui/wifiSerial.cpp
jhNsXO/UnifiedFirmware
a3649d67d9fa6219c7fb58ab9e18594b1b0a24df
[ "Info-ZIP" ]
97
2020-09-14T13:35:17.000Z
2022-03-28T20:15:49.000Z
Firmware/Marlin/src/lcd/extui/mks_ui/wifiSerial.cpp
jhNsXO/UnifiedFirmware
a3649d67d9fa6219c7fb58ab9e18594b1b0a24df
[ "Info-ZIP" ]
8
2020-11-11T21:01:38.000Z
2022-01-22T01:22:10.000Z
Firmware/Marlin/src/lcd/extui/mks_ui/wifiSerial.cpp
jhNsXO/UnifiedFirmware
a3649d67d9fa6219c7fb58ab9e18594b1b0a24df
[ "Info-ZIP" ]
49
2020-09-22T09:33:37.000Z
2022-03-19T21:23:04.000Z
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #include "../../../inc/MarlinConfigPre.h" #if HAS_TFT_LVGL_UI #include "tft_lvgl_configuration.h" #if ENABLED(MKS_WIFI_MODULE) #include "draw_ui.h" #include "wifiSerial.h" #include <libmaple/libmaple.h> #include <libmaple/gpio.h> #include <libmaple/timer.h> #include <libmaple/usart.h> #include <libmaple/ring_buffer.h> #include "../../../MarlinCore.h" DEFINE_WFSERIAL(WifiSerial1, 1); WifiSerial::WifiSerial(usart_dev *usart_device, uint8 tx_pin, uint8 rx_pin) { this->usart_device = usart_device; this->tx_pin = tx_pin; this->rx_pin = rx_pin; } /** * Set up / tear down */ #if STM32_MCU_SERIES == STM32_SERIES_F1 /* F1 MCUs have no GPIO_AFR[HL], so turn off PWM if there's a conflict * on this GPIO bit. */ static void disable_timer_if_necessary(timer_dev *dev, uint8 ch) { if (dev) timer_set_mode(dev, ch, TIMER_DISABLED); } static void usart_enable_no_irq(usart_dev *usart_device, bool with_irq) { if (with_irq) usart_enable(usart_device); else { usart_reg_map *regs = usart_device->regs; regs->CR1 |= (USART_CR1_TE | USART_CR1_RE); // don't change the word length etc, and 'or' in the pattern not overwrite |USART_CR1_M_8N1); regs->CR1 |= USART_CR1_UE; } } #elif STM32_MCU_SERIES == STM32_SERIES_F2 || STM32_MCU_SERIES == STM32_SERIES_F4 #define disable_timer_if_necessary(dev, ch) ((void)0) static void usart_enable_no_irq(usart_dev *usart_device, bool with_irq) { if (with_irq) usart_enable(usart_device); else { usart_reg_map *regs = usart_device->regs; regs->CR1 |= (USART_CR1_TE | USART_CR1_RE); // don't change the word length etc, and 'or' in the pattern not overwrite |USART_CR1_M_8N1); regs->CR1 |= USART_CR1_UE; } } #else #warning "Unsupported STM32 series; timer conflicts are possible" #define usart_enable_no_irq(X, Y) usart_enable(X) #endif void WifiSerial::begin(uint32 baud) { begin(baud, SERIAL_8N1); } /** * Roger Clark. * Note. The config parameter is not currently used. This is a work in progress. * Code needs to be written to set the config of the hardware serial control register in question. */ void WifiSerial::begin(uint32 baud, uint8_t config) { //ASSERT(baud <= this->usart_device->max_baud); // Roger Clark. Assert doesn't do anything useful, we may as well save the space in flash and ram etc if (baud > this->usart_device->max_baud) return; const stm32_pin_info *txi = &PIN_MAP[this->tx_pin], *rxi = &PIN_MAP[this->rx_pin]; disable_timer_if_necessary(txi->timer_device, txi->timer_channel); usart_init(this->usart_device); // Reinitialize the receive buffer, mks_esp8266 fixed data frame length is 1k bytes rb_init(this->usart_device->rb, WIFI_RX_BUF_SIZE, wifiRxBuf); usart_config_gpios_async(this->usart_device, rxi->gpio_device, rxi->gpio_bit, txi->gpio_device, txi->gpio_bit, config); usart_set_baud_rate(this->usart_device, USART_USE_PCLK, baud); usart_enable_no_irq(this->usart_device, baud == WIFI_BAUDRATE); } void WifiSerial::end() { usart_disable(this->usart_device); } int WifiSerial::available() { return usart_data_available(this->usart_device); } // // I/O // int WifiSerial::read() { if (usart_data_available(usart_device) <= 0) return -1; return usart_getc(usart_device); } int WifiSerial::write(unsigned char ch) { usart_putc(this->usart_device, ch); return 1; } int WifiSerial::wifi_rb_is_full() { return rb_is_full(this->usart_device->rb); } #endif // MKS_WIFI_MODULE #endif // HAS_TFT_LVGL_UI
31.521127
151
0.710679
[ "3d" ]
d014f52f8e2afb06df8db7253b04a769b461e80a
1,763
cpp
C++
codeforces/822C.cpp
Victoralin10/ACMSolutions
6d6e50da87b2bc455e953629737215b74b10269c
[ "MIT" ]
null
null
null
codeforces/822C.cpp
Victoralin10/ACMSolutions
6d6e50da87b2bc455e953629737215b74b10269c
[ "MIT" ]
null
null
null
codeforces/822C.cpp
Victoralin10/ACMSolutions
6d6e50da87b2bc455e953629737215b74b10269c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define pb push_back #define mp make_pair #define pii pair <int, int> #define all(v) (v).begin() (v).end() #define fi first #define se second #define ll long long #define ull long long #define ld long double #define MOD 1000000007 #define MAXN 200005 using namespace std; vector < pair <int, int > > tikets[MAXN]; int mn[MAXN]; int main(int nargs, char **args) { int n, x; cin >> n >> x; for (int i = 0, l, r, w; i < n; i++) { cin >> l >> r >> w; tikets[r-l+1].pb(mp(l, w)); } for (int i = 0; i <= x; i++) { sort(tikets[i].begin(), tikets[i].end()); } int ans = (1L<<31) - 1; for (int d1 = 1, d2 = x - 1; d1 <= d2; d1++, d2--) { mn[tikets[d2].size()] = (1<<30); for (int i = (int)tikets[d2].size() - 1; i >= 0; i--) { mn[i] = min(tikets[d2][i].se, mn[i+1]); } for (int i = 0, j = 0; i < tikets[d1].size(); i++) { while (j < tikets[d2].size() && tikets[d2][j].fi < tikets[d1][i].fi + d1) { j++; } if (j < tikets[d2].size()) { ans = min(ans, tikets[d1][i].se + mn[j]); } } mn[tikets[d1].size()] = (1<<30); for (int i = (int)tikets[d1].size() - 1; i >= 0; i--) { mn[i] = min(tikets[d1][i].se, mn[i+1]); } for (int i = 0, j = 0; i < tikets[d2].size(); i++) { while (j < tikets[d1].size() && tikets[d1][j].fi < tikets[d2][i].fi + d2) { j++; } if (j < tikets[d1].size()) { ans = min(ans, mn[j] + tikets[d2][i].se); } } } if (ans != (1L<<31) - 1) cout << ans << endl; else puts("-1"); return 0; }
25.550725
87
0.434487
[ "vector" ]
d016987f84956dcb5981865b368af8762a4067ff
980
cpp
C++
Array/TwoSum/TwoSum.cpp
yijingbai/LeetCode
6ae6dbdf3a720b4206323401a0ed16ac2066031e
[ "MIT" ]
2
2015-08-28T03:52:05.000Z
2015-09-03T09:54:40.000Z
Array/TwoSum/TwoSum.cpp
yijingbai/LeetCode
6ae6dbdf3a720b4206323401a0ed16ac2066031e
[ "MIT" ]
null
null
null
Array/TwoSum/TwoSum.cpp
yijingbai/LeetCode
6ae6dbdf3a720b4206323401a0ed16ac2066031e
[ "MIT" ]
null
null
null
#include <vector> #include <map> #include <utility> #include <iostream> using std::vector; using std::map; using std::pair; class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { map<int, int> num_index_map; for (int i = 0; i < nums.size(); i++) { int current = nums[i]; if (num_index_map.end() != num_index_map.find(target - current)) { vector<int> res; res.push_back(num_index_map[target - current] + 1); res.push_back(i + 1); return res; } num_index_map.insert(std::make_pair(current, i)); } } }; int main() { Solution s; vector<int> sample; sample.push_back(2); sample.push_back(7); sample.push_back(11); sample.push_back(15); vector<int> res = s.twoSum(sample, 9); for (int i = 0; i < res.size(); i++) { std::cout << res[i] << std::endl; } }
24.5
67
0.529592
[ "vector" ]
d01800b81645c7270dcd65757627b73c0455353a
41,626
cpp
C++
src/gui_state.cpp
noraabiakar/arbor-gui
6849d0e282ede2aabd8af2094ba036b96c68eece
[ "BSD-3-Clause" ]
null
null
null
src/gui_state.cpp
noraabiakar/arbor-gui
6849d0e282ede2aabd8af2094ba036b96c68eece
[ "BSD-3-Clause" ]
null
null
null
src/gui_state.cpp
noraabiakar/arbor-gui
6849d0e282ede2aabd8af2094ba036b96c68eece
[ "BSD-3-Clause" ]
null
null
null
#include "gui_state.hpp" #include <IconsForkAwesome.h> #include <nlohmann/json.hpp> #include <imgui.h> #include <misc/cpp/imgui_stdlib.h> #include <arbornml/arbornml.hpp> #include <arbornml/nmlexcept.hpp> #include <sstream> extern float delta_phi; extern float delta_zoom; extern float delta_x; extern float delta_y; gui_state::gui_state(): builder{} {} void load_swc(gui_state& state, const std::string& fn, std::function<arb::morphology(const std::vector<arborio::swc_record>&)> swc_to_morph) { log_debug("Reading {}", fn); std::ifstream in(fn.c_str()); auto swc = arborio::parse_swc(in).records(); auto morph = swc_to_morph(swc); // Clean-up & Re-build ourself state.reset(); state.builder = cell_builder{morph}; state.renderer = geometry{morph}; state.region_defs.emplace_back("soma", "(tag 1)"); state.region_defs.emplace_back("axon", "(tag 2)"); state.region_defs.emplace_back("dend", "(tag 3)"); state.region_defs.emplace_back("apic", "(tag 4)"); state.locset_defs.emplace_back("center", "(location 0 0)"); } template<typename T> std::string to_string(const T& r) { std::stringstream ss; ss << r; return ss.str(); } void gui_state::reset() { render_regions.clear(); render_locsets.clear(); locset_defs.clear(); region_defs.clear(); ion_defs.clear(); mechanism_defs.clear(); } void gui_state::load_allen_swc(const std::string& fn) { load_swc(*this, fn, [](const auto& d){ return arborio::load_swc_allen(d); }); } void gui_state::load_neuron_swc(const std::string& fn) { load_swc(*this, fn, [](const auto& d){ return arborio::load_swc_neuron(d); }); } void gui_state::load_arbor_swc(const std::string& fn) { load_swc(*this, fn, [](const auto& d){ return arborio::load_swc_arbor(d); }); } void gui_state::load_neuroml(const std::string& fn) { // Read in morph std::ifstream fd(fn.c_str()); std::string xml(std::istreambuf_iterator<char>(fd), {}); arbnml::neuroml nml(xml); // Extract segment tree auto cell_ids = nml.cell_ids(); auto id = cell_ids.front(); auto morph_data = nml.cell_morphology(id).value(); auto morph = morph_data.morphology; // Clean-up & Re-build ourself reset(); builder = cell_builder{morph}; renderer = geometry{morph}; // Copy over locations for (const auto& [k, v]: morph_data.groups.regions()) { log_debug("NML region {}\n {}", k, to_string(v)); region_defs.push_back({k, to_string(v)}); } for (const auto& [k, v]: morph_data.groups.locsets()) { log_debug("NML locset {}\n {}", k, to_string(v)); locset_defs.push_back({k, to_string(v)}); } } template<typename D> void update_def(D& def) { if (def.state == def_state::erase) return; if (def.definition.empty() || !def.definition[0]) { def.data = {}; def.empty(); } else { try { def.data = {def.definition}; def.good(); } catch (const arb::label_parse_error& e) { def.data = {}; std::string m = e.what(); auto colon = m.find(':') + 1; colon = m.find(':', colon) + 1; def.error(m.substr(colon, m.size() - 1)); } } } void def_set_renderable(geometry& renderer, cell_builder& builder, renderable& render, ls_def& def) { render.active = false; if (!def.data || (def.state != def_state::good)) return; log_info("Making markers for locset {} '{}'", def.name, def.definition); try { auto points = builder.make_points(def.data.value()); render = renderer.make_marker(points, render.color); } catch (arb::morphology_error& e) { def.error(e.what()); } } void def_set_renderable(geometry& renderer, cell_builder& builder, renderable& render, reg_def& def) { render.active = false; if (!def.data || (def.state != def_state::good)) return; log_info("Making frustrums for region {} '{}'", def.name, def.definition); try { auto points = builder.make_segments(def.data.value()); render = renderer.make_region(points, render.color); } catch (arb::morphology_error& e) { def.error(e.what()); } } template<typename Item> void update_placables(std::unordered_map<std::string, ls_def>& locsets, std::vector<Item>& defs) { std::erase_if(defs, [](const auto& p) { return p.state == def_state::erase; }); for (auto& def: defs) { if (def.locset_name.empty()) { def.empty(); } else { if (locsets.contains(def.locset_name)) { const auto& ls = locsets[def.locset_name]; switch (ls.state) { case def_state::error: def.error("Linked locset malformed."); break; case def_state::empty: def.error("Linked locset empty."); break; case def_state::good: def.good(); break; default: log_fatal("invalid code path: unknown state {}", def.locset_name); } } else { def.error("Linked locset absent."); } } } } void gui_state::update() { { if (render_locsets.size() < locset_defs.size()) render_locsets.resize(locset_defs.size()); auto idx = 0; for (auto& def: locset_defs) { auto& render = render_locsets[idx]; if (def.state == def_state::changed) { update_def(def); def_set_renderable(renderer, builder, render, def); } if (def.state == def_state::erase) { render_locsets[idx].state = def_state::erase; } idx++; } std::erase_if(locset_defs, [](const auto& p) { return p.state == def_state::erase; }); std::erase_if(render_locsets, [](const auto& p) { return p.state == def_state::erase; }); // collect what is left std::unordered_map<std::string, ls_def> locsets; for (const auto& def: locset_defs) locsets[def.name] = def; // finally update individual lists of placeables update_placables(locsets, probe_defs); update_placables(locsets, iclamp_defs); update_placables(locsets, detector_defs); } // Update paintables { if (render_regions.size() < region_defs.size()) render_regions.resize(region_defs.size()); if (parameter_defs.size() < region_defs.size()) parameter_defs.resize(region_defs.size()); if (mechanism_defs.size() < region_defs.size()) mechanism_defs.resize(region_defs.size()); if (ion_defs.size() < ion_defaults.size()) ion_defs.resize(ion_defaults.size()); for (auto& ion: ion_defs) if (ion.size() < region_defs.size()) ion.resize(region_defs.size()); auto idx = 0; for (auto& def: region_defs) { auto& render = render_regions[idx]; if (def.state == def_state::changed) { update_def(def); def_set_renderable(renderer, builder, render, def); } if (def.state == def_state::erase) { render_regions[idx].state = def_state::erase; parameter_defs[idx].state = def_state::erase; for (auto& ion: ion_defs) ion.erase(ion.begin() + idx); mechanism_defs.erase(mechanism_defs.begin() + idx); render_regions[idx].state = def_state::erase; } idx++; } std::erase_if(region_defs, [](const auto& p) { return p.state == def_state::erase; }); std::erase_if(render_regions, [](const auto& p) { return p.state == def_state::erase; }); std::erase_if(parameter_defs, [](const auto& p) { return p.state == def_state::erase; }); } } void gui_main(gui_state& state); void gui_menu_bar(gui_state& state); void gui_read_morphology(gui_state& state, bool& open); void gui_locations(gui_state& state); void gui_cell(gui_state& state); void gui_place(gui_state& state); void gui_tooltip(const std::string&); void gui_check_state(def_state); void gui_painting(gui_state& state); void gui_trash(definition&); void gui_debug(bool&); void gui_style(bool&); void gui_trash(definition& def) { if (ImGui::Button((const char*) ICON_FK_TRASH)) def.erase(); } void gui_tooltip(const std::string& message) { if (ImGui::IsItemHovered()) { ImGui::BeginTooltip(); ImGui::PushTextWrapPos(ImGui::GetFontSize()*35.0f); ImGui::TextUnformatted(message.c_str()); ImGui::PopTextWrapPos(); ImGui::EndTooltip(); } } void gui_check_state(const definition& def) { const char* tag = ""; switch (def.state) { case def_state::error: tag = (const char*) ICON_FK_EXCLAMATION_TRIANGLE; break; case def_state::good: tag = (const char*) ICON_FK_CHECK; break; case def_state::empty: tag = (const char*) ICON_FK_QUESTION; break; default: break; } ImGui::Text("%s", tag); gui_tooltip(def.message); } void gui_toggle(const char* on, const char* off, bool& flag) { if (ImGui::Button(flag ? on : off)) flag = !flag; } void gui_main(gui_state& state) { static bool opt_fullscreen = true; static bool opt_padding = false; static ImGuiDockNodeFlags dockspace_flags = ImGuiDockNodeFlags_None; // We are using the ImGuiWindowFlags_NoDocking flag to make the parent window not dockable into, // because it would be confusing to have two docking targets within each others. ImGuiWindowFlags window_flags = ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoDocking; if (opt_fullscreen) { ImGuiViewport* viewport = ImGui::GetMainViewport(); ImGui::SetNextWindowPos(viewport->GetWorkPos()); ImGui::SetNextWindowSize(viewport->GetWorkSize()); ImGui::SetNextWindowViewport(viewport->ID); ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f); window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove; window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus; } else { dockspace_flags &= ~ImGuiDockNodeFlags_PassthruCentralNode; } // When using ImGuiDockNodeFlags_PassthruCentralNode, DockSpace() will render our background // and handle the pass-thru hole, so we ask Begin() to not render a background. if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode) window_flags |= ImGuiWindowFlags_NoBackground; // Important: note that we proceed even if Begin() returns false (aka window is collapsed). // This is because we want to keep our DockSpace() active. If a DockSpace() is inactive, // all active windows docked into it will lose their parent and become undocked. // We cannot preserve the docking relationship between an active window and an inactive docking, otherwise // any change of dockspace/settings would lead to windows being stuck in limbo and never being visible. if (!opt_padding) ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); ImGui::Begin("DockSpace Demo", nullptr, window_flags); if (!opt_padding) ImGui::PopStyleVar(); if (opt_fullscreen) ImGui::PopStyleVar(2); // DockSpace ImGuiIO& io = ImGui::GetIO(); if (io.ConfigFlags & ImGuiConfigFlags_DockingEnable) { ImGuiID dockspace_id = ImGui::GetID("MyDockSpace"); ImGui::DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags); } gui_menu_bar(state); ImGui::End(); } void gui_save_decoration(gui_state& state, bool& open) { state.serialize("test"); open = false; } void gui_read_decoration(gui_state& state, bool& open) { state.deserialize("test"); open = false; } void gui_menu_bar(gui_state& state) { ImGui::BeginMenuBar(); static auto open_morph_read = false; static auto open_decor_read = false; static auto open_decor_save = false; static auto open_debug = false; static auto open_style = false; if (ImGui::BeginMenu("File")) { open_morph_read = ImGui::MenuItem(fmt::format("{} Load morphology", (const char*) ICON_FK_UPLOAD).c_str()); ImGui::Separator(); open_decor_read = ImGui::MenuItem(fmt::format("{} Load decoration", (const char*) ICON_FK_UPLOAD).c_str()); open_decor_save = ImGui::MenuItem(fmt::format("{} Save decoration", (const char*) ICON_FK_DOWNLOAD).c_str()); ImGui::EndMenu(); } if (ImGui::BeginMenu("Help")) { open_debug = ImGui::MenuItem(fmt::format("{} Metrics", (const char*) ICON_FK_BUG).c_str()); open_style = ImGui::MenuItem(fmt::format("{} Style", (const char*) ICON_FK_PAINT_BRUSH).c_str()); ImGui::EndMenu(); } ImGui::EndMenuBar(); if (open_morph_read) gui_read_morphology(state, open_morph_read); if (open_decor_read) gui_read_decoration(state, open_decor_read); if (open_decor_save) gui_save_decoration(state, open_decor_save); if (open_debug) gui_debug(open_debug); if (open_style) gui_style(open_style); } void gui_dir_view(file_chooser_state& state) { // Draw the current path + show hidden { auto acc = std::filesystem::path{}; if (ImGui::Button((const char *) ICON_FK_FOLDER_OPEN)) state.cwd = "/"; for (const auto& part: state.cwd) { acc = acc / part; if ("/" == part) continue; ImGui::SameLine(0.0f, 0.0f); if (ImGui::Button(fmt::format("/ {}", part.c_str()).c_str())) state.cwd = acc; } ImGui::SameLine(ImGui::GetWindowWidth() - 30.0f); if(ImGui::Button((const char*) ICON_FK_SNAPCHAT_GHOST)) state.show_hidden = !state.show_hidden; } // Draw the current dir { ImGui::BeginChild("Files", {-0.35f*ImGui::GetTextLineHeightWithSpacing(), -3.0f*ImGui::GetTextLineHeightWithSpacing()}, true); std::vector<std::tuple<std::string, std::filesystem::path>> dirnames; std::vector<std::tuple<std::string, std::filesystem::path>> filenames; for (const auto& it: std::filesystem::directory_iterator(state.cwd)) { const auto& path = it.path(); const auto& ext = path.extension(); std::string fn = path.filename(); if (fn.empty() || (!state.show_hidden && (fn.front() == '.'))) continue; if (it.is_directory()) dirnames.push_back({fn, path}); if (state.filter && state.filter.value() != ext) continue; if (it.is_regular_file()) filenames.push_back({fn, path}); } std::sort(filenames.begin(), filenames.end()); std::sort(dirnames.begin(), dirnames.end()); for (const auto& [dn, path]: dirnames) { auto lbl = fmt::format("{} {}", (const char *) ICON_FK_FOLDER, dn); ImGui::Selectable(lbl.c_str(), false); if (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(0)) { state.cwd = path; state.file.clear(); } } for (const auto& [fn, path]: filenames) { if (ImGui::Selectable(fn.c_str(), path == state.file)) state.file = path; } ImGui::EndChild(); } } struct loader_state { std::string message; const char* icon; std::optional<std::function<void(gui_state&, const std::string&)>> load; }; std::unordered_map<std::string, std::unordered_map<std::string, std::function<void(gui_state&, const std::string&)>>> loaders{{".swc", {{"Arbor", [](gui_state& s, const std::string& fn) { s.load_arbor_swc(fn); }}, {"Allen", [](gui_state& s, const std::string& fn) { s.load_allen_swc(fn); }}, {"Neuron", [](gui_state& s, const std::string& fn) { s.load_neuron_swc(fn); }}}}, {".nml", {{"Default", [](gui_state& s, const std::string& fn) { s.load_neuroml(fn); }}}}}; loader_state get_loader(const std::string& extension, const std::string& flavor) { if (extension.empty()) return {"Please select a file.", (const char*) ICON_FK_EXCLAMATION_TRIANGLE, {}}; if (!loaders.contains(extension)) return {"Unknown file type.", (const char*) ICON_FK_EXCLAMATION_TRIANGLE, {}}; if (flavor.empty()) return {"Please select a flavor.", (const char*) ICON_FK_EXCLAMATION_TRIANGLE, {}}; if (!loaders[extension].contains(flavor)) return {"Unknown flavor type.", (const char*) ICON_FK_EXCLAMATION_TRIANGLE, {}}; return {"Ok.", (const char*) ICON_FK_CHECK, {loaders[extension][flavor]}}; } void gui_read_morphology(gui_state& state, bool& open_file) { ImGui::PushID("open_file"); ImGui::OpenPopup("Open"); if (ImGui::BeginPopupModal("Open")) { gui_dir_view(state.file_chooser); ImGui::PushItemWidth(120.0f); // this is pixels { auto lbl = state.file_chooser.filter.value_or("all"); if (ImGui::BeginCombo("Filter", lbl.c_str())) { if (ImGui::Selectable("all", "all" == lbl)) state.file_chooser.filter = {}; for (const auto& [k, v]: loaders) { if (ImGui::Selectable(k.c_str(), k == lbl)) state.file_chooser.filter = {k}; } ImGui::EndCombo(); } } auto extension = state.file_chooser.file.extension(); static std::string current_flavor = ""; if (loaders.contains(extension)) { auto flavors = loaders[extension]; if (!flavors.contains(current_flavor)) current_flavor = flavors.begin()->first; ImGui::SameLine(); if (ImGui::BeginCombo("Flavor", current_flavor.c_str())) { for (const auto& [k, v]: flavors) { if (ImGui::Selectable(k.c_str(), k == current_flavor)) current_flavor = k; } ImGui::EndCombo(); } } else { current_flavor = ""; } ImGui::PopItemWidth(); { auto loader = get_loader(extension, current_flavor); auto alpha = loader.load ? 1.0f : 0.6f; ImGui::PushStyleVar(ImGuiStyleVar_Alpha, alpha); auto do_load = ImGui::Button("Load"); ImGui::PopStyleVar(); ImGui::SameLine(); ImGui::Text("%s", loader.icon); gui_tooltip(loader.message); ImGui::SameLine(); if (ImGui::Button("Cancel")) open_file = false; { static std::string loader_error = ""; if (do_load && loader.load) { try { loader.load.value()(state, state.file_chooser.file); open_file = false; } catch (arborio::swc_error& e) { loader_error = e.what(); } } if (ImGui::BeginPopupModal("Cannot Load Morphology")) { ImGui::PushTextWrapPos(ImGui::GetFontSize()*50.0f); ImGui::TextUnformatted(loader_error.c_str()); ImGui::PopTextWrapPos(); if (ImGui::Button("Close")) { loader_error.clear(); ImGui::CloseCurrentPopup(); } ImGui::EndPopup(); } if (!loader_error.empty()) { ImGui::SetNextWindowSize(ImVec2(0, ImGui::GetFontSize()*50.0f)); ImGui::OpenPopup("Cannot Load Morphology"); } } } ImGui::EndPopup(); } ImGui::PopID(); } void gui_cell(gui_state& state) { static float zoom = 45.0f; static float phi = 0.0f; static glm::vec2 offset = {0.0, 0.0f}; if (ImGui::Begin("Cell")) { ImGui::BeginChild("Cell Render"); auto size = ImGui::GetWindowSize(); auto image = state.renderer.render(zoom, phi, to_glmvec(size), offset, state.render_regions, state.render_locsets); ImGui::Image((ImTextureID) image, size, ImVec2(0, 1), ImVec2(1, 0)); if (ImGui::IsItemHovered()) { offset -= glm::vec2{delta_x, delta_y}; zoom += delta_zoom; if (zoom < 1.0f) zoom = 1.0f; if (zoom > 45.0f) zoom = 45.0f; phi += delta_phi; if (phi > 2.0f*PI) phi -= 2*PI; if (phi < 0.0f) phi += 2*PI; } if (ImGui::BeginPopupContextWindow()) { if (ImGui::MenuItem("Reset camera")) { offset = {0.0, 0.0}; state.renderer.target = {0.0f, 0.0f, 0.0f}; } if (ImGui::BeginMenu("Snap to locset")) { for (const auto& ls: state.locset_defs) { if (ls.state != def_state::good) continue; auto name = ls.name.c_str(); if (ImGui::BeginMenu(name)) { auto points = state.builder.make_points(ls.data.value()); for (const auto& point: points) { const auto lbl = fmt::format("({: 7.3f} {: 7.3f} {: 7.3f})", point.x, point.y, point.z); if (ImGui::MenuItem(lbl.c_str())) { offset = {0.0, 0.0}; state.renderer.target = point; } } ImGui::EndMenu(); } } ImGui::EndMenu(); } ImGui::EndPopup(); } ImGui::EndChild(); } ImGui::End(); delta_x = 0.0f; delta_y = 0.0f; delta_phi = 0.0f; delta_zoom = 0.0f; } void gui_locdef(loc_def& def, renderable& render) { ImGui::Bullet(); ImGui::SameLine(); ImGui::InputText("Name", &def.name); ImGui::Indent(24.0f); if (ImGui::InputText("Definition", &def.definition)) def.state = def_state::changed; ImGui::SameLine(); gui_check_state(def); gui_trash(def); ImGui::SameLine(); gui_toggle((const char*) ICON_FK_EYE, (const char*) ICON_FK_EYE_SLASH, render.active); ImGui::SameLine(); ImGui::ColorEdit4("", &render.color.x, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel); ImGui::Unindent(24.0f); } template<typename Item> void gui_locdefs(const std::string& name, std::vector<Item>& items, std::vector<renderable>& render) { bool add = false; ImGui::PushID(name.c_str()); ImGui::AlignTextToFramePadding(); auto open = ImGui::TreeNodeEx(name.c_str(), ImGuiTreeNodeFlags_AllowItemOverlap); ImGui::SameLine(ImGui::GetWindowWidth() - 30); if (ImGui::Button((const char*) ICON_FK_PLUS_SQUARE)) add = true; if (open) { ImGui::PushItemWidth(120.0f); // this is pixels int idx = 0; for (auto& def: items) { ImGui::PushID(idx); gui_locdef(def, render[idx]); ImGui::PopID(); idx++; } ImGui::PopItemWidth(); ImGui::TreePop(); } ImGui::PopID(); if (add) items.emplace_back(); } void gui_locations(gui_state& state) { if (ImGui::Begin("Locations")) { gui_locdefs("Regions", state.region_defs, state.render_regions); ImGui::Separator(); gui_locdefs("Locsets", state.locset_defs, state.render_locsets); } ImGui::End(); } void gui_placeable(prb_def& probe) { ImGui::InputDouble("Frequency", &probe.frequency, 0.0, 0.0, "%.0f Hz", ImGuiInputTextFlags_CharsScientific); static std::vector<std::string> probe_variables{"voltage", "current"}; if (ImGui::BeginCombo("Variable", probe.variable.c_str())) { for (const auto& v: probe_variables) { if (ImGui::Selectable(v.c_str(), v == probe.variable)) probe.variable = v; } ImGui::EndCombo(); } } void gui_placeable(stm_def& iclamp) { ImGui::InputDouble("Delay", &iclamp.delay, 0.0, 0.0, "%.0f ms", ImGuiInputTextFlags_CharsScientific); ImGui::InputDouble("Duration", &iclamp.duration, 0.0, 0.0, "%.0f ms", ImGuiInputTextFlags_CharsScientific); ImGui::InputDouble("Amplitude", &iclamp.amplitude, 0.0, 0.0, "%.0f nA", ImGuiInputTextFlags_CharsScientific); } void gui_placeable(sdt_def& detector) { ImGui::InputDouble("Threshold", &detector.threshold, 0.0, 0.0, "%.0f mV", ImGuiInputTextFlags_CharsScientific); } template<typename Item> void gui_placeables(const std::string& label, const std::vector<ls_def>& locsets, std::vector<Item>& items) { ImGui::PushID(label.c_str()); ImGui::AlignTextToFramePadding(); auto open = ImGui::TreeNodeEx(label.c_str(), ImGuiTreeNodeFlags_AllowItemOverlap); ImGui::SameLine(ImGui::GetWindowWidth() - 30); if (ImGui::Button((const char*) ICON_FK_PLUS_SQUARE)) items.emplace_back(); if (open) { ImGui::PushItemWidth(120.0f); // this is pixels auto idx = 0; for (auto& item: items) { ImGui::PushID(idx); ImGui::Bullet(); ImGui::SameLine(); if (ImGui::BeginCombo("Locset", item.locset_name.c_str())) { for (const auto& ls: locsets) { auto nm = ls.name; if (ImGui::Selectable(nm.c_str(), nm == item.locset_name)) item.locset_name = nm; } ImGui::EndCombo(); } ImGui::SameLine(); gui_check_state(item); ImGui::Indent(24.0f); gui_placeable(item); gui_trash(item); ImGui::Unindent(24.0f); ImGui::PopID(); idx++; } ImGui::PopItemWidth(); ImGui::TreePop(); } ImGui::PopID(); } void gui_place(gui_state& state) { if (ImGui::Begin("Placings")) { gui_placeables("Probes", state.locset_defs, state.probe_defs); ImGui::Separator(); gui_placeables("Stimuli", state.locset_defs, state.iclamp_defs); ImGui::Separator(); gui_placeables("Detectors", state.locset_defs, state.detector_defs); } ImGui::End(); } void gui_defaulted_double(const std::string& label, const char* format, std::optional<double>& value, const double fallback) { auto tmp = value.value_or(fallback); if (ImGui::InputDouble(label.c_str(), &tmp, 0, 0, format)) value = {tmp}; ImGui::SameLine(ImGui::GetWindowWidth() - 30.0f); if (ImGui::Button((const char*) ICON_FK_REFRESH)) value = {}; } void gui_painting_preset(gui_state& state) { static std::string preset = "Neuron"; static std::unordered_map<std::string, arb::cable_cell_parameter_set> presets{{"Neuron", arb::neuron_parameter_defaults}}; ImGui::Text("Load Preset"); if (ImGui::BeginCombo("", preset.c_str())) { for (const auto& [k, v]: presets) { if (ImGui::Selectable(k.c_str(), k == preset)) preset = k; } ImGui::EndCombo(); } ImGui::SameLine(); if (ImGui::Button((const char*) ICON_FK_UPLOAD)) { auto df = presets[preset]; state.parameter_defaults.TK = df.temperature_K.value(); state.parameter_defaults.Vm = df.init_membrane_potential.value(); state.parameter_defaults.RL = df.axial_resistivity.value(); state.parameter_defaults.Cm = df.membrane_capacitance.value(); state.ion_defaults.clear(); state.ion_defs.clear(); auto blank = std::vector<ion_def>(state.region_defs.size(), ion_def{}); for (const auto& [k, v]: df.ion_data) { state.ion_defaults.push_back({.name=k, .Xi=v.init_int_concentration.value(), .Xo=v.init_ext_concentration.value(), .Er=v.init_reversal_potential.value()}); state.ion_defs.push_back(blank); } } } void gui_painting_parameter(gui_state& state) { if (ImGui::TreeNodeEx("Parameters")) { if (ImGui::TreeNodeEx("Defaults")) { ImGui::InputDouble("Temperature", &state.parameter_defaults.TK, 0, 0, "%.0f K"); ImGui::InputDouble("Membrane Potential", &state.parameter_defaults.Vm, 0, 0, "%.0f mV"); ImGui::InputDouble("Axial Resistivity", &state.parameter_defaults.RL, 0, 0, "%.0f Ω·cm"); ImGui::InputDouble("Membrane Capacitance", &state.parameter_defaults.Cm, 0, 0, "%.0f F/m²"); ImGui::TreePop(); } auto region = state.region_defs.begin(); for (auto& p: state.parameter_defs) { if (ImGui::TreeNodeEx(region->name.c_str())) { gui_defaulted_double("Temperature", "%.0f K", p.TK, state.parameter_defaults.TK); gui_defaulted_double("Membrane Potential", "%.0f mV", p.Vm, state.parameter_defaults.Vm); gui_defaulted_double("Axial Resistivity", "%.0f Ω·cm ", p.RL, state.parameter_defaults.RL); gui_defaulted_double("Membrane Capacitance", "%.0f F/m²", p.Cm, state.parameter_defaults.Cm); ImGui::TreePop(); } ++region; } ImGui::TreePop(); } } void gui_painting_ion(std::vector<ion_default>& ion_defaults, std::vector<std::vector<ion_def>>& ion_defs, const std::vector<reg_def>& region_defs) { // These could be name strings only if (ImGui::TreeNodeEx("Ions")) { static std::vector<std::string> methods{"constant", "Nernst"}; auto defaults = ion_defaults.begin(); for (auto& ion: ion_defs) { auto name = defaults->name; if (ImGui::TreeNodeEx(name.c_str())) { if (ImGui::TreeNodeEx("Defaults")) { ImGui::InputDouble("Internal Concentration", &defaults->Xi, 0, 0, "%.0f F/m²"); ImGui::InputDouble("External Concentration", &defaults->Xo, 0, 0, "%.0f F/m²"); ImGui::InputDouble("Reversal Potential", &defaults->Er, 0, 0, "%.0f F/m²"); if (ImGui::BeginCombo("Method", defaults->method.c_str())) { for (auto& meth: methods) { if (ImGui::Selectable(meth.c_str(), meth == defaults->method)) defaults->method = meth; } ImGui::EndCombo(); } ImGui::TreePop(); } auto region = region_defs.begin(); for (auto& def: ion) { if (ImGui::TreeNodeEx(region->name.c_str())) { gui_defaulted_double("Internal Concentration", "%.0f F/m²", def.Xi, defaults->Xi); gui_defaulted_double("External Concentration", "%.0f F/m²", def.Xo, defaults->Xo); gui_defaulted_double("Reversal Potential", "%.0f F/m²", def.Er, defaults->Er); ImGui::TreePop(); } ++region; } ImGui::TreePop(); } ++defaults; } ImGui::TreePop(); } } const static std::unordered_map<std::string, arb::mechanism_catalogue> catalogues = {{"default", arb::global_default_catalogue()}, {"allen", arb::global_allen_catalogue()}}; void gui_mechanism(mech_def& mech) { ImGui::Bullet(); ImGui::SameLine(); if (ImGui::BeginCombo("Mechanism", mech.name.c_str())) { for (const auto& [cat_name, cat]: catalogues) { ImGui::Selectable(cat_name.c_str(), false); ImGui::Indent(); for (const auto& mech_name: cat.mechanism_names()) { if (ImGui::Selectable(mech_name.c_str(), mech_name == mech.name)) { mech.name = mech_name; auto info = cat[mech_name]; mech.global_vars.clear(); for (const auto& [k,v]: info.globals) mech.global_vars[k] = v.default_value; mech.parameters.clear(); for (const auto& [k,v]: info.parameters) mech.parameters[k] = v.default_value; } } ImGui::Unindent(); } ImGui::EndCombo(); } ImGui::SameLine(); gui_trash(mech); ImGui::Indent(); if (!mech.global_vars.empty()) { ImGui::BulletText("Global Values"); ImGui::Indent(); for (auto& [k, v]: mech.global_vars) { ImGui::InputDouble(k.c_str(), &v, 0.0, 0.0, "%.3f", ImGuiInputTextFlags_CharsScientific); } ImGui::Unindent(); } if (!mech.parameters.empty()) { ImGui::BulletText("Parameters"); ImGui::Indent(); for (auto& [k, v]: mech.parameters) { ImGui::InputDouble(k.c_str(), &v, 0.0, 0.0, "%.3f", ImGuiInputTextFlags_CharsScientific); } ImGui::Unindent(); } ImGui::Unindent(); } void gui_painting_mechanism(gui_state& state) { ImGui::PushID("mechanims"); if (ImGui::TreeNodeEx("Mechanisms", ImGuiTreeNodeFlags_AllowItemOverlap)) { auto region = state.region_defs.begin(); auto ridx = 0; for (auto& mechanisms: state.mechanism_defs) { ImGui::PushID(ridx++); ImGui::AlignTextToFramePadding(); auto open = ImGui::TreeNodeEx(region->name.c_str(), ImGuiTreeNodeFlags_AllowItemOverlap); ImGui::SameLine(ImGui::GetWindowWidth() - 30.0f); if (ImGui::Button((const char*) ICON_FK_PLUS_SQUARE)) mechanisms.emplace_back(); if (open) { auto idx = 0; for (auto& mechanism: mechanisms) { ImGui::PushID(idx++); gui_mechanism(mechanism); ImGui::PopID(); } ImGui::TreePop(); } ImGui::PopID(); ++region; } ImGui::TreePop(); } ImGui::PopID(); } void gui_painting(gui_state& state) { if (ImGui::Begin("Paintings")) { ImGui::PushItemWidth(120.0f); // this is pixels gui_painting_preset(state); ImGui::Separator(); gui_painting_parameter(state); ImGui::Separator(); gui_painting_ion(state.ion_defaults, state.ion_defs, state.region_defs); ImGui::Separator(); gui_painting_mechanism(state); ImGui::PopItemWidth(); } ImGui::End(); } void gui_debug(bool& open) { ImGui::ShowMetricsWindow(&open); } void gui_style(bool& open) { if (ImGui::Begin("Style", &open)) ImGui::ShowStyleEditor(); ImGui::End(); } void gui_state::gui() { gui_main(*this); gui_locations(*this); gui_cell(*this); gui_place(*this); gui_painting(*this); } using nlohmann::json; void rd_optional(const json& j, const std::string& k, std::optional<double>& v) { if (j.contains(k)) { double t; j.at(k).get_to(t); v = t; } else { v = {}; } } void wr_optional(json& j, const std::string& k, const std::optional<double>& v) { if (v) j[k] = v.value(); } void to_json(json& result, const par_default& d) { result = {{"temperature", d.TK - 273.15}, {"membrane-capacitance", d.Cm}, {"axial-resistivity", d.RL}, {"membrane-potential", d.Vm}}; } void from_json(const json& j, par_default& d) { j.at("temperature").get_to(d.TK); d.TK += 273.15; j.at("membrane-capacitance").get_to(d.Cm); j.at("axial-resistivity").get_to(d.RL); j.at("membrane-potential").get_to(d.Vm); } void to_json(json& result, const par_def& d) { wr_optional(result, "temperature", d.TK ? std::make_optional(d.TK.value() - 273.15) : d.TK); wr_optional(result, "membrane-capacitance", d.Cm); wr_optional(result, "axial-resistivity", d.RL); wr_optional(result, "membrane-potential", d.Vm); } void from_json(const json& j, par_def& d) { rd_optional(j, "temperature", d.TK); if (d.TK) d.TK.value() += 273.15; rd_optional(j, "membrane-capacitance", d.Cm); rd_optional(j, "membrane-potential", d.Vm); rd_optional(j, "axial-resistivity", d.RL); } void to_json(json& result, const ion_default& d) { result = {{"name", d.name}, {"internal-concentration", d.Xi}, {"external-concentration", d.Xo}, {"reversal-potential", d.Er}, {"method", d.method}}; } void from_json(const json& j, ion_default& d) { j.at("name").get_to(d.name); j.at("internal-concentration").get_to(d.Xi); j.at("external-concentration").get_to(d.Xo); j.at("reversal-potential").get_to(d.Er); j.at("method").get_to(d.method); } void to_json(json& result, const ion_def& d) { wr_optional(result, "internal-concentration", d.Xi); wr_optional(result, "external-concentration", d.Xo); wr_optional(result, "reversal-potential", d.Er); } void from_json(const json& j, ion_def& d) { rd_optional(j, "internal-concentration", d.Xi); rd_optional(j, "membrane-capacitance", d.Xo); rd_optional(j, "membrane-potential", d.Er); } void to_json(json& result, const mech_def& d) { result["name"] = d.name; result["parameters"] = d.parameters; } void from_json(const json& j, mech_def& d) { try { j.at("name").get_to(d.name); j.at("parameters").get_to(d.parameters); } catch(const json::exception& e) { log_warn("Failed to de-serialize mechanism {}\n{}", j.dump(), e.what()); } } void gui_state::serialize(const std::string& dn) { std::filesystem::path dir{dn}; std::filesystem::create_directory(dir); { std::ofstream os(dir / "defaults.json"); json defaults = parameter_defaults; defaults["ions"] = ion_defaults; os << defaults << '\n'; } { std::ofstream os(dir / "cell.json"); json cell; { json local; auto idx = 0; for (const auto& region: region_defs) { json settings = parameter_defs[idx]; auto defaults = ion_defaults.begin(); for (const auto& ion: ion_defs) { if (json tmp = ion[idx]; !tmp.is_null()) { tmp["name"] = defaults++->name; settings["ions"].push_back(tmp); } } if (!settings.is_null()) { settings["region"] = region.name; local.push_back(settings); } idx++; } if (!local.is_null()) { cell["local"] = local; } } { json mechanisms; auto definitions = mechanism_defs.begin(); for (const auto& region: region_defs) { for (const auto& definition: *definitions) { if (!definition.name.empty()) { json mech = definition; mech["region"] = region.name; mechanisms.push_back(mech); } } ++definitions; } cell["mechanisms"] = mechanisms; } os << cell << '\n'; } } void gui_state::deserialize(const std::string& dn) { std::filesystem::path dir{dn}; { std::ifstream is(dir / "defaults.json"); json defaults; is >> defaults; parameter_defaults = defaults; ion_defaults = defaults.at("ions").get<std::vector<ion_default>>(); } { std::ifstream is(dir / "cell.json"); json cell; is >> cell; if (cell.contains("local")) { log_debug("Loading parameters"); for (const auto& mechanism: cell["local"]) { auto region = mechanism["region"]; auto idx = 0ul; for (const auto& r: region_defs) { if (r.name == region) break; idx++; } if (idx >= region_defs.size()) { log_debug("Extending regions by: {}", region); region_defs.emplace_back(); mechanism_defs.emplace_back(); region_defs[idx].name = region; } log_debug("Loading mechanism: '{}'", mechanism.dump()); mech_def mech = mechanism; mechanism_defs[idx].push_back(mech); } } if (cell.contains("mechanisms")) { log_debug("Loading mechasnims"); for (const auto& mechanism: cell["mechanisms"]) { auto region = mechanism["region"]; auto idx = 0ul; for (const auto& r: region_defs) { if (r.name == region) break; idx++; } if (idx >= region_defs.size()) { log_debug("Extending regions by: {}", region); region_defs.emplace_back(); mechanism_defs.emplace_back(); region_defs[idx].name = region; } log_debug("Loading mechanism: '{}'", mechanism.dump()); mech_def mech = mechanism; mechanism_defs[idx].push_back(mech); } } } }
39.568441
142
0.5701
[ "geometry", "render", "vector" ]
d01899e1b5e1c768378c3517dc6fc9cdaa5a2dce
6,573
cc
C++
tests/stats-agg/stat_aggregator.cc
wurikiji/forestdb-optimize
8248dfd677572577bb523890fdab86ed146a3292
[ "Apache-2.0" ]
null
null
null
tests/stats-agg/stat_aggregator.cc
wurikiji/forestdb-optimize
8248dfd677572577bb523890fdab86ed146a3292
[ "Apache-2.0" ]
null
null
null
tests/stats-agg/stat_aggregator.cc
wurikiji/forestdb-optimize
8248dfd677572577bb523890fdab86ed146a3292
[ "Apache-2.0" ]
null
null
null
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2016 Couchbase, 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 <algorithm> #include <cmath> #include <iterator> #include <numeric> #include <string> #include "stat_aggregator.h" StatAggregator::StatAggregator(int _num_stats, int _num_samples) { num_stats = _num_stats; num_samples = _num_samples; t_stats = new stat_history_t*[num_stats]; for (int i = 0; i < num_stats; ++i) { t_stats[i] = new stat_history_t[num_samples]; } } StatAggregator::~StatAggregator() { for (int i = 0; i < num_stats; ++i) { delete[] t_stats[i]; } delete[] t_stats; } void StatAggregator::aggregateAndPrintStats(const char* title, int count, const char* unit) { samples_t all_timings; for (int i = 0; i < num_stats; ++i) { for (int j = 1; j < num_samples; ++j) { t_stats[i][0].latencies.insert(t_stats[i][0].latencies.end(), t_stats[i][j].latencies.begin(), t_stats[i][j].latencies.end()); t_stats[i][j].latencies.clear(); } all_timings.push_back(std::make_pair(t_stats[i][0].name, &t_stats[i][0].latencies)); } int printed = 0; printf("\n========== Avg Latencies (%s) - %d samples (%s) %n", title, count, unit, &printed); fillLineWith('=', 88-printed); printValues(all_timings, unit); fillLineWith('=', 87); } // Given a vector of values (each a vector<T>) calcuate metrics on them // and print to stdout. void StatAggregator::printValues(samples_t values, std::string unit) { // First, calculate mean, median, standard deviation and percentiles // of each set of values, both for printing and to derive what the // range of the graphs should be. std::vector<Stats> value_stats; for (const auto& t : values) { Stats stats; if (t.second->size() == 0) { continue; } stats.name = t.first; stats.values = t.second; std::vector<uint64_t>& vec = *t.second; // Calculate latency percentiles std::sort(vec.begin(), vec.end()); stats.median = vec[(vec.size() * 50) / 100]; stats.pct5 = vec[(vec.size() * 5) / 100]; stats.pct95 = vec[(vec.size() * 95) / 100]; stats.pct99 = vec[(vec.size() * 99) / 100]; const double sum = std::accumulate(vec.begin(), vec.end(), 0.0); stats.mean = sum / vec.size(); double accum = 0.0; for (auto &d : vec) { accum += (d - stats.mean) * (d - stats.mean); } stats.stddev = sqrt(accum / (vec.size() - 1)); value_stats.push_back(stats); } // From these find the start and end for the spark graphs which covers the // a "reasonable sample" of each value set. We define that as from the 5th // to the 95th percentile, so we ensure *all* sets have that range covered. uint64_t spark_start = std::numeric_limits<uint64_t>::max(); uint64_t spark_end = 0; for (const auto& stats : value_stats) { spark_start = (stats.pct5 < spark_start) ? stats.pct5 : spark_start; spark_end = (stats.pct95 > spark_end) ? stats.pct95 : spark_end; } printf("\n Percentile\n"); printf(" %-16s Median 95th 99th Std Dev " "Histogram of samples\n\n", ""); // Finally, print out each set. for (const auto& stats : value_stats) { if (unit == "µs") { printf("%-16s %8.03f %8.03f %8.03f %8.03f ", stats.name.c_str(), stats.median, stats.pct95, stats.pct99, stats.stddev); } else if (unit == "ms") { printf("%-16s %8.03f %8.03f %8.03f %8.03f ", stats.name.c_str(), stats.median/1e3, stats.pct95/1e3, stats.pct99/1e3, stats.stddev/1e3); } else { // unit == "s" printf("%-16s %8.03f %8.03f %8.03f %8.03f ", stats.name.c_str(), stats.median/1e6, stats.pct95/1e6, stats.pct99/1e6, stats.stddev/1e6); } // Calculate and render Sparkline (requires UTF-8 terminal). const int nbins = 32; int prev_distance = 0; std::vector<size_t> histogram; for (unsigned int bin = 0; bin < nbins; bin++) { const uint64_t max_for_bin = (spark_end / nbins) * bin; auto it = std::lower_bound(stats.values->begin(), stats.values->end(), max_for_bin); const int distance = std::distance(stats.values->begin(), it); histogram.push_back(distance - prev_distance); prev_distance = distance; } const auto minmax = std::minmax_element(histogram.begin(), histogram.end()); const size_t range = *minmax.second - *minmax.first + 1; const int levels = 8; for (const auto& h : histogram) { int bar_size = ((h - *minmax.first + 1) * (levels - 1)) / range; putchar('\xe2'); putchar('\x96'); putchar('\x81' + bar_size); } putchar('\n'); } if (unit == "µs") { printf("%52s %-14d %s %14d\n", "", int(spark_start), unit.c_str(), int(spark_end)); } else if (unit == "ms") { printf("%52s %-14d %s %14d\n", "", int(spark_start/1e3), unit.c_str(), int(spark_end/1e3)); } else { // unit == "s" printf("%52s %-14d %s %14d\n", "", int(spark_start/1e6), unit.c_str(), int(spark_end/1e6)); } } void StatAggregator::fillLineWith(const char c, int spaces) { for (int i = 0; i < spaces; ++i) { putchar(c); } putchar('\n'); }
36.314917
79
0.544652
[ "render", "vector" ]
d0197b5c44392e074889eae768382d923187ae47
2,259
hpp
C++
include/GlobalNamespace/NamedPreset.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/NamedPreset.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/NamedPreset.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Type namespace: namespace GlobalNamespace { // Size: 0x18 #pragma pack(push, 1) // Autogenerated type: NamedPreset class NamedPreset : public ::Il2CppObject { public: // [LocalizationKeyAttribute] Offset: 0xE17574 // private System.String _presetNameLocalizationKey // Size: 0x8 // Offset: 0x10 ::Il2CppString* presetNameLocalizationKey; // Field size check static_assert(sizeof(::Il2CppString*) == 0x8); // Creating value type constructor for type: NamedPreset NamedPreset(::Il2CppString* presetNameLocalizationKey_ = {}) noexcept : presetNameLocalizationKey{presetNameLocalizationKey_} {} // Creating conversion operator: operator ::Il2CppString* constexpr operator ::Il2CppString*() const noexcept { return presetNameLocalizationKey; } // public System.String get_presetNameLocalizationKey() // Offset: 0x23EAC48 ::Il2CppString* get_presetNameLocalizationKey(); // public System.Void .ctor() // Offset: 0x23EAC50 // Implemented from: System.Object // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static NamedPreset* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::NamedPreset::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<NamedPreset*, creationType>())); } }; // NamedPreset #pragma pack(pop) static check_size<sizeof(NamedPreset), 16 + sizeof(::Il2CppString*)> __GlobalNamespace_NamedPresetSizeCheck; static_assert(sizeof(NamedPreset) == 0x18); } DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::NamedPreset*, "", "NamedPreset");
45.18
133
0.698539
[ "object" ]
d01e188e8686e67101fc68124b02d423eed540e6
20,927
cc
C++
src/compute_metrics_2way.cc
wdj/CoMet
3e3c099c6eadafc24a1b69d81f07b3a4ed3e16ef
[ "BSD-2-Clause" ]
1
2021-04-14T23:16:32.000Z
2021-04-14T23:16:32.000Z
src/compute_metrics_2way.cc
wdj/comet
3e3c099c6eadafc24a1b69d81f07b3a4ed3e16ef
[ "BSD-2-Clause" ]
null
null
null
src/compute_metrics_2way.cc
wdj/comet
3e3c099c6eadafc24a1b69d81f07b3a4ed3e16ef
[ "BSD-2-Clause" ]
null
null
null
//----------------------------------------------------------------------------- /*! * \file compute_metrics_2way.cc * \author Wayne Joubert * \date Thu Jan 7 10:21:09 EST 2016 * \brief Calculate metrics, 2-way. */ //----------------------------------------------------------------------------- /*----------------------------------------------------------------------------- Copyright 2020, UT-Battelle, LLC Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -----------------------------------------------------------------------------*/ #include "string.h" #include "env.hh" #include "linalg.hh" #include "mirrored_buf.hh" #include "vectors.hh" #include "metrics.hh" #include "vector_sums.hh" #include "comm_xfer_utils.hh" #include "compute_metrics_2way_block_nums.hh" #include "compute_metrics_2way_block_combine.hh" #include "compute_metrics_2way.hh" //============================================================================= void GMComputeMetrics2Way_create( GMComputeMetrics2Way* this_, GMDecompMgr* dm, GMEnv* env) { GMInsist(this_ && dm && env); if (!(GMEnv_num_way(env) == 2 && GMEnv_all2all(env))) { return; } if (! GMEnv_is_proc_active(env)) { return; } *this_ = {0}; GMVectorSums_create(&this_->vector_sums_onproc, dm->num_vector_local, env); GMVectorSums_create(&this_->vector_sums_offproc, dm->num_vector_local, env); for (int i = 0; i < 2; ++i) { GMVectors_create_with_buf(&this_->vectors_01[i], GMEnv_data_type_vectors(env), dm, env); } for (int i = 0; i < 2; ++i) { GMMirroredBuf_create(&this_->metrics_buf_01[i], dm->num_vector_local, dm->num_vector_local, env); } GMMirroredBuf_create(&this_->vectors_buf, dm->num_packedfield_local, dm->num_vector_local, env); if (env->do_reduce) { GMMirroredBuf_create(&this_->metrics_tmp_buf, dm->num_vector_local, dm->num_vector_local, env); } } //----------------------------------------------------------------------------- void GMComputeMetrics2Way_destroy( GMComputeMetrics2Way* this_, GMEnv* env) { GMInsist(this_ && env); if (!(GMEnv_num_way(env) == 2 && GMEnv_all2all(env))) { return; } if (! GMEnv_is_proc_active(env)) { return; } GMVectorSums_destroy(&this_->vector_sums_onproc, env); GMVectorSums_destroy(&this_->vector_sums_offproc, env); for (int i = 0; i < 2; ++i) { GMVectors_destroy(&this_->vectors_01[i], env); } for (int i = 0; i < 2; ++i) { GMMirroredBuf_destroy(&this_->metrics_buf_01[i], env); } GMMirroredBuf_destroy(&this_->vectors_buf, env); if (env->do_reduce) { GMMirroredBuf_destroy(&this_->metrics_tmp_buf, env); } } //============================================================================= void gm_compute_metrics_2way_notall2all( GMComputeMetrics2Way* this_, GMMetrics* metrics, GMVectors* vectors, GMEnv* env) { GMInsist(metrics && vectors && env); GMInsist(! GMEnv_all2all(env)); // Denominator GMVectorSums vector_sums = GMVectorSums_null(); GMVectorSums_create(&vector_sums, vectors->num_vector_local, env); GMVectorSums_compute(&vector_sums, vectors, env); // Numerator gm_linalg_initialize(env); const int nvl = vectors->num_vector_local; const int npvfl = vectors->num_packedval_field_local; // Allocate memory for vectors and for result GMMirroredBuf vectors_buf = GMMirroredBuf_null(); GMMirroredBuf_create(&vectors_buf, npvfl, nvl, env); GMMirroredBuf metrics_buf = GMMirroredBuf_null(); GMMirroredBuf_create(&metrics_buf, nvl, nvl, env); GMMirroredBuf metrics_tmp_buf = GMMirroredBuf_null(); if (env->do_reduce) { GMMirroredBuf_create(&metrics_tmp_buf, nvl, nvl, env); } GMMirroredBuf* metrics_buf_ptr = env->do_reduce ? &metrics_tmp_buf : &metrics_buf; // Copy in vectors gm_vectors_to_buf(&vectors_buf, vectors, env); // Send vectors to GPU gm_set_vectors_start(vectors, &vectors_buf, env); gm_set_vectors_wait(env); gm_compute_2way_proc_nums_start(vectors, vectors, metrics, &vectors_buf, &vectors_buf, metrics_buf_ptr, GMEnv_proc_num_vector_i(env), true, env); gm_compute_wait(env); // Copy result from GPU gm_get_metrics_start(metrics, metrics_buf_ptr, env); gm_get_metrics_wait(metrics, metrics_buf_ptr, env); gm_metrics_pad_adjust(metrics, metrics_buf_ptr, env); // Do reduction across field procs if needed if (env->do_reduce) { gm_reduce_metrics(metrics, &metrics_buf, metrics_buf_ptr, env); } // Combine gm_compute_2way_proc_combine(metrics, &metrics_buf, &vector_sums, &vector_sums, GMEnv_proc_num_vector_i(env), true, env); // Terminations GMVectorSums_destroy(&vector_sums, env); GMMirroredBuf_destroy(&vectors_buf, env); GMMirroredBuf_destroy(&metrics_buf, env); if (env->do_reduce) { GMMirroredBuf_destroy(&metrics_tmp_buf, env); } gm_linalg_finalize(env); } //============================================================================= static void lock(bool& lock_val) { GMInsist(! lock_val); lock_val = true; }; static void unlock(bool& lock_val) { GMInsist(lock_val); lock_val = false; }; //============================================================================= void gm_compute_metrics_2way_all2all( GMComputeMetrics2Way* this_, GMMetrics* metrics, GMVectors* vectors, GMEnv* env) { GMInsist(metrics && vectors && env); GMInsist(GMEnv_all2all(env)); // Initializations const int num_block = GMEnv_num_block_vector(env); const int i_block = GMEnv_proc_num_vector_i(env); GMVectorSums vector_sums_onproc = this_->vector_sums_onproc; GMVectorSums vector_sums_offproc = this_->vector_sums_offproc; gm_linalg_initialize(env); // Create double buffer of vectors objects for send/recv GMVectors* const & vectors_01 = this_->vectors_01; // Allocate GPU buffers // To overlap transfers with compute, set up double buffers for the // vectors sent to the GPU and the metrics received from the GPU. GMMirroredBuf* const & metrics_buf_01 = this_->metrics_buf_01; GMMirroredBuf& vectors_buf = this_->vectors_buf; GMMirroredBuf& metrics_tmp_buf = this_->metrics_tmp_buf; // Result matrix is diagonal block and half the blocks to the right // (including wraparound to left side of matrix when appropriate). // For even number of vector blocks, block rows of lower half of matrix // have one less block to make correct count. const int num_proc_r = GMEnv_num_proc_repl(env); const int proc_num_r = GMEnv_proc_num_repl(env); // Flatten the proc_vector and proc_repl indices into a single index. const int num_proc_rv = num_block * num_proc_r; const int proc_num_rv = proc_num_r + num_proc_r * i_block; MPI_Request mpi_requests[2]; // Prepare for loop over blocks of result. /*---Summary of the opertions in this loop: send VECTORS next step start recv VECTORS next step start set VECTORS this step wait compute numerators start get METRICS prev step wait combine prev step wait (GPU case) recv VECTORS next step wait set VECTORS next step start compute numerators wait get METRICS this step start compute denominators combine this step (CPU case) send VECTORS next step wait ---*/ // Add extra step at begin/end to fill/drain pipeline. const int extra_step = 1; // Lowest/highest (block) diag to be computed for this phase, // measured from (block) main diag. // For all repl procs. const int j_i_offset_min = gm_bdiag_computed_min(env); const int j_i_offset_max = gm_bdiag_computed_max(env); const int j_i_offset_this_row_max = gm_block_computed_this_row_max(env); const int num_bdiag_computed = j_i_offset_max - j_i_offset_min; // Num steps to take to compute blocks // (note: at each step, num_proc_r processors each compute a block) // NOTE: num_step should be consistent within same proc_r. const int num_step = gm_ceil_i(num_bdiag_computed, num_proc_r); typedef struct { GMVectors* vectors_right; GMMirroredBuf* vectors_right_buf; GMMirroredBuf* metrics_buf; bool is_compute_step; bool is_first_compute_step; bool do_compute_block; bool is_main_diag; bool is_right_aliased; int step_num; int index_01; int j_i_offset; int j_block; } LoopVars; LoopVars vars = {0}; LoopVars vars_prev = {0}; LoopVars vars_next = {0}; // Use locks to verify no race condition on a buffer. // Lock buffer when in use for read or write, unlock when done. bool lock_vectors_01_buf_h[2] = {false, false}; bool lock_vectors_01_buf_d[2] = {false, false}; bool lock_metrics_buf_01_h[2] = {false, false}; bool lock_metrics_buf_01_d[2] = {false, false}; bool lock_vectors_buf_h = false; bool lock_vectors_buf_d = false; //bool lock_metrics_tmp_buf_d = false; // Not needed bool lock_metrics_tmp_buf_h = false; //======================================== for (int step_num = 0-extra_step; step_num < num_step+extra_step; ++step_num){ //======================================== //double t0 = GMEnv_get_time(); // Set per-step variables vars_prev = vars; vars = vars_next; vars_next.step_num = step_num + 1; vars_next.is_compute_step = vars_next.step_num >= 0 && vars_next.step_num < num_step; vars_next.is_first_compute_step = vars_next.step_num == 0; vars_next.index_01 = gm_mod_i(vars_next.step_num, 2); vars_next.j_i_offset = j_i_offset_min + vars_next.step_num * num_proc_r + proc_num_r; vars_next.is_main_diag = vars_next.j_i_offset == 0; vars_next.j_block = gm_mod_i(i_block + vars_next.j_i_offset, num_block); vars_next.do_compute_block = vars_next.is_compute_step && vars_next.j_i_offset < j_i_offset_this_row_max; // Pointers to left/right-side vecs. // Here we are computing V^T W, for V, W containing column vectors. vars_next.is_right_aliased = vars_next.is_main_diag; GMVectors* vectors_left = vectors; vars_next.vectors_right = vars_next.is_right_aliased ? vectors_left : &vectors_01[vars_next.index_01]; GMMirroredBuf* vectors_left_buf = &vectors_buf; vars_next.vectors_right_buf = vars_next.is_right_aliased ? vectors_left_buf : &vectors_01[vars_next.index_01].buf; // Pointer to metrics buffer vars_next.metrics_buf = &metrics_buf_01[vars_next.index_01]; // Set up lock aliases bool& lock_metrics_buf_ptr_h_prev = lock_metrics_buf_01_h[vars_prev.index_01]; bool& lock_metrics_buf_ptr_d_prev = lock_metrics_buf_01_d[vars_prev.index_01]; bool& lock_metrics_buf_ptr_h = lock_metrics_buf_01_h[vars.index_01]; bool& lock_metrics_buf_ptr_d = lock_metrics_buf_01_d[vars.index_01]; bool& lock_vectors_left_buf_h = lock_vectors_buf_h; bool& lock_vectors_left_buf_d = lock_vectors_buf_d; bool& lock_vectors_right_buf_h_next = vars_next.is_right_aliased ? lock_vectors_left_buf_h : lock_vectors_01_buf_h[vars_next.index_01]; bool& lock_vectors_right_buf_d_next = vars_next.is_right_aliased ? lock_vectors_left_buf_d : lock_vectors_01_buf_d[vars_next.index_01]; bool& lock_vectors_right_buf_h = vars.is_right_aliased ? lock_vectors_left_buf_h : lock_vectors_01_buf_h[vars.index_01]; bool& lock_vectors_right_buf_d = vars.is_right_aliased ? lock_vectors_left_buf_d : lock_vectors_01_buf_d[vars.index_01]; // Prepare for sends/recvs: procs for communication const int proc_send = gm_mod_i(proc_num_rv - vars_next.j_i_offset*num_proc_r, num_proc_rv); const int proc_recv = gm_mod_i(proc_num_rv + vars_next.j_i_offset*num_proc_r, num_proc_rv); const bool comm_with_self = vars_next.is_main_diag; // Initiate sends/recvs for vecs needed on next step if (vars_next.is_compute_step && ! comm_with_self) { const int mpi_tag = step_num + 1; // NOTE: the following order helps performance GMInsist((!vars_next.is_right_aliased) && "Next step should always compute off-diag block."); lock(lock_vectors_right_buf_h_next); mpi_requests[1] = gm_recv_vectors_start(vars_next.vectors_right, proc_recv, mpi_tag, env); mpi_requests[0] = gm_send_vectors_start(vectors_left, proc_send, mpi_tag, env); } // Send right vectors to GPU end if (vars.is_compute_step && vars.do_compute_block && ! vars.is_right_aliased) { gm_set_vectors_wait(env); unlock(lock_vectors_right_buf_h); unlock(lock_vectors_right_buf_d); } // First step (for any repl or phase): send (left) vecs to GPU if (vars_next.is_first_compute_step) { lock(lock_vectors_left_buf_h); gm_vectors_to_buf(vectors_left_buf, vectors_left, env); lock(lock_vectors_left_buf_d); gm_set_vectors_start(vectors_left, vectors_left_buf, env); // TODO: examine whether overlap possible. // May not be possible for general repl and phase (??). gm_set_vectors_wait(env); unlock(lock_vectors_left_buf_h); unlock(lock_vectors_left_buf_d); } // Commence numerators computation if (vars.is_compute_step && vars.do_compute_block) { lock(lock_vectors_left_buf_d); if (! vars.is_right_aliased) { lock(lock_vectors_right_buf_d); } lock(lock_metrics_buf_ptr_d); gm_compute_2way_proc_nums_start( vectors_left, vars.vectors_right, metrics, vectors_left_buf, vars.vectors_right_buf, vars.metrics_buf, vars.j_block, vars.is_main_diag, env); } // GPU case: wait for prev step get metrics to complete, then combine. // Note this is hidden under GPU computation if (GMEnv_compute_method(env) == GM_COMPUTE_METHOD_GPU) { if (vars_prev.is_compute_step && vars_prev.do_compute_block) { gm_get_metrics_wait(metrics, vars_prev.metrics_buf, env); unlock(lock_metrics_buf_ptr_d_prev); unlock(lock_metrics_buf_ptr_h_prev); lock(lock_metrics_buf_ptr_h_prev); gm_metrics_pad_adjust(metrics, vars_prev.metrics_buf, env); unlock(lock_metrics_buf_ptr_h_prev); GMVectorSums* vector_sums_left = &vector_sums_onproc; GMVectorSums* vector_sums_right = vars_prev.is_main_diag ? &vector_sums_onproc : &vector_sums_offproc; //TODO: remove need to allocate metrics_tmp_buf device array GMMirroredBuf* metrics_buf_prev_ptr = env->do_reduce ? &metrics_tmp_buf : vars_prev.metrics_buf; lock(lock_metrics_buf_ptr_h_prev); // semantics not perfect but ok if (env->do_reduce) { lock(lock_metrics_tmp_buf_h); gm_reduce_metrics(metrics, metrics_buf_prev_ptr, vars_prev.metrics_buf, env); } gm_compute_2way_proc_combine( metrics, metrics_buf_prev_ptr, vector_sums_left, vector_sums_right, vars_prev.j_block, vars_prev.is_main_diag, env); unlock(lock_metrics_buf_ptr_h_prev); // semantics not perfect but ok if (env->do_reduce) { unlock(lock_metrics_tmp_buf_h); } } } // ISSUE: it may be possible to increase performance by swapping the // some code blocks below and the one code block above. It depends // on the relative speeds. If these would be put in two different // CPU threads, then it wouldn't matter. // Compute sums for denominators //const bool compute_sums_early = GMEnv_is_ppc64(); const bool compute_sums_early = true; if (compute_sums_early) { // put it here for speed on this arch if (vars.is_compute_step && vars.do_compute_block) { //TODO: possibly move this if (vars.is_first_compute_step) { GMVectorSums_compute(&vector_sums_onproc, vectors_left, env); } if (! vars.is_main_diag) { GMVectorSums_compute(&vector_sums_offproc, vars.vectors_right, env); } } } // Wait for recvs to complete if (vars_next.is_compute_step && ! comm_with_self) { gm_recv_vectors_wait(&(mpi_requests[1]), env); GMInsist((!vars_next.is_right_aliased) && "Next step should always compute off-diag block."); unlock(lock_vectors_right_buf_h_next); } // Send right vectors for next step to GPU start if (vars_next.is_compute_step && vars_next.do_compute_block && ! vars_next.is_right_aliased) { // ISSUE: make sure not necessary if vars_next.is_right_aliased lock(lock_vectors_right_buf_h_next); lock(lock_vectors_right_buf_d_next); gm_set_vectors_start(vars_next.vectors_right, vars_next.vectors_right_buf, env); } // Wait for numerators computation to complete if (vars.is_compute_step && vars.do_compute_block) { gm_compute_wait(env); unlock(lock_vectors_left_buf_d); if (! vars.is_right_aliased) { unlock(lock_vectors_right_buf_d); } unlock(lock_metrics_buf_ptr_d); } // Commence copy of completed numerators back from GPU if (vars.is_compute_step && vars.do_compute_block) { lock(lock_metrics_buf_ptr_h); lock(lock_metrics_buf_ptr_d); gm_get_metrics_start(metrics, vars.metrics_buf, env); } // Compute sums for denominators if (! compute_sums_early) { // put it here for speed on this arch if (vars.is_compute_step && vars.do_compute_block) { //TODO: possibly move this if (vars.is_first_compute_step) { GMVectorSums_compute(&vector_sums_onproc, vectors_left, env); } if (! vars.is_main_diag) { GMVectorSums_compute(&vector_sums_offproc, vars.vectors_right, env); } } } // CPU case: combine numerators, denominators to obtain final result if (GMEnv_compute_method(env) != GM_COMPUTE_METHOD_GPU) { if (vars.is_compute_step && vars.do_compute_block) { GMVectorSums* vector_sums_left = &vector_sums_onproc; GMVectorSums* vector_sums_right = vars.is_main_diag ? &vector_sums_onproc : &vector_sums_offproc; gm_get_metrics_wait(metrics, vars.metrics_buf, env); // NO-OP unlock(lock_metrics_buf_ptr_d); unlock(lock_metrics_buf_ptr_h); lock(lock_metrics_buf_ptr_h); gm_compute_2way_proc_combine( metrics, vars.metrics_buf, vector_sums_left, vector_sums_right, vars.j_block, vars.is_main_diag, env); unlock(lock_metrics_buf_ptr_h); } } // Wait for sends to complete if (vars_next.is_compute_step && ! comm_with_self) { gm_send_vectors_wait(&(mpi_requests[0]), env); } //double t1 = GMEnv_get_time(); //printf("%i %f\n", step_num, t1-t0); //======================================== } // step_num //======================================== // Terminations for (int i=0; i<2; ++i) { GMInsist(!lock_vectors_01_buf_h[i]); GMInsist(!lock_vectors_01_buf_d[i]); GMInsist(!lock_metrics_buf_01_h[i]); GMInsist(!lock_metrics_buf_01_d[i]); } GMInsist(!lock_vectors_buf_h); GMInsist(!lock_vectors_buf_d); GMInsist(!lock_metrics_tmp_buf_h); gm_linalg_finalize(env); } //-----------------------------------------------------------------------------
33.112342
80
0.666173
[ "vector" ]
d0214a1c46953db7c58b59f82e8890a68b50ad06
20,279
cpp
C++
src/circuitcocircuit.cpp
OndrejSlamecka/mincuts
b9cd5913db77eec7576a8eb2ac85d464025158b0
[ "MIT" ]
2
2019-04-13T04:28:32.000Z
2019-06-29T19:10:59.000Z
src/circuitcocircuit.cpp
OndrejSlamecka/mincuts
b9cd5913db77eec7576a8eb2ac85d464025158b0
[ "MIT" ]
null
null
null
src/circuitcocircuit.cpp
OndrejSlamecka/mincuts
b9cd5913db77eec7576a8eb2ac85d464025158b0
[ "MIT" ]
null
null
null
/* * Copyright (c) 2015, Ondrej Slamecka <ondrej@slamecka.cz> * See the LICENSE file in the root folder of this repository. */ /* * Note about colouring: * Vertices: Red go all red, but vertices are blue only if they are in X * Edges: All red or blue in red or blue subgraph respectively */ #include "./circuitcocircuit.h" #include <limits> #include <cstdint> #include <algorithm> // swap #include "./helpers.h" #ifdef MEASURE_RUNTIME #include "./runtimemeasurement.h" RuntimeMeasurement rtm; #define RTM_START RuntimeMeasurement::point start(rtm.mark(nBondsOutput)); #define RTM_END if (j <= measurementDepth) { rtm.log(j, nBondsOutput, start); } #else #define RTM_START #define RTM_END #endif using std::ostream; using std::invalid_argument; using std::logic_error; using std::cout; using std::cerr; using std::endl; using ogdf::edge; using ogdf::node; using ogdf::adjEntry; using ogdf::ListConstIterator; using ogdf::Graph; using ogdf::Stack; using ogdf::NodeArray; using ogdf::Queue; using ogdf::Prioritized; using ogdf::DisjointSets; using ogdf::List; using ogdf::ListConstIterator; ostream & operator<<(ostream &os, const bond &L) { return os << L.edges; } #ifdef MEASURE_RUNTIME CircuitCocircuit::CircuitCocircuit(ogdf::Graph &Graph, int cutSizeBound, int md) : G(Graph), cutSizeBound(cutSizeBound), lambda(G), measurementDepth(md) { #else CircuitCocircuit::CircuitCocircuit(ogdf::Graph &Graph, int cutSizeBound) : G(Graph), cutSizeBound(cutSizeBound), lambda(G) { #endif // Sort edges by index for use in minimalSpanningForest for (edge e : G.edges) { allEdgesSortedByIndex.pushBack(Prioritized<edge, int>(e, e->index())); } allEdgesSortedByIndex.quicksort(); #ifdef MEASURE_RUNTIME rtm = RuntimeMeasurement(); #endif } void CircuitCocircuit::run(int k, List<bond> &bonds) { // Create map lambda : E(G) -> N (the natural numbers) for selection of // the unique shortest path. The map is randomized with each algorithm run // in order to detect mistakes related to graph traversing order. // |V| - k + 2 is the maximum length of a cycle, thus the maximum possible // length of a path is |V| - k + 1 // (|V| - k + 1) * UB == max. long int std::random_device rd; std::default_random_engine engine(rd()); constexpr uint64_t max_uint64_t = std::numeric_limits<uint64_t>::max(); uint64_t upper_bound = max_uint64_t / (G.numberOfNodes() - k + 1); std::uniform_int_distribution<uint64_t> distribution(1, upper_bound); for (edge e : G.edges) { lambda[e] = distribution(engine); } // Run bond Y; extendBond(k, Y, 1, bonds); } void CircuitCocircuit::run(int k) { List<bond> bonds; outputToStdout = true; run(k, bonds); } void CircuitCocircuit::extendBond(int components, const bond &Y, int j, List<bond> &bonds) { GraphColouring colouring(G); // D is an arbitrary matroid base List<edge> D; minimalSpanningForest(components, Y, D); for (edge e : D) { if ((!Y.edges.empty() && e->index() < Y.lastBondFirstEdge->index())) { continue; } bond X; X.edges.pushBack(e); X.lastBondFirstEdge = e; node u = e->source(), v = e->target(); if (u->index() > v->index()) swap(u, v); // Definition 4.1.a colouring.set(u, Colour::RED); colouring.set(v, Colour::BLUE); RTM_START genStage(colouring, components, Y, j, bonds, X); RTM_END colouring.set(u, Colour::BLACK); colouring.set(v, Colour::BLACK); } } void CircuitCocircuit::genStage(GraphColouring &colouring, int components, const bond &Y, int j, List<bond> &bonds, const bond &X) { if (Y.edges.size() + X.edges.size() > cutSizeBound - components + j + 1) { return; } // Find the path P minimizing (|P|, lambda_length(P), index_vector(P)) // See shortestPath for more info node firstRed = NULL; List<edge> P; shortestPath(colouring, Y.edges, X.edges, firstRed, P); #ifdef MEASURE_PATHS_LENGTHS cout << j << " " << X.edges.size() << " " << P.size() << endl; #endif if (P.empty()) { // If there is no such path P, then return ‘(j + 1) bond: Y union X’ bond XY; XY.lastBondFirstEdge = X.lastBondFirstEdge; List<edge> Yedges(Y.edges); XY.edges.conc(Yedges); List<edge> Xedges(X.edges); XY.edges.conc(Xedges); if (j == components - 1) { if (outputToStdout) { #ifndef MEASURE_PATHS_LENGTHS cout << XY << "\n"; #endif } else { bonds.pushBack(XY); } #ifdef MEASURE_RUNTIME nBondsOutput += 1; #endif } else { extendBond(components, XY, j + 1, bonds); } } else { // Try adding each c in P to X. List<edge> blueBefore; List<edge> newBlueTreeEdges; List<edge> oldBlueTreeEdges; // Colour the path blue but remember the previous colours for (edge e : P) { if (colouring[e] == Colour::BLUE) { blueBefore.pushBack(e); } colouring[e] = Colour::BLUE; } // c = (u,v), u is red, v is blue node u, v = firstRed; // we're doing u = v at the begining of each step // for each c in P, recursively call GenCocircuits(X union {c}). for (edge c : P) { // We're traversing P in order, so we can do this: u = v; v = c->opposite(u); // Colour as with u and v in X // (the colour of u has to be set red here in order to avoid being // used in a possible re-creation of the blue tree, the colour of c // cannot be set here so that we can satisfy the input condition of // the method reCreateBlueTreeIfDisconnected colouring.set(v, Colour::BLUE); colouring.set(u, Colour::RED); // Do we still have a hyperplane? if ( isBlueTreeDisconnected(colouring, c, u) && !reCreateBlueTreeIfDisconnected(colouring, Y.edges, X.edges, v, c, oldBlueTreeEdges, newBlueTreeEdges)) { // Revert colouring and end break; } // This condition has to be checked after the hyperplane test! if (c->index() <= X.lastBondFirstEdge->index()) { colouring[c] = Colour::RED; continue; } // all went fine, add c to X bond newX(X); newX.edges.pushBack(c); // Don't set colour before we check for a hyperplane colouring[c] = Colour::BLACK; genStage(colouring, components, Y, j, bonds, newX); colouring[c] = Colour::RED; } // Revert colouring so that the original colouring is used in the // recursion level above revertColouring(colouring, P, blueBefore, firstRed, X, oldBlueTreeEdges, newBlueTreeEdges); } } /** * Iota minimal path P_{u,v} is a path between vertices u,v which minimizes * the vector of its indicies (P_{u,v}[0].index, P_{u,v}[1].index,...) * This function selects such path from two paths starting in s1 or s2, * respectivelly (note s1 and s2 are blue) and returns one of s1 or s2. * * Both paths are expected to be equally long. */ node CircuitCocircuit::getStartNodeOfIotaMinimalPath(GraphColouring &colouring, NodeArray<edge> &accessEdge, node s1, node s2) { // Alternatively we could enumerate P1 and P2 and use // lexicographical_compare on list of their indicies node n, m, a, b; edge e1, e2; node lexMinStartNode = NULL; for (n = s1, m = s2; colouring[n] != Colour::RED && colouring[m] != Colour::RED; n = a, m = b) { e1 = accessEdge[n]; a = e1->opposite(n); e2 = accessEdge[m]; b = e2->opposite(m); if (e1->index() < e2->index()) { lexMinStartNode = s1; } else if (e2->index() < e1->index()) { lexMinStartNode = s2; } } // One path hits red sooner -> they're not both equaly long which shows // an error in shortestPath implementation if (lexMinStartNode == NULL) { // This should never happen if this implementation is correct throw logic_error("Comparing index vector of two paths which are " \ "not of equal length."); } return lexMinStartNode; } /** * Performs BFS to find the canonical shortest path from some red vertex to * some blue vertex in graph G without using any edge from X union Y. */ void CircuitCocircuit::shortestPath(GraphColouring &colouring, const List<edge> &Y, const List<edge> &X, node &lastRed, List<edge> &path) { // For every path P = (e_0, e_1, e_2,...) we have the following triplet // (|P|, lambda_length(P), index_vector(P)), where |P| is number of its // edges, lambda length is the sum of lambda(e) through all e in P and // index_vector of P is the vector (e_0.index, e_1.index, e_2.index) // // In this function we're looking for such path P which (lexicographically) // minimizes this triplet. A modification of BFS is used. // // We compute the lambda length of paths by assigning the lambda distance // to nodes. Lambda distance ld is 0 for the starting nodes and when // discovering a new node v from node u (where e = {u, v}) then we set // ld[v] = ld[u] + lambda[e]. If we can arrive to v from a different node // w (which is in the same distance from the start as u) using edge f and // with ld[w] + lambda[f] < ld[v] then we use f as an access edge and set // ld[v] = ld[w] + lambda[f]. // // Note that we only calculate the lambda distance of a node as we discover // it from path P1 and if we find an edge from P2 to the node then we only // update the lambda distance if it would decrease and if |P1| = |P2|. This // is because we don't care about the lambda distance primarily, our // approach only computes the lambda length correctly for the shortest // (wrt. # of edges) paths currently discovered by BFS. path.clear(); Queue<node> Q; NodeArray<bool> visited(G, false); NodeArray<u_int64_t> lambdaDistance(G, 0); NodeArray<int> vertexDistance(G, 0); NodeArray<edge> accessEdge(G); // Hide Y and X Graph::HiddenEdgeSet hidden_xy(G); for (edge e : Y) { hidden_xy.hide(e); } for (edge e : X) { hidden_xy.hide(e); } // Init for (node n : colouring.getRedVertices()) { Q.append(n); visited[n] = true; lambdaDistance[n] = 0; vertexDistance[n] = 0; } // Start BFS node foundBlue = NULL; node u, v; while (!Q.empty()) { u = Q.pop(); if (colouring[u] == Colour::BLUE) { if (foundBlue == NULL || lambdaDistance[u] < lambdaDistance[foundBlue]) { foundBlue = u; } else if (lambdaDistance[u] == lambdaDistance[foundBlue]) { // Compare path P1 = v-u and path P2 = v-foundBlue, and choose // the one which lexicographically minimizes its edge indicies // vector (P[0].index, P[1].index, P[2].index,...) // Note that by the start node we actually mean the blue node foundBlue = getStartNodeOfIotaMinimalPath(colouring, accessEdge, u, foundBlue); } } for (adjEntry adj : u->adjEntries) { edge e = adj->theEdge(); v = e->opposite(u); // The vertexDistance[u] == vertexDistance[v] - 1 condition is // required in order to prevent setting a wrong accessEdge // (wrong as in wrong result of comparison between paths which // would be produced by switching the access edge) // This condition can't be replaced by v == foundBlue (a simple // counterexample can be shown) if (visited[v] && vertexDistance[u] == vertexDistance[v] - 1 && lambdaDistance[v] > lambdaDistance[u] + lambda[e]) { lambdaDistance[v] = lambdaDistance[u] + lambda[e]; accessEdge[v] = e; } if (!visited[v] && foundBlue == NULL) { accessEdge[v] = e; visited[v] = true; Q.append(v); lambdaDistance[v] = lambdaDistance[u] + lambda[e]; vertexDistance[v] = vertexDistance[u] + 1; } } } if (foundBlue) { for (node n = foundBlue; colouring[n] != Colour::RED; n = v) { edge e = accessEdge[n]; v = e->opposite(n); // Note that lastRed is set correctly only in the iteration // when colouring[n] == RED is satisfied (which is the last iter.) lastRed = v; // In reverse direction it is the first red... path.pushFront(e); } } hidden_xy.restore(); } /* --- Colouring, re-creating the blue tree --- */ bool CircuitCocircuit::isBlueTreeDisconnected(GraphColouring &colouring, edge c, node u) { // We will test whether adding c to X would disconnect the blue tree Graph::HiddenEdgeSet hidden_edges(G); hidden_edges.hide(c); // Don't consider c to be part of blue subgraph for (adjEntry adj : u->adjEntries) { edge e = adj->theEdge(); if (colouring[e] == Colour::BLUE) { hidden_edges.restore(c); return true; } } hidden_edges.restore(c); return false; } /** * Recolours only edges of course */ void CircuitCocircuit::recolourBlueTreeBlack(GraphColouring &colouring, node start, List<edge> &oldBlueTreeEdges) { Stack<node> Q; NodeArray<bool> visited(G, false); Q.push(start); node u, v; while (!Q.empty()) { u = Q.pop(); for (adjEntry adj : u->adjEntries) { edge e = adj->theEdge(); if (colouring[e] != Colour::BLUE) { continue; } v = e->opposite(u); if (!visited[v]) { visited[v] = true; Q.push(v); } colouring[e] = Colour::BLACK; oldBlueTreeEdges.pushBack(e); } } } /** * Returns true iff it was possible to re-create the blue tree such that it is connected * Expects graph with single blue tree as input (due to use of recolourBlueTreeBlack) */ bool CircuitCocircuit::reCreateBlueTreeIfDisconnected( GraphColouring &colouring, const List<edge> &Y, const List<edge> &X, node v, edge c, List<edge> &oldBlueTreeEdges, List<edge> &newBlueTreeEdges) { // We will colour black what is blue and start building blue tree from scratch // * recolour both components of T_b \ c black // * run bfs from one blue vertex // * - for each found blue vertex colour the path to it blue, // increase the counter of found blue vertices // * - if all blue vertices weren't found then fail node m, // m is node currently being examined in BFS n, // neighbours of u a, b; // node currently being coloured on the path, its successor // This recolours only edges of course, note that c is used too recolourBlueTreeBlack(colouring, v, oldBlueTreeEdges); // Run BFS in G \ Y \ X \ T_r \ {c}. // Each time blue vertex x is found, colour path v-x blue // and increase nBlueVerticesFound: // - if nBlueVerticesFound == colouring.nBlueVertices, return true // - if BFS ends and nBlueVerticesFound < colouring.nBlueVertices, // return false Graph::HiddenEdgeSet hidden_xyc(G); for (edge e : Y) { hidden_xyc.hide(e); } for (edge e : X) { hidden_xyc.hide(e); } hidden_xyc.hide(c); // Declare variables for use in the BFS Queue<node> Q; Q.append(v); int nBlueVerticesFound = 0; // v will be counted in the first iteration NodeArray<bool> visited(G, false); visited[v] = true; NodeArray<edge> accessEdge(G, NULL); while (!Q.empty()) { m = Q.pop(); if (colouring[m] == Colour::BLUE) { nBlueVerticesFound++; // Colour path from v to u for (a = m; a != v; a = b) { edge e = accessEdge[a]; b = e->opposite(a); colouring[e] = Colour::BLUE; newBlueTreeEdges.pushBack(e); } if (nBlueVerticesFound == colouring.nBlueVertices) { break; } } for (adjEntry adj : m->adjEntries) { edge e = adj->theEdge(); n = e->opposite(m); if (!visited[n] && colouring[n] != Colour::RED) { visited[n] = true; accessEdge[n] = e; Q.append(n); } } } hidden_xyc.restore(); if (nBlueVerticesFound == colouring.nBlueVertices) { return true; } else { return false; } } void CircuitCocircuit::revertColouring(GraphColouring &colouring, List<edge> &P, List<edge> &blueEdgesOnP, node firstRed, const bond &X, List<edge> &oldBlueTreeEdges, List<edge> &newBlueTreeEdges) { // The order is important here! for (edge e : newBlueTreeEdges) { colouring[e] = Colour::BLACK; } for (edge e : oldBlueTreeEdges) { colouring[e] = Colour::BLUE; } for (edge e : P) { colouring.set(e->source(), Colour::BLACK); colouring.set(e->target(), Colour::BLACK); colouring[e] = Colour::BLACK; } for (edge e : X.edges) { if (colouring[e->source()] != Colour::RED) { colouring.set(e->source(), Colour::BLUE); } if (colouring[e->target()] != Colour::RED) { colouring.set(e->target(), Colour::BLUE); } } for (edge e : blueEdgesOnP) { colouring[e] = Colour::BLUE; } colouring.set(firstRed, Colour::RED); } /* --- Minimal forest computation --- */ /** * @brief An implementation of Kruskal's algorithm to return minimal spanning * forest on (components-1) components. * @param components The k in k-bonds * @param forbidden Forbidden edges to use, typically existing bonds * @param result */ void CircuitCocircuit::minimalSpanningForest(int components, const bond &Y, List<edge> &result) { // An modified implementation of Kruskal's algorithm // taken from OGDF's makeMinimumSpanningTree NodeArray<int> setID(G); DisjointSets<> uf(G.numberOfNodes()); for (node v = G.firstNode(); v; v = v->succ()) { setID[v] = uf.makeSet(); } int stSize = 0; for (ListConstIterator<Prioritized<edge, int>> it = allEdgesSortedByIndex.begin(); it.valid(); ++it) { const edge e = (*it).item(); const int v = setID[e->source()]; const int w = setID[e->target()]; if ((uf.find(v) != uf.find(w)) && !Y.edges.search(e).valid()) { // Faster than characteristic vector uf.link(uf.find(v), uf.find(w)); result.pushBack(e); stSize++; } // Span. forest on n vertices and k-1 comp. has n-(k-1) edges if (stSize == G.numberOfNodes() - components + 1) break; } } CircuitCocircuit::~CircuitCocircuit() { }
33.630182
106
0.566793
[ "vector" ]
d028f9ee327c14f3699db250876d15ecfd4ac9a2
9,189
cpp
C++
example/fds132text.cpp
BartDeWaal/FDS132-textdriver
6bc109f52e943accdcfbc71a7f60954d94570456
[ "MIT" ]
3
2016-04-14T22:30:08.000Z
2020-12-02T03:18:31.000Z
example/fds132text.cpp
BartDeWaal/FDS132-textdriver
6bc109f52e943accdcfbc71a7f60954d94570456
[ "MIT" ]
1
2020-12-31T12:42:11.000Z
2020-12-31T12:42:11.000Z
example/fds132text.cpp
BartDeWaal/FDS132-textdriver
6bc109f52e943accdcfbc71a7f60954d94570456
[ "MIT" ]
1
2020-12-01T19:01:52.000Z
2020-12-01T19:01:52.000Z
#include "fds132text.h" fdsScreen::fdsScreen(){ first = NULL; //make sure it's a null pointer } void fdsScreen::setPins(){ // using the defaults from the example setup setPins(10,13,11,7,6,5,9,2000); } void fdsScreen::setPins(int p_strobePin, int p_clockPin, int p_dataPin, int p_row_c, int p_row_b, int p_row_a, int p_resredPin, int p_delay){ strobePin = p_strobePin; clockPin = p_clockPin; dataPin = p_dataPin; resredPin = p_resredPin; row_a = p_row_a; row_b = p_row_b; row_c = p_row_c; delay = p_delay; pinMode (strobePin, OUTPUT); pinMode (clockPin, OUTPUT); pinMode (dataPin, OUTPUT); pinMode (row_c, OUTPUT); pinMode (row_b, OUTPUT); pinMode (row_a, OUTPUT); pinMode (resredPin, OUTPUT); digitalWrite (resredPin, HIGH); digitalWrite (strobePin, LOW); SPI.begin(clockPin, -1, dataPin); // start the SPI library SPI.setBitOrder(MSBFIRST); //Code was written for this bit Order } // Takes a C-style string and puts it in the list of fdsStrings fdsString* fdsScreen::addString(char initialValue[], int position) { fdsString* newString; newString = (fdsString*) malloc(sizeof(class fdsString)); newString -> startLocation = position; placeString(newString); newString -> firstNode = 0; newString -> set(initialValue); return newString; } // Takes a fdsChar and puts it in the list of fdsStrings fdsString* fdsScreen::addString(fdsChar *value, int position) { fdsString* newString; newString = (fdsString*) malloc(sizeof(class fdsString)); newString -> startLocation = position; placeString(newString); newString -> firstNode = 0; newString -> set(value); return newString; } // Place the string in the right location void fdsScreen::placeString(fdsString* theString) { int position = theString -> startLocation; if (first == 0){ //if there is no string yet first = theString; theString -> next = 0; } else { // If there is already a string fdsString* stringNavigator = first; // Find the place where the string should be, as the strings should be ordered by position while((stringNavigator -> next != 0) //The loop should quit if there is no next item, in which case theString should be last && (((stringNavigator -> next) -> startLocation) < position)) // also if the next item has a bigger start position, // so we found the right position { stringNavigator = stringNavigator -> next; } theString -> next = stringNavigator -> next; stringNavigator -> next = theString; } } // Set this string to the C-style string supplied // If there is already a string it will be overwritten void fdsString::set(char value[]){ if (firstNode == 0) { // If there is no string make a node for the fist character firstNode = (fdsStringNode*) malloc(sizeof(fdsStringNode)); firstNode -> next = 0; } lastNode = firstNode -> set(value); } // Set a string to a character void fdsString::set(fdsChar *value){ if (firstNode == 0) { // If there is no string make a node for the fist character firstNode = (fdsStringNode*) malloc(sizeof(fdsStringNode)); firstNode -> next = 0; } lastNode = firstNode -> set(value); } // Outputs the point where this string should stop displaying. // Either the end of the screen or the start of the next string int fdsString::nextStart(){ if (next == 0){ return 271; } return (next -> startLocation); } // Chage the output array to what's currently in the strings void fdsScreen::update() { fdsString *current = first; // pointer to the string we are converting into our output right now //clear the output memset(output, 0, sizeof(output[0][0]) * 35 * 7); while (current != 0){ // if we still have at least one string to go // put it on the buffer starting at it's start updateFromfdsStringNode(current -> firstNode, current -> startLocation, current -> nextStart()); current = current -> next; } } void fdsScreen::updateFromfdsStringNode(fdsStringNode *current, int currentbit, int endbit){ fdsChar *currentValue = 0; // Pointer to the Character object current is pointing to. byte b; //The bits that we are currently inserting into the array. while (true) { if (current == 0) {break;} // We should end if we have reached the end of the string (last stringnode) if (currentbit > endbit) {break;} // We should end if we have reached the end of the bit // set b to the byte that cointains (at the end) the bits needed to display this part of the current character currentValue = (*current).value; for (int row = 0; row < 7; row++){ b = currentValue -> character_map[row]; // integer division in C always rounds down, so currentbit/8 gives us the right byte to write to // To this byte we want to add the bits in b, and not change the ones that are already there. // Bitwise or "|" lets us do this // currentbit % 8 gives us a number from 0 to 7 indicating how many bits in the byte we have already used // So we want to shift b that many spaces to the left using << output[row][currentbit/8] = output[row][currentbit/8] | (b << (currentbit % 8)); // Now that last shift may have shifted some of the bits off the byte, so we need to put them on the next one. // if these bits exist, then shifting b to the right will give us exactly those bits, no more, and put them // on the right side of the byte, just where we want them. output[row][(currentbit/8) + 1] = output[row][(currentbit/8) + 1] | (b >> (8 - (currentbit % 8))); } // shift our address to the location for the next character currentbit += currentValue -> width; // and load our next character current = current -> next; } // clean up what is left over after the endbit for (int row = 0; row < 7; row++){ // Make sure the byte after the endbit is empty output[row][(endbit/8)+1] = 0; output[row][endbit/8] = output[row][endbit/8] & (B11111111 >> (8 - (endbit % 8))); } } void fdsScreen::zeroDisplay() //Clear the display { for(int i=0; i<34; i++) { SPI.transfer(0); } } void fdsScreen::display() //Display the current fdsScreen::output array { for (int row=0; row<7; row++) // The screen can only display one line at a time, // We can make it look like it can write them all by writing quickly { digitalWrite(strobePin, LOW); // strobePin LOW so the LEDs don't change when we send the bits. for(int i=34; i>=0; i--){ SPI.transfer(output[row][i]); }; digitalWrite(resredPin, LOW); // dim the display to prevent ghosting. digitalWrite(strobePin, HIGH); // update the shiftregisters. setRow(row); digitalWrite(resredPin, HIGH); // turn the display back on. delayMicroseconds(delay); // pause, because otherwise it will update too quickly } // Make sure the last row it turned on for the same amount of time the rest are. // We don't *really* need to do SPI here, but it's the easiest way to find the right // amount of time to pause ;) digitalWrite(strobePin, LOW); for(int i=34; i>=0; i--){ SPI.transfer(output[0][i]); }; digitalWrite(resredPin, LOW); } // The LED screen only shows 1 (out of 7) rows at a time. This activates the row // (The full screen is shown by quickly alternating between these) void fdsScreen::setRow (int row) { digitalWrite (row_a, row & 1); digitalWrite (row_b, row & 2); digitalWrite (row_c, row & 4); } // Set the value of this node to the first character in the array // Then do the rest of the nodes recursively fdsStringNode* fdsStringNode::set(char *newValue){ value = charTofdsChar(*newValue); if (*(newValue + sizeof(char))==0) { // C-strings are null teminated. If the next character is 0 this // is the end of the string. setEnd(); return this; } if (next == NULL){ // make more memory availible for the next bit of the string next = (fdsStringNode*) malloc(sizeof(fdsStringNode)); next -> next = NULL; } return next -> set(newValue + sizeof(char)); } // Set a node to a character, and make that node the last one fdsStringNode* fdsStringNode::set(fdsChar *newValue){ value = newValue; //We know it's only one value long, so we can just end it here setEnd(); return this; } // Free the memory used by the rest of the string and NULL the pointer void fdsStringNode::setEnd(){ if (next == NULL){ return; } next -> setEnd(); free(next); next = NULL; }
36.177165
141
0.62466
[ "object" ]
d02a7d376ce7f7e3b07f5a712d41b5a768292a18
2,110
cpp
C++
HackerBlocks/More/PIRATES AND THEIR CHESTS.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
HackerBlocks/More/PIRATES AND THEIR CHESTS.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
HackerBlocks/More/PIRATES AND THEIR CHESTS.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
// https://www.hackerearth.com/practice/algorithms/greedy/basics-of-greedy-algorithms/practice-problems/algorithm/monk-in-the-magical-land/description/ #include<bits/stdc++.h> #include<unordered_set> using namespace std; #define ll long long in #define s(x) scanf("%lld",&x) #define s2(x,y) s(x)+s(y) #define s3(x,y,z) s(x)+s(y)+s(z) #define p(x) printf("%lld\n",x) #define p2(x,y) p(x)+p(y) #define p3(x,y,z) p(x)+p(y)+p(z) #define F(i,a,b) for(ll i = (ll)(a); i <= (ll)(b); i++) #define RF(i,a,b) for(ll i = (ll)(a); i >= (ll)(b); i--) #define ff first #define ss second #define mp(x,y) make_pair(x,y) #define pll pair<ll,ll> #define pb push_back ll mod = 1e9 + 7 ; ll inf = 1e18 ; ll gcd(ll a , ll b){return b==0?a:gcd(b,a%b);} int main() { // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); ll t; cin>>t; while(t--){ ll n,m,k; cin>>n>>m>>k; vector<ll>K(n),C(m),Z(m); // Chose this data type as we need atleast 100 bits to keep track of 100 possible chests __int128_t one=1; // key[i] will contain the bit representation of the chests ith key can open vector<__int128_t>key(n,0); for(ll i=0;i<n;i++)cin>>K[i]; for(ll i=0;i<m;i++)cin>>C[i]; for(ll i=0;i<m;i++)cin>>Z[i]; for(ll i=0;i<n;i++){ for(ll j=0;j<m;j++){ if(__gcd(K[i],C[j])>1){ key[i]|=one<<j; } } } ll ans=-inf; // all possible combination of K keys from the given n are checked for(ll mask=1;mask<(1<<n);mask++){ if(__builtin_popcount(mask) > k)continue; // 'chests' contain the bit representation of the chests which K keys // (set bits in the mask)can together open. __int128_t chests=0; for(ll j=0;j<n;j++){ if(mask&(1<<j)){ chests|=key[j]; } } ll sum=0; // Calculate the total treasure which can be obtained together from // all the chests indicated by the set bits in the variable 'chest' for(ll z=0;z<m;z++){ if(chests&(one<<z))sum+=Z[z]; } ans=max(ans,sum); } p(ans); } }
26.375
151
0.57109
[ "vector" ]
d02af566252b7bd820c0168a544a5a50016d934e
31,549
cpp
C++
toolsrc/src/test_install_plan.cpp
jjzhang166/vcpkg
17b6d75d0d16d8b620e6680c0364208aa8a52651
[ "MIT" ]
null
null
null
toolsrc/src/test_install_plan.cpp
jjzhang166/vcpkg
17b6d75d0d16d8b620e6680c0364208aa8a52651
[ "MIT" ]
null
null
null
toolsrc/src/test_install_plan.cpp
jjzhang166/vcpkg
17b6d75d0d16d8b620e6680c0364208aa8a52651
[ "MIT" ]
null
null
null
#include "CppUnitTest.h" #include "vcpkg_Dependencies.h" #include "vcpkg_Util.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; using namespace vcpkg; namespace UnitTest1 { class InstallPlanTests : public TestClass<InstallPlanTests> { struct PackageSpecMap { std::unordered_map<PackageSpec, SourceControlFile> map; Triplet triplet; PackageSpecMap(const Triplet& t) { triplet = t; } PackageSpec get_package_spec(std::vector<std::unordered_map<std::string, std::string>>&& fields) { auto m_pgh = vcpkg::SourceControlFile::parse_control_file(std::move(fields)); Assert::IsTrue(m_pgh.has_value()); auto& scf = *m_pgh.get(); auto spec = PackageSpec::from_name_and_triplet(scf->core_paragraph->name, triplet); Assert::IsTrue(spec.has_value()); map.emplace(*spec.get(), std::move(*scf.get())); return PackageSpec{*spec.get()}; } PackageSpec set_package_map(std::string source, std::string version, std::string build_depends) { return get_package_spec({{{"Source", source}, {"Version", version}, {"Build-Depends", build_depends}}}); } }; static void features_check(Dependencies::AnyAction* install_action, std::string pkg_name, std::vector<std::string> vec, const Triplet& triplet = Triplet::X86_WINDOWS) { const auto& plan = install_action->install_plan.value_or_exit(VCPKG_LINE_INFO); const auto& feature_list = plan.feature_list; Assert::AreEqual(plan.spec.triplet().to_string().c_str(), triplet.to_string().c_str()); Assert::AreEqual(pkg_name.c_str(), (*plan.any_paragraph.source_control_file.get())->core_paragraph->name.c_str()); Assert::AreEqual(size_t(vec.size()), feature_list.size()); for (auto&& feature_name : vec) { if (feature_name == "core" || feature_name == "") { Assert::IsTrue(Util::find(feature_list, "core") != feature_list.end() || Util::find(feature_list, "") != feature_list.end()); continue; } Assert::IsTrue(Util::find(feature_list, feature_name) != feature_list.end()); } } static void remove_plan_check(Dependencies::AnyAction* remove_action, std::string pkg_name, const Triplet& triplet = Triplet::X86_WINDOWS) { const auto& plan = remove_action->remove_plan.value_or_exit(VCPKG_LINE_INFO); Assert::AreEqual(plan.spec.triplet().to_string().c_str(), triplet.to_string().c_str()); Assert::AreEqual(pkg_name.c_str(), plan.spec.name().c_str()); } TEST_METHOD(basic_install_scheme) { std::vector<std::unique_ptr<StatusParagraph>> status_paragraphs; PackageSpecMap spec_map(Triplet::X86_WINDOWS); auto spec_a = spec_map.set_package_map("a", "1.2.8", "b"); auto spec_b = spec_map.set_package_map("b", "1.3", "c"); auto spec_c = spec_map.set_package_map("c", "2.5.3", ""); auto map_port = Dependencies::MapPortFile(spec_map.map); auto install_plan = Dependencies::create_install_plan(map_port, {spec_a}, StatusParagraphs(std::move(status_paragraphs))); Assert::AreEqual(size_t(3), install_plan.size()); Assert::AreEqual("c", install_plan[0].spec.name().c_str()); Assert::AreEqual("b", install_plan[1].spec.name().c_str()); Assert::AreEqual("a", install_plan[2].spec.name().c_str()); } TEST_METHOD(multiple_install_scheme) { std::vector<std::unique_ptr<StatusParagraph>> status_paragraphs; PackageSpecMap spec_map(Triplet::X86_WINDOWS); auto spec_a = spec_map.set_package_map("a", "1.2.8", "d"); auto spec_b = spec_map.set_package_map("b", "1.3", "d, e"); auto spec_c = spec_map.set_package_map("c", "2.5.3", "e, h"); auto spec_d = spec_map.set_package_map("d", "4.0", "f, g, h"); auto spec_e = spec_map.set_package_map("e", "1.0", "g"); auto spec_f = spec_map.set_package_map("f", "1.0", ""); auto spec_g = spec_map.set_package_map("g", "1.0", ""); auto spec_h = spec_map.set_package_map("h", "1.0", ""); auto map_port = Dependencies::MapPortFile(spec_map.map); auto install_plan = Dependencies::create_install_plan( map_port, {spec_a, spec_b, spec_c}, StatusParagraphs(std::move(status_paragraphs))); auto iterator_pos = [&](const PackageSpec& spec) -> int { auto it = std::find_if( install_plan.begin(), install_plan.end(), [&](auto& action) { return action.spec == spec; }); Assert::IsTrue(it != install_plan.end()); return (int)(it - install_plan.begin()); }; int a_pos = iterator_pos(spec_a), b_pos = iterator_pos(spec_b), c_pos = iterator_pos(spec_c), d_pos = iterator_pos(spec_d), e_pos = iterator_pos(spec_e), f_pos = iterator_pos(spec_f), g_pos = iterator_pos(spec_g), h_pos = iterator_pos(spec_h); Assert::IsTrue(a_pos > d_pos); Assert::IsTrue(b_pos > e_pos); Assert::IsTrue(b_pos > d_pos); Assert::IsTrue(c_pos > e_pos); Assert::IsTrue(c_pos > h_pos); Assert::IsTrue(d_pos > f_pos); Assert::IsTrue(d_pos > g_pos); Assert::IsTrue(d_pos > h_pos); Assert::IsTrue(e_pos > g_pos); } TEST_METHOD(long_install_scheme) { using Pgh = std::unordered_map<std::string, std::string>; std::vector<std::unique_ptr<StatusParagraph>> status_paragraphs; status_paragraphs.push_back(std::make_unique<StatusParagraph>(Pgh{{"Package", "j"}, {"Version", "1.2.8"}, {"Architecture", "x86-windows"}, {"Multi-Arch", "same"}, {"Depends", "k"}, {"Status", "install ok installed"}})); status_paragraphs.push_back(std::make_unique<StatusParagraph>(Pgh{{"Package", "k"}, {"Version", "1.2.8"}, {"Architecture", "x86-windows"}, {"Multi-Arch", "same"}, {"Depends", ""}, {"Status", "install ok installed"}})); PackageSpecMap spec_map(Triplet::X86_WINDOWS); auto spec_a = spec_map.set_package_map("a", "1.2.8", "b, c, d, e, f, g, h, j, k"); auto spec_b = spec_map.set_package_map("b", "1.2.8", "c, d, e, f, g, h, j, k"); auto spec_c = spec_map.set_package_map("c", "1.2.8", "d, e, f, g, h, j, k"); auto spec_d = spec_map.set_package_map("d", "1.2.8", "e, f, g, h, j, k"); auto spec_e = spec_map.set_package_map("e", "1.2.8", "f, g, h, j, k"); auto spec_f = spec_map.set_package_map("f", "1.2.8", "g, h, j, k"); auto spec_g = spec_map.set_package_map("g", "1.2.8", "h, j, k"); auto spec_h = spec_map.set_package_map("h", "1.2.8", "j, k"); auto spec_j = spec_map.set_package_map("j", "1.2.8", "k"); auto spec_k = spec_map.set_package_map("k", "1.2.8", ""); auto map_port = Dependencies::MapPortFile(spec_map.map); auto install_plan = Dependencies::create_install_plan(map_port, {spec_a}, StatusParagraphs(std::move(status_paragraphs))); Assert::AreEqual(size_t(8), install_plan.size()); Assert::AreEqual("h", install_plan[0].spec.name().c_str()); Assert::AreEqual("g", install_plan[1].spec.name().c_str()); Assert::AreEqual("f", install_plan[2].spec.name().c_str()); Assert::AreEqual("e", install_plan[3].spec.name().c_str()); Assert::AreEqual("d", install_plan[4].spec.name().c_str()); Assert::AreEqual("c", install_plan[5].spec.name().c_str()); Assert::AreEqual("b", install_plan[6].spec.name().c_str()); Assert::AreEqual("a", install_plan[7].spec.name().c_str()); } TEST_METHOD(basic_feature_test_1) { using Pgh = std::unordered_map<std::string, std::string>; std::vector<std::unique_ptr<StatusParagraph>> status_paragraphs; status_paragraphs.push_back(std::make_unique<StatusParagraph>(Pgh{{"Package", "a"}, {"Default-Features", ""}, {"Version", "1.3.8"}, {"Architecture", "x86-windows"}, {"Multi-Arch", "same"}, {"Depends", "b, b[beefeatureone]"}, {"Status", "install ok installed"}})); status_paragraphs.push_back(std::make_unique<StatusParagraph>(Pgh{{"Package", "b"}, {"Feature", "beefeatureone"}, {"Architecture", "x86-windows"}, {"Multi-Arch", "same"}, {"Depends", ""}, {"Status", "install ok installed"}})); status_paragraphs.push_back(std::make_unique<StatusParagraph>(Pgh{{"Package", "b"}, {"Default-Features", "beefeatureone"}, {"Version", "1.3"}, {"Architecture", "x86-windows"}, {"Multi-Arch", "same"}, {"Depends", ""}, {"Status", "install ok installed"}})); PackageSpecMap spec_map(Triplet::X86_WINDOWS); auto spec_a = FullPackageSpec{spec_map.get_package_spec({ {{"Source", "a"}, {"Version", "1.3.8"}, {"Build-Depends", "b, b[beefeatureone]"}}, {{"Feature", "featureone"}, {"Description", "the first feature for a"}, {"Build-Depends", "b[beefeaturetwo]"}}, }), {"featureone"}}; auto spec_b = FullPackageSpec{spec_map.get_package_spec({ {{"Source", "b"}, {"Version", "1.3"}, {"Build-Depends", ""}}, {{"Feature", "beefeatureone"}, {"Description", "the first feature for b"}, {"Build-Depends", ""}}, {{"Feature", "beefeaturetwo"}, {"Description", "the second feature for b"}, {"Build-Depends", ""}}, {{"Feature", "beefeaturethree"}, {"Description", "the third feature for b"}, {"Build-Depends", ""}}, })}; auto install_plan = Dependencies::create_feature_install_plan( spec_map.map, {spec_a}, StatusParagraphs(std::move(status_paragraphs))); Assert::AreEqual(size_t(4), install_plan.size()); remove_plan_check(&install_plan[0], "a"); remove_plan_check(&install_plan[1], "b"); features_check(&install_plan[2], "b", {"beefeatureone", "core", "beefeatureone"}); features_check(&install_plan[3], "a", {"featureone", "core"}); } TEST_METHOD(basic_feature_test_2) { using Pgh = std::unordered_map<std::string, std::string>; std::vector<std::unique_ptr<StatusParagraph>> status_paragraphs; PackageSpecMap spec_map(Triplet::X86_WINDOWS); auto spec_a = FullPackageSpec{spec_map.get_package_spec( {{{"Source", "a"}, {"Version", "1.3.8"}, {"Build-Depends", "b[beefeatureone]"}}, {{"Feature", "featureone"}, {"Description", "the first feature for a"}, {"Build-Depends", "b[beefeaturetwo]"}} }), {"featureone"}}; auto spec_b = FullPackageSpec{spec_map.get_package_spec({ {{"Source", "b"}, {"Version", "1.3"}, {"Build-Depends", ""}}, {{"Feature", "beefeatureone"}, {"Description", "the first feature for b"}, {"Build-Depends", ""}}, {{"Feature", "beefeaturetwo"}, {"Description", "the second feature for b"}, {"Build-Depends", ""}}, {{"Feature", "beefeaturethree"}, {"Description", "the third feature for b"}, {"Build-Depends", ""}}, })}; auto install_plan = Dependencies::create_feature_install_plan( spec_map.map, {spec_a}, StatusParagraphs(std::move(status_paragraphs))); Assert::AreEqual(size_t(2), install_plan.size()); features_check(&install_plan[0], "b", {"beefeatureone", "beefeaturetwo", "core"}); features_check(&install_plan[1], "a", {"featureone", "core"}); } TEST_METHOD(basic_feature_test_3) { using Pgh = std::unordered_map<std::string, std::string>; std::vector<std::unique_ptr<StatusParagraph>> status_paragraphs; status_paragraphs.push_back(std::make_unique<StatusParagraph>(Pgh{{"Package", "a"}, {"Default-Features", ""}, {"Version", "1.3"}, {"Architecture", "x86-windows"}, {"Multi-Arch", "same"}, {"Depends", ""}, {"Status", "install ok installed"}})); PackageSpecMap spec_map(Triplet::X86_WINDOWS); auto spec_a = FullPackageSpec{ spec_map.get_package_spec( {{{"Source", "a"}, {"Version", "1.3"}, {"Build-Depends", "b"}}, {{"Feature", "one"}, {"Description", "the first feature for a"}, {"Build-Depends", ""}}}), {"core"}}; auto spec_b = FullPackageSpec{spec_map.get_package_spec({ {{"Source", "b"}, {"Version", "1.3"}, {"Build-Depends", ""}}, })}; auto spec_c = FullPackageSpec{spec_map.get_package_spec({ {{"Source", "c"}, {"Version", "1.3"}, {"Build-Depends", "a[one]"}}, }), {"core"}}; auto install_plan = Dependencies::create_feature_install_plan( spec_map.map, {spec_c, spec_a}, StatusParagraphs(std::move(status_paragraphs))); Assert::AreEqual(size_t(4), install_plan.size()); remove_plan_check(&install_plan[0], "a"); features_check(&install_plan[1], "b", {"core"}); features_check(&install_plan[2], "a", {"one", "core"}); features_check(&install_plan[3], "c", {"core"}); } TEST_METHOD(basic_feature_test_4) { using Pgh = std::unordered_map<std::string, std::string>; std::vector<std::unique_ptr<StatusParagraph>> status_paragraphs; status_paragraphs.push_back(std::make_unique<StatusParagraph>(Pgh{{"Package", "a"}, {"Default-Features", ""}, {"Version", "1.3"}, {"Architecture", "x86-windows"}, {"Multi-Arch", "same"}, {"Depends", ""}, {"Status", "install ok installed"}})); status_paragraphs.push_back(std::make_unique<StatusParagraph>(Pgh{{"Package", "a"}, {"Feature", "one"}, {"Architecture", "x86-windows"}, {"Multi-Arch", "same"}, {"Depends", ""}, {"Status", "install ok installed"}})); PackageSpecMap spec_map(Triplet::X86_WINDOWS); auto spec_a = FullPackageSpec{ spec_map.get_package_spec( {{{"Source", "a"}, {"Version", "1.3"}, {"Build-Depends", "b"}}, {{"Feature", "one"}, {"Description", "the first feature for a"}, {"Build-Depends", ""}}}), }; auto spec_b = FullPackageSpec{spec_map.get_package_spec({ {{"Source", "b"}, {"Version", "1.3"}, {"Build-Depends", ""}}, })}; auto spec_c = FullPackageSpec{spec_map.get_package_spec({ {{"Source", "c"}, {"Version", "1.3"}, {"Build-Depends", "a[one]"}}, }), {"core"}}; auto install_plan = Dependencies::create_feature_install_plan( spec_map.map, {spec_c}, StatusParagraphs(std::move(status_paragraphs))); Assert::AreEqual(size_t(1), install_plan.size()); features_check(&install_plan[0], "c", {"core"}); } TEST_METHOD(basic_feature_test_5) { using Pgh = std::unordered_map<std::string, std::string>; std::vector<std::unique_ptr<StatusParagraph>> status_paragraphs; PackageSpecMap spec_map(Triplet::X86_WINDOWS); auto spec_a = FullPackageSpec{ spec_map.get_package_spec( {{{"Source", "a"}, {"Version", "1.3"}, {"Build-Depends", ""}}, {{"Feature", "1"}, {"Description", "the first feature for a"}, {"Build-Depends", "b[1]"}}, {{"Feature", "2"}, {"Description", "the first feature for a"}, {"Build-Depends", "b[2]"}}, {{"Feature", "3"}, {"Description", "the first feature for a"}, {"Build-Depends", "a[2]"}}}), {"3"}}; auto spec_b = FullPackageSpec{spec_map.get_package_spec({ {{"Source", "b"}, {"Version", "1.3"}, {"Build-Depends", ""}}, {{"Feature", "1"}, {"Description", "the first feature for a"}, {"Build-Depends", ""}}, {{"Feature", "2"}, {"Description", "the first feature for a"}, {"Build-Depends", ""}}, })}; auto install_plan = Dependencies::create_feature_install_plan( spec_map.map, {spec_a}, StatusParagraphs(std::move(status_paragraphs))); Assert::AreEqual(size_t(2), install_plan.size()); features_check(&install_plan[0], "b", {"core", "2"}); features_check(&install_plan[1], "a", {"core", "3", "2"}); } TEST_METHOD(basic_feature_test_6) { using Pgh = std::unordered_map<std::string, std::string>; std::vector<std::unique_ptr<StatusParagraph>> status_paragraphs; status_paragraphs.push_back(std::make_unique<StatusParagraph>(Pgh{{"Package", "b"}, {"Default-Features", ""}, {"Version", "1.3"}, {"Architecture", "x86-windows"}, {"Multi-Arch", "same"}, {"Depends", ""}, {"Status", "install ok installed"}})); PackageSpecMap spec_map(Triplet::X86_WINDOWS); auto spec_a = FullPackageSpec{spec_map.get_package_spec({ {{"Source", "a"}, {"Version", "1.3"}, {"Build-Depends", "b[core]"}}, }), {"core"}}; auto spec_b = FullPackageSpec{ spec_map.get_package_spec({ {{"Source", "b"}, {"Version", "1.3"}, {"Build-Depends", ""}}, {{"Feature", "1"}, {"Description", "the first feature for a"}, {"Build-Depends", ""}}, }), {"1"}}; auto install_plan = Dependencies::create_feature_install_plan( spec_map.map, {spec_a, spec_b}, StatusParagraphs(std::move(status_paragraphs))); Assert::AreEqual(size_t(3), install_plan.size()); remove_plan_check(&install_plan[0], "b"); features_check(&install_plan[1], "b", {"core", "1"}); features_check(&install_plan[2], "a", {"core"}); } TEST_METHOD(basic_feature_test_7) { using Pgh = std::unordered_map<std::string, std::string>; std::vector<std::unique_ptr<StatusParagraph>> status_paragraphs; status_paragraphs.push_back(std::make_unique<StatusParagraph>(Pgh{{"Package", "x"}, {"Default-Features", ""}, {"Version", "1.3"}, {"Architecture", "x86-windows"}, {"Multi-Arch", "same"}, {"Depends", "b"}, {"Status", "install ok installed"}})); status_paragraphs.push_back(std::make_unique<StatusParagraph>(Pgh{{"Package", "b"}, {"Default-Features", ""}, {"Version", "1.3"}, {"Architecture", "x86-windows"}, {"Multi-Arch", "same"}, {"Depends", ""}, {"Status", "install ok installed"}})); PackageSpecMap spec_map(Triplet::X86_WINDOWS); auto spec_a = FullPackageSpec{spec_map.get_package_spec({ {{"Source", "a"}, {"Version", "1.3"}, {"Build-Depends", ""}}, })}; auto spec_x = FullPackageSpec{spec_map.get_package_spec({ {{"Source", "x"}, {"Version", "1.3"}, {"Build-Depends", "a"}}, }), {"core"}}; auto spec_b = FullPackageSpec{ spec_map.get_package_spec({ {{"Source", "b"}, {"Version", "1.3"}, {"Build-Depends", ""}, {"Default-Features", ""}}, {{"Feature", "1"}, {"Description", "the first feature for a"}, {"Build-Depends", ""}}, }), {"1"}}; auto install_plan = Dependencies::create_feature_install_plan( spec_map.map, {spec_b, spec_x}, StatusParagraphs(std::move(status_paragraphs))); Assert::AreEqual(size_t(5), install_plan.size()); remove_plan_check(&install_plan[0], "x"); remove_plan_check(&install_plan[1], "b"); // TODO: order here may change but A < X, and B anywhere features_check(&install_plan[2], "a", {"core"}); features_check(&install_plan[3], "x", {"core"}); features_check(&install_plan[4], "b", {"core", "1"}); } TEST_METHOD(basic_feature_test_8) { using Pgh = std::unordered_map<std::string, std::string>; std::vector<std::unique_ptr<StatusParagraph>> status_paragraphs; status_paragraphs.push_back(std::make_unique<StatusParagraph>(Pgh{{"Package", "a"}, {"Default-Features", ""}, {"Version", "1.3"}, {"Architecture", "x64-windows"}, {"Multi-Arch", "same"}, {"Depends", ""}, {"Status", "install ok installed"}})); status_paragraphs.push_back(std::make_unique<StatusParagraph>(Pgh{{"Package", "a"}, {"Default-Features", ""}, {"Version", "1.3"}, {"Architecture", "x86-windows"}, {"Multi-Arch", "same"}, {"Depends", ""}, {"Status", "install ok installed"}})); PackageSpecMap spec_map(Triplet::X64_WINDOWS); auto spec_a_64 = FullPackageSpec{ spec_map.get_package_spec( {{{"Source", "a"}, {"Version", "1.3"}, {"Build-Depends", "b"}}, {{"Feature", "one"}, {"Description", "the first feature for a"}, {"Build-Depends", ""}}}), {"core"}}; auto spec_b_64 = FullPackageSpec{spec_map.get_package_spec({ {{"Source", "b"}, {"Version", "1.3"}, {"Build-Depends", ""}}, })}; auto spec_c_64 = FullPackageSpec{spec_map.get_package_spec({ {{"Source", "c"}, {"Version", "1.3"}, {"Build-Depends", "a[one]"}}, }), {"core"}}; spec_map.triplet = Triplet::X86_WINDOWS; auto spec_a_86 = FullPackageSpec{ spec_map.get_package_spec( {{{"Source", "a"}, {"Version", "1.3"}, {"Build-Depends", "b"}}, {{"Feature", "one"}, {"Description", "the first feature for a"}, {"Build-Depends", ""}}}), {"core"}}; auto spec_b_86 = FullPackageSpec{spec_map.get_package_spec({ {{"Source", "b"}, {"Version", "1.3"}, {"Build-Depends", ""}}, })}; auto spec_c_86 = FullPackageSpec{spec_map.get_package_spec({ {{"Source", "c"}, {"Version", "1.3"}, {"Build-Depends", "a[one]"}}, }), {"core"}}; auto install_plan = Dependencies::create_feature_install_plan(spec_map.map, {spec_c_64, spec_a_86, spec_a_64, spec_c_86}, StatusParagraphs(std::move(status_paragraphs))); /*Assert::AreEqual(size_t(8), install_plan.size()); auto iterator_pos = [&](const PackageSpec& spec, size_t start) -> int { auto it = std::find_if(install_plan.begin() + start, install_plan.end(), [&](auto& action) { return action.spec == spec; }); Assert::IsTrue(it != install_plan.end()); return (int)(it - install_plan.begin()); }; int a_64_1 = iterator_pos(spec_a_64.package_spec, 0), a_86_1 = iterator_pos(spec_a_86.package_spec, 0), b_64 = iterator_pos(spec_b_64.package_spec, 0), b_86 = iterator_pos(spec_b_86.package_spec, 0), c_64 = iterator_pos(spec_c_64.package_spec, 0), c_86 = iterator_pos(spec_c_86.package_spec, 0), a_64_2 = iterator_pos(spec_a_64.package_spec, a_64_1 + 1), a_86_2 = iterator_pos(spec_a_86.package_spec, a_86_1 + 1);*/ remove_plan_check(&install_plan[0], "a", Triplet::X64_WINDOWS); remove_plan_check(&install_plan[1], "a"); features_check(&install_plan[2], "b", {"core"}, Triplet::X64_WINDOWS); features_check(&install_plan[3], "a", {"one", "core"}, Triplet::X64_WINDOWS); features_check(&install_plan[4], "c", {"core"}, Triplet::X64_WINDOWS); features_check(&install_plan[5], "b", {"core"}); features_check(&install_plan[6], "a", {"one", "core"}); features_check(&install_plan[7], "c", {"core"}); } }; }
59.865275
120
0.436591
[ "vector" ]
d02c6264ba795f9fedf169035b00859bcaf35950
1,241
cpp
C++
DSA Crack Sheet/solutions/Left View of Binary Tree.cpp
Akshad7829/DataStructures-Algorithms
439822c6a374672d1734e2389d3fce581a35007d
[ "MIT" ]
5
2021-08-10T18:47:49.000Z
2021-08-21T15:42:58.000Z
DSA Crack Sheet/solutions/Left View of Binary Tree.cpp
Akshad7829/DataStructures-Algorithms
439822c6a374672d1734e2389d3fce581a35007d
[ "MIT" ]
2
2022-02-25T13:36:46.000Z
2022-02-25T14:06:44.000Z
DSA Crack Sheet/solutions/Left View of Binary Tree.cpp
Akshad7829/DataStructures-Algorithms
439822c6a374672d1734e2389d3fce581a35007d
[ "MIT" ]
1
2021-10-08T10:07:41.000Z
2021-10-08T10:07:41.000Z
/* Left View of Binary Tree ======================== Given a Binary Tree, print Left view of it. Left view of a Binary Tree is set of nodes visible when tree is visited from Left side. The task is to complete the function leftView(), which accepts root of the tree as argument. Left view of following tree is 1 2 4 8. 1 / \ 2 3 / \ / \ 4 5 6 7 \ 8 Example 1: Input: 1 / \ 3 2 Output: 1 3 Example 2: Input: Output: 10 20 40 Your Task: You just have to complete the function leftView() that prints the left view. The newline is automatically appended by the driver code. Expected Time Complexity: O(N). Expected Auxiliary Space: O(Height of the Tree). Constraints: 0 <= Number of nodes <= 100 1 <= Data of a node <= 1000 */ vector<int> leftView(Node *root) { if (!root) return {}; vector<int> ans; queue<Node *> q; q.push(root); while (q.size()) { int size = q.size(); for (int i = size; i > 0; --i) { auto curr = q.front(); q.pop(); if (i == size) ans.push_back(curr->data); if (curr->left) q.push(curr->left); if (curr->right) q.push(curr->right); } } return ans; }
19.698413
224
0.572119
[ "vector" ]
d02ee06530666936ed67d8a9b020a7d80581597e
4,745
cc
C++
crunchy/internal/keyset/hybrid_crypter_factory.cc
google/crunchy
9d241ffd619889ed9855e2cf41dc0c5485a7148c
[ "Apache-2.0" ]
125
2017-11-21T14:23:02.000Z
2021-06-15T10:13:54.000Z
crunchy/internal/keyset/hybrid_crypter_factory.cc
Jason-Cooke/crunchy
9d241ffd619889ed9855e2cf41dc0c5485a7148c
[ "Apache-2.0" ]
2
2018-01-11T14:07:18.000Z
2018-07-12T16:20:30.000Z
crunchy/internal/keyset/hybrid_crypter_factory.cc
google/crunchy
9d241ffd619889ed9855e2cf41dc0c5485a7148c
[ "Apache-2.0" ]
19
2017-12-08T16:49:06.000Z
2022-01-22T12:34:19.000Z
// Copyright 2017 The CrunchyCrypt 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 "crunchy/internal/keyset/hybrid_crypter_factory.h" #include <stddef.h> #include <string> #include <utility> #include <vector> #include "absl/memory/memory.h" #include "absl/strings/str_cat.h" #include "absl/strings/strip.h" #include "crunchy/internal/keys/hybrid_crypting_key.h" #include "crunchy/internal/keyset/keyset_util.h" #include "crunchy/internal/port/port.h" #include "crunchy/key_management/keyset_handle.h" namespace crunchy { namespace { class HybridEncrypterImpl : public CrunchyHybridEncrypter { public: HybridEncrypterImpl(std::unique_ptr<HybridEncryptingKey> key, absl::string_view prefix) : key_(std::move(key)), prefix_(prefix) {} StatusOr<std::string> Encrypt(absl::string_view plaintext) const override { auto status_or_ciphertext = key_->Encrypt(plaintext); if (!status_or_ciphertext.ok()) { return status_or_ciphertext.status(); } return absl::StrCat(prefix_, status_or_ciphertext.ValueOrDie()); } private: const std::unique_ptr<HybridEncryptingKey> key_; const std::string prefix_; }; class HybridDecrypterImpl : public CrunchyHybridDecrypter { public: HybridDecrypterImpl(std::vector<std::unique_ptr<HybridDecryptingKey>> keys, std::vector<std::string> prefices) : keys_(std::move(keys)), prefices_(std::move(prefices)) { CRUNCHY_CHECK_EQ(keys_.size(), prefices_.size()); } StatusOr<std::string> Decrypt(absl::string_view ciphertext) const override { bool key_found = false; Status error_status; for (size_t i = 0; i < keys_.size(); i++) { absl::string_view crypto_ciphertext = ciphertext; if (!absl::ConsumePrefix(&crypto_ciphertext, prefices_[i])) { continue; } key_found = true; auto status_or_plaintext = keys_[i]->Decrypt(crypto_ciphertext); if (status_or_plaintext.ok()) { return std::move(status_or_plaintext.ValueOrDie()); } error_status = status_or_plaintext.status(); } if (key_found) { return error_status; } return FailedPreconditionErrorBuilder(CRUNCHY_LOC).LogInfo() << "Key not found"; } private: const std::vector<std::unique_ptr<HybridDecryptingKey>> keys_; const std::vector<std::string> prefices_; }; } // namespace StatusOr<std::unique_ptr<CrunchyHybridEncrypter>> MakeCrunchyHybridEncrypter( const HybridCryptingKeyRegistry& registry, const Keyset& keyset) { if (keyset.primary_key_id() < 0) { return InvalidArgumentErrorBuilder(CRUNCHY_LOC).LogInfo() << "Invalid primary key id: " << keyset.primary_key_id(); } if (keyset.key_size() <= keyset.primary_key_id()) { return InvalidArgumentErrorBuilder(CRUNCHY_LOC).LogInfo() << "primary_key_id is " << keyset.primary_key_id() << " but there are only " << keyset.key_size() << " keys"; } const Key& key = keyset.key(keyset.primary_key_id()); auto status_or_key = registry.MakeHybridEncryptingKey( key.metadata().type().crunchy_label(), key.data()); if (!status_or_key.ok()) { return status_or_key.status(); } return {absl::make_unique<HybridEncrypterImpl>( std::move(status_or_key.ValueOrDie()), key.metadata().prefix())}; } StatusOr<std::unique_ptr<CrunchyHybridDecrypter>> MakeCrunchyHybridDecrypter( const HybridCryptingKeyRegistry& registry, const Keyset& keyset) { if (keyset.key_size() == 0) { return InvalidArgumentErrorBuilder(CRUNCHY_LOC).LogInfo() << "keyset must contain at least one key"; } std::vector<std::unique_ptr<HybridDecryptingKey>> keys; std::vector<std::string> prefices; for (const Key& key : keyset.key()) { auto status_or_key = registry.MakeHybridDecryptingKey( key.metadata().type().crunchy_label(), key.data()); if (!status_or_key.ok()) { return status_or_key.status(); } keys.push_back(std::move(status_or_key.ValueOrDie())); prefices.push_back(key.metadata().prefix()); } return {absl::make_unique<HybridDecrypterImpl>(std::move(keys), std::move(prefices))}; } } // namespace crunchy
35.676692
78
0.696523
[ "vector" ]
d03d9b9307fee6da46f613f97fdde9e7b82691b1
6,878
hpp
C++
include/GTGE/DefaultSceneRenderer/DefaultSceneRenderer_MultiPassPipeline.hpp
mackron/GTGameEngine
380d1e01774fe6bc2940979e4e5983deef0bf082
[ "BSD-3-Clause" ]
31
2015-03-19T08:44:48.000Z
2021-12-15T20:52:31.000Z
include/GTGE/DefaultSceneRenderer/DefaultSceneRenderer_MultiPassPipeline.hpp
mackron/GTGameEngine
380d1e01774fe6bc2940979e4e5983deef0bf082
[ "BSD-3-Clause" ]
19
2015-07-09T09:02:44.000Z
2016-06-09T03:51:03.000Z
include/GTGE/DefaultSceneRenderer/DefaultSceneRenderer_MultiPassPipeline.hpp
mackron/GTGameEngine
380d1e01774fe6bc2940979e4e5983deef0bf082
[ "BSD-3-Clause" ]
3
2017-10-04T23:38:18.000Z
2022-03-07T08:27:13.000Z
// Copyright (C) 2011 - 2014 David Reid. See included LICENCE. #ifndef GT_DefaultSceneRenderer_MultiPassPipeline #define GT_DefaultSceneRenderer_MultiPassPipeline #include <GTGE/Core/Map.hpp> #include <GTGE/Core/Vector.hpp> #include <GTGE/Material.hpp> namespace GT { class DefaultSceneRenderer; class DefaultSceneRenderer_VisibilityProcessor; struct DefaultSceneRendererFramebuffer; struct DefaultSceneRendererMesh; class DefaultSceneRenderer_MultiPassPipeline { public: /// Constructor. DefaultSceneRenderer_MultiPassPipeline(DefaultSceneRenderer &renderer, DefaultSceneRendererFramebuffer &viewportFramebuffer, const DefaultSceneRenderer_VisibilityProcessor &visibleObjects, bool splitShadowLights); /// Destructor. ~DefaultSceneRenderer_MultiPassPipeline(); /// Executes the pipeline. void Execute(); private: /// Binds the objects that should be rendered during the next rendering operations. /// /// @param opaqueObjects [in] A pointer to the list of opaque objects. /// @param transparentObjects [in] A pointer to the list of blended transparent objects. void BindObjects(const Map<const MaterialDefinition*, Vector<DefaultSceneRendererMesh>*>* opaqueObjects, const Vector<DefaultSceneRendererMesh>* transparentObjects); /// Performs the opaque pass on the currently bound objects. void OpaquePass(); /// Performs the transparent pass on the currently bound objects. void TransparentPass(); /// Performs a depth-only pass. void DepthPass(); /// Performs the lighting pass. void OpaqueLightingPass(); /// Performs the material pass. void OpaqueMaterialPass(); /// Subdivides the given light group into smaller groups for rendering. /// /// @param sourceLightGroup [in ] A reference to the light group to subdivide. /// @param lightGroupsOut [out] A reference to the container that will receive the subdivided groups. /// @param options [in ] A bitfield containing options to control how the lights are subdivided. /// /// @remarks /// This will always return at least 1 light group. If there are no lights, it will just be an empty group. void SubdivideLightGroup(const DefaultSceneRenderer_LightGroup* sourceLightGroup, Vector<DefaultSceneRenderer_LightGroup> &lightGroupsOut, uint32_t options); /////////////////////////////////////////// // Rendering Helpers. /// Changes the framebuffer state to that needed for lighting. void SwitchToLightingFramebuffer(); /// Enables lighting blending. void EnableLightingBlending(); /// Enables lighting depth testing. void EnableLightingDepthTesting(); /// Changes the state of the renderer in order to render lighting. /// /// @remarks /// This will include a framebuffer switch, so only use this where convenient. void EnableLightingState(); /// Helper for rendering the given mesh using the given light group. /// /// @param mesh [in] A reference to the mesh to draw. /// @param lightGroup [in] A reference to the light group. /// @param shaderFlags [in] The shader flags. void RenderMesh(const DefaultSceneRendererMesh &mesh, const DefaultSceneRenderer_LightGroup &lightGroup, uint32_t shaderFlags); /// Helper for rendering the lighting information of a mesh. /// /// @param mesh [in] A reference to the mesh whose lighting is being drawn. /// @param lightGroups [in] A reference to the list of light groups. void RenderMeshLighting(const DefaultSceneRendererMesh &mesh, const Vector<DefaultSceneRenderer_LightGroup> &lightGroups); /// Helper for rendering the highlight effect of the given mesh. /// /// @remarks /// This requires that blending be enabled explicitly before calling this. void RenderMeshHighlight(const DefaultSceneRendererMesh &mesh); /// Helper for drawing the background texture for refraction. void RenderRefractionBackgroundTexture(); /// Performs a background clear of the main colour buffer if it hasn't already been cleared. void TryClearBackground(); /// Retrieves a reference to the main light group which will contain every light. const DefaultSceneRenderer_LightGroup & GetMainLightGroup() const; private: /// A reference to the owner renderer. DefaultSceneRenderer &renderer; /// A reference to the viewport framebuffer. DefaultSceneRendererFramebuffer &viewportFramebuffer; /// A reference to the visibility processor containing the visible objects. const DefaultSceneRenderer_VisibilityProcessor &visibleObjects; /// Whether or not the shadow-casting lights need to be split when rendering (not grouped). bool splitShadowLights; /// A pointer to the currently bound opaque objects. const Map<const MaterialDefinition*, Vector<DefaultSceneRendererMesh>*>* opaqueObjects; /// A pointer to the currently bound blended transparent objects. const Vector<DefaultSceneRendererMesh>* transparentObjects; /// Keeps track of whether or not the background has been cleared. bool hasBackgroundBeenCleared; /// Keeps track of whether or not the main light group has been generated. mutable bool hasGeneratedMainLightGroup; /// The main light group containing every visible light. This will be empty by default until GetMainLightGroup() /// is called. mutable DefaultSceneRenderer_LightGroup mainLightGroup; /// A list of opaque meshes that are not having their depth written. This will be cleared when new objects are /// bound with BindObjects(). We need to keep track of these because they are rendered differently. Vector<DefaultSceneRendererMesh*> opaqueMeshesWithNoDepthWrites; /// Enumerator containing flags for light group subdivision options. enum LightSubdivionFlags { NoAmbientLights = (1 << 1), // <-- Exclude ambient lights. NoShadowLights = (1 << 2), // <-- Exclude shadow-casting lights. ConvertShadowLights = (1 << 3) // <-- Convert shadow-casting lights to non-shadow-casting lights. }; private: // No copying. DefaultSceneRenderer_MultiPassPipeline(const DefaultSceneRenderer_MultiPassPipeline &); DefaultSceneRenderer_MultiPassPipeline & operator=(const DefaultSceneRenderer_MultiPassPipeline &); }; } #endif
38.858757
221
0.679849
[ "mesh", "render", "vector" ]
d03da14daa56c2edc6a3b170d07c64c0a0059136
1,135
cpp
C++
src/MyBloom.cpp
gaurav16gupta/RAMBO_MSMT
4f14fc1f86f884c2d5bb3a8dcfd780cff7582d5a
[ "MIT" ]
5
2021-06-30T06:48:42.000Z
2022-01-15T21:17:33.000Z
src/MyBloom.cpp
gaurav16gupta/RAMBO_MSMT
4f14fc1f86f884c2d5bb3a8dcfd780cff7582d5a
[ "MIT" ]
null
null
null
src/MyBloom.cpp
gaurav16gupta/RAMBO_MSMT
4f14fc1f86f884c2d5bb3a8dcfd780cff7582d5a
[ "MIT" ]
4
2020-07-21T01:33:44.000Z
2021-07-18T20:28:38.000Z
#include "MurmurHash3.h" #include <iostream> #include <cstring> #include <chrono> #include <vector> #include "MyBloom.h" #include <math.h> #include "constants.h" #include <bitset> #include "bitArray.h" using namespace std; vector<uint> myhash( std::string key, int len, int k, int r, int range){ // int hashvals[k]; vector <uint> hashvals; uint op; // takes 4 byte for (int i=0+ k*r; i<k+ k*r; i++){ MurmurHash3_x86_32(key.c_str(), len, i, &op); hashvals.push_back(op%range); } return hashvals; } BloomFiler::BloomFiler(int sz, float FPR, int k){ p = FPR; k = k; //number of hash m_bits = new bitArray(sz); } void BloomFiler::insert(vector<uint> a){ int N = a.size(); for (int n =0 ; n<N; n++){ m_bits->SetBit(a[n]); } } bool BloomFiler::test(vector<uint> a){ int N = a.size(); for (int n =0 ; n<N; n++){ if (!m_bits->TestBit(a[n])){ return false; } } return true; } void BloomFiler::serializeBF(string BF_file){ m_bits->serializeBitAr(BF_file); } void BloomFiler::deserializeBF(vector<string> BF_file){ m_bits->deserializeBitAr(BF_file); }
20.267857
72
0.626432
[ "vector" ]
d04139e0fd95ff7713868f3178f0ff34b692a553
5,521
cpp
C++
src/Platform/Graphics/Vulkan/DescriptorPool.cpp
MisterVento3/SteelEngine
403511b53b6575eb869b4ccfbda18514f0838e8d
[ "MIT" ]
3
2017-05-10T10:58:17.000Z
2018-10-30T09:50:26.000Z
src/Platform/Graphics/Vulkan/DescriptorPool.cpp
mVento3/SteelEngine
403511b53b6575eb869b4ccfbda18514f0838e8d
[ "MIT" ]
3
2017-05-09T21:17:09.000Z
2020-02-24T14:46:22.000Z
src/Platform/Graphics/Vulkan/DescriptorPool.cpp
mVento3/SteelEngine
403511b53b6575eb869b4ccfbda18514f0838e8d
[ "MIT" ]
null
null
null
#include "Platform/Graphics/Vulkan/DescriptorPool.h" #include "Platform/Graphics/Vulkan/Pipeline.h" namespace SteelEngine { namespace Platform { namespace Vulkan { DescriptorPool::DescriptorPool() { } DescriptorPool::~DescriptorPool() { } bool DescriptorPool::SetupDescriptorPool(LogicalDevice* lDevice, const Pipeline* pipeline, uint32_t poolSize, uint32_t maxSets) { std::vector<VkDescriptorPoolSize> poolSizes; for(uint32_t i = 0; i < pipeline->m_CreateInfo.m_DescriptorSetLayoutBindings.size(); i++) { VkDescriptorPoolSize poolSize_ = {}; poolSize_.type = pipeline->m_CreateInfo.m_DescriptorSetLayoutBindings[i].descriptorType; poolSize_.descriptorCount = poolSize; poolSizes.push_back(poolSize_); } VkDescriptorPoolCreateInfo poolInfo = {}; poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; poolInfo.poolSizeCount = static_cast<uint32_t>(poolSizes.size()); poolInfo.pPoolSizes = poolSizes.data(); poolInfo.maxSets = maxSets; if(!lDevice->CreateDescriptorPool(poolInfo, &m_DescriptorPool)) { printf("Failed to create descriptor pool!\n"); return false; } // std::vector<VkDescriptorSetLayout> layouts(createInfo.m_PoolSize, createInfo.m_Pipeline->m_DescriptorSetLayout); // VkDescriptorSetAllocateInfo allocInfo = {}; // allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; // allocInfo.descriptorPool = m_DescriptorPool; // allocInfo.descriptorSetCount = static_cast<uint32_t>(createInfo.m_PoolSize); // allocInfo.pSetLayouts = layouts.data(); // m_DescriptorSets.resize(createInfo.m_PoolSize); // if(!lDevice->AllocateDescriptorSets(allocInfo, m_DescriptorSets.data())) // { // printf("Failed to allocate descriptor sets!\n"); // return false; // } // for(size_t i = 0; i < createInfo.m_PoolSize; i++) // { // VkDescriptorImageInfo imageInfo = createInfo.m_Texture->GetDescriptorImageInfo(); // VkWriteDescriptorSet descriptorWrite = {}; // descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; // descriptorWrite.dstSet = m_DescriptorSets[i]; // descriptorWrite.dstBinding = 0; // TODO: remeber about that!!!!!!! // descriptorWrite.dstArrayElement = 0; // descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; // descriptorWrite.descriptorCount = 1; // descriptorWrite.pImageInfo = &imageInfo; // lDevice->UpdateDescriptorSet(descriptorWrite); // } return true; } bool DescriptorPool::SetupDescriptorSets(LogicalDevice* lDevice, const Pipeline* pipeline, uint32_t poolSize, Texture* texture) { std::vector<VkDescriptorSetLayout> layouts(poolSize, pipeline->m_DescriptorSetLayout); VkDescriptorSetAllocateInfo allocInfo = {}; allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; allocInfo.descriptorPool = m_DescriptorPool; allocInfo.descriptorSetCount = static_cast<uint32_t>(poolSize); allocInfo.pSetLayouts = layouts.data(); m_DescriptorSets.resize(poolSize); if(!lDevice->AllocateDescriptorSets(allocInfo, m_DescriptorSets.data())) { printf("Failed to allocate descriptor sets!\n"); return false; } for(size_t i = 0; i < poolSize; i++) { VkDescriptorImageInfo imageInfo = texture->GetDescriptorImageInfo(); VkWriteDescriptorSet descriptorWrite = {}; descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; descriptorWrite.dstSet = m_DescriptorSets[i]; descriptorWrite.dstBinding = 0; // TODO: remeber about that!!!!!!! descriptorWrite.dstArrayElement = 0; descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; descriptorWrite.descriptorCount = 1; descriptorWrite.pImageInfo = &imageInfo; lDevice->UpdateDescriptorSet(descriptorWrite); } return true; } bool DescriptorPool::SetupDescriptorSet(LogicalDevice* lDevice, const Pipeline* pipeline, const VkDescriptorImageInfo& info, VkDescriptorSet& descriptorSet) { VkDescriptorSetAllocateInfo allocInfo = {}; allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; allocInfo.descriptorPool = m_DescriptorPool; allocInfo.descriptorSetCount = 1; allocInfo.pSetLayouts = &pipeline->m_DescriptorSetLayout; if(!lDevice->AllocateDescriptorSets(allocInfo, &descriptorSet)) { printf("Failed to allocate descriptor sets!\n"); return false; } VkWriteDescriptorSet writeDescriptorSet = {}; writeDescriptorSet.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; writeDescriptorSet.dstSet = descriptorSet; writeDescriptorSet.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; writeDescriptorSet.dstBinding = 0; writeDescriptorSet.pImageInfo = &info; writeDescriptorSet.descriptorCount = 1; lDevice->UpdateDescriptorSet(writeDescriptorSet); return true; } }}}
38.340278
160
0.663829
[ "vector" ]
d04294d14fbd4c3b792d053a222bd3c2b4f2ab3a
725
cpp
C++
voidproc-siv3d-examples-src/intersect.cpp
voidproc/voidproc-siv3d-examples-src
4c66b26aca6864d6654e2d081d8b248bffb8c072
[ "MIT" ]
1
2021-09-19T12:30:54.000Z
2021-09-19T12:30:54.000Z
voidproc-siv3d-examples-src/intersect.cpp
voidproc/voidproc-siv3d-examples-src
4c66b26aca6864d6654e2d081d8b248bffb8c072
[ "MIT" ]
null
null
null
voidproc-siv3d-examples-src/intersect.cpp
voidproc/voidproc-siv3d-examples-src
4c66b26aca6864d6654e2d081d8b248bffb8c072
[ "MIT" ]
null
null
null
#include <Siv3D.hpp> // OpenSiv3D v0.6.0 #include <variant> void Main() { Scene::SetBackground(Palette::Slategray); const Vec2 pos{ 800 / 2, 600 / 2 }; Array<std::variant<Circle, RectF, Quad, Triangle>> shapes; shapes.push_back(Circle(pos, 50)); //Circle shapes.push_back(RectF(pos.movedBy(-130, -130), 100, 200)); //RectF shapes.push_back(RectF(pos.movedBy(0, -100), 120, 100).rotated(45_deg)); //Quad shapes.push_back(Triangle(pos, pos.movedBy(140, 0), pos.movedBy(0, 120))); //Triangle while (System::Update()) { for (auto& shape : shapes) { std::visit([](auto s) { if (Geometry2D::Intersect(Cursor::PosF(), s)) { s.draw(Palette::Orange); } s.drawFrame(3); }, shape); } } }
25
87
0.634483
[ "shape" ]
d04813c35b308d0a85312ea824df1fa4bceed09c
2,047
cpp
C++
ext/pronto-v1.1/src/cpu_info.cpp
rvs314/Montage
d4c49e66addefe947c03ff2bd0c463ebd2c34436
[ "MIT" ]
9
2020-10-04T22:03:31.000Z
2021-10-08T01:52:57.000Z
ext/pronto-v1.1/src/cpu_info.cpp
rvs314/Montage
d4c49e66addefe947c03ff2bd0c463ebd2c34436
[ "MIT" ]
18
2020-10-20T02:39:12.000Z
2021-08-30T00:23:32.000Z
ext/pronto-v1.1/src/cpu_info.cpp
rvs314/Montage
d4c49e66addefe947c03ff2bd0c463ebd2c34436
[ "MIT" ]
9
2020-10-04T22:06:11.000Z
2021-02-19T17:23:17.000Z
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <assert.h> #include <vector> #include <algorithm> #include <fstream> #include <iostream> #define MAX_SOCKETS 2 bool core_info_compare(std::pair<long,long> a, std::pair<long,long> b) { if (a.first != b.first) return a.first < b.first; return a.second < b.second; } void get_cpu_info(uint8_t *core_map, int *map_size) { FILE *f = fopen("/proc/cpuinfo", "r"); char line[1024]; char tag[128]; char value[1024]; long processor; // core id (with HT) long core_id; // physical core id (no HT) long physical_id; // socket id long cpu_cores; // physical cores per socket *map_size = 0; std::vector<std::pair<long,long>> sockets[MAX_SOCKETS]; while (fgets(line, sizeof(line), f) != NULL) { if (strlen(line) == 1) continue; sscanf(line, "%[^\t:] : %[^\t\n]", tag, value); if (strcmp(tag, "core id") == 0) { core_id = strtol(value, NULL, 10); } else if (strcmp(tag, "physical id") == 0) { physical_id = strtol(value, NULL, 10); } else if (strcmp(tag, "processor") == 0) { processor = strtol(value, NULL, 10); } else if (strcmp(tag, "cpu cores") == 0) { cpu_cores = strtol(value, NULL, 10); } else if (strcmp(tag, "flags") == 0) { assert(physical_id < MAX_SOCKETS); sockets[physical_id].push_back(std::pair<long,long>(core_id, processor)); *map_size = *map_size + 1; } } fclose(f); for (int i = 0; i < MAX_SOCKETS; i++) { assert(i < 7); // 3 bits std::sort(sockets[i].begin(), sockets[i].end(), core_info_compare); // <first, second> = <core_id, processor> for (auto core = sockets[i].begin(); core != sockets[i].end(); core++) { assert(core->first < 32); // 5 bits core_map[core->second] = core->first | (i << 5); } sockets[i].clear(); } }
29.242857
85
0.550562
[ "vector" ]
d04a332d908baf17868f3c3bd7320c96d15926bd
3,779
cpp
C++
Data/testsuite/src/SessionImpl.cpp
flachesis/poco
5b911e4191f6f5a5cf18c1d2af3d51b0b678b219
[ "BSL-1.0" ]
null
null
null
Data/testsuite/src/SessionImpl.cpp
flachesis/poco
5b911e4191f6f5a5cf18c1d2af3d51b0b678b219
[ "BSL-1.0" ]
null
null
null
Data/testsuite/src/SessionImpl.cpp
flachesis/poco
5b911e4191f6f5a5cf18c1d2af3d51b0b678b219
[ "BSL-1.0" ]
null
null
null
// // SessionImpl.cpp // // $Id: //poco/Main/Data/testsuite/src/SessionImpl.cpp#4 $ // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "SessionImpl.h" #include "TestStatementImpl.h" #include "Connector.h" namespace Poco { namespace Data { namespace Test { SessionImpl::SessionImpl(const std::string& init, std::size_t timeout): Poco::Data::AbstractSessionImpl<SessionImpl>(init, timeout), _f(false), _connected(true) { addFeature("f1", &SessionImpl::setF, &SessionImpl::getF); addFeature("f2", 0, &SessionImpl::getF); addFeature("f3", &SessionImpl::setF, 0); addFeature("connected", &SessionImpl::setConnected, &SessionImpl::getConnected); addProperty("p1", &SessionImpl::setP, &SessionImpl::getP); addProperty("p2", 0, &SessionImpl::getP); addProperty("p3", &SessionImpl::setP, &SessionImpl::getP); } SessionImpl::~SessionImpl() { } void SessionImpl::open(const std::string& connectionString) { _connected = true; } void SessionImpl::close() { _connected = false; } bool SessionImpl::isConnected() { return _connected; } void SessionImpl::setConnectionTimeout(std::size_t timeout) { } std::size_t SessionImpl::getConnectionTimeout() { return 0; } Poco::Data::StatementImpl* SessionImpl::createStatementImpl() { return new TestStatementImpl(*this); } void SessionImpl::begin() { } void SessionImpl::commit() { } void SessionImpl::rollback() { } bool SessionImpl::canTransact() { return false; } bool SessionImpl::isTransaction() { return false; } void SessionImpl::setTransactionIsolation(Poco::UInt32) { } Poco::UInt32 SessionImpl::getTransactionIsolation() { return 0; } bool SessionImpl::hasTransactionIsolation(Poco::UInt32) { return false; } bool SessionImpl::isTransactionIsolation(Poco::UInt32) { return false; } const std::string& SessionImpl::connectorName() { return Connector::KEY; } bool SessionImpl::getConnected(const std::string& name) { return _connected; } void SessionImpl::setConnected(const std::string& name, bool value) { _connected = value; } void SessionImpl::setF(const std::string& name, bool value) { _f = value; } bool SessionImpl::getF(const std::string& name) { return _f; } void SessionImpl::setP(const std::string& name, const Poco::Any& value) { _p = value; } Poco::Any SessionImpl::getP(const std::string& name) { return _p; } } } } // namespace Poco::Data::Test
19.78534
81
0.735115
[ "object" ]
d04c1eefeb3abd51b2a65c6b010d739ae8073c59
3,331
hxx
C++
external/hunspell-1.6.2/src/hunspell2/hunspell.hxx
binhetech/CyHunspell
03d6ed3596711e1fbda29e08020889a71ff04b6b
[ "MIT" ]
null
null
null
external/hunspell-1.6.2/src/hunspell2/hunspell.hxx
binhetech/CyHunspell
03d6ed3596711e1fbda29e08020889a71ff04b6b
[ "MIT" ]
1
2022-01-26T09:30:21.000Z
2022-01-26T09:34:04.000Z
external/hunspell-1.6.2/src/hunspell2/hunspell.hxx
binhetech/CyHunspell
03d6ed3596711e1fbda29e08020889a71ff04b6b
[ "MIT" ]
null
null
null
#include <string> namespace hunspell { enum spell_result { bad_word, good_word, affixed_good_word, compound_good_word }; class hunspell { public: using string = std::string; using u16string = std::u16string; private: /* (0) All the major work is done here. (1) and (2) are the lowest level specializations. The rest just do some conversions and delegate to them. (1) will simply call this with ConversionIterator set to string::iterator (2) will call this with u8_u32 on the fly conversion iterator. */ template <class ConvIter> auto spell(ConvIter start, ConvIter end, const string& s) -> spell_result; /** (1) This should be called when the input and the dictionary are in the same encoding and that encoding is single byte encoding. */ auto spell_singlechar_input_singlechar_dict(const string& word) -> spell_result; /** (2) This should be called when the input and the dictionary are in the same encoding and that encoding UTF-8. */ auto spell_u8_input_u8_dict(const string& word) -> spell_result; /* (3) This should be called when the input is UTF-8 string and the dictionary is byte encoding. Lossy conversion should happend UTF-8 to single byte, and then (1) should be called. */ auto spell_u8_input_singlechar_dict(const string& word) -> spell_result; /* (4) This should be called when the input is single-byte narow OR multi-byte narrow string. and the dictionary is UTF-8 The input can be anything so we must use some info about the input encoding, a C locale od C++ locale object. One can do narrow -> u16 -> u8 like this: get old C locale, set C locale to loc, call mbrtoc16, revert old C locale, then codecvt<char16_t, char, mbstate_t> There is no C++ way to go mbr to u16, we're limited to mbrtoc16. For that reason we will do similar conversion, but in a more high level public funcrion. Tis function should be UNUSED. */ // spell_result spell_narrow_input_u8_dict(const string& word); public: /** (5) This should be called when the input and the dictionary are in the same encoding which can be single byte or UTF-8. Simply calls (1) or (2). This is the same as spell() in v1. */ auto spell(const string& word) -> spell_result; /** (6) Unknown narrow input (single byte or multi byte). Use current C locale and mbrtoc16 to convert it to known. Do a conversion mbr -> u16 -> u8. Use mbrtoc16, codecvt<char16_t, char, mbstate_t> We can check if the the current locale is already utf-8 to skip this. Once we know we have a u8 string, just call (7). This should be the recomended way to interface with the command line utility. Before calling this function, one should call setlocale(LC_ALL, "") or locale::global(locale("")). If we use std::cin, we should imbue it with cin.imbue(locale()) */ auto spell_narrow_input(const string& word) -> spell_result; /** (7) UTF-8 input. Will delegate either to (2) or (3). */ auto spell_u8_input(const string& word) -> spell_result; private: /** (8) */ auto spell_u16_input_singlechar_dict(const u16string& word) -> spell_result; /** (9) */ auto spell_u16_input_u8_dict(const u16string& word) -> spell_result; public: /** (10) */ auto spell_u16_input(const u16string& word) -> spell_result; }; }
28.228814
73
0.711198
[ "object" ]
d04cf5b96b8fb598d22c1018eca517c2c90991cf
4,640
cpp
C++
plugin/gui/custom_tooltip.cpp
cristivlas/zerobugs
5f080c8645b123d7887fd8a64f60e8d226e3b1d5
[ "BSL-1.0" ]
2
2018-03-19T23:27:47.000Z
2018-06-24T16:15:19.000Z
plugin/gui/custom_tooltip.cpp
cristivlas/zerobugs
5f080c8645b123d7887fd8a64f60e8d226e3b1d5
[ "BSL-1.0" ]
null
null
null
plugin/gui/custom_tooltip.cpp
cristivlas/zerobugs
5f080c8645b123d7887fd8a64f60e8d226e3b1d5
[ "BSL-1.0" ]
1
2021-11-28T05:39:05.000Z
2021-11-28T05:39:05.000Z
// // $Id$ // // ------------------------------------------------------------------------- // This file is part of ZeroBugs, Copyright (c) 2010 Cristian L. Vlasceanu // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // ------------------------------------------------------------------------- // #include <assert.h> #include <iostream> #include <vector> #include "generic/temporary.h" #include "gtkmm/clist.h" #include "gtkmm/connect.h" #include "gtkmm/ctree.h" #include "gtkmm/flags.h" #include "gtkmm/label.h" #include "gtkmm/resize.h" #include "gtkmm/style.h" #include "gtkmm/widget.h" #include "gtkmm/window.h" #include "custom_tooltip.h" CustomToolTip::CustomToolTip(Gtk::Widget* w, GetTextAtPointer fn) : widget_(w) , getTextAtPointer_(fn) , hrow_(INIT_ROW_HANDLE) , hcol_(-1) , drawing_(false) { assert(w); assert(fn); w->add_events(Gdk_FLAG(POINTER_MOTION_MASK) | Gdk_FLAG(ENTER_NOTIFY_MASK) | Gdk_FLAG(LEAVE_NOTIFY_MASK) /* | Gdk_FLAG(BUTTON_PRESS_MASK) */); } CustomToolTip::~CustomToolTip() { } void CustomToolTip::reset_tooltip() { tooltip_.reset(); } #if !GTKMM_2 void CustomToolTip::position_tooltip(int x, int y) { assert(tooltip_.get()); // show the tooltip slightly off from the mouse x += 10; y += 10; // make sure that the tooltip is fully visible, // by forcing its coordinates inside the screen Gtk_adjust_coords_for_visibility(tooltip_, x, y); Gtk_move(tooltip_.get(), x, y); } #endif int CustomToolTip::on_pointer_motion(GdkEventMotion* event) { #if !GTKMM_2 // silence off compiler warnings about converting doubles to ints const int x_root = static_cast<int>(event->x_root); const int y_root = static_cast<int>(event->y_root); if (tooltip_.get()) { position_tooltip(x_root, y_root); } #endif assert(widget_); std::string text; if (!(*getTextAtPointer_)(*widget_, event->x, event->y, hrow_, hcol_, text)) { return 0; } #if (GTKMM_2) widget_->set_tooltip_text(text); #else // Gtk-1.2 gunk if (text.empty()) { tooltip_.reset(); hrow_ = INIT_ROW_HANDLE; hcol_ = -1; } else { tooltip_.reset(new Gtk::Window(Gtk_FLAG(WINDOW_POPUP))); assert(tooltip_.get()); tooltip_->set_name("tooltip"); tooltip_->set_border_width(3); Gtk_set_resizable(tooltip_, false); tooltip_->set_app_paintable(true); Gtk_CONNECT_0(tooltip_, expose_event, this, &CustomToolTip::on_paint_custom_tip); Gtk::Label* label = manage(new Gtk::Label(text, .0)); tooltip_->add(*label); label->set_line_wrap(false); label->set_justify(Gtk_FLAG(JUSTIFY_LEFT)); StylePtr style = CHKPTR(tooltip_->get_style())->copy(); // fixme: get the background color from the current theme style->set_bg(Gtk_FLAG(STATE_NORMAL), Gdk_Color("lightyellow")); style->set_fg(Gtk_FLAG(STATE_NORMAL), Gdk_Color("black")); Gtk_set_style(tooltip_, style); //move it out of sight, initially Gtk_move(tooltip_.get(), gdk_screen_width(), gdk_screen_height()); assert(tooltip_.get()); tooltip_->show_all(); position_tooltip(x_root, y_root); } #endif return 0; } int CustomToolTip::on_pointer_leave(GdkEventCrossing*) { #if GTKMM_2 widget_->set_has_tooltip(false); #else tooltip_.reset(); hrow_ = INIT_ROW_HANDLE; hcol_ = -1; #endif return 0; } int CustomToolTip::on_paint_custom_tip(GdkEventExpose* event) { if (drawing_) { return 0; } assert(event); assert(widget_); // otherwise how could we get this event? if (event->count == 0 && tooltip_.get()) { Temporary<bool> setFlag(drawing_, true); assert(tooltip_->get_style()); const GdkRectangle& r = event->area; gtk_paint_flat_box(GTKOBJ(tooltip_->get_style()), event->window, GTK_STATE_NORMAL, GTK_SHADOW_OUT, NULL, GTK_WIDGET(GTKOBJ(tooltip_)), "tooltip", r.x, r.y, r.width, r.height); //#ifdef GTKMM_2 // std::vector<Gtk::Widget*> children = tooltip_->get_children(); // gtk_widget_draw(GTKOBJ(children[0]), NULL); //#endif } return 0; } // vim: tabstop=4:softtabstop=4:expandtab:shiftwidth=4
24.812834
89
0.6
[ "vector" ]
d055ff8961e2547f0952cd83f1b5fd90fd88ca89
1,111
cpp
C++
algorithms/cpp/368.cpp
viing937/leetcode
e21ca52c98bddf59e43522c0aace5e8cf84350eb
[ "MIT" ]
3
2016-10-01T10:15:09.000Z
2017-07-09T02:53:36.000Z
algorithms/cpp/368.cpp
viing937/leetcode
e21ca52c98bddf59e43522c0aace5e8cf84350eb
[ "MIT" ]
null
null
null
algorithms/cpp/368.cpp
viing937/leetcode
e21ca52c98bddf59e43522c0aace5e8cf84350eb
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <unordered_map> using namespace std; class Solution { public: vector<int> largestDivisibleSubset(vector<int> &nums) { vector<int> result; if (nums.empty()) return result; sort(nums.begin(), nums.end()); int n = nums.size(); vector<int> dp(n, 1); unordered_map<int, int> link; for (int i = 0; i < n; i++) { for (int j = i+1; j < n; j++) { if (nums[j] % nums[i] == 0 && dp[j] <= dp[i]) { dp[j] = dp[i]+1; link[j] = i; } } } int maxNum = *max_element(dp.begin(), dp.end()); for (int i = 0; i < n; i++) { if (dp[i] != maxNum) continue; int j = i; result.push_back(nums[j]); while (link.find(j) != link.end()) { j = link[j]; result.push_back(nums[j]); } reverse(result.begin(), result.end()); break; } return result; } }; int main() { return 0; }
26.452381
63
0.432943
[ "vector" ]
d05ccdbdd67f350bb21bd109dd6d1088e9e59101
12,194
cpp
C++
libdariadb/storage/wal/wal_manager.cpp
dariadb/dariadb
1edf637122752ba21c582675e2a9183fff91fa50
[ "Apache-2.0" ]
null
null
null
libdariadb/storage/wal/wal_manager.cpp
dariadb/dariadb
1edf637122752ba21c582675e2a9183fff91fa50
[ "Apache-2.0" ]
null
null
null
libdariadb/storage/wal/wal_manager.cpp
dariadb/dariadb
1edf637122752ba21c582675e2a9183fff91fa50
[ "Apache-2.0" ]
null
null
null
#include <libdariadb/flags.h> #include <libdariadb/storage/callbacks.h> #include <libdariadb/storage/manifest.h> #include <libdariadb/storage/settings.h> #include <libdariadb/storage/wal/wal_manager.h> #include <libdariadb/utils/async/thread_manager.h> #include <libdariadb/utils/exception.h> #include <libdariadb/utils/fs.h> #include <libdariadb/utils/logger.h> #include <iterator> #include <tuple> using namespace dariadb; using namespace dariadb::storage; using namespace dariadb::utils::async; EXPORT WALManager *WALManager::_instance = nullptr; WALManager::~WALManager() { this->flush(); } WALManager_ptr WALManager::create(const EngineEnvironment_ptr env){ return WALManager_ptr{ new WALManager(env) }; } WALManager::WALManager(const EngineEnvironment_ptr env) { _env = env; _settings = _env->getResourceObject<Settings>(EngineEnvironment::Resource::SETTINGS); _down = nullptr; auto manifest = _env->getResourceObject<Manifest>(EngineEnvironment::Resource::MANIFEST); if (dariadb::utils::fs::path_exists(_settings->raw_path.value())) { auto wals = manifest->wal_list(); for (auto f : wals) { auto full_filename = utils::fs::append_path(_settings->raw_path.value(), f); if (WALFile::writed(full_filename) != _settings->wal_file_size.value()) { logger_info("engine: WalManager open exist file ", f); WALFile_Ptr p = WALFile::open(_env, full_filename); _wal = p; break; } } } _buffer.resize(_settings->wal_cache_size.value()); _buffer_pos = 0; } void WALManager::create_new() { _wal = nullptr; if (_settings->strategy.value() != STRATEGY::WAL) { drop_old_if_needed(); } _wal = WALFile::create(_env); } void WALManager::dropAll() { if (_down != nullptr) { auto all_files = wal_files(); this->_wal = nullptr; for (auto f : all_files) { auto without_path = utils::fs::extract_filename(f); if (_files_send_to_drop.find(without_path) == _files_send_to_drop.end()) { // logger_info("engine: drop ",without_path); this->dropWAL(f, _down); } } } } void WALManager::dropClosedFiles(size_t count) { if (_down != nullptr) { auto closed = this->closedWals(); size_t to_drop = std::min(closed.size(), count); for (size_t i = 0; i < to_drop; ++i) { auto f = closed.front(); closed.pop_front(); auto without_path = utils::fs::extract_filename(f); if (_files_send_to_drop.find(without_path) == _files_send_to_drop.end()) { this->dropWAL(f, _down); } } // clean set of sended to drop files. auto manifest = _env->getResourceObject<Manifest>(EngineEnvironment::Resource::MANIFEST); auto wals_exists = manifest->wal_list(); std::set<std::string> wal_exists_set{wals_exists.begin(), wals_exists.end()}; std::set<std::string> new_sended_files; for (auto &v : _files_send_to_drop) { if (wal_exists_set.find(v) != wal_exists_set.end()) { new_sended_files.emplace(v); } } _files_send_to_drop = new_sended_files; } } void WALManager::drop_old_if_needed() { if (_settings->strategy.value() != STRATEGY::WAL) { auto closed = this->closedWals(); dropClosedFiles(closed.size()); } } std::list<std::string> WALManager::wal_files() const { std::list<std::string> res; auto files = _env->getResourceObject<Manifest>(EngineEnvironment::Resource::MANIFEST) ->wal_list(); for (auto f : files) { auto full_path = utils::fs::append_path(_settings->raw_path.value(), f); res.push_back(full_path); } return res; } std::list<std::string> WALManager::closedWals() { auto all_files = wal_files(); std::list<std::string> result; for (auto fn : all_files) { if (_wal == nullptr) { result.push_back(fn); } else { if (fn != this->_wal->filename()) { result.push_back(fn); } } } return result; } void WALManager::dropWAL(const std::string &fname, IWALDropper *storage) { WALFile_Ptr ptr = WALFile::open(_env, fname, false); auto without_path = utils::fs::extract_filename(fname); _files_send_to_drop.emplace(without_path); storage->dropWAL(without_path); } void WALManager::setDownlevel(IWALDropper *down) { _down = down; this->drop_old_if_needed(); } dariadb::Time WALManager::minTime() { std::lock_guard<std::mutex> lg(_locker); auto files = wal_files(); dariadb::Time result = dariadb::MAX_TIME; auto env = _env; AsyncTask at = [files, &result, env](const ThreadInfo &ti) { TKIND_CHECK(THREAD_KINDS::DISK_IO, ti.kind); for (auto filename : files) { auto wal = WALFile::open(env, filename, true); auto local = wal->minTime(); result = std::min(local, result); } return false; }; auto am_async = ThreadManager::instance()->post(THREAD_KINDS::DISK_IO, AT(at)); am_async->wait(); size_t pos = 0; for (auto &v : _buffer) { result = std::min(v.time, result); ++pos; if (pos > _buffer_pos) { break; } } return result; } dariadb::Time WALManager::maxTime() { std::lock_guard<std::mutex> lg(_locker); auto files = wal_files(); dariadb::Time result = dariadb::MIN_TIME; auto env = _env; AsyncTask at = [files, &result, env](const ThreadInfo &ti) { TKIND_CHECK(THREAD_KINDS::DISK_IO, ti.kind); for (auto filename : files) { auto wal = WALFile::open(env, filename, true); auto local = wal->maxTime(); result = std::max(local, result); } return false; }; auto am_async = ThreadManager::instance()->post(THREAD_KINDS::DISK_IO, AT(at)); am_async->wait(); for (auto &v : _buffer) { result = std::max(v.time, result); } return result; } bool WALManager::minMaxTime(dariadb::Id id, dariadb::Time *minResult, dariadb::Time *maxResult) { std::lock_guard<std::mutex> lg(_locker); auto files = wal_files(); using MMRes = std::tuple<bool, dariadb::Time, dariadb::Time>; std::vector<MMRes> results{files.size()}; auto env = _env; AsyncTask at = [files, &results, id, env](const ThreadInfo &ti) { TKIND_CHECK(THREAD_KINDS::DISK_IO, ti.kind); size_t num = 0; for (auto filename : files) { auto wal = WALFile::open(env, filename, true); dariadb::Time lmin = dariadb::MAX_TIME, lmax = dariadb::MIN_TIME; if (wal->minMaxTime(id, &lmin, &lmax)) { results[num] = MMRes(true, lmin, lmax); } else { results[num] = MMRes(false, lmin, lmax); } num++; } return false; }; auto am_async = ThreadManager::instance()->post(THREAD_KINDS::DISK_IO, AT(at)); am_async->wait(); bool res = false; *minResult = dariadb::MAX_TIME; *maxResult = dariadb::MIN_TIME; for (auto &subRes : results) { if (std::get<0>(subRes)) { res = true; *minResult = std::min(std::get<1>(subRes), *minResult); *maxResult = std::max(std::get<2>(subRes), *maxResult); } } size_t pos = 0; for (auto v : _buffer) { if (v.id == id) { res = true; *minResult = std::min(v.time, *minResult); *maxResult = std::max(v.time, *maxResult); } ++pos; if (pos > _buffer_pos) { break; } } return res; } void WALManager::foreach (const QueryInterval &q, IReaderClb * clbk) { std::lock_guard<std::mutex> lg(_locker); auto files = wal_files(); if (!files.empty()) { auto env = _env; AsyncTask at = [files, &q, clbk, env](const ThreadInfo &ti) { TKIND_CHECK(THREAD_KINDS::DISK_IO, ti.kind); for (auto filename : files) { if (clbk->is_canceled()) { break; } auto wal = WALFile::open(env, filename, true); wal->foreach (q, clbk); } return false; }; auto am_async = ThreadManager::instance()->post(THREAD_KINDS::DISK_IO, AT(at)); am_async->wait(); } size_t pos = 0; for (auto v : _buffer) { if (pos >= _buffer_pos) { break; } if (v.inQuery(q.ids, q.flag, q.from, q.to)) { clbk->call(v); } ++pos; } } Id2Meas WALManager::readTimePoint(const QueryTimePoint &query) { std::lock_guard<std::mutex> lg(_locker); auto files = wal_files(); dariadb::Id2Meas sub_result; std::vector<Id2Meas> results{files.size()}; auto env = _env; AsyncTask at = [files, &query, &results, env](const ThreadInfo &ti) { TKIND_CHECK(THREAD_KINDS::DISK_IO, ti.kind); size_t num = 0; for (auto filename : files) { auto wal = WALFile::open(env, filename, true); results[num] = wal->readTimePoint(query); num++; } return false; }; auto am_async = ThreadManager::instance()->post(THREAD_KINDS::DISK_IO, AT(at)); am_async->wait(); for (auto &out : results) { for (auto &kv : out) { auto it = sub_result.find(kv.first); if (it == sub_result.end()) { sub_result.emplace(std::make_pair(kv.first, kv.second)); } else { if (it->second.flag == Flags::_NO_DATA) { sub_result[kv.first] = kv.second; } } } } size_t pos = 0; for (auto v : _buffer) { if (v.inQuery(query.ids, query.flag)) { auto it = sub_result.find(v.id); if (it == sub_result.end()) { sub_result.emplace(std::make_pair(v.id, v)); } else { if ((v.flag == Flags::_NO_DATA) || ((v.time > it->second.time) && (v.time <= query.time_point))) { sub_result[v.id] = v; } } } ++pos; if (pos > _buffer_pos) { break; } } for (auto id : query.ids) { if (sub_result.find(id) == sub_result.end()) { sub_result[id].flag = Flags::_NO_DATA; sub_result[id].time = query.time_point; } } return sub_result; } Id2Meas WALManager::currentValue(const IdArray &ids, const Flag &flag) { dariadb::Id2Meas meases; AsyncTask at = [&ids, flag, &meases, this](const ThreadInfo &ti) { TKIND_CHECK(THREAD_KINDS::DISK_IO, ti.kind); auto files = wal_files(); for (const auto &f : files) { auto c = WALFile::open(_env, f, true); auto sub_rdr = c->currentValue(ids, flag); for (auto &kv : sub_rdr) { auto it = meases.find(kv.first); if (it == meases.end()) { meases.emplace(std::make_pair(kv.first, kv.second)); } else { if ((it->second.flag == Flags::_NO_DATA) || (it->second.time < kv.second.time)) { meases[kv.first] = kv.second; } } } } return false; }; auto am_async = ThreadManager::instance()->post(THREAD_KINDS::DISK_IO, AT(at)); am_async->wait(); return meases; } dariadb::Status WALManager::append(const Meas &value) { std::lock_guard<std::mutex> lg(_locker); _buffer[_buffer_pos] = value; _buffer_pos++; if (_buffer_pos >= _settings->wal_cache_size.value()) { flush_buffer(); } return dariadb::Status(1, 0); } void WALManager::flush_buffer() { if (_buffer_pos == size_t(0)) { return; } AsyncTask at = [this](const ThreadInfo &ti) { TKIND_CHECK(THREAD_KINDS::DISK_IO, ti.kind); if (_wal == nullptr) { create_new(); } size_t pos = 0; size_t total_writed = 0; while (1) { auto res = _wal->append(_buffer.begin() + pos, _buffer.begin() + _buffer_pos); total_writed += res.writed; if (total_writed != _buffer_pos) { create_new(); pos += res.writed; } else { break; } } _buffer_pos = 0; return false; }; auto async_r = ThreadManager::instance()->post(THREAD_KINDS::DISK_IO, AT(at)); async_r->wait(); } void WALManager::flush() { flush_buffer(); } size_t WALManager::filesCount() const { return wal_files().size(); } void WALManager::erase(const std::string &fname) { _env->getResourceObject<Manifest>(EngineEnvironment::Resource::MANIFEST)->wal_rm(fname); utils::fs::rm(utils::fs::append_path(_settings->raw_path.value(), fname)); } Id2MinMax WALManager::loadMinMax() { auto files = wal_files(); dariadb::Id2MinMax result; for (const auto &f : files) { auto c = WALFile::open(_env, f, true); auto sub_res = c->loadMinMax(); minmax_append(result, sub_res); } return result; }
27.713636
90
0.622355
[ "vector" ]
d05f3207925f566986a81408274d3e28e1aa64d8
1,219
hpp
C++
Level_8_HW/Exercise 3/Exercise 3/ShapeVisitor.hpp
ZhehaoLi9705/QuantNet_CPP
a889f4656e757842f4163b0cda7e098cc6ad1193
[ "MIT" ]
null
null
null
Level_8_HW/Exercise 3/Exercise 3/ShapeVisitor.hpp
ZhehaoLi9705/QuantNet_CPP
a889f4656e757842f4163b0cda7e098cc6ad1193
[ "MIT" ]
null
null
null
Level_8_HW/Exercise 3/Exercise 3/ShapeVisitor.hpp
ZhehaoLi9705/QuantNet_CPP
a889f4656e757842f4163b0cda7e098cc6ad1193
[ "MIT" ]
null
null
null
// // ShapeVisitor.hpp // Exercise 3 // // Created by Zhehao Li on 2020/4/17. // Copyright © 2020 Zhehao Li. All rights reserved. // #ifndef ShapeVisitor_hpp #define ShapeVisitor_hpp #include "Point.hpp" #include "Line.hpp" #include "Circle.hpp" #include "boost/variant.hpp" namespace CAD = ZhehaoLi::CAD; class ShapeVisitor: boost::static_visitor<void>{ private: double m_dx; // distance to move along x double m_dy; // distance to move along y public: /* Constructor */ ShapeVisitor(); // Default constructor ShapeVisitor(double dx, double dy); // Constructor with value ShapeVisitor(const ShapeVisitor & source); // Copy consturctor /* Desturctor */ ~ShapeVisitor(); /* Accessing Functions */ void operator () (CAD::Point & pt) const; // Move Point object void operator () (CAD::Line & ln) const; // Move Line object void operator () (CAD::Circle & cr) const; // Move Circle object /* Modifier Functions */ ShapeVisitor & operator = (const ShapeVisitor & source); // Assignment operators }; #endif /* ShapeVisitor_hpp */
26.5
89
0.607055
[ "cad", "object" ]
d061d0df2eb3cf116aa8c381a5a258ce512803f7
834
cpp
C++
BackTracking/permutationsii.cpp
thisisnitish/cp-dsa-
9ae94930b65f8dc293d088e9148960939b9f6fa4
[ "MIT" ]
4
2020-12-29T09:27:10.000Z
2022-02-12T14:20:23.000Z
BackTracking/permutationsii.cpp
thisisnitish/cp-dsa-
9ae94930b65f8dc293d088e9148960939b9f6fa4
[ "MIT" ]
1
2021-11-27T06:15:28.000Z
2021-11-27T06:15:28.000Z
BackTracking/permutationsii.cpp
thisisnitish/cp-dsa-
9ae94930b65f8dc293d088e9148960939b9f6fa4
[ "MIT" ]
1
2021-11-17T21:42:57.000Z
2021-11-17T21:42:57.000Z
/* Leetcode Question 47. Permutations II https://leetcode.com/problems/permutations-ii/ */ class Solution { public: //Time: O(N.N! + NlogN), Space: O(N) vector<vector<int> > permutations; vector<vector<int> > permuteUnique(vector<int> &nums) { sort(nums.begin(), nums.end()); generatePermutations(nums, 0); return permutations; } void generatePermutations(vector<int> nums, int idx) { if (idx == nums.size()) { permutations.push_back(nums); return; } for (int i = idx; i < nums.size(); i++) { if (idx != i && nums[i] == nums[idx]) continue; swap(nums[idx], nums[i]); generatePermutations(nums, idx + 1); // swap(nums[idx], nums[i]); } } };
23.828571
57
0.517986
[ "vector" ]
d067faa245a90f5533f83c960c97fc9d2eec5972
1,749
cpp
C++
src/submain_key.cpp
jsdelivrbot/LUIS
8a5682c52f27601fb0fc0b2230c45be3738fc1f1
[ "MIT" ]
1
2020-02-21T12:58:22.000Z
2020-02-21T12:58:22.000Z
src/submain_key.cpp
jsdelivrbot/LUIS
8a5682c52f27601fb0fc0b2230c45be3738fc1f1
[ "MIT" ]
null
null
null
src/submain_key.cpp
jsdelivrbot/LUIS
8a5682c52f27601fb0fc0b2230c45be3738fc1f1
[ "MIT" ]
1
2018-12-08T17:47:50.000Z
2018-12-08T17:47:50.000Z
#include "submains.hpp" int submain_key(MainArgs &args) { const std::string &cmd = args.get("2"); if(cmd == "set"){ if(args.has("3")){ std::string public_key(args.get("3")); std::string path(args.get("cfg-data-dir")+"/keys/"+public_key); MapData mdata; mdata.loadFile(path); if(args.has("deny")) mdata.set("deny", ""); else if(args.has("allow")) mdata.unset("deny"); if(!mdata.writeFile(path)){ std::cerr << "couldn't write client/service to " << path << std::endl; return 1; } } else{ std::cerr << "missing public_key parameter" << std::endl; return 1; } } else if(cmd == "unset"){ if(args.has("3")){ std::string path(args.get("cfg-data-dir")+"/keys/"+args.get("3")); if(!Dir::rmfile(path)) std::cerr << "couldn't delete " << path << std::endl; } else{ std::cerr << "missing public_key parameter" << std::endl; return 1; } } else if(cmd == "list"){ std::string dir(args.get("cfg-data-dir")+"/keys/"); std::vector<std::string> pfiles; Dir::explode(dir, pfiles, Dir::SFILE); // header std::cout << "public_key deny" << std::endl; for(int i = 0; i < pfiles.size(); i++){ MapData mdata; if(mdata.loadFile(pfiles[i])){ std::string public_key(pfiles[i].substr(dir.size())); std::cout << public_key << " " << (mdata.has("deny") ? "yes" : "no ") << std::endl; } else std::cerr << "couldn't read " << pfiles[i] << std::endl; } } else{ std::cerr << "key subcommand \"" << cmd << "\" not found" << std::endl; return 1; } return 0; }
25.720588
102
0.507147
[ "vector" ]
d06b4e9361eee2fd1868bab32220d90e433e6c52
473
hpp
C++
Sharp/Statements/FunctionStatement.hpp
gth747m/Sharp
5c3d88779f4ba3f596bf0250a1397d4bcf84b3a7
[ "MIT" ]
null
null
null
Sharp/Statements/FunctionStatement.hpp
gth747m/Sharp
5c3d88779f4ba3f596bf0250a1397d4bcf84b3a7
[ "MIT" ]
null
null
null
Sharp/Statements/FunctionStatement.hpp
gth747m/Sharp
5c3d88779f4ba3f596bf0250a1397d4bcf84b3a7
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include <vector> #include "Statement.hpp" #include "../Token.hpp" class FunctionStatement : public Statement { public: FunctionStatement(Token&& name, std::vector<Token>&& params, std::vector<std::unique_ptr<Statement>>&& body); virtual ~FunctionStatement() = default; protected: virtual void Print(std::ostream& os); private: Token name; std::vector<Token> params; std::vector<std::unique_ptr<Statement>> body; };
23.65
113
0.704017
[ "vector" ]
d06b514459e1138b7a8d64976832bfc6ac44e626
7,625
cpp
C++
Max2D/hoa.2d.exchanger_tilde.cpp
CICM/HoaLibrary-Max
cfe110ff040cfda0dd3547ee7e9ec7c11d6dd3b6
[ "Naumen", "Condor-1.1", "MS-PL" ]
71
2015-02-23T12:24:05.000Z
2022-02-15T00:18:30.000Z
Max2D/hoa.2d.exchanger_tilde.cpp
pb5/HoaLibrary-Max
cfe110ff040cfda0dd3547ee7e9ec7c11d6dd3b6
[ "Naumen", "Condor-1.1", "MS-PL" ]
13
2015-04-22T17:13:53.000Z
2020-11-12T10:54:29.000Z
Max2D/hoa.2d.exchanger_tilde.cpp
pb5/HoaLibrary-Max
cfe110ff040cfda0dd3547ee7e9ec7c11d6dd3b6
[ "Naumen", "Condor-1.1", "MS-PL" ]
8
2015-04-11T21:34:51.000Z
2020-02-29T14:37:53.000Z
/* // Copyright (c) 2012-2015 Eliott Paris, Julien Colafrancesco & Pierre Guillot, CICM, Universite Paris 8. // For information on usage and redistribution, and for a DISCLAIMER OF ALL // WARRANTIES, see the file, "LICENSE.txt," in this distribution. */ /** @file hoa.2d.exchanger~.cpp @name hoa.2d.exchanger~ @realname hoa.2d.exchanger~ @type object @module hoa @author Julien Colafrancesco, Pierre Guillot, Eliott Paris. @digest Renumbers and normalizes the channels. @description <o>hoa.2d.exchanger~</o> renumbers and normalizes the channels. @discussion The library default normalization is SN3D and the numbering is ACN (cf tutorials). The exchangers will always convert from or to the standard. The exchanger can take one or two arguments for the numbering and the normalization. For further information <a href="http://en.wikipedia.org/wiki/Ambisonic_data_exchange_formats">click here</a>. @category 2d, Ambisonics, MSP @seealso hoa.3d.exchanger~, hoa.2d.decoder~, hoa.2d.encoder~ */ #include "Hoa2D.max.h" typedef struct _hoa_2d_exchanger { t_pxobject f_obj; t_sample* f_ins; t_sample* f_outs; Exchanger<Hoa2d, t_sample>* f_exchanger; } t_hoa_2d_exchanger; t_class *hoa_2d_exchanger_class; t_hoa_err hoa_getinfos(t_hoa_2d_exchanger* x, t_hoa_boxinfos* boxinfos) { boxinfos->object_type = HOA_OBJECT_2D; boxinfos->autoconnect_inputs = boxinfos->autoconnect_outputs = x->f_exchanger->getNumberOfHarmonics(); boxinfos->autoconnect_inputs_type = boxinfos->autoconnect_outputs_type = HOA_CONNECT_TYPE_AMBISONICS; return HOA_ERR_NONE; } t_hoa_err hoa_get_output_harmonic_order(t_hoa_2d_exchanger* x, ulong index, long* order) { *order = x->f_exchanger->getOutputHarmonicOrder(index); return HOA_ERR_NONE; } void hoa_2d_exchanger_assist(t_hoa_2d_exchanger *x, void *b, long m, long a, char *s) { if(m == ASSIST_INLET) sprintf(s,"(signal) %s", x->f_exchanger->getHarmonicName(a, true).c_str()); else sprintf(s,"(signal) %s", x->f_exchanger->getHarmonicName(a, false).c_str()); } void hoa_2d_exchanger_perform(t_hoa_2d_exchanger *x, t_object *dsp, t_sample **ins, long nins, t_sample **outs, long numouts, long sampleframes, long f,void *up) { for(long i = 0; i < nins; i++) { Signal<t_sample>::copy(sampleframes, ins[i], 1, x->f_ins+i, nins); } for(long i = 0; i < sampleframes; i++) { x->f_exchanger->process(x->f_ins + nins * i, x->f_outs + numouts * i); } for(long i = 0; i < numouts; i++) { Signal<t_sample>::copy(sampleframes, x->f_outs+i, numouts, outs[i], 1); } } void hoa_2d_exchanger_dsp(t_hoa_2d_exchanger *x, t_object *dsp, short *count, double samplerate, long maxvectorsize, long flags) { object_method(dsp, gensym("dsp_add64"), x, (method)hoa_2d_exchanger_perform, 0, NULL); } void hoa_2d_exchanger_free(t_hoa_2d_exchanger *x) { dsp_free((t_pxobject *)x); delete x->f_exchanger; delete [] x->f_ins; delete [] x->f_outs; } void *hoa_2d_exchanger_new(t_symbol *s, long argc, t_atom *argv) { // @arg 0 @name decomposition-order @optional 0 @type int @digest The ambisonic order of decomposition // @description First argument is the ambisonic order of decomposition. // @arg 1 @name numbering @optional 1 @type symbol @digest The numbering format. // @description numbering format can be "toFurseMalham", "toSID", "fromFurseMalham", "fromSID" // @arg 2 @name normalisation @optional 1 @type symbol @digest The normalisation format. // @description numbering format can be "toMaxN", "fromMaxN". // Numbering and Normalisation args can be combined into a single as follows : "toBFormat" (aka. toFurseMalham toMaxN), "fromBFormat" (aka. fromFurseMalham fromMaxN). t_hoa_2d_exchanger *x = (t_hoa_2d_exchanger *)object_alloc(hoa_2d_exchanger_class); if (x) { long order = 1l; if(argc && argv && atom_gettype(argv) == A_LONG) order = Math<long>::clip(atom_getlong(argv), 1l, 63l); Exchanger<Hoa2d, t_sample>::Numbering numb = Exchanger<Hoa2d, t_sample>::ACN; Exchanger<Hoa2d, t_sample>::Normalization norm = Exchanger<Hoa2d, t_sample>::SN2D; for(int i = 1; i < 3; i++) { if(argc > i && atom_gettype(argv+i) == A_SYM) { if(atom_getsym(argv+i) == gensym("toMaxN")) { norm = Exchanger<Hoa2d, t_sample>::toMaxN; } else if(atom_getsym(argv+i) == gensym("fromMaxN")) { norm = Exchanger<Hoa2d, t_sample>::fromMaxN; } else if(atom_getsym(argv+i) == gensym("toFurseMalham")) { numb = Exchanger<Hoa2d, t_sample>::toFurseMalham; } else if(atom_getsym(argv+i) == gensym("toSID")) { numb = Exchanger<Hoa2d, t_sample>::toSID; } else if(atom_getsym(argv+i) == gensym("fromFurseMalham")) { numb = Exchanger<Hoa2d, t_sample>::fromFurseMalham; } else if(atom_getsym(argv+i) == gensym("fromSID")) { numb = Exchanger<Hoa2d, t_sample>::fromSID; } else if(atom_getsym(argv+i) == gensym("toBFormat")) { norm = Exchanger<Hoa2d, t_sample>::toMaxN; numb = Exchanger<Hoa2d, t_sample>::toFurseMalham; } else if(atom_getsym(argv+i) == gensym("fromBFormat")) { norm = Exchanger<Hoa2d, t_sample>::fromMaxN; numb = Exchanger<Hoa2d, t_sample>::fromFurseMalham; } else { object_error((t_object*)x, "%s : wrong symbol.", atom_getsym(argv+i)->s_name); } } } x->f_exchanger = new Exchanger<Hoa2d, t_sample>(order); x->f_exchanger->setNormalization(norm); x->f_exchanger->setNumbering(numb); dsp_setup((t_pxobject *)x, x->f_exchanger->getNumberOfHarmonics()); for(int i = 0; i < x->f_exchanger->getNumberOfHarmonics(); i++) outlet_new(x, "signal"); x->f_ins = new t_sample[x->f_exchanger->getNumberOfHarmonics() * HOA_MAXBLKSIZE]; x->f_outs = new t_sample[x->f_exchanger->getNumberOfHarmonics() * HOA_MAXBLKSIZE]; return x; } return NULL; } #ifdef HOA_PACKED_LIB int hoa_2d_exchanger_main(void) #else void ext_main(void *r) #endif { t_class *c; c = class_new("hoa.2d.exchanger~", (method)hoa_2d_exchanger_new, (method)hoa_2d_exchanger_free, (long)sizeof(t_hoa_2d_exchanger), 0L, A_GIMME, 0); hoa_initclass(c, (method)hoa_getinfos); // @method signal @digest Array of circular harmonic signals. // @description Array of circular harmonic signals. class_addmethod(c, (method)hoa_2d_exchanger_dsp, "dsp64", A_CANT, 0); class_addmethod(c, (method)hoa_2d_exchanger_assist, "assist", A_CANT, 0); // @internal : used by hoa.connect object to color patchlines depending on exchanger numbering config. class_addmethod(c, (method)hoa_get_output_harmonic_order, "hoa_get_output_harmonic_order", A_CANT, 0); class_dspinit(c); class_register(CLASS_BOX, c); hoa_2d_exchanger_class = c; }
38.316583
339
0.624918
[ "object", "3d" ]
d06b6cdb589ac42a7fc051ffd32eafcb9236ff70
243
hpp
C++
Delta/math/box.hpp
vedard/DeltaEngine
49296b8277023dc8cc656d0597624cf49254dcf0
[ "MIT" ]
null
null
null
Delta/math/box.hpp
vedard/DeltaEngine
49296b8277023dc8cc656d0597624cf49254dcf0
[ "MIT" ]
null
null
null
Delta/math/box.hpp
vedard/DeltaEngine
49296b8277023dc8cc656d0597624cf49254dcf0
[ "MIT" ]
null
null
null
#pragma once #include "vector.hpp" namespace dt { class Box { public: Vector position; Vector size; Box(const Vector& position, const Vector& size); bool is_colliding_with(const Box& other) const; }; } // namespace dt
14.294118
52
0.666667
[ "vector" ]
d0755a0fa653dd90d4aa234cb7b5dcf46dc60dc1
4,144
cpp
C++
libman/gmm.cpp
disa-mhembere/knor
5c4174b80726eb5fc8da7042d517e8c3929ec747
[ "Apache-2.0" ]
13
2017-06-30T12:48:54.000Z
2021-05-26T06:54:10.000Z
libman/gmm.cpp
disa-mhembere/knor
5c4174b80726eb5fc8da7042d517e8c3929ec747
[ "Apache-2.0" ]
30
2016-11-21T23:21:48.000Z
2017-03-05T06:26:52.000Z
libman/gmm.cpp
disa-mhembere/k-par-means
5c4174b80726eb5fc8da7042d517e8c3929ec747
[ "Apache-2.0" ]
5
2017-04-11T00:44:04.000Z
2018-11-01T10:41:06.000Z
/* * Copyright 2016 neurodata (http://neurodata.io/) * Written by Disa Mhembere (disa@jhu.edu) * * This file is part of knor * * 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 CURRENT_KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <math.h> #include <iostream> #include <cassert> #include "gmm.hpp" #include "types.hpp" #include "util.hpp" #include "io.hpp" #include "linalg.hpp" namespace knor { gmm::gmm(const int node_id, const unsigned thd_id, const unsigned start_rid, const unsigned nprocrows, const unsigned ncol, const std::string fn, kbase::dist_t dist_metric) : thread(node_id, thd_id, ncol, NULL, start_rid, fn, dist_metric), nprocrows(nprocrows), L(0){ local_clusters = nullptr; set_data_size(sizeof(double)*nprocrows*ncol); #if VERBOSE #ifndef std::cout << "Initializing gmm. Metadata: thd_id: " << this->thd_id << ", start_rid: " << this->start_rid << ", node_id: " << this->node_id << ", nprocrows: " << this->nprocrows << ", ncol: " << this->ncol << std::endl; #endif #endif } void gmm::set_alg_metadata(unsigned k, base::dense_matrix<double>* mu_k, base::dense_matrix<double>** sigma_k, base::dense_matrix<double>* P_nk, double* Pk, base::dense_matrix<double>** isk, double* dets, double* Px) { this->k = k; this->mu_k = mu_k; this->sigma_k = sigma_k; this->P_nk = P_nk; inv_sigma_k = isk; this->dets = dets; this->Pk = Pk; this->Px = Px; } void gmm::Estep() { // Compute Pnk L = 0; // Reset for (unsigned row = 0; row < nprocrows; row++) { unsigned true_row_id = get_global_data_id(row); for (unsigned cid = 0; cid < k; cid++) { std::vector<double> diff(ncol); base::linalg::vdiff(&local_data[row*ncol], &(mu_k->as_pointer()[row*ncol]), ncol, diff); std::vector<double> resdot(inv_sigma_k[cid]->get_ncol()); base::linalg::dot(&diff[0], inv_sigma_k[cid]->as_pointer(), inv_sigma_k[cid]->get_nrow(), inv_sigma_k[cid]->get_ncol(), resdot); double lhs = -.5*(base::linalg::dot(resdot, diff)); double rhs = .5*M*std::log2(2*M_PI) - (.5*std::log2(dets[cid])); double gaussian_density = lhs - rhs; // for one of the k guassians auto tmp = gaussian_density * Pk[cid]; Px[true_row_id] += tmp; P_nk->set(row, cid, tmp); } // Finish P_nk for (unsigned cid = 0; cid < k; cid++) { P_nk->set(row, cid, P_nk->get(row, cid)/Px[true_row_id]); } // L is Per thread if (L == 0) L = Px[true_row_id]; else L *= Px[true_row_id]; } } void gmm::Mstep() { } void gmm::run() { switch(state) { case TEST: test(); break; case ALLOC_DATA: numa_alloc_mem(); break; case E: Estep(); break; case M: Mstep(); break; case EXIT: throw kbase::thread_exception( "Thread state is EXIT but running!\n"); default: throw kbase::thread_exception("Unknown thread state\n"); } sleep(); } void gmm::start(const thread_state_t state=WAIT) { this->state = state; int rc = pthread_create(&hw_thd, NULL, callback<gmm>, this); if (rc) throw kbase::thread_exception( "Thread creation (pthread_create) failed!", rc); } } // End namespace knor
30.470588
83
0.569498
[ "vector" ]
d07c5806d7c5deb92b50bfe4e6601671814131e0
56,508
cpp
C++
cplus/libcfint/CFIntMajorVersionTableObj.cpp
msobkow/cfint_2_13
63ff9dfc85647066d0c8d61469ada572362e2b48
[ "Apache-2.0" ]
null
null
null
cplus/libcfint/CFIntMajorVersionTableObj.cpp
msobkow/cfint_2_13
63ff9dfc85647066d0c8d61469ada572362e2b48
[ "Apache-2.0" ]
null
null
null
cplus/libcfint/CFIntMajorVersionTableObj.cpp
msobkow/cfint_2_13
63ff9dfc85647066d0c8d61469ada572362e2b48
[ "Apache-2.0" ]
null
null
null
// Description: C++18 Table Object implementation for CFInt. /* * org.msscf.msscf.CFInt * * Copyright (c) 2020 Mark Stephen Sobkow * * MSS Code Factory CFInt 2.13 Internet Essentials * * Copyright 2020-2021 Mark Stephen Sobkow * * This file is part of MSS Code Factory. * * MSS Code Factory is available under dual commercial license from Mark Stephen * Sobkow, or under the terms of the GNU General Public License, Version 3 * or later. * * MSS Code Factory 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. * * MSS Code Factory 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 MSS Code Factory. If not, see <https://www.gnu.org/licenses/>. * * Donations to support MSS Code Factory can be made at * https://www.paypal.com/paypalme2/MarkSobkow * * Please contact Mark Stephen Sobkow at mark.sobkow@gmail.com for commercial licensing. * * Manufactured by MSS Code Factory 2.12 */ #include <cflib/ICFLibPublic.hpp> using namespace std; #include <cfint/ICFIntPublic.hpp> #include <cfintobj/ICFIntObjPublic.hpp> #include <cfintobj/CFIntClusterObj.hpp> #include <cfintobj/CFIntHostNodeObj.hpp> #include <cfintobj/CFIntISOCcyObj.hpp> #include <cfintobj/CFIntISOCtryObj.hpp> #include <cfintobj/CFIntISOCtryCcyObj.hpp> #include <cfintobj/CFIntISOCtryLangObj.hpp> #include <cfintobj/CFIntISOLangObj.hpp> #include <cfintobj/CFIntISOTZoneObj.hpp> #include <cfintobj/CFIntLicenseObj.hpp> #include <cfintobj/CFIntMajorVersionObj.hpp> #include <cfintobj/CFIntMimeTypeObj.hpp> #include <cfintobj/CFIntMinorVersionObj.hpp> #include <cfintobj/CFIntSecAppObj.hpp> #include <cfintobj/CFIntSecDeviceObj.hpp> #include <cfintobj/CFIntSecFormObj.hpp> #include <cfintobj/CFIntSecGroupObj.hpp> #include <cfintobj/CFIntSecGroupFormObj.hpp> #include <cfintobj/CFIntSecGrpIncObj.hpp> #include <cfintobj/CFIntSecGrpMembObj.hpp> #include <cfintobj/CFIntSecSessionObj.hpp> #include <cfintobj/CFIntSecUserObj.hpp> #include <cfintobj/CFIntServiceObj.hpp> #include <cfintobj/CFIntServiceTypeObj.hpp> #include <cfintobj/CFIntSubProjectObj.hpp> #include <cfintobj/CFIntSysClusterObj.hpp> #include <cfintobj/CFIntTSecGroupObj.hpp> #include <cfintobj/CFIntTSecGrpIncObj.hpp> #include <cfintobj/CFIntTSecGrpMembObj.hpp> #include <cfintobj/CFIntTenantObj.hpp> #include <cfintobj/CFIntTldObj.hpp> #include <cfintobj/CFIntTopDomainObj.hpp> #include <cfintobj/CFIntTopProjectObj.hpp> #include <cfintobj/CFIntURLProtocolObj.hpp> #include <cfintobj/CFIntClusterEditObj.hpp> #include <cfintobj/CFIntHostNodeEditObj.hpp> #include <cfintobj/CFIntISOCcyEditObj.hpp> #include <cfintobj/CFIntISOCtryEditObj.hpp> #include <cfintobj/CFIntISOCtryCcyEditObj.hpp> #include <cfintobj/CFIntISOCtryLangEditObj.hpp> #include <cfintobj/CFIntISOLangEditObj.hpp> #include <cfintobj/CFIntISOTZoneEditObj.hpp> #include <cfintobj/CFIntLicenseEditObj.hpp> #include <cfintobj/CFIntMajorVersionEditObj.hpp> #include <cfintobj/CFIntMimeTypeEditObj.hpp> #include <cfintobj/CFIntMinorVersionEditObj.hpp> #include <cfintobj/CFIntSecAppEditObj.hpp> #include <cfintobj/CFIntSecDeviceEditObj.hpp> #include <cfintobj/CFIntSecFormEditObj.hpp> #include <cfintobj/CFIntSecGroupEditObj.hpp> #include <cfintobj/CFIntSecGroupFormEditObj.hpp> #include <cfintobj/CFIntSecGrpIncEditObj.hpp> #include <cfintobj/CFIntSecGrpMembEditObj.hpp> #include <cfintobj/CFIntSecSessionEditObj.hpp> #include <cfintobj/CFIntSecUserEditObj.hpp> #include <cfintobj/CFIntServiceEditObj.hpp> #include <cfintobj/CFIntServiceTypeEditObj.hpp> #include <cfintobj/CFIntSubProjectEditObj.hpp> #include <cfintobj/CFIntSysClusterEditObj.hpp> #include <cfintobj/CFIntTSecGroupEditObj.hpp> #include <cfintobj/CFIntTSecGrpIncEditObj.hpp> #include <cfintobj/CFIntTSecGrpMembEditObj.hpp> #include <cfintobj/CFIntTenantEditObj.hpp> #include <cfintobj/CFIntTldEditObj.hpp> #include <cfintobj/CFIntTopDomainEditObj.hpp> #include <cfintobj/CFIntTopProjectEditObj.hpp> #include <cfintobj/CFIntURLProtocolEditObj.hpp> #include <cfintobj/CFIntClusterTableObj.hpp> #include <cfintobj/CFIntHostNodeTableObj.hpp> #include <cfintobj/CFIntISOCcyTableObj.hpp> #include <cfintobj/CFIntISOCtryTableObj.hpp> #include <cfintobj/CFIntISOCtryCcyTableObj.hpp> #include <cfintobj/CFIntISOCtryLangTableObj.hpp> #include <cfintobj/CFIntISOLangTableObj.hpp> #include <cfintobj/CFIntISOTZoneTableObj.hpp> #include <cfintobj/CFIntLicenseTableObj.hpp> #include <cfintobj/CFIntMajorVersionTableObj.hpp> #include <cfintobj/CFIntMimeTypeTableObj.hpp> #include <cfintobj/CFIntMinorVersionTableObj.hpp> #include <cfintobj/CFIntSecAppTableObj.hpp> #include <cfintobj/CFIntSecDeviceTableObj.hpp> #include <cfintobj/CFIntSecFormTableObj.hpp> #include <cfintobj/CFIntSecGroupTableObj.hpp> #include <cfintobj/CFIntSecGroupFormTableObj.hpp> #include <cfintobj/CFIntSecGrpIncTableObj.hpp> #include <cfintobj/CFIntSecGrpMembTableObj.hpp> #include <cfintobj/CFIntSecSessionTableObj.hpp> #include <cfintobj/CFIntSecUserTableObj.hpp> #include <cfintobj/CFIntServiceTableObj.hpp> #include <cfintobj/CFIntServiceTypeTableObj.hpp> #include <cfintobj/CFIntSubProjectTableObj.hpp> #include <cfintobj/CFIntSysClusterTableObj.hpp> #include <cfintobj/CFIntTSecGroupTableObj.hpp> #include <cfintobj/CFIntTSecGrpIncTableObj.hpp> #include <cfintobj/CFIntTSecGrpMembTableObj.hpp> #include <cfintobj/CFIntTenantTableObj.hpp> #include <cfintobj/CFIntTldTableObj.hpp> #include <cfintobj/CFIntTopDomainTableObj.hpp> #include <cfintobj/CFIntTopProjectTableObj.hpp> #include <cfintobj/CFIntURLProtocolTableObj.hpp> namespace cfint { const std::string CFIntMajorVersionTableObj::CLASS_NAME( "CFIntMajorVersionTableObj" ); const std::string CFIntMajorVersionTableObj::TABLE_NAME( "MajorVersion" ); const std::string CFIntMajorVersionTableObj::TABLE_DBNAME( "mjvrdef" ); CFIntMajorVersionTableObj::CFIntMajorVersionTableObj() { schema = NULL; members = new std::map<cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj*>(); allMajorVersion = NULL; indexByTenantIdx = new std::map< cfint::CFIntMajorVersionByTenantIdxKey, std::map< cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj*>*>(); indexBySubProjectIdx = new std::map< cfint::CFIntMajorVersionBySubProjectIdxKey, std::map< cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj*>*>(); indexByNameIdx = new std::map< cfint::CFIntMajorVersionByNameIdxKey, cfint::ICFIntMajorVersionObj*>(); } CFIntMajorVersionTableObj::CFIntMajorVersionTableObj( cfint::ICFIntSchemaObj* argSchema ) { schema = dynamic_cast<cfint::ICFIntSchemaObj*>( argSchema ); members = new std::map<cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj*>(); allMajorVersion = NULL; indexByTenantIdx = new std::map< cfint::CFIntMajorVersionByTenantIdxKey, std::map< cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj*>*>(); indexBySubProjectIdx = new std::map< cfint::CFIntMajorVersionBySubProjectIdxKey, std::map< cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj*>*>(); indexByNameIdx = new std::map< cfint::CFIntMajorVersionByNameIdxKey, cfint::ICFIntMajorVersionObj*>(); } CFIntMajorVersionTableObj::~CFIntMajorVersionTableObj() { minimizeMemory(); if( indexByTenantIdx != NULL ) { delete indexByTenantIdx; indexByTenantIdx = NULL; } if( indexBySubProjectIdx != NULL ) { delete indexBySubProjectIdx; indexBySubProjectIdx = NULL; } if( indexByNameIdx != NULL ) { delete indexByNameIdx; indexByNameIdx = NULL; } if( members != NULL ) { cfint::ICFIntMajorVersionObj* curMember; auto membersIter = members->begin(); while( membersIter != members->end() ) { curMember = membersIter->second; if( curMember != NULL ) { delete curMember; } members->erase( membersIter ); membersIter = members->begin(); } delete members; members = NULL; } } cfint::ICFIntSchemaObj* CFIntMajorVersionTableObj::getSchema() { return( schema ); } void CFIntMajorVersionTableObj::setSchema( cfint::ICFIntSchemaObj* value ) { schema = dynamic_cast<cfint::ICFIntSchemaObj*>( value ); } const std::string CFIntMajorVersionTableObj::getTableName() { return( TABLE_NAME ); } const std::string CFIntMajorVersionTableObj::getTableDbName() { return( TABLE_DBNAME ); } const classcode_t* CFIntMajorVersionTableObj::getObjQualifyingClassCode() { return( &cfsec::CFSecTenantBuff::CLASS_CODE ); } void CFIntMajorVersionTableObj::minimizeMemory() { if( allMajorVersion != NULL ) { allMajorVersion->clear(); delete allMajorVersion; allMajorVersion = NULL; } if( indexByTenantIdx != NULL ) { std::map< cfint::CFIntMajorVersionByTenantIdxKey, std::map< cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj*>* >::iterator iterByTenantIdx = indexByTenantIdx->begin(); std::map< cfint::CFIntMajorVersionByTenantIdxKey, std::map< cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj*>* >::iterator endByTenantIdx = indexByTenantIdx->end(); std::map< cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj*>* curByTenantIdx = NULL; while( iterByTenantIdx != endByTenantIdx ) { curByTenantIdx = iterByTenantIdx->second; if( curByTenantIdx != NULL ) { curByTenantIdx->clear(); delete curByTenantIdx; curByTenantIdx = NULL; iterByTenantIdx->second = NULL; } iterByTenantIdx ++; } indexByTenantIdx->clear(); } if( indexBySubProjectIdx != NULL ) { std::map< cfint::CFIntMajorVersionBySubProjectIdxKey, std::map< cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj*>* >::iterator iterBySubProjectIdx = indexBySubProjectIdx->begin(); std::map< cfint::CFIntMajorVersionBySubProjectIdxKey, std::map< cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj*>* >::iterator endBySubProjectIdx = indexBySubProjectIdx->end(); std::map< cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj*>* curBySubProjectIdx = NULL; while( iterBySubProjectIdx != endBySubProjectIdx ) { curBySubProjectIdx = iterBySubProjectIdx->second; if( curBySubProjectIdx != NULL ) { curBySubProjectIdx->clear(); delete curBySubProjectIdx; curBySubProjectIdx = NULL; iterBySubProjectIdx->second = NULL; } iterBySubProjectIdx ++; } indexBySubProjectIdx->clear(); } if( indexByNameIdx != NULL ) { indexByNameIdx->clear(); } if( members != NULL ) { cfint::ICFIntMajorVersionObj* cur = NULL; cfint::ICFIntMajorVersionEditObj* edit = NULL; auto iter = members->begin(); auto end = members->end(); while( iter != end ) { cur = iter->second; if( cur != NULL ) { iter->second = NULL; edit = cur->getEdit(); if( edit != NULL ) { edit->endEdit(); edit = NULL; } delete cur; cur = NULL; } iter ++; } members->clear(); } } cfint::ICFIntMajorVersionObj* CFIntMajorVersionTableObj::newInstance() { cfint::ICFIntMajorVersionObj* inst = dynamic_cast<cfint::ICFIntMajorVersionObj*>( new CFIntMajorVersionObj( schema ) ); return( inst ); } cfint::ICFIntMajorVersionEditObj* CFIntMajorVersionTableObj::newEditInstance( cfint::ICFIntMajorVersionObj* orig ) { cfint::ICFIntMajorVersionEditObj* edit = dynamic_cast<cfint::ICFIntMajorVersionEditObj*>( new CFIntMajorVersionEditObj( orig )); return( edit ); } cfint::ICFIntMajorVersionObj* CFIntMajorVersionTableObj::realizeMajorVersion( cfint::ICFIntMajorVersionObj* Obj ) { static const std::string S_ProcName( "realizeMajorVersion" ); static const std::string S_ExistingObj( "existingObj" ); static const std::string S_KeepObj( "keepObj" ); static const std::string S_Obj( "Obj" ); if( Obj == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 1, S_Obj ); } cfint::ICFIntMajorVersionObj* obj = Obj; cfint::ICFIntMajorVersionObj* existingObj = NULL; cfint::CFIntMajorVersionPKey* pkey = obj->getPKey(); cfint::ICFIntMajorVersionObj* keepObj = NULL; auto searchMembers = members->find( *pkey ); if( searchMembers != members->end() ) { existingObj = searchMembers->second; if( existingObj == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_ExistingObj ); } keepObj = existingObj; pkey = keepObj->getPKey(); /* * We always rebind the data because if we're being called, some index may have been * updated and is refreshing it's data, which may require binding a different lookup key */ // Detach object from alternate and duplicate indexes, leave PKey alone if( indexByTenantIdx != NULL ) { cfint::CFIntMajorVersionByTenantIdxKey keyTenantIdx; keyTenantIdx.setRequiredTenantId( keepObj->getRequiredTenantId() ); auto searchTenantIdx = indexByTenantIdx->find( keyTenantIdx ); if( searchTenantIdx != indexByTenantIdx->end() ) { std::map<cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj*>* mapTenantIdx = searchTenantIdx->second; if( mapTenantIdx != NULL ) { auto removalProbe = mapTenantIdx->find( *(keepObj->getPKey()) ); if( removalProbe != mapTenantIdx->end() ) { mapTenantIdx->erase( removalProbe ); } } } } if( indexBySubProjectIdx != NULL ) { cfint::CFIntMajorVersionBySubProjectIdxKey keySubProjectIdx; keySubProjectIdx.setRequiredTenantId( keepObj->getRequiredTenantId() ); keySubProjectIdx.setRequiredSubProjectId( keepObj->getRequiredSubProjectId() ); auto searchSubProjectIdx = indexBySubProjectIdx->find( keySubProjectIdx ); if( searchSubProjectIdx != indexBySubProjectIdx->end() ) { std::map<cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj*>* mapSubProjectIdx = searchSubProjectIdx->second; if( mapSubProjectIdx != NULL ) { auto removalProbe = mapSubProjectIdx->find( *(keepObj->getPKey()) ); if( removalProbe != mapSubProjectIdx->end() ) { mapSubProjectIdx->erase( removalProbe ); } } } } if( indexByNameIdx != NULL ) { cfint::CFIntMajorVersionByNameIdxKey keyNameIdx; keyNameIdx.setRequiredTenantId( keepObj->getRequiredTenantId() ); keyNameIdx.setRequiredSubProjectId( keepObj->getRequiredSubProjectId() ); keyNameIdx.setRequiredName( keepObj->getRequiredName() ); auto removalProbe = indexByNameIdx->find( keyNameIdx ); if( removalProbe != indexByNameIdx->end() ) { indexByNameIdx->erase( removalProbe ); } } keepObj->setBuff( dynamic_cast<cfint::CFIntMajorVersionBuff*>( Obj->getBuff()->clone() ) ); // Attach new object to alternate and duplicate indexes -- PKey stays stable if( indexByTenantIdx != NULL ) { static const std::string S_ATenantIdxObj( "aTenantIdxObj" ); cfint::ICFIntMajorVersionObj* aTenantIdxObj = dynamic_cast<cfint::ICFIntMajorVersionObj*>( keepObj ); if( aTenantIdxObj == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_ATenantIdxObj ); } cfint::CFIntMajorVersionByTenantIdxKey keyTenantIdx; keyTenantIdx.setRequiredTenantId( keepObj->getRequiredTenantId() ); auto searchIndexByTenantIdx = indexByTenantIdx->find( keyTenantIdx ); if( searchIndexByTenantIdx != indexByTenantIdx->end() ) { std::map<cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj*>* mapTenantIdx = searchIndexByTenantIdx->second; if( mapTenantIdx != NULL ) { mapTenantIdx->insert( std::map< cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj* >::value_type( *(keepObj->getPKey()), aTenantIdxObj ) ); } } } if( indexBySubProjectIdx != NULL ) { static const std::string S_ASubProjectIdxObj( "aSubProjectIdxObj" ); cfint::ICFIntMajorVersionObj* aSubProjectIdxObj = dynamic_cast<cfint::ICFIntMajorVersionObj*>( keepObj ); if( aSubProjectIdxObj == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_ASubProjectIdxObj ); } cfint::CFIntMajorVersionBySubProjectIdxKey keySubProjectIdx; keySubProjectIdx.setRequiredTenantId( keepObj->getRequiredTenantId() ); keySubProjectIdx.setRequiredSubProjectId( keepObj->getRequiredSubProjectId() ); auto searchIndexBySubProjectIdx = indexBySubProjectIdx->find( keySubProjectIdx ); if( searchIndexBySubProjectIdx != indexBySubProjectIdx->end() ) { std::map<cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj*>* mapSubProjectIdx = searchIndexBySubProjectIdx->second; if( mapSubProjectIdx != NULL ) { mapSubProjectIdx->insert( std::map< cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj* >::value_type( *(keepObj->getPKey()), aSubProjectIdxObj ) ); } } } if( indexByNameIdx != NULL ) { static const std::string S_ANameIdxObj( "aNameIdxObj" ); cfint::ICFIntMajorVersionObj* aNameIdxObj = dynamic_cast<cfint::ICFIntMajorVersionObj*>( keepObj ); if( aNameIdxObj == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_ANameIdxObj ); } cfint::CFIntMajorVersionByNameIdxKey keyNameIdx; keyNameIdx.setRequiredTenantId( keepObj->getRequiredTenantId() ); keyNameIdx.setRequiredSubProjectId( keepObj->getRequiredSubProjectId() ); keyNameIdx.setRequiredName( keepObj->getRequiredName() ); indexByNameIdx->insert( std::map< cfint::CFIntMajorVersionByNameIdxKey, cfint::ICFIntMajorVersionObj* >::value_type( keyNameIdx, aNameIdxObj ) ); } if( allMajorVersion != NULL ) { allMajorVersion->insert( std::map< cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj* >::value_type( *(keepObj->getPKey()), keepObj ) ); } } else { keepObj = obj; keepObj->setIsNew( false ); pkey = keepObj->getPKey(); // Attach new object to PKey, all, alternate, and duplicate indexes members->insert( std::map< cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj* >::value_type( *(keepObj->getPKey()), keepObj ) ); // Attach new object to alternate and duplicate indexes -- PKey stay stable if( indexByTenantIdx != NULL ) { static const std::string S_ATenantIdxObj( "aTenantIdxObj" ); cfint::ICFIntMajorVersionObj* aTenantIdxObj = dynamic_cast<cfint::ICFIntMajorVersionObj*>( keepObj ); if( aTenantIdxObj == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_ATenantIdxObj ); } cfint::CFIntMajorVersionByTenantIdxKey keyTenantIdx; keyTenantIdx.setRequiredTenantId( keepObj->getRequiredTenantId() ); auto searchIndexByTenantIdx = indexByTenantIdx->find( keyTenantIdx ); if( searchIndexByTenantIdx != indexByTenantIdx->end() ) { std::map<cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj*>* mapTenantIdx = searchIndexByTenantIdx->second; if( mapTenantIdx != NULL ) { mapTenantIdx->insert( std::map< cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj* >::value_type( *(keepObj->getPKey()), aTenantIdxObj ) ); } } } if( indexBySubProjectIdx != NULL ) { static const std::string S_ASubProjectIdxObj( "aSubProjectIdxObj" ); cfint::ICFIntMajorVersionObj* aSubProjectIdxObj = dynamic_cast<cfint::ICFIntMajorVersionObj*>( keepObj ); if( aSubProjectIdxObj == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_ASubProjectIdxObj ); } cfint::CFIntMajorVersionBySubProjectIdxKey keySubProjectIdx; keySubProjectIdx.setRequiredTenantId( keepObj->getRequiredTenantId() ); keySubProjectIdx.setRequiredSubProjectId( keepObj->getRequiredSubProjectId() ); auto searchIndexBySubProjectIdx = indexBySubProjectIdx->find( keySubProjectIdx ); if( searchIndexBySubProjectIdx != indexBySubProjectIdx->end() ) { std::map<cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj*>* mapSubProjectIdx = searchIndexBySubProjectIdx->second; if( mapSubProjectIdx != NULL ) { mapSubProjectIdx->insert( std::map< cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj* >::value_type( *(keepObj->getPKey()), aSubProjectIdxObj ) ); } } } if( indexByNameIdx != NULL ) { static const std::string S_ANameIdxObj( "aNameIdxObj" ); cfint::ICFIntMajorVersionObj* aNameIdxObj = dynamic_cast<cfint::ICFIntMajorVersionObj*>( keepObj ); if( aNameIdxObj == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_ANameIdxObj ); } cfint::CFIntMajorVersionByNameIdxKey keyNameIdx; keyNameIdx.setRequiredTenantId( keepObj->getRequiredTenantId() ); keyNameIdx.setRequiredSubProjectId( keepObj->getRequiredSubProjectId() ); keyNameIdx.setRequiredName( keepObj->getRequiredName() ); indexByNameIdx->insert( std::map< cfint::CFIntMajorVersionByNameIdxKey, cfint::ICFIntMajorVersionObj* >::value_type( keyNameIdx, aNameIdxObj ) ); } if( allMajorVersion != NULL ) { allMajorVersion->insert( std::map< cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj* >::value_type( *(keepObj->getPKey()), keepObj ) ); } } if( keepObj != obj ) { delete obj; obj = NULL; } // Something is leaking, so I've added this paranoid check if( ( keepObj != existingObj ) && ( existingObj != NULL ) ) { delete existingObj; existingObj = NULL; } return( keepObj ); } void CFIntMajorVersionTableObj::deepDisposeByIdIdx( const int64_t TenantId, const int64_t Id ) { static const std::string S_ProcName( "deepDisposeByIdIdx" ); std::vector<cfint::ICFIntMajorVersionObj*> list; cfint::ICFIntMajorVersionObj* existingObj = readCachedMajorVersionByIdIdx( TenantId, Id ); if( existingObj != NULL ) { list.push_back( existingObj ); } cfint::ICFIntMajorVersionObj* cur = NULL; classcode_t classCode; auto listIter = list.begin(); auto listEnd = list.end(); while( listIter != listEnd ) { cur = *listIter; if( cur != NULL ) { classCode = cur->getClassCode(); if( classCode == cfint::CFIntMajorVersionBuff::CLASS_CODE ) { dynamic_cast<cfint::CFIntMajorVersionTableObj*>( schema->getMajorVersionTableObj() )->reallyDeepDisposeMajorVersion( dynamic_cast<cfint::ICFIntMajorVersionObj*>( cur ) ); } } listIter ++; } } void CFIntMajorVersionTableObj::deepDisposeByTenantIdx( const int64_t TenantId ) { static const std::string S_ProcName( "deepDisposeByTenantIdx" ); std::vector<cfint::ICFIntMajorVersionObj*> list; std::vector<cfint::ICFIntMajorVersionObj*> matchesFound = readCachedMajorVersionByTenantIdx( TenantId ); auto iterMatches = matchesFound.begin(); auto endMatches = matchesFound.end(); while( iterMatches != endMatches ) { if( *iterMatches != NULL ) { list.push_back( *iterMatches ); } iterMatches ++; } cfint::ICFIntMajorVersionObj* cur = NULL; classcode_t classCode; auto listIter = list.begin(); auto listEnd = list.end(); while( listIter != listEnd ) { cur = *listIter; if( cur != NULL ) { classCode = cur->getClassCode(); if( classCode == cfint::CFIntMajorVersionBuff::CLASS_CODE ) { dynamic_cast<cfint::CFIntMajorVersionTableObj*>( schema->getMajorVersionTableObj() )->reallyDeepDisposeMajorVersion( dynamic_cast<cfint::ICFIntMajorVersionObj*>( cur ) ); } } listIter ++; } } void CFIntMajorVersionTableObj::deepDisposeBySubProjectIdx( const int64_t TenantId, const int64_t SubProjectId ) { static const std::string S_ProcName( "deepDisposeBySubProjectIdx" ); std::vector<cfint::ICFIntMajorVersionObj*> list; std::vector<cfint::ICFIntMajorVersionObj*> matchesFound = readCachedMajorVersionBySubProjectIdx( TenantId, SubProjectId ); auto iterMatches = matchesFound.begin(); auto endMatches = matchesFound.end(); while( iterMatches != endMatches ) { if( *iterMatches != NULL ) { list.push_back( *iterMatches ); } iterMatches ++; } cfint::ICFIntMajorVersionObj* cur = NULL; classcode_t classCode; auto listIter = list.begin(); auto listEnd = list.end(); while( listIter != listEnd ) { cur = *listIter; if( cur != NULL ) { classCode = cur->getClassCode(); if( classCode == cfint::CFIntMajorVersionBuff::CLASS_CODE ) { dynamic_cast<cfint::CFIntMajorVersionTableObj*>( schema->getMajorVersionTableObj() )->reallyDeepDisposeMajorVersion( dynamic_cast<cfint::ICFIntMajorVersionObj*>( cur ) ); } } listIter ++; } } void CFIntMajorVersionTableObj::deepDisposeByNameIdx( const int64_t TenantId, const int64_t SubProjectId, const std::string& Name ) { static const std::string S_ProcName( "deepDisposeByNameIdx" ); std::vector<cfint::ICFIntMajorVersionObj*> list; cfint::ICFIntMajorVersionObj* existingObj = readCachedMajorVersionByNameIdx( TenantId, SubProjectId, Name ); if( existingObj != NULL ) { list.push_back( existingObj ); } cfint::ICFIntMajorVersionObj* cur = NULL; classcode_t classCode; auto listIter = list.begin(); auto listEnd = list.end(); while( listIter != listEnd ) { cur = *listIter; if( cur != NULL ) { classCode = cur->getClassCode(); if( classCode == cfint::CFIntMajorVersionBuff::CLASS_CODE ) { dynamic_cast<cfint::CFIntMajorVersionTableObj*>( schema->getMajorVersionTableObj() )->reallyDeepDisposeMajorVersion( dynamic_cast<cfint::ICFIntMajorVersionObj*>( cur ) ); } } listIter ++; } } void CFIntMajorVersionTableObj::reallyDeepDisposeMajorVersion( cfint::ICFIntMajorVersionObj* Obj ) { static const std::string S_ProcName( "reallyDeepDisposeMajorVersion" ); if( Obj == NULL ) { return; } cfint::ICFIntMajorVersionObj* obj = Obj; dynamic_cast<cfint::CFIntMinorVersionTableObj*>( schema->getMinorVersionTableObj() )->deepDisposeByMajorVerIdx( obj->getRequiredTenantId(), obj->getRequiredId() ); classcode_t classCode = obj->getClassCode(); if( classCode == cfint::CFIntMajorVersionBuff::CLASS_CODE ) { dynamic_cast<cfint::CFIntMajorVersionTableObj*>( schema->getMajorVersionTableObj() )->reallyDetachFromIndexesMajorVersion( dynamic_cast<cfint::ICFIntMajorVersionObj*>( obj ) ); } if( obj->getEdit() != NULL ) { obj->endEdit(); } delete obj; obj = NULL; } cfint::ICFIntMajorVersionObj* CFIntMajorVersionTableObj::createMajorVersion( cfint::ICFIntMajorVersionEditObj* Obj ) { static const std::string S_ProcName( "createMajorVersion" ); static const std::string S_Obj( "obj" ); static const std::string S_Cloneable( "cloneable" ); static const std::string S_ClonedBuff( "clonedbuff" ); CFLIB_EXCEPTION_DECLINFO cfint::ICFIntMajorVersionObj* obj = dynamic_cast<cfint::ICFIntMajorVersionObj*>( Obj->getOrig() ); try { cfint::CFIntMajorVersionBuff* buff = dynamic_cast<cfint::CFIntMajorVersionBuff*>( Obj->getBuff()->clone() ); // C++18 version of create returns a new buffer instance and takes over ownership of the passed-in buffer // MSS TODO WORKING The xmsg client will need to return the buffer instance created by processing // the response message, while xmsg rqst will have to delete the backing store instance // it receives after preparing the reply message so that memory doesn't leak on every request. cflib::ICFLibCloneableObj* cloneable = dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMajorVersion()->createMajorVersion( schema->getAuthorization(), buff ); if( cloneable == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_Cloneable ); } Obj->endEdit(); obj->setBuff( dynamic_cast<cfint::CFIntMajorVersionBuff*>( cloneable ) ); obj = dynamic_cast<cfint::ICFIntMajorVersionObj*>( obj->realize() ); if( obj == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_Obj ); } } CFLIB_EXCEPTION_CATCH_FALLTHROUGH if( ! CFLIB_EXCEPTION_EMPTY ) { if( obj->getEdit() != NULL ) { obj->endEdit(); } if( obj->getIsNew() ) { delete obj; obj = NULL; } CFLIB_EXCEPTION_RETHROW_CFLIBEXCEPTION } return( obj ); } cfint::ICFIntMajorVersionObj* CFIntMajorVersionTableObj::readMajorVersion( cfint::CFIntMajorVersionPKey* pkey, bool forceRead ) { static const std::string S_Obj( "obj" ); static const std::string S_Realized( "realized" ); static const std::string S_ProcName( "readMajorVersion" ); cfint::ICFIntMajorVersionObj* obj = NULL; cfint::ICFIntMajorVersionObj* realized = NULL; if( ! forceRead ) { auto searchMembers = members->find( *pkey ); if( searchMembers != members->end() ) { // obj could be NULL if cache misses is enabled obj = searchMembers->second; realized = obj; } } if( forceRead || ( obj == NULL ) ) { cfint::CFIntMajorVersionBuff* readBuff = dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMajorVersion()->readDerivedByIdIdx( schema->getAuthorization(), pkey->getRequiredTenantId(), pkey->getRequiredId() ); if( readBuff != NULL ) { obj = dynamic_cast<cfint::CFIntMajorVersionTableObj*>( schema->getMajorVersionTableObj() )->newInstance(); obj->setBuff( readBuff ); realized = dynamic_cast<cfint::ICFIntMajorVersionObj*>( obj->realize() ); if( realized == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_Realized ); } // No need to delete obj -- realize() auto-destructs the instance it decided to discard obj = NULL; } } return( realized ); } cfint::ICFIntMajorVersionObj* CFIntMajorVersionTableObj::lockMajorVersion( cfint::CFIntMajorVersionPKey* pkey ) { static const std::string S_ProcName( "lockMajorVersion" ); cfint::ICFIntMajorVersionObj* locked = NULL; cfint::CFIntMajorVersionBuff* lockBuff = dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMajorVersion()->lockDerived( schema->getAuthorization(), pkey ); if( lockBuff != NULL ) { locked = dynamic_cast<cfint::CFIntMajorVersionTableObj*>( schema->getMajorVersionTableObj() )->newInstance(); locked->setBuff( lockBuff ); locked = dynamic_cast<cfint::ICFIntMajorVersionObj*>( locked->realize() ); } else { return( NULL ); } return( locked ); } std::vector<cfint::ICFIntMajorVersionObj*> CFIntMajorVersionTableObj::readAllMajorVersion( bool forceRead ) { static const std::string S_ProcName( "readAllMajorVersion" ); static const std::string S_Idx( "idx" ); static const std::string S_Realized( "realized" ); CFLIB_EXCEPTION_DECLINFO cfint::ICFIntMajorVersionObj* realized = NULL; if( forceRead || ( allMajorVersion == NULL ) ) { std::map<cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj*>* map = new std::map<cfint::CFIntMajorVersionPKey,cfint::ICFIntMajorVersionObj*>(); allMajorVersion = map; std::TCFLibOwningVector<cfint::CFIntMajorVersionBuff*> buffList = dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMajorVersion()->readAllDerived( schema->getAuthorization() ); cfint::CFIntMajorVersionBuff* buff = NULL; cfint::ICFIntMajorVersionObj* obj = NULL; try { for( size_t idx = 0; idx < buffList.size(); idx ++ ) { buff = buffList[ idx ]; buffList[ idx ] = NULL; obj = newInstance(); obj->setBuff( buff ); realized = dynamic_cast<cfint::ICFIntMajorVersionObj*>( obj->realize() ); if( realized == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_Realized ); } allMajorVersion->insert( std::map< cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj* >::value_type( *(realized->getPKey()), realized ) ); // No need to delete obj -- realize() auto-destructs the instance it decided to discard obj = NULL; } } CFLIB_EXCEPTION_CATCH_FALLTHROUGH if( ( obj != NULL ) && obj->getIsNew() ) { delete obj; obj = NULL; } CFLIB_EXCEPTION_RETHROW_CFLIBEXCEPTION } size_t len = allMajorVersion->size(); std::vector<cfint::ICFIntMajorVersionObj*> arr; auto valIter = allMajorVersion->begin(); size_t idx = 0; while( valIter != allMajorVersion->end() ) { arr.push_back( valIter->second ); valIter ++; } return( arr ); } cfint::ICFIntMajorVersionObj* CFIntMajorVersionTableObj::readMajorVersionByIdIdx( const int64_t TenantId, const int64_t Id, bool forceRead ) { static const std::string S_ProcName( "readMajorVersionByIdIdx" ); static const std::string S_Realized( "realized" ); cfint::CFIntMajorVersionPKey pkey; pkey.setRequiredTenantId( TenantId ); pkey.setRequiredId( Id ); cfint::ICFIntMajorVersionObj* obj = readMajorVersion( &pkey, forceRead ); return( obj ); } std::vector<cfint::ICFIntMajorVersionObj*> CFIntMajorVersionTableObj::readMajorVersionByTenantIdx( const int64_t TenantId, bool forceRead ) { static const std::string S_ProcName( "readMajorVersionByTenantIdx" ); static const std::string S_Idx( "idx" ); static const std::string S_Obj( "obj" ); static const std::string S_Realized( "realized" ); cfint::CFIntMajorVersionByTenantIdxKey key; key.setRequiredTenantId( TenantId ); std::map<cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj*>* dict; std::map<cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj*>* oldDict; if( indexByTenantIdx == NULL ) { indexByTenantIdx = new std::map< cfint::CFIntMajorVersionByTenantIdxKey, std::map< cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj*>*>(); } auto searchIndexByTenantIdx = indexByTenantIdx->find( key ); if( searchIndexByTenantIdx != indexByTenantIdx->end() ) { oldDict = searchIndexByTenantIdx->second; } else { oldDict = NULL; } if( ( oldDict != NULL ) && ( ! forceRead ) ) { dict = oldDict; } else { dict = new std::map<cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj*>(); cfint::ICFIntMajorVersionObj* obj; std::TCFLibOwningVector<cfint::CFIntMajorVersionBuff*> buffList = dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMajorVersion()->readDerivedByTenantIdx( schema->getAuthorization(), TenantId ); cfint::CFIntMajorVersionBuff* buff; for( size_t idx = 0; idx < buffList.size(); idx ++ ) { buff = buffList[ idx ]; buffList[ idx ] = NULL; obj = dynamic_cast<cfint::CFIntMajorVersionTableObj*>( schema->getMajorVersionTableObj() )->newInstance(); if( obj == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_Obj ); } obj->setBuff( buff ); cfint::ICFIntMajorVersionObj* realized = dynamic_cast<cfint::ICFIntMajorVersionObj*>( obj->realize() ); if( realized == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_Realized ); } dict->insert( std::map< cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj* >::value_type( *(realized->getPKey()), realized ) ); // No need to delete obj -- realize() auto-destructs the instance it decided to discard obj = NULL; } if( oldDict != NULL ) { indexByTenantIdx->erase( searchIndexByTenantIdx ); delete oldDict; oldDict = NULL; } indexByTenantIdx->insert( std::map< cfint::CFIntMajorVersionByTenantIdxKey, std::map< cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj* >* >::value_type( key, dict ) ); } size_t len = dict->size(); std::vector<cfint::ICFIntMajorVersionObj*> arr; arr.reserve( len ); auto valIter = dict->begin(); while( valIter != dict->end() ) { arr.push_back( valIter->second ); valIter ++; } return( arr ); } std::vector<cfint::ICFIntMajorVersionObj*> CFIntMajorVersionTableObj::readMajorVersionBySubProjectIdx( const int64_t TenantId, const int64_t SubProjectId, bool forceRead ) { static const std::string S_ProcName( "readMajorVersionBySubProjectIdx" ); static const std::string S_Idx( "idx" ); static const std::string S_Obj( "obj" ); static const std::string S_Realized( "realized" ); cfint::CFIntMajorVersionBySubProjectIdxKey key; key.setRequiredTenantId( TenantId ); key.setRequiredSubProjectId( SubProjectId ); std::map<cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj*>* dict; std::map<cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj*>* oldDict; if( indexBySubProjectIdx == NULL ) { indexBySubProjectIdx = new std::map< cfint::CFIntMajorVersionBySubProjectIdxKey, std::map< cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj*>*>(); } auto searchIndexBySubProjectIdx = indexBySubProjectIdx->find( key ); if( searchIndexBySubProjectIdx != indexBySubProjectIdx->end() ) { oldDict = searchIndexBySubProjectIdx->second; } else { oldDict = NULL; } if( ( oldDict != NULL ) && ( ! forceRead ) ) { dict = oldDict; } else { dict = new std::map<cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj*>(); cfint::ICFIntMajorVersionObj* obj; std::TCFLibOwningVector<cfint::CFIntMajorVersionBuff*> buffList = dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMajorVersion()->readDerivedBySubProjectIdx( schema->getAuthorization(), TenantId, SubProjectId ); cfint::CFIntMajorVersionBuff* buff; for( size_t idx = 0; idx < buffList.size(); idx ++ ) { buff = buffList[ idx ]; buffList[ idx ] = NULL; obj = dynamic_cast<cfint::CFIntMajorVersionTableObj*>( schema->getMajorVersionTableObj() )->newInstance(); if( obj == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_Obj ); } obj->setBuff( buff ); cfint::ICFIntMajorVersionObj* realized = dynamic_cast<cfint::ICFIntMajorVersionObj*>( obj->realize() ); if( realized == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_Realized ); } dict->insert( std::map< cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj* >::value_type( *(realized->getPKey()), realized ) ); // No need to delete obj -- realize() auto-destructs the instance it decided to discard obj = NULL; } if( oldDict != NULL ) { indexBySubProjectIdx->erase( searchIndexBySubProjectIdx ); delete oldDict; oldDict = NULL; } indexBySubProjectIdx->insert( std::map< cfint::CFIntMajorVersionBySubProjectIdxKey, std::map< cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj* >* >::value_type( key, dict ) ); } size_t len = dict->size(); std::vector<cfint::ICFIntMajorVersionObj*> arr; arr.reserve( len ); auto valIter = dict->begin(); while( valIter != dict->end() ) { arr.push_back( valIter->second ); valIter ++; } return( arr ); } cfint::ICFIntMajorVersionObj* CFIntMajorVersionTableObj::readMajorVersionByNameIdx( const int64_t TenantId, const int64_t SubProjectId, const std::string& Name, bool forceRead ) { static const std::string S_ProcName( "readMajorVersionByNameIdx" ); static const std::string S_Realized( "realized" ); if( indexByNameIdx == NULL ) { indexByNameIdx = new std::map< cfint::CFIntMajorVersionByNameIdxKey, cfint::ICFIntMajorVersionObj*>(); } cfint::CFIntMajorVersionByNameIdxKey key; key.setRequiredTenantId( TenantId ); key.setRequiredSubProjectId( SubProjectId ); key.setRequiredName( Name ); cfint::ICFIntMajorVersionObj* obj = NULL; cfint::ICFIntMajorVersionObj* realized = NULL; if( ! forceRead ) { auto searchIndexByNameIdx = indexByNameIdx->find( key ); if( searchIndexByNameIdx != indexByNameIdx->end() ) { // Note: obj may be null if cache misses is enabled obj = searchIndexByNameIdx->second; realized = obj; } } if( forceRead || ( obj == NULL ) ) { cfint::CFIntMajorVersionBuff* buff = dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMajorVersion()->readDerivedByNameIdx( schema->getAuthorization(), TenantId, SubProjectId, Name ); if( buff != NULL ) { obj = dynamic_cast<cfint::CFIntMajorVersionTableObj*>( schema->getMajorVersionTableObj() )->newInstance(); obj->setBuff( buff ); realized = dynamic_cast<cfint::ICFIntMajorVersionObj*>( obj->realize() ); if( realized == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_Realized ); } indexByNameIdx->insert( std::map< cfint::CFIntMajorVersionByNameIdxKey, cfint::ICFIntMajorVersionObj*>::value_type( key, dynamic_cast<cfint::ICFIntMajorVersionObj*>( realized ) ) ); // No need to delete obj -- realize() auto-destructs the instance it decided to discard obj = realized; } } return( obj ); } cfint::ICFIntMajorVersionObj* CFIntMajorVersionTableObj::readMajorVersionByLookupNameIdx( const int64_t TenantId, const int64_t SubProjectId, const std::string& Name, bool forceRead ) { static const std::string S_Realized( "realized" ); static const std::string S_Obj( "obj" ); static const std::string S_ProcName( "readMajorVersionByLookupNameIdx" ); if( indexByNameIdx == NULL ) { indexByNameIdx = new std::map< cfint::CFIntMajorVersionByNameIdxKey, cfint::ICFIntMajorVersionObj*>(); } cfint::CFIntMajorVersionByNameIdxKey key; key.setRequiredTenantId( TenantId ); key.setRequiredSubProjectId( SubProjectId ); key.setRequiredName( Name ); cfint::ICFIntMajorVersionObj* obj = NULL; cfint::ICFIntMajorVersionObj* realized = NULL; if( ! forceRead ) { auto searchIndexByNameIdx = indexByNameIdx->find( key ); if( searchIndexByNameIdx != indexByNameIdx->end() ) { obj = searchIndexByNameIdx->second; } } if( forceRead || ( obj == NULL ) ) { cfint::CFIntMajorVersionBuff* buff = dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMajorVersion()->readDerivedByLookupNameIdx( schema->getAuthorization(), TenantId, SubProjectId, Name ); if( buff != NULL ) { obj = dynamic_cast<cfint::ICFIntMajorVersionObj*>( dynamic_cast<cfint::CFIntMajorVersionTableObj*>( schema->getMajorVersionTableObj() )->newInstance() ); obj->setBuff( buff ); realized = dynamic_cast<cfint::ICFIntMajorVersionObj*>( obj->realize() ); if( realized == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_Realized ); } indexByNameIdx->insert( std::map< cfint::CFIntMajorVersionByNameIdxKey, cfint::ICFIntMajorVersionObj*>::value_type( key, dynamic_cast<cfint::ICFIntMajorVersionObj*>( realized ) ) ); // No need to delete obj -- realize() auto-destructs the instance it decided to discard obj = realized; } } return( obj ); } cfint::ICFIntMajorVersionObj* CFIntMajorVersionTableObj::readCachedMajorVersion( cfint::CFIntMajorVersionPKey* pkey ) { static const std::string S_Obj( "obj" ); static const std::string S_Realized( "realized" ); static const std::string S_ProcName( "readMajorVersion" ); cfint::ICFIntMajorVersionObj* obj = NULL; cfint::ICFIntMajorVersionObj* realized = NULL; auto searchMembers = members->find( *pkey ); if( searchMembers != members->end() ) { // obj could be NULL if cache misses is enabled obj = searchMembers->second; realized = obj; } return( realized ); } cfint::ICFIntMajorVersionObj* CFIntMajorVersionTableObj::readCachedMajorVersionByIdIdx( const int64_t TenantId, const int64_t Id ) { static const std::string S_ProcName( "readCachedMajorVersionByIdIdx" ); static const std::string S_Realized( "realized" ); cfint::CFIntMajorVersionPKey pkey; pkey.setRequiredTenantId( TenantId ); pkey.setRequiredId( Id ); cfint::ICFIntMajorVersionObj* obj = readCachedMajorVersion( &pkey ); return( obj ); } std::vector<cfint::ICFIntMajorVersionObj*> CFIntMajorVersionTableObj::readCachedMajorVersionByTenantIdx( const int64_t TenantId ) { static const std::string S_ProcName( "readCachedMajorVersionByTenantIdx" ); static const std::string S_Idx( "idx" ); static const std::string S_Obj( "obj" ); static const std::string S_Realized( "realized" ); std::vector<cfint::ICFIntMajorVersionObj*> arr; cfint::CFIntMajorVersionByTenantIdxKey key; key.setRequiredTenantId( TenantId ); std::map<cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj*>* dict; if( indexByTenantIdx == NULL ) { return( arr ); } auto searchIndexByTenantIdx = indexByTenantIdx->find( key ); if( searchIndexByTenantIdx != indexByTenantIdx->end() ) { dict = searchIndexByTenantIdx->second; size_t len = dict->size(); std::vector<cfint::ICFIntMajorVersionObj*> arr; arr.reserve( len ); auto valIter = dict->begin(); while( valIter != dict->end() ) { arr.push_back( valIter->second ); valIter ++; } } else { cfint::ICFIntMajorVersionObj* obj; for( auto iterMembers = members->begin(); iterMembers != members->end(); iterMembers ++ ) { obj = iterMembers->second; if( obj != NULL ) { if( *(dynamic_cast<cfint::CFIntMajorVersionBuff*>( obj->getBuff() ) ) == key ) { arr.push_back( obj ); } } } } return( arr ); } std::vector<cfint::ICFIntMajorVersionObj*> CFIntMajorVersionTableObj::readCachedMajorVersionBySubProjectIdx( const int64_t TenantId, const int64_t SubProjectId ) { static const std::string S_ProcName( "readCachedMajorVersionBySubProjectIdx" ); static const std::string S_Idx( "idx" ); static const std::string S_Obj( "obj" ); static const std::string S_Realized( "realized" ); std::vector<cfint::ICFIntMajorVersionObj*> arr; cfint::CFIntMajorVersionBySubProjectIdxKey key; key.setRequiredTenantId( TenantId ); key.setRequiredSubProjectId( SubProjectId ); std::map<cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj*>* dict; if( indexBySubProjectIdx == NULL ) { return( arr ); } auto searchIndexBySubProjectIdx = indexBySubProjectIdx->find( key ); if( searchIndexBySubProjectIdx != indexBySubProjectIdx->end() ) { dict = searchIndexBySubProjectIdx->second; size_t len = dict->size(); std::vector<cfint::ICFIntMajorVersionObj*> arr; arr.reserve( len ); auto valIter = dict->begin(); while( valIter != dict->end() ) { arr.push_back( valIter->second ); valIter ++; } } else { cfint::ICFIntMajorVersionObj* obj; for( auto iterMembers = members->begin(); iterMembers != members->end(); iterMembers ++ ) { obj = iterMembers->second; if( obj != NULL ) { if( *(dynamic_cast<cfint::CFIntMajorVersionBuff*>( obj->getBuff() ) ) == key ) { arr.push_back( obj ); } } } } return( arr ); } cfint::ICFIntMajorVersionObj* CFIntMajorVersionTableObj::readCachedMajorVersionByNameIdx( const int64_t TenantId, const int64_t SubProjectId, const std::string& Name ) { static const std::string S_ProcName( "readCachedMajorVersionByNameIdx" ); static const std::string S_Realized( "realized" ); if( indexByNameIdx == NULL ) { indexByNameIdx = new std::map< cfint::CFIntMajorVersionByNameIdxKey, cfint::ICFIntMajorVersionObj*>(); } cfint::CFIntMajorVersionByNameIdxKey key; key.setRequiredTenantId( TenantId ); key.setRequiredSubProjectId( SubProjectId ); key.setRequiredName( Name ); cfint::ICFIntMajorVersionObj* obj = NULL; auto searchIndexByNameIdx = indexByNameIdx->find( key ); if( searchIndexByNameIdx != indexByNameIdx->end() ) { // Note: obj may be null if cache misses is enabled obj = searchIndexByNameIdx->second; } else { for( auto iterMembers = members->begin(); ( obj == NULL ) && ( iterMembers != members->end() ); iterMembers ++ ) { obj = iterMembers->second; if( obj != NULL ) { if( *(dynamic_cast<cfint::CFIntMajorVersionBuff*>( obj->getBuff() ) ) != key ) { obj = NULL; } } } } return( obj ); } cfint::ICFIntMajorVersionObj* CFIntMajorVersionTableObj::readCachedMajorVersionByLookupNameIdx( const int64_t TenantId, const int64_t SubProjectId, const std::string& Name ) { static const std::string S_Realized( "realized" ); static const std::string S_Obj( "obj" ); static const std::string S_ProcName( "readCachedMajorVersionByLookupNameIdx" ); if( indexByNameIdx == NULL ) { indexByNameIdx = new std::map< cfint::CFIntMajorVersionByNameIdxKey, cfint::ICFIntMajorVersionObj*>(); } cfint::CFIntMajorVersionByNameIdxKey key; key.setRequiredTenantId( TenantId ); key.setRequiredSubProjectId( SubProjectId ); key.setRequiredName( Name ); cfint::ICFIntMajorVersionObj* obj = NULL; cfint::ICFIntMajorVersionObj* realized = NULL; auto searchIndexByNameIdx = indexByNameIdx->find( key ); if( searchIndexByNameIdx != indexByNameIdx->end() ) { obj = searchIndexByNameIdx->second; } else { for( auto iterMembers = members->begin(); ( obj == NULL ) && ( iterMembers != members->end() ); iterMembers ++ ) { obj = iterMembers->second; if( obj != NULL ) { if( *(dynamic_cast<cfint::CFIntMajorVersionBuff*>( obj->getBuff() ) ) != key ) { obj = NULL; } } } } return( obj ); } cfint::ICFIntMajorVersionObj* CFIntMajorVersionTableObj::updateMajorVersion( cfint::ICFIntMajorVersionEditObj* Obj ) { static const std::string S_ProcName( "updateMajorVersion" ); static const std::string S_Obj( "obj" ); static const std::string S_Updated( "updated" ); CFLIB_EXCEPTION_DECLINFO cfint::ICFIntMajorVersionObj* obj = dynamic_cast<cfint::ICFIntMajorVersionObj*>( Obj->getOrig() ); try { cfint::CFIntMajorVersionBuff* updated = dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMajorVersion()->updateMajorVersion( schema->getAuthorization(), dynamic_cast<cfint::CFIntMajorVersionBuff*>( Obj->getMajorVersionBuff()->clone() ) ); if( updated == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_Updated ); } obj = dynamic_cast<cfint::ICFIntMajorVersionObj*>( dynamic_cast<cfint::CFIntMajorVersionTableObj*>( schema->getMajorVersionTableObj() )->newInstance() ); obj->setBuff( updated ); obj = dynamic_cast<cfint::ICFIntMajorVersionObj*>( obj->realize() ); if( obj == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_Obj ); } if( obj->getEdit() != NULL ) { obj->endEdit(); } } CFLIB_EXCEPTION_CATCH_FALLTHROUGH if( ! CFLIB_EXCEPTION_EMPTY ) { if( obj->getEdit() != NULL ) { obj->endEdit(); } CFLIB_EXCEPTION_RETHROW_CFLIBEXCEPTION } return( obj ); } void CFIntMajorVersionTableObj::deleteMajorVersion( cfint::ICFIntMajorVersionEditObj* Obj ) { cfint::ICFIntMajorVersionObj* obj = Obj; dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMajorVersion()->deleteMajorVersion( schema->getAuthorization(), obj->getMajorVersionBuff() ); deepDisposeByIdIdx( obj->getRequiredTenantId(), obj->getRequiredId() ); } void CFIntMajorVersionTableObj::deleteMajorVersionByIdIdx( const int64_t TenantId, const int64_t Id ) { cfint::CFIntMajorVersionPKey pkey; pkey.setRequiredTenantId( TenantId ); pkey.setRequiredId( Id ); cfint::ICFIntMajorVersionObj* obj = readMajorVersion( &pkey, true ); if( obj != NULL ) { cfint::ICFIntMajorVersionEditObj* editObj = dynamic_cast<cfint::ICFIntMajorVersionEditObj*>( obj->getEdit() ); if( editObj == NULL ) { editObj = dynamic_cast<cfint::ICFIntMajorVersionEditObj*>( obj->beginEdit() ); } if( editObj != NULL ) { editObj->deleteInstance(); editObj = NULL; } } } void CFIntMajorVersionTableObj::deleteMajorVersionByTenantIdx( const int64_t TenantId ) { dynamic_cast<cfint::ICFIntSchema*>( schema->getBackingStore() )->getTableMajorVersion()->deleteMajorVersionByTenantIdx( schema->getAuthorization(), TenantId ); deepDisposeByTenantIdx( TenantId ); } void CFIntMajorVersionTableObj::deleteMajorVersionBySubProjectIdx( const int64_t TenantId, const int64_t SubProjectId ) { dynamic_cast<cfint::ICFIntSchema*>( schema->getBackingStore() )->getTableMajorVersion()->deleteMajorVersionBySubProjectIdx( schema->getAuthorization(), TenantId, SubProjectId ); deepDisposeBySubProjectIdx( TenantId, SubProjectId ); } void CFIntMajorVersionTableObj::deleteMajorVersionByNameIdx( const int64_t TenantId, const int64_t SubProjectId, const std::string& Name ) { if( indexByNameIdx == NULL ) { indexByNameIdx = new std::map< cfint::CFIntMajorVersionByNameIdxKey, cfint::ICFIntMajorVersionObj*>(); } cfint::CFIntMajorVersionByNameIdxKey key; key.setRequiredTenantId( TenantId ); key.setRequiredSubProjectId( SubProjectId ); key.setRequiredName( Name ); cfint::ICFIntMajorVersionObj* obj = NULL; auto searchIndexByNameIdx = indexByNameIdx->find( key ); if( searchIndexByNameIdx != indexByNameIdx->end() ) { dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMajorVersion()->deleteMajorVersionByNameIdx( schema->getAuthorization(), TenantId, SubProjectId, Name ); } else { dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMajorVersion()->deleteMajorVersionByNameIdx( schema->getAuthorization(), TenantId, SubProjectId, Name ); } deepDisposeByNameIdx( TenantId, SubProjectId, Name ); } void CFIntMajorVersionTableObj::reallyDetachFromIndexesMajorVersion( cfint::ICFIntMajorVersionObj* Obj ) { static const std::string S_ProcName( "reallyDetachFromIndexesMajorVersion" ); static const std::string S_Obj( "Obj" ); static const std::string S_ExistingObj( "ExistingObj" ); if( Obj == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 1, S_Obj ); } cfint::ICFIntMajorVersionObj* obj = Obj; cfint::CFIntMajorVersionPKey* pkey = obj->getPKey(); auto searchMembers = members->find( *pkey ); if( searchMembers != members->end() ) { cfint::ICFIntMajorVersionObj* existingObj = searchMembers->second; if( existingObj == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_ExistingObj ); } if( indexByTenantIdx != NULL ) { cfint::CFIntMajorVersionByTenantIdxKey keyTenantIdx; keyTenantIdx.setRequiredTenantId( obj->getRequiredTenantId() ); auto searchTenantIdx = indexByTenantIdx->find( keyTenantIdx ); if( searchTenantIdx != indexByTenantIdx->end() ) { std::map<cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj*>* mapTenantIdx = searchTenantIdx->second; if( mapTenantIdx != NULL ) { auto removalProbe = mapTenantIdx->find( *(obj->getPKey()) ); if( removalProbe != mapTenantIdx->end() ) { mapTenantIdx->erase( removalProbe ); if( mapTenantIdx->empty() ) { delete mapTenantIdx; mapTenantIdx = NULL; indexByTenantIdx->erase( searchTenantIdx ); } } } } } if( indexBySubProjectIdx != NULL ) { cfint::CFIntMajorVersionBySubProjectIdxKey keySubProjectIdx; keySubProjectIdx.setRequiredTenantId( obj->getRequiredTenantId() ); keySubProjectIdx.setRequiredSubProjectId( obj->getRequiredSubProjectId() ); auto searchSubProjectIdx = indexBySubProjectIdx->find( keySubProjectIdx ); if( searchSubProjectIdx != indexBySubProjectIdx->end() ) { std::map<cfint::CFIntMajorVersionPKey, cfint::ICFIntMajorVersionObj*>* mapSubProjectIdx = searchSubProjectIdx->second; if( mapSubProjectIdx != NULL ) { auto removalProbe = mapSubProjectIdx->find( *(obj->getPKey()) ); if( removalProbe != mapSubProjectIdx->end() ) { mapSubProjectIdx->erase( removalProbe ); if( mapSubProjectIdx->empty() ) { delete mapSubProjectIdx; mapSubProjectIdx = NULL; indexBySubProjectIdx->erase( searchSubProjectIdx ); } } } } } if( indexByNameIdx != NULL ) { cfint::CFIntMajorVersionByNameIdxKey keyNameIdx; keyNameIdx.setRequiredTenantId( obj->getRequiredTenantId() ); keyNameIdx.setRequiredSubProjectId( obj->getRequiredSubProjectId() ); keyNameIdx.setRequiredName( obj->getRequiredName() ); auto removalProbe = indexByNameIdx->find( keyNameIdx ); if( removalProbe != indexByNameIdx->end() ) { indexByNameIdx->erase( removalProbe ); } } members->erase( searchMembers ); } } }
39.738397
206
0.720128
[ "object", "vector" ]
4edd846a6883f72f362f25095e5f93615a3cf004
743
cpp
C++
consoleLoadingBar/consoleLoadingBar.cpp
Sharkbyteprojects/consoleLoadingBar-win
64b81c566d86a83078e339c613b29eb339612d77
[ "MIT" ]
null
null
null
consoleLoadingBar/consoleLoadingBar.cpp
Sharkbyteprojects/consoleLoadingBar-win
64b81c566d86a83078e339c613b29eb339612d77
[ "MIT" ]
null
null
null
consoleLoadingBar/consoleLoadingBar.cpp
Sharkbyteprojects/consoleLoadingBar-win
64b81c566d86a83078e339c613b29eb339612d77
[ "MIT" ]
null
null
null
#include <iostream> #include "../loadingBarConsole/loadingBarConsole.h" #include <thread> #include <chrono> void rengine(CloadingBarConsole* c, bool* ok) { while (*ok){ c->render();//RENDER THE BAR std::this_thread::sleep_for(std::chrono::milliseconds(5)); } } int main() { std::cout << "LOADING SOMETHING" << std::endl; CloadingBarConsole l; bool sok = true; std::thread renderer(rengine, &l, &sok); for (int x = 0; x <= 100; x++) { if (x <= 40) l.setColorCode(//SET COLOR CODE x < 20 ? colorcode::CANCEL : x == 40 ? colorcode::OK : colorcode::SUSPEND ); l.setPercent(x);//SET PERCENT VALUE std::this_thread::sleep_for(std::chrono::milliseconds(x < 40 ? 1500 : 900)); } sok = false; renderer.join(); }
23.21875
78
0.641992
[ "render" ]
4ede157e955b795507aea29bfb71a5aba462bf27
1,900
cpp
C++
source/ast/abstraction.cpp
k1r0d3v/lambda
3db2e5895dd19f1111845b6f47840b6f9eff3c36
[ "MIT" ]
null
null
null
source/ast/abstraction.cpp
k1r0d3v/lambda
3db2e5895dd19f1111845b6f47840b6f9eff3c36
[ "MIT" ]
null
null
null
source/ast/abstraction.cpp
k1r0d3v/lambda
3db2e5895dd19f1111845b6f47840b6f9eff3c36
[ "MIT" ]
null
null
null
#include <ast/abstraction.hpp> #include <ast/types/arrow_type.hpp> #include <ast/node_visitor.hpp> #include <ast/context.hpp> #include <ast/exception.hpp> #include <ast/types/undefined_type.hpp> using namespace ast; Abstraction::Abstraction(Variable::Pointer variable, Node::Pointer body) : Node(NodeKind::Abstraction), mVariable(std::move(variable)), mBody(std::move(body)) { } Node::Pointer Abstraction::evaluate(Context &context) const { if (!mResolved) { // Resolve id's auto abstraction = Node::cast<Abstraction>(Node::transform(this->copy(), IdentifierResolver(context))); abstraction->mResolved = true; return abstraction; } return this->copy(); } Type::Pointer Abstraction::typecheck(TypeContext &context) { // Push argument auto lastArgumentType = context.setTypeFor(mVariable->name(), mVariable->type()); // Resolve aliases Type::Pointer varType = mVariable->type(); varType->resolve(context); // Typecheck auto arrowType = Type::make<ArrowType>(varType, mBody->typecheck(context)); // Pop argument context.setTypeFor(mVariable->name(), lastArgumentType); return arrowType; } Node::Pointer Abstraction::copy() const { return Node::make<Abstraction>(Node::cast<Variable>(mVariable->copy()), mBody->copy()); } string Abstraction::toString() const { auto os = std::ostringstream(); os << "(\xce\xbb" << mVariable->toString() << " : " << mVariable->type()->toString() << ". " << mBody->toString() << ")"; return os.str(); } Node::Pointer Abstraction::transform(NodeVisitor *visitor) { auto self = visitor->visitAbstraction(this); if (self != nullptr) return self; mVariable = Node::cast<Variable>(Node::transform(mVariable, visitor)); mBody = Node::transform(mBody, visitor); return nullptr; }
26.760563
111
0.655263
[ "transform" ]
4ee0e83f5cbb8ba95e58ea43dcb66dca6526d5cd
327,004
cc
C++
src/proto/epics_event.pb.cc
carneirofc/epics-archiver-pb-parser
66483108f168bc6542278af80be2b96b9f0e6f0b
[ "Unlicense" ]
null
null
null
src/proto/epics_event.pb.cc
carneirofc/epics-archiver-pb-parser
66483108f168bc6542278af80be2b96b9f0e6f0b
[ "Unlicense" ]
null
null
null
src/proto/epics_event.pb.cc
carneirofc/epics-archiver-pb-parser
66483108f168bc6542278af80be2b96b9f0e6f0b
[ "Unlicense" ]
1
2021-11-18T16:49:56.000Z
2021-11-18T16:49:56.000Z
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: epics_event.proto #include "epics_event.pb.h" #include <algorithm> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/wire_format_lite.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> PROTOBUF_PRAGMA_INIT_SEG namespace EPICS { constexpr FieldValue::FieldValue( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : name_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , val_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string){} struct FieldValueDefaultTypeInternal { constexpr FieldValueDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~FieldValueDefaultTypeInternal() {} union { FieldValue _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT FieldValueDefaultTypeInternal _FieldValue_default_instance_; constexpr ScalarString::ScalarString( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : fieldvalues_() , val_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , secondsintoyear_(0u) , nano_(0u) , severity_(0) , status_(0) , repeatcount_(0u) , fieldactualchange_(false){} struct ScalarStringDefaultTypeInternal { constexpr ScalarStringDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~ScalarStringDefaultTypeInternal() {} union { ScalarString _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT ScalarStringDefaultTypeInternal _ScalarString_default_instance_; constexpr ScalarByte::ScalarByte( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : fieldvalues_() , val_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , secondsintoyear_(0u) , nano_(0u) , severity_(0) , status_(0) , repeatcount_(0u) , fieldactualchange_(false){} struct ScalarByteDefaultTypeInternal { constexpr ScalarByteDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~ScalarByteDefaultTypeInternal() {} union { ScalarByte _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT ScalarByteDefaultTypeInternal _ScalarByte_default_instance_; constexpr ScalarShort::ScalarShort( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : fieldvalues_() , secondsintoyear_(0u) , nano_(0u) , val_(0) , severity_(0) , status_(0) , repeatcount_(0u) , fieldactualchange_(false){} struct ScalarShortDefaultTypeInternal { constexpr ScalarShortDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~ScalarShortDefaultTypeInternal() {} union { ScalarShort _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT ScalarShortDefaultTypeInternal _ScalarShort_default_instance_; constexpr ScalarInt::ScalarInt( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : fieldvalues_() , secondsintoyear_(0u) , nano_(0u) , val_(0) , severity_(0) , status_(0) , repeatcount_(0u) , fieldactualchange_(false){} struct ScalarIntDefaultTypeInternal { constexpr ScalarIntDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~ScalarIntDefaultTypeInternal() {} union { ScalarInt _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT ScalarIntDefaultTypeInternal _ScalarInt_default_instance_; constexpr ScalarEnum::ScalarEnum( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : fieldvalues_() , secondsintoyear_(0u) , nano_(0u) , val_(0) , severity_(0) , status_(0) , repeatcount_(0u) , fieldactualchange_(false){} struct ScalarEnumDefaultTypeInternal { constexpr ScalarEnumDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~ScalarEnumDefaultTypeInternal() {} union { ScalarEnum _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT ScalarEnumDefaultTypeInternal _ScalarEnum_default_instance_; constexpr ScalarFloat::ScalarFloat( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : fieldvalues_() , secondsintoyear_(0u) , nano_(0u) , val_(0) , severity_(0) , status_(0) , repeatcount_(0u) , fieldactualchange_(false){} struct ScalarFloatDefaultTypeInternal { constexpr ScalarFloatDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~ScalarFloatDefaultTypeInternal() {} union { ScalarFloat _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT ScalarFloatDefaultTypeInternal _ScalarFloat_default_instance_; constexpr ScalarDouble::ScalarDouble( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : fieldvalues_() , secondsintoyear_(0u) , nano_(0u) , val_(0) , severity_(0) , status_(0) , repeatcount_(0u) , fieldactualchange_(false){} struct ScalarDoubleDefaultTypeInternal { constexpr ScalarDoubleDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~ScalarDoubleDefaultTypeInternal() {} union { ScalarDouble _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT ScalarDoubleDefaultTypeInternal _ScalarDouble_default_instance_; constexpr VectorString::VectorString( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : val_() , fieldvalues_() , secondsintoyear_(0u) , nano_(0u) , severity_(0) , status_(0) , repeatcount_(0u) , fieldactualchange_(false){} struct VectorStringDefaultTypeInternal { constexpr VectorStringDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~VectorStringDefaultTypeInternal() {} union { VectorString _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT VectorStringDefaultTypeInternal _VectorString_default_instance_; constexpr VectorChar::VectorChar( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : fieldvalues_() , val_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , secondsintoyear_(0u) , nano_(0u) , severity_(0) , status_(0) , repeatcount_(0u) , fieldactualchange_(false){} struct VectorCharDefaultTypeInternal { constexpr VectorCharDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~VectorCharDefaultTypeInternal() {} union { VectorChar _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT VectorCharDefaultTypeInternal _VectorChar_default_instance_; constexpr VectorShort::VectorShort( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : val_() , _val_cached_byte_size_() , fieldvalues_() , secondsintoyear_(0u) , nano_(0u) , severity_(0) , status_(0) , repeatcount_(0u) , fieldactualchange_(false){} struct VectorShortDefaultTypeInternal { constexpr VectorShortDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~VectorShortDefaultTypeInternal() {} union { VectorShort _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT VectorShortDefaultTypeInternal _VectorShort_default_instance_; constexpr VectorInt::VectorInt( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : val_() , fieldvalues_() , secondsintoyear_(0u) , nano_(0u) , severity_(0) , status_(0) , repeatcount_(0u) , fieldactualchange_(false){} struct VectorIntDefaultTypeInternal { constexpr VectorIntDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~VectorIntDefaultTypeInternal() {} union { VectorInt _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT VectorIntDefaultTypeInternal _VectorInt_default_instance_; constexpr VectorEnum::VectorEnum( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : val_() , _val_cached_byte_size_() , fieldvalues_() , secondsintoyear_(0u) , nano_(0u) , severity_(0) , status_(0) , repeatcount_(0u) , fieldactualchange_(false){} struct VectorEnumDefaultTypeInternal { constexpr VectorEnumDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~VectorEnumDefaultTypeInternal() {} union { VectorEnum _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT VectorEnumDefaultTypeInternal _VectorEnum_default_instance_; constexpr VectorFloat::VectorFloat( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : val_() , fieldvalues_() , secondsintoyear_(0u) , nano_(0u) , severity_(0) , status_(0) , repeatcount_(0u) , fieldactualchange_(false){} struct VectorFloatDefaultTypeInternal { constexpr VectorFloatDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~VectorFloatDefaultTypeInternal() {} union { VectorFloat _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT VectorFloatDefaultTypeInternal _VectorFloat_default_instance_; constexpr VectorDouble::VectorDouble( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : val_() , fieldvalues_() , secondsintoyear_(0u) , nano_(0u) , severity_(0) , status_(0) , repeatcount_(0u) , fieldactualchange_(false){} struct VectorDoubleDefaultTypeInternal { constexpr VectorDoubleDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~VectorDoubleDefaultTypeInternal() {} union { VectorDouble _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT VectorDoubleDefaultTypeInternal _VectorDouble_default_instance_; constexpr V4GenericBytes::V4GenericBytes( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : fieldvalues_() , val_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , secondsintoyear_(0u) , nano_(0u) , severity_(0) , status_(0) , repeatcount_(0u) , fieldactualchange_(false) , usertag_(0u){} struct V4GenericBytesDefaultTypeInternal { constexpr V4GenericBytesDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~V4GenericBytesDefaultTypeInternal() {} union { V4GenericBytes _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT V4GenericBytesDefaultTypeInternal _V4GenericBytes_default_instance_; constexpr PayloadInfo::PayloadInfo( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : headers_() , pvname_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , unused09_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , type_(0) , year_(0) , unused00_(0) , unused01_(0) , unused02_(0) , unused03_(0) , unused04_(0) , unused05_(0) , unused06_(0) , unused07_(0) , unused08_(0) , elementcount_(0){} struct PayloadInfoDefaultTypeInternal { constexpr PayloadInfoDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~PayloadInfoDefaultTypeInternal() {} union { PayloadInfo _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PayloadInfoDefaultTypeInternal _PayloadInfo_default_instance_; } // namespace EPICS static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_epics_5fevent_2eproto[17]; static const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* file_level_enum_descriptors_epics_5fevent_2eproto[1]; static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_epics_5fevent_2eproto = nullptr; const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_epics_5fevent_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { PROTOBUF_FIELD_OFFSET(::EPICS::FieldValue, _has_bits_), PROTOBUF_FIELD_OFFSET(::EPICS::FieldValue, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::EPICS::FieldValue, name_), PROTOBUF_FIELD_OFFSET(::EPICS::FieldValue, val_), 0, 1, PROTOBUF_FIELD_OFFSET(::EPICS::ScalarString, _has_bits_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarString, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::EPICS::ScalarString, secondsintoyear_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarString, nano_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarString, val_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarString, severity_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarString, status_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarString, repeatcount_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarString, fieldvalues_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarString, fieldactualchange_), 1, 2, 0, 3, 4, 5, ~0u, 6, PROTOBUF_FIELD_OFFSET(::EPICS::ScalarByte, _has_bits_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarByte, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::EPICS::ScalarByte, secondsintoyear_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarByte, nano_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarByte, val_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarByte, severity_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarByte, status_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarByte, repeatcount_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarByte, fieldvalues_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarByte, fieldactualchange_), 1, 2, 0, 3, 4, 5, ~0u, 6, PROTOBUF_FIELD_OFFSET(::EPICS::ScalarShort, _has_bits_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarShort, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::EPICS::ScalarShort, secondsintoyear_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarShort, nano_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarShort, val_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarShort, severity_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarShort, status_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarShort, repeatcount_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarShort, fieldvalues_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarShort, fieldactualchange_), 0, 1, 2, 3, 4, 5, ~0u, 6, PROTOBUF_FIELD_OFFSET(::EPICS::ScalarInt, _has_bits_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarInt, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::EPICS::ScalarInt, secondsintoyear_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarInt, nano_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarInt, val_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarInt, severity_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarInt, status_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarInt, repeatcount_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarInt, fieldvalues_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarInt, fieldactualchange_), 0, 1, 2, 3, 4, 5, ~0u, 6, PROTOBUF_FIELD_OFFSET(::EPICS::ScalarEnum, _has_bits_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarEnum, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::EPICS::ScalarEnum, secondsintoyear_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarEnum, nano_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarEnum, val_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarEnum, severity_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarEnum, status_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarEnum, repeatcount_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarEnum, fieldvalues_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarEnum, fieldactualchange_), 0, 1, 2, 3, 4, 5, ~0u, 6, PROTOBUF_FIELD_OFFSET(::EPICS::ScalarFloat, _has_bits_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarFloat, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::EPICS::ScalarFloat, secondsintoyear_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarFloat, nano_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarFloat, val_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarFloat, severity_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarFloat, status_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarFloat, repeatcount_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarFloat, fieldvalues_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarFloat, fieldactualchange_), 0, 1, 2, 3, 4, 5, ~0u, 6, PROTOBUF_FIELD_OFFSET(::EPICS::ScalarDouble, _has_bits_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarDouble, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::EPICS::ScalarDouble, secondsintoyear_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarDouble, nano_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarDouble, val_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarDouble, severity_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarDouble, status_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarDouble, repeatcount_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarDouble, fieldvalues_), PROTOBUF_FIELD_OFFSET(::EPICS::ScalarDouble, fieldactualchange_), 0, 1, 2, 3, 4, 5, ~0u, 6, PROTOBUF_FIELD_OFFSET(::EPICS::VectorString, _has_bits_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorString, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::EPICS::VectorString, secondsintoyear_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorString, nano_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorString, val_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorString, severity_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorString, status_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorString, repeatcount_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorString, fieldvalues_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorString, fieldactualchange_), 0, 1, ~0u, 2, 3, 4, ~0u, 5, PROTOBUF_FIELD_OFFSET(::EPICS::VectorChar, _has_bits_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorChar, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::EPICS::VectorChar, secondsintoyear_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorChar, nano_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorChar, val_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorChar, severity_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorChar, status_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorChar, repeatcount_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorChar, fieldvalues_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorChar, fieldactualchange_), 1, 2, 0, 3, 4, 5, ~0u, 6, PROTOBUF_FIELD_OFFSET(::EPICS::VectorShort, _has_bits_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorShort, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::EPICS::VectorShort, secondsintoyear_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorShort, nano_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorShort, val_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorShort, severity_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorShort, status_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorShort, repeatcount_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorShort, fieldvalues_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorShort, fieldactualchange_), 0, 1, ~0u, 2, 3, 4, ~0u, 5, PROTOBUF_FIELD_OFFSET(::EPICS::VectorInt, _has_bits_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorInt, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::EPICS::VectorInt, secondsintoyear_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorInt, nano_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorInt, val_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorInt, severity_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorInt, status_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorInt, repeatcount_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorInt, fieldvalues_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorInt, fieldactualchange_), 0, 1, ~0u, 2, 3, 4, ~0u, 5, PROTOBUF_FIELD_OFFSET(::EPICS::VectorEnum, _has_bits_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorEnum, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::EPICS::VectorEnum, secondsintoyear_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorEnum, nano_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorEnum, val_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorEnum, severity_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorEnum, status_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorEnum, repeatcount_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorEnum, fieldvalues_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorEnum, fieldactualchange_), 0, 1, ~0u, 2, 3, 4, ~0u, 5, PROTOBUF_FIELD_OFFSET(::EPICS::VectorFloat, _has_bits_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorFloat, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::EPICS::VectorFloat, secondsintoyear_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorFloat, nano_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorFloat, val_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorFloat, severity_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorFloat, status_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorFloat, repeatcount_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorFloat, fieldvalues_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorFloat, fieldactualchange_), 0, 1, ~0u, 2, 3, 4, ~0u, 5, PROTOBUF_FIELD_OFFSET(::EPICS::VectorDouble, _has_bits_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorDouble, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::EPICS::VectorDouble, secondsintoyear_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorDouble, nano_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorDouble, val_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorDouble, severity_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorDouble, status_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorDouble, repeatcount_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorDouble, fieldvalues_), PROTOBUF_FIELD_OFFSET(::EPICS::VectorDouble, fieldactualchange_), 0, 1, ~0u, 2, 3, 4, ~0u, 5, PROTOBUF_FIELD_OFFSET(::EPICS::V4GenericBytes, _has_bits_), PROTOBUF_FIELD_OFFSET(::EPICS::V4GenericBytes, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::EPICS::V4GenericBytes, secondsintoyear_), PROTOBUF_FIELD_OFFSET(::EPICS::V4GenericBytes, nano_), PROTOBUF_FIELD_OFFSET(::EPICS::V4GenericBytes, val_), PROTOBUF_FIELD_OFFSET(::EPICS::V4GenericBytes, severity_), PROTOBUF_FIELD_OFFSET(::EPICS::V4GenericBytes, status_), PROTOBUF_FIELD_OFFSET(::EPICS::V4GenericBytes, repeatcount_), PROTOBUF_FIELD_OFFSET(::EPICS::V4GenericBytes, fieldvalues_), PROTOBUF_FIELD_OFFSET(::EPICS::V4GenericBytes, fieldactualchange_), PROTOBUF_FIELD_OFFSET(::EPICS::V4GenericBytes, usertag_), 1, 2, 0, 3, 4, 5, ~0u, 6, 7, PROTOBUF_FIELD_OFFSET(::EPICS::PayloadInfo, _has_bits_), PROTOBUF_FIELD_OFFSET(::EPICS::PayloadInfo, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::EPICS::PayloadInfo, type_), PROTOBUF_FIELD_OFFSET(::EPICS::PayloadInfo, pvname_), PROTOBUF_FIELD_OFFSET(::EPICS::PayloadInfo, year_), PROTOBUF_FIELD_OFFSET(::EPICS::PayloadInfo, elementcount_), PROTOBUF_FIELD_OFFSET(::EPICS::PayloadInfo, unused00_), PROTOBUF_FIELD_OFFSET(::EPICS::PayloadInfo, unused01_), PROTOBUF_FIELD_OFFSET(::EPICS::PayloadInfo, unused02_), PROTOBUF_FIELD_OFFSET(::EPICS::PayloadInfo, unused03_), PROTOBUF_FIELD_OFFSET(::EPICS::PayloadInfo, unused04_), PROTOBUF_FIELD_OFFSET(::EPICS::PayloadInfo, unused05_), PROTOBUF_FIELD_OFFSET(::EPICS::PayloadInfo, unused06_), PROTOBUF_FIELD_OFFSET(::EPICS::PayloadInfo, unused07_), PROTOBUF_FIELD_OFFSET(::EPICS::PayloadInfo, unused08_), PROTOBUF_FIELD_OFFSET(::EPICS::PayloadInfo, unused09_), PROTOBUF_FIELD_OFFSET(::EPICS::PayloadInfo, headers_), 2, 0, 3, 13, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, ~0u, }; static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, 7, sizeof(::EPICS::FieldValue)}, { 9, 22, sizeof(::EPICS::ScalarString)}, { 30, 43, sizeof(::EPICS::ScalarByte)}, { 51, 64, sizeof(::EPICS::ScalarShort)}, { 72, 85, sizeof(::EPICS::ScalarInt)}, { 93, 106, sizeof(::EPICS::ScalarEnum)}, { 114, 127, sizeof(::EPICS::ScalarFloat)}, { 135, 148, sizeof(::EPICS::ScalarDouble)}, { 156, 169, sizeof(::EPICS::VectorString)}, { 177, 190, sizeof(::EPICS::VectorChar)}, { 198, 211, sizeof(::EPICS::VectorShort)}, { 219, 232, sizeof(::EPICS::VectorInt)}, { 240, 253, sizeof(::EPICS::VectorEnum)}, { 261, 274, sizeof(::EPICS::VectorFloat)}, { 282, 295, sizeof(::EPICS::VectorDouble)}, { 303, 317, sizeof(::EPICS::V4GenericBytes)}, { 326, 346, sizeof(::EPICS::PayloadInfo)}, }; static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = { reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::EPICS::_FieldValue_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::EPICS::_ScalarString_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::EPICS::_ScalarByte_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::EPICS::_ScalarShort_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::EPICS::_ScalarInt_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::EPICS::_ScalarEnum_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::EPICS::_ScalarFloat_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::EPICS::_ScalarDouble_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::EPICS::_VectorString_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::EPICS::_VectorChar_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::EPICS::_VectorShort_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::EPICS::_VectorInt_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::EPICS::_VectorEnum_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::EPICS::_VectorFloat_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::EPICS::_VectorDouble_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::EPICS::_V4GenericBytes_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::EPICS::_PayloadInfo_default_instance_), }; const char descriptor_table_protodef_epics_5fevent_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = "\n\021epics_event.proto\022\005EPICS\"\'\n\nFieldValue" "\022\014\n\004name\030\001 \002(\t\022\013\n\003val\030\002 \002(\t\"\302\001\n\014ScalarSt" "ring\022\027\n\017secondsintoyear\030\001 \002(\r\022\014\n\004nano\030\002 " "\002(\r\022\013\n\003val\030\003 \002(\t\022\023\n\010severity\030\004 \001(\005:\0010\022\021\n" "\006status\030\005 \001(\005:\0010\022\023\n\013repeatcount\030\006 \001(\r\022&\n" "\013fieldvalues\030\007 \003(\0132\021.EPICS.FieldValue\022\031\n" "\021fieldactualchange\030\010 \001(\010\"\300\001\n\nScalarByte\022" "\027\n\017secondsintoyear\030\001 \002(\r\022\014\n\004nano\030\002 \002(\r\022\013" "\n\003val\030\003 \002(\014\022\023\n\010severity\030\004 \001(\005:\0010\022\021\n\006stat" "us\030\005 \001(\005:\0010\022\023\n\013repeatcount\030\006 \001(\r\022&\n\013fiel" "dvalues\030\007 \003(\0132\021.EPICS.FieldValue\022\031\n\021fiel" "dactualchange\030\010 \001(\010\"\301\001\n\013ScalarShort\022\027\n\017s" "econdsintoyear\030\001 \002(\r\022\014\n\004nano\030\002 \002(\r\022\013\n\003va" "l\030\003 \002(\021\022\023\n\010severity\030\004 \001(\005:\0010\022\021\n\006status\030\005" " \001(\005:\0010\022\023\n\013repeatcount\030\006 \001(\r\022&\n\013fieldval" "ues\030\007 \003(\0132\021.EPICS.FieldValue\022\031\n\021fieldact" "ualchange\030\010 \001(\010\"\277\001\n\tScalarInt\022\027\n\017seconds" "intoyear\030\001 \002(\r\022\014\n\004nano\030\002 \002(\r\022\013\n\003val\030\003 \002(" "\017\022\023\n\010severity\030\004 \001(\005:\0010\022\021\n\006status\030\005 \001(\005:\001" "0\022\023\n\013repeatcount\030\006 \001(\r\022&\n\013fieldvalues\030\007 " "\003(\0132\021.EPICS.FieldValue\022\031\n\021fieldactualcha" "nge\030\010 \001(\010\"\300\001\n\nScalarEnum\022\027\n\017secondsintoy" "ear\030\001 \002(\r\022\014\n\004nano\030\002 \002(\r\022\013\n\003val\030\003 \002(\021\022\023\n\010" "severity\030\004 \001(\005:\0010\022\021\n\006status\030\005 \001(\005:\0010\022\023\n\013" "repeatcount\030\006 \001(\r\022&\n\013fieldvalues\030\007 \003(\0132\021" ".EPICS.FieldValue\022\031\n\021fieldactualchange\030\010" " \001(\010\"\301\001\n\013ScalarFloat\022\027\n\017secondsintoyear\030" "\001 \002(\r\022\014\n\004nano\030\002 \002(\r\022\013\n\003val\030\003 \002(\002\022\023\n\010seve" "rity\030\004 \001(\005:\0010\022\021\n\006status\030\005 \001(\005:\0010\022\023\n\013repe" "atcount\030\006 \001(\r\022&\n\013fieldvalues\030\007 \003(\0132\021.EPI" "CS.FieldValue\022\031\n\021fieldactualchange\030\010 \001(\010" "\"\302\001\n\014ScalarDouble\022\027\n\017secondsintoyear\030\001 \002" "(\r\022\014\n\004nano\030\002 \002(\r\022\013\n\003val\030\003 \002(\001\022\023\n\010severit" "y\030\004 \001(\005:\0010\022\021\n\006status\030\005 \001(\005:\0010\022\023\n\013repeatc" "ount\030\006 \001(\r\022&\n\013fieldvalues\030\007 \003(\0132\021.EPICS." "FieldValue\022\031\n\021fieldactualchange\030\010 \001(\010\"\302\001" "\n\014VectorString\022\027\n\017secondsintoyear\030\001 \002(\r\022" "\014\n\004nano\030\002 \002(\r\022\013\n\003val\030\003 \003(\t\022\023\n\010severity\030\004" " \001(\005:\0010\022\021\n\006status\030\005 \001(\005:\0010\022\023\n\013repeatcoun" "t\030\006 \001(\r\022&\n\013fieldvalues\030\007 \003(\0132\021.EPICS.Fie" "ldValue\022\031\n\021fieldactualchange\030\010 \001(\010\"\300\001\n\nV" "ectorChar\022\027\n\017secondsintoyear\030\001 \002(\r\022\014\n\004na" "no\030\002 \002(\r\022\013\n\003val\030\003 \002(\014\022\023\n\010severity\030\004 \001(\005:" "\0010\022\021\n\006status\030\005 \001(\005:\0010\022\023\n\013repeatcount\030\006 \001" "(\r\022&\n\013fieldvalues\030\007 \003(\0132\021.EPICS.FieldVal" "ue\022\031\n\021fieldactualchange\030\010 \001(\010\"\305\001\n\013Vector" "Short\022\027\n\017secondsintoyear\030\001 \002(\r\022\014\n\004nano\030\002" " \002(\r\022\017\n\003val\030\003 \003(\021B\002\020\001\022\023\n\010severity\030\004 \001(\005:" "\0010\022\021\n\006status\030\005 \001(\005:\0010\022\023\n\013repeatcount\030\006 \001" "(\r\022&\n\013fieldvalues\030\007 \003(\0132\021.EPICS.FieldVal" "ue\022\031\n\021fieldactualchange\030\010 \001(\010\"\303\001\n\tVector" "Int\022\027\n\017secondsintoyear\030\001 \002(\r\022\014\n\004nano\030\002 \002" "(\r\022\017\n\003val\030\003 \003(\017B\002\020\001\022\023\n\010severity\030\004 \001(\005:\0010" "\022\021\n\006status\030\005 \001(\005:\0010\022\023\n\013repeatcount\030\006 \001(\r" "\022&\n\013fieldvalues\030\007 \003(\0132\021.EPICS.FieldValue" "\022\031\n\021fieldactualchange\030\010 \001(\010\"\304\001\n\nVectorEn" "um\022\027\n\017secondsintoyear\030\001 \002(\r\022\014\n\004nano\030\002 \002(" "\r\022\017\n\003val\030\003 \003(\021B\002\020\001\022\023\n\010severity\030\004 \001(\005:\0010\022" "\021\n\006status\030\005 \001(\005:\0010\022\023\n\013repeatcount\030\006 \001(\r\022" "&\n\013fieldvalues\030\007 \003(\0132\021.EPICS.FieldValue\022" "\031\n\021fieldactualchange\030\010 \001(\010\"\305\001\n\013VectorFlo" "at\022\027\n\017secondsintoyear\030\001 \002(\r\022\014\n\004nano\030\002 \002(" "\r\022\017\n\003val\030\003 \003(\002B\002\020\001\022\023\n\010severity\030\004 \001(\005:\0010\022" "\021\n\006status\030\005 \001(\005:\0010\022\023\n\013repeatcount\030\006 \001(\r\022" "&\n\013fieldvalues\030\007 \003(\0132\021.EPICS.FieldValue\022" "\031\n\021fieldactualchange\030\010 \001(\010\"\306\001\n\014VectorDou" "ble\022\027\n\017secondsintoyear\030\001 \002(\r\022\014\n\004nano\030\002 \002" "(\r\022\017\n\003val\030\003 \003(\001B\002\020\001\022\023\n\010severity\030\004 \001(\005:\0010" "\022\021\n\006status\030\005 \001(\005:\0010\022\023\n\013repeatcount\030\006 \001(\r" "\022&\n\013fieldvalues\030\007 \003(\0132\021.EPICS.FieldValue" "\022\031\n\021fieldactualchange\030\010 \001(\010\"\325\001\n\016V4Generi" "cBytes\022\027\n\017secondsintoyear\030\001 \002(\r\022\014\n\004nano\030" "\002 \002(\r\022\013\n\003val\030\003 \002(\014\022\023\n\010severity\030\004 \001(\005:\0010\022" "\021\n\006status\030\005 \001(\005:\0010\022\023\n\013repeatcount\030\006 \001(\r\022" "&\n\013fieldvalues\030\007 \003(\0132\021.EPICS.FieldValue\022" "\031\n\021fieldactualchange\030\010 \001(\010\022\017\n\007userTag\030\t " "\001(\r\"\273\002\n\013PayloadInfo\022 \n\004type\030\001 \002(\0162\022.EPIC" "S.PayloadType\022\016\n\006pvname\030\002 \002(\t\022\014\n\004year\030\003 " "\002(\005\022\024\n\014elementCount\030\004 \001(\005\022\020\n\010unused00\030\005 " "\001(\001\022\020\n\010unused01\030\006 \001(\001\022\020\n\010unused02\030\007 \001(\001\022" "\020\n\010unused03\030\010 \001(\001\022\020\n\010unused04\030\t \001(\001\022\020\n\010u" "nused05\030\n \001(\001\022\020\n\010unused06\030\013 \001(\001\022\020\n\010unuse" "d07\030\014 \001(\001\022\020\n\010unused08\030\r \001(\001\022\020\n\010unused09\030" "\016 \001(\t\022\"\n\007headers\030\017 \003(\0132\021.EPICS.FieldValu" "e*\251\002\n\013PayloadType\022\021\n\rSCALAR_STRING\020\000\022\020\n\014" "SCALAR_SHORT\020\001\022\020\n\014SCALAR_FLOAT\020\002\022\017\n\013SCAL" "AR_ENUM\020\003\022\017\n\013SCALAR_BYTE\020\004\022\016\n\nSCALAR_INT" "\020\005\022\021\n\rSCALAR_DOUBLE\020\006\022\023\n\017WAVEFORM_STRING" "\020\007\022\022\n\016WAVEFORM_SHORT\020\010\022\022\n\016WAVEFORM_FLOAT" "\020\t\022\021\n\rWAVEFORM_ENUM\020\n\022\021\n\rWAVEFORM_BYTE\020\013" "\022\020\n\014WAVEFORM_INT\020\014\022\023\n\017WAVEFORM_DOUBLE\020\r\022" "\024\n\020V4_GENERIC_BYTES\020\016B4\n&edu.stanford.sl" "ac.archiverappliance.PBB\nEPICSEvent" ; static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_epics_5fevent_2eproto_once; const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_epics_5fevent_2eproto = { false, false, 3715, descriptor_table_protodef_epics_5fevent_2eproto, "epics_event.proto", &descriptor_table_epics_5fevent_2eproto_once, nullptr, 0, 17, schemas, file_default_instances, TableStruct_epics_5fevent_2eproto::offsets, file_level_metadata_epics_5fevent_2eproto, file_level_enum_descriptors_epics_5fevent_2eproto, file_level_service_descriptors_epics_5fevent_2eproto, }; PROTOBUF_ATTRIBUTE_WEAK const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable* descriptor_table_epics_5fevent_2eproto_getter() { return &descriptor_table_epics_5fevent_2eproto; } // Force running AddDescriptors() at dynamic initialization time. PROTOBUF_ATTRIBUTE_INIT_PRIORITY static ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptorsRunner dynamic_init_dummy_epics_5fevent_2eproto(&descriptor_table_epics_5fevent_2eproto); namespace EPICS { const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* PayloadType_descriptor() { ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&descriptor_table_epics_5fevent_2eproto); return file_level_enum_descriptors_epics_5fevent_2eproto[0]; } bool PayloadType_IsValid(int value) { switch (value) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: case 12: case 13: case 14: return true; default: return false; } } // =================================================================== class FieldValue::_Internal { public: using HasBits = decltype(std::declval<FieldValue>()._has_bits_); static void set_has_name(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_val(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static bool MissingRequiredFields(const HasBits& has_bits) { return ((has_bits[0] & 0x00000003) ^ 0x00000003) != 0; } }; FieldValue::FieldValue(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:EPICS.FieldValue) } FieldValue::FieldValue(const FieldValue& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_name()) { name_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_name(), GetArenaForAllocation()); } val_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_val()) { val_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_val(), GetArenaForAllocation()); } // @@protoc_insertion_point(copy_constructor:EPICS.FieldValue) } void FieldValue::SharedCtor() { name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); val_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } FieldValue::~FieldValue() { // @@protoc_insertion_point(destructor:EPICS.FieldValue) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void FieldValue::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); val_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } void FieldValue::ArenaDtor(void* object) { FieldValue* _this = reinterpret_cast< FieldValue* >(object); (void)_this; } void FieldValue::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void FieldValue::SetCachedSize(int size) const { _cached_size_.Set(size); } void FieldValue::Clear() { // @@protoc_insertion_point(message_clear_start:EPICS.FieldValue) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { val_.ClearNonDefaultToEmpty(); } } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* FieldValue::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // required string name = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { auto str = _internal_mutable_name(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); #ifndef NDEBUG ::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "EPICS.FieldValue.name"); #endif // !NDEBUG CHK_(ptr); } else goto handle_unusual; continue; // required string val = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { auto str = _internal_mutable_val(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); #ifndef NDEBUG ::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "EPICS.FieldValue.val"); #endif // !NDEBUG CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* FieldValue::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:EPICS.FieldValue) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required string name = 1; if (cached_has_bits & 0x00000001u) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->_internal_name().data(), static_cast<int>(this->_internal_name().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "EPICS.FieldValue.name"); target = stream->WriteStringMaybeAliased( 1, this->_internal_name(), target); } // required string val = 2; if (cached_has_bits & 0x00000002u) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->_internal_val().data(), static_cast<int>(this->_internal_val().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "EPICS.FieldValue.val"); target = stream->WriteStringMaybeAliased( 2, this->_internal_val(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:EPICS.FieldValue) return target; } size_t FieldValue::RequiredFieldsByteSizeFallback() const { // @@protoc_insertion_point(required_fields_byte_size_fallback_start:EPICS.FieldValue) size_t total_size = 0; if (_internal_has_name()) { // required string name = 1; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_name()); } if (_internal_has_val()) { // required string val = 2; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_val()); } return total_size; } size_t FieldValue::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:EPICS.FieldValue) size_t total_size = 0; if (((_has_bits_[0] & 0x00000003) ^ 0x00000003) == 0) { // All required fields are present. // required string name = 1; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_name()); // required string val = 2; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_val()); } else { total_size += RequiredFieldsByteSizeFallback(); } ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void FieldValue::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:EPICS.FieldValue) GOOGLE_DCHECK_NE(&from, this); const FieldValue* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<FieldValue>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:EPICS.FieldValue) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:EPICS.FieldValue) MergeFrom(*source); } } void FieldValue::MergeFrom(const FieldValue& from) { // @@protoc_insertion_point(class_specific_merge_from_start:EPICS.FieldValue) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { _internal_set_name(from._internal_name()); } if (cached_has_bits & 0x00000002u) { _internal_set_val(from._internal_val()); } } } void FieldValue::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:EPICS.FieldValue) if (&from == this) return; Clear(); MergeFrom(from); } void FieldValue::CopyFrom(const FieldValue& from) { // @@protoc_insertion_point(class_specific_copy_from_start:EPICS.FieldValue) if (&from == this) return; Clear(); MergeFrom(from); } bool FieldValue::IsInitialized() const { if (_Internal::MissingRequiredFields(_has_bits_)) return false; return true; } void FieldValue::InternalSwap(FieldValue* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), &name_, GetArenaForAllocation(), &other->name_, other->GetArenaForAllocation() ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), &val_, GetArenaForAllocation(), &other->val_, other->GetArenaForAllocation() ); } ::PROTOBUF_NAMESPACE_ID::Metadata FieldValue::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_epics_5fevent_2eproto_getter, &descriptor_table_epics_5fevent_2eproto_once, file_level_metadata_epics_5fevent_2eproto[0]); } // =================================================================== class ScalarString::_Internal { public: using HasBits = decltype(std::declval<ScalarString>()._has_bits_); static void set_has_secondsintoyear(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static void set_has_nano(HasBits* has_bits) { (*has_bits)[0] |= 4u; } static void set_has_val(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_severity(HasBits* has_bits) { (*has_bits)[0] |= 8u; } static void set_has_status(HasBits* has_bits) { (*has_bits)[0] |= 16u; } static void set_has_repeatcount(HasBits* has_bits) { (*has_bits)[0] |= 32u; } static void set_has_fieldactualchange(HasBits* has_bits) { (*has_bits)[0] |= 64u; } static bool MissingRequiredFields(const HasBits& has_bits) { return ((has_bits[0] & 0x00000007) ^ 0x00000007) != 0; } }; ScalarString::ScalarString(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena), fieldvalues_(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:EPICS.ScalarString) } ScalarString::ScalarString(const ScalarString& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_), fieldvalues_(from.fieldvalues_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); val_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_val()) { val_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_val(), GetArenaForAllocation()); } ::memcpy(&secondsintoyear_, &from.secondsintoyear_, static_cast<size_t>(reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); // @@protoc_insertion_point(copy_constructor:EPICS.ScalarString) } void ScalarString::SharedCtor() { val_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&secondsintoyear_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); } ScalarString::~ScalarString() { // @@protoc_insertion_point(destructor:EPICS.ScalarString) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void ScalarString::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); val_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } void ScalarString::ArenaDtor(void* object) { ScalarString* _this = reinterpret_cast< ScalarString* >(object); (void)_this; } void ScalarString::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void ScalarString::SetCachedSize(int size) const { _cached_size_.Set(size); } void ScalarString::Clear() { // @@protoc_insertion_point(message_clear_start:EPICS.ScalarString) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; fieldvalues_.Clear(); cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000001u) { val_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x0000007eu) { ::memset(&secondsintoyear_, 0, static_cast<size_t>( reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* ScalarString::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // required uint32 secondsintoyear = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { _Internal::set_has_secondsintoyear(&has_bits); secondsintoyear_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // required uint32 nano = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) { _Internal::set_has_nano(&has_bits); nano_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // required string val = 3; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) { auto str = _internal_mutable_val(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); #ifndef NDEBUG ::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "EPICS.ScalarString.val"); #endif // !NDEBUG CHK_(ptr); } else goto handle_unusual; continue; // optional int32 severity = 4 [default = 0]; case 4: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 32)) { _Internal::set_has_severity(&has_bits); severity_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional int32 status = 5 [default = 0]; case 5: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 40)) { _Internal::set_has_status(&has_bits); status_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional uint32 repeatcount = 6; case 6: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 48)) { _Internal::set_has_repeatcount(&has_bits); repeatcount_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // repeated .EPICS.FieldValue fieldvalues = 7; case 7: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 58)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseMessage(_internal_add_fieldvalues(), ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<58>(ptr)); } else goto handle_unusual; continue; // optional bool fieldactualchange = 8; case 8: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 64)) { _Internal::set_has_fieldactualchange(&has_bits); fieldactualchange_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* ScalarString::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:EPICS.ScalarString) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required uint32 secondsintoyear = 1; if (cached_has_bits & 0x00000002u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(1, this->_internal_secondsintoyear(), target); } // required uint32 nano = 2; if (cached_has_bits & 0x00000004u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(2, this->_internal_nano(), target); } // required string val = 3; if (cached_has_bits & 0x00000001u) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->_internal_val().data(), static_cast<int>(this->_internal_val().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "EPICS.ScalarString.val"); target = stream->WriteStringMaybeAliased( 3, this->_internal_val(), target); } // optional int32 severity = 4 [default = 0]; if (cached_has_bits & 0x00000008u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(4, this->_internal_severity(), target); } // optional int32 status = 5 [default = 0]; if (cached_has_bits & 0x00000010u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(5, this->_internal_status(), target); } // optional uint32 repeatcount = 6; if (cached_has_bits & 0x00000020u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(6, this->_internal_repeatcount(), target); } // repeated .EPICS.FieldValue fieldvalues = 7; for (unsigned int i = 0, n = static_cast<unsigned int>(this->_internal_fieldvalues_size()); i < n; i++) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage(7, this->_internal_fieldvalues(i), target, stream); } // optional bool fieldactualchange = 8; if (cached_has_bits & 0x00000040u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(8, this->_internal_fieldactualchange(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:EPICS.ScalarString) return target; } size_t ScalarString::RequiredFieldsByteSizeFallback() const { // @@protoc_insertion_point(required_fields_byte_size_fallback_start:EPICS.ScalarString) size_t total_size = 0; if (_internal_has_val()) { // required string val = 3; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_val()); } if (_internal_has_secondsintoyear()) { // required uint32 secondsintoyear = 1; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_secondsintoyear()); } if (_internal_has_nano()) { // required uint32 nano = 2; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_nano()); } return total_size; } size_t ScalarString::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:EPICS.ScalarString) size_t total_size = 0; if (((_has_bits_[0] & 0x00000007) ^ 0x00000007) == 0) { // All required fields are present. // required string val = 3; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_val()); // required uint32 secondsintoyear = 1; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_secondsintoyear()); // required uint32 nano = 2; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_nano()); } else { total_size += RequiredFieldsByteSizeFallback(); } ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated .EPICS.FieldValue fieldvalues = 7; total_size += 1UL * this->_internal_fieldvalues_size(); for (const auto& msg : this->fieldvalues_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000078u) { // optional int32 severity = 4 [default = 0]; if (cached_has_bits & 0x00000008u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_severity()); } // optional int32 status = 5 [default = 0]; if (cached_has_bits & 0x00000010u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_status()); } // optional uint32 repeatcount = 6; if (cached_has_bits & 0x00000020u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_repeatcount()); } // optional bool fieldactualchange = 8; if (cached_has_bits & 0x00000040u) { total_size += 1 + 1; } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void ScalarString::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:EPICS.ScalarString) GOOGLE_DCHECK_NE(&from, this); const ScalarString* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<ScalarString>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:EPICS.ScalarString) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:EPICS.ScalarString) MergeFrom(*source); } } void ScalarString::MergeFrom(const ScalarString& from) { // @@protoc_insertion_point(class_specific_merge_from_start:EPICS.ScalarString) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; fieldvalues_.MergeFrom(from.fieldvalues_); cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x0000007fu) { if (cached_has_bits & 0x00000001u) { _internal_set_val(from._internal_val()); } if (cached_has_bits & 0x00000002u) { secondsintoyear_ = from.secondsintoyear_; } if (cached_has_bits & 0x00000004u) { nano_ = from.nano_; } if (cached_has_bits & 0x00000008u) { severity_ = from.severity_; } if (cached_has_bits & 0x00000010u) { status_ = from.status_; } if (cached_has_bits & 0x00000020u) { repeatcount_ = from.repeatcount_; } if (cached_has_bits & 0x00000040u) { fieldactualchange_ = from.fieldactualchange_; } _has_bits_[0] |= cached_has_bits; } } void ScalarString::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:EPICS.ScalarString) if (&from == this) return; Clear(); MergeFrom(from); } void ScalarString::CopyFrom(const ScalarString& from) { // @@protoc_insertion_point(class_specific_copy_from_start:EPICS.ScalarString) if (&from == this) return; Clear(); MergeFrom(from); } bool ScalarString::IsInitialized() const { if (_Internal::MissingRequiredFields(_has_bits_)) return false; if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(fieldvalues_)) return false; return true; } void ScalarString::InternalSwap(ScalarString* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); fieldvalues_.InternalSwap(&other->fieldvalues_); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), &val_, GetArenaForAllocation(), &other->val_, other->GetArenaForAllocation() ); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(ScalarString, fieldactualchange_) + sizeof(ScalarString::fieldactualchange_) - PROTOBUF_FIELD_OFFSET(ScalarString, secondsintoyear_)>( reinterpret_cast<char*>(&secondsintoyear_), reinterpret_cast<char*>(&other->secondsintoyear_)); } ::PROTOBUF_NAMESPACE_ID::Metadata ScalarString::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_epics_5fevent_2eproto_getter, &descriptor_table_epics_5fevent_2eproto_once, file_level_metadata_epics_5fevent_2eproto[1]); } // =================================================================== class ScalarByte::_Internal { public: using HasBits = decltype(std::declval<ScalarByte>()._has_bits_); static void set_has_secondsintoyear(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static void set_has_nano(HasBits* has_bits) { (*has_bits)[0] |= 4u; } static void set_has_val(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_severity(HasBits* has_bits) { (*has_bits)[0] |= 8u; } static void set_has_status(HasBits* has_bits) { (*has_bits)[0] |= 16u; } static void set_has_repeatcount(HasBits* has_bits) { (*has_bits)[0] |= 32u; } static void set_has_fieldactualchange(HasBits* has_bits) { (*has_bits)[0] |= 64u; } static bool MissingRequiredFields(const HasBits& has_bits) { return ((has_bits[0] & 0x00000007) ^ 0x00000007) != 0; } }; ScalarByte::ScalarByte(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena), fieldvalues_(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:EPICS.ScalarByte) } ScalarByte::ScalarByte(const ScalarByte& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_), fieldvalues_(from.fieldvalues_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); val_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_val()) { val_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_val(), GetArenaForAllocation()); } ::memcpy(&secondsintoyear_, &from.secondsintoyear_, static_cast<size_t>(reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); // @@protoc_insertion_point(copy_constructor:EPICS.ScalarByte) } void ScalarByte::SharedCtor() { val_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&secondsintoyear_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); } ScalarByte::~ScalarByte() { // @@protoc_insertion_point(destructor:EPICS.ScalarByte) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void ScalarByte::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); val_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } void ScalarByte::ArenaDtor(void* object) { ScalarByte* _this = reinterpret_cast< ScalarByte* >(object); (void)_this; } void ScalarByte::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void ScalarByte::SetCachedSize(int size) const { _cached_size_.Set(size); } void ScalarByte::Clear() { // @@protoc_insertion_point(message_clear_start:EPICS.ScalarByte) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; fieldvalues_.Clear(); cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000001u) { val_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x0000007eu) { ::memset(&secondsintoyear_, 0, static_cast<size_t>( reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* ScalarByte::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // required uint32 secondsintoyear = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { _Internal::set_has_secondsintoyear(&has_bits); secondsintoyear_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // required uint32 nano = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) { _Internal::set_has_nano(&has_bits); nano_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // required bytes val = 3; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) { auto str = _internal_mutable_val(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; // optional int32 severity = 4 [default = 0]; case 4: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 32)) { _Internal::set_has_severity(&has_bits); severity_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional int32 status = 5 [default = 0]; case 5: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 40)) { _Internal::set_has_status(&has_bits); status_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional uint32 repeatcount = 6; case 6: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 48)) { _Internal::set_has_repeatcount(&has_bits); repeatcount_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // repeated .EPICS.FieldValue fieldvalues = 7; case 7: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 58)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseMessage(_internal_add_fieldvalues(), ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<58>(ptr)); } else goto handle_unusual; continue; // optional bool fieldactualchange = 8; case 8: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 64)) { _Internal::set_has_fieldactualchange(&has_bits); fieldactualchange_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* ScalarByte::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:EPICS.ScalarByte) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required uint32 secondsintoyear = 1; if (cached_has_bits & 0x00000002u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(1, this->_internal_secondsintoyear(), target); } // required uint32 nano = 2; if (cached_has_bits & 0x00000004u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(2, this->_internal_nano(), target); } // required bytes val = 3; if (cached_has_bits & 0x00000001u) { target = stream->WriteBytesMaybeAliased( 3, this->_internal_val(), target); } // optional int32 severity = 4 [default = 0]; if (cached_has_bits & 0x00000008u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(4, this->_internal_severity(), target); } // optional int32 status = 5 [default = 0]; if (cached_has_bits & 0x00000010u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(5, this->_internal_status(), target); } // optional uint32 repeatcount = 6; if (cached_has_bits & 0x00000020u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(6, this->_internal_repeatcount(), target); } // repeated .EPICS.FieldValue fieldvalues = 7; for (unsigned int i = 0, n = static_cast<unsigned int>(this->_internal_fieldvalues_size()); i < n; i++) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage(7, this->_internal_fieldvalues(i), target, stream); } // optional bool fieldactualchange = 8; if (cached_has_bits & 0x00000040u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(8, this->_internal_fieldactualchange(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:EPICS.ScalarByte) return target; } size_t ScalarByte::RequiredFieldsByteSizeFallback() const { // @@protoc_insertion_point(required_fields_byte_size_fallback_start:EPICS.ScalarByte) size_t total_size = 0; if (_internal_has_val()) { // required bytes val = 3; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::BytesSize( this->_internal_val()); } if (_internal_has_secondsintoyear()) { // required uint32 secondsintoyear = 1; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_secondsintoyear()); } if (_internal_has_nano()) { // required uint32 nano = 2; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_nano()); } return total_size; } size_t ScalarByte::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:EPICS.ScalarByte) size_t total_size = 0; if (((_has_bits_[0] & 0x00000007) ^ 0x00000007) == 0) { // All required fields are present. // required bytes val = 3; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::BytesSize( this->_internal_val()); // required uint32 secondsintoyear = 1; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_secondsintoyear()); // required uint32 nano = 2; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_nano()); } else { total_size += RequiredFieldsByteSizeFallback(); } ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated .EPICS.FieldValue fieldvalues = 7; total_size += 1UL * this->_internal_fieldvalues_size(); for (const auto& msg : this->fieldvalues_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000078u) { // optional int32 severity = 4 [default = 0]; if (cached_has_bits & 0x00000008u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_severity()); } // optional int32 status = 5 [default = 0]; if (cached_has_bits & 0x00000010u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_status()); } // optional uint32 repeatcount = 6; if (cached_has_bits & 0x00000020u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_repeatcount()); } // optional bool fieldactualchange = 8; if (cached_has_bits & 0x00000040u) { total_size += 1 + 1; } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void ScalarByte::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:EPICS.ScalarByte) GOOGLE_DCHECK_NE(&from, this); const ScalarByte* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<ScalarByte>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:EPICS.ScalarByte) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:EPICS.ScalarByte) MergeFrom(*source); } } void ScalarByte::MergeFrom(const ScalarByte& from) { // @@protoc_insertion_point(class_specific_merge_from_start:EPICS.ScalarByte) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; fieldvalues_.MergeFrom(from.fieldvalues_); cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x0000007fu) { if (cached_has_bits & 0x00000001u) { _internal_set_val(from._internal_val()); } if (cached_has_bits & 0x00000002u) { secondsintoyear_ = from.secondsintoyear_; } if (cached_has_bits & 0x00000004u) { nano_ = from.nano_; } if (cached_has_bits & 0x00000008u) { severity_ = from.severity_; } if (cached_has_bits & 0x00000010u) { status_ = from.status_; } if (cached_has_bits & 0x00000020u) { repeatcount_ = from.repeatcount_; } if (cached_has_bits & 0x00000040u) { fieldactualchange_ = from.fieldactualchange_; } _has_bits_[0] |= cached_has_bits; } } void ScalarByte::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:EPICS.ScalarByte) if (&from == this) return; Clear(); MergeFrom(from); } void ScalarByte::CopyFrom(const ScalarByte& from) { // @@protoc_insertion_point(class_specific_copy_from_start:EPICS.ScalarByte) if (&from == this) return; Clear(); MergeFrom(from); } bool ScalarByte::IsInitialized() const { if (_Internal::MissingRequiredFields(_has_bits_)) return false; if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(fieldvalues_)) return false; return true; } void ScalarByte::InternalSwap(ScalarByte* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); fieldvalues_.InternalSwap(&other->fieldvalues_); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), &val_, GetArenaForAllocation(), &other->val_, other->GetArenaForAllocation() ); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(ScalarByte, fieldactualchange_) + sizeof(ScalarByte::fieldactualchange_) - PROTOBUF_FIELD_OFFSET(ScalarByte, secondsintoyear_)>( reinterpret_cast<char*>(&secondsintoyear_), reinterpret_cast<char*>(&other->secondsintoyear_)); } ::PROTOBUF_NAMESPACE_ID::Metadata ScalarByte::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_epics_5fevent_2eproto_getter, &descriptor_table_epics_5fevent_2eproto_once, file_level_metadata_epics_5fevent_2eproto[2]); } // =================================================================== class ScalarShort::_Internal { public: using HasBits = decltype(std::declval<ScalarShort>()._has_bits_); static void set_has_secondsintoyear(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_nano(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static void set_has_val(HasBits* has_bits) { (*has_bits)[0] |= 4u; } static void set_has_severity(HasBits* has_bits) { (*has_bits)[0] |= 8u; } static void set_has_status(HasBits* has_bits) { (*has_bits)[0] |= 16u; } static void set_has_repeatcount(HasBits* has_bits) { (*has_bits)[0] |= 32u; } static void set_has_fieldactualchange(HasBits* has_bits) { (*has_bits)[0] |= 64u; } static bool MissingRequiredFields(const HasBits& has_bits) { return ((has_bits[0] & 0x00000007) ^ 0x00000007) != 0; } }; ScalarShort::ScalarShort(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena), fieldvalues_(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:EPICS.ScalarShort) } ScalarShort::ScalarShort(const ScalarShort& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_), fieldvalues_(from.fieldvalues_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::memcpy(&secondsintoyear_, &from.secondsintoyear_, static_cast<size_t>(reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); // @@protoc_insertion_point(copy_constructor:EPICS.ScalarShort) } void ScalarShort::SharedCtor() { ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&secondsintoyear_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); } ScalarShort::~ScalarShort() { // @@protoc_insertion_point(destructor:EPICS.ScalarShort) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void ScalarShort::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); } void ScalarShort::ArenaDtor(void* object) { ScalarShort* _this = reinterpret_cast< ScalarShort* >(object); (void)_this; } void ScalarShort::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void ScalarShort::SetCachedSize(int size) const { _cached_size_.Set(size); } void ScalarShort::Clear() { // @@protoc_insertion_point(message_clear_start:EPICS.ScalarShort) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; fieldvalues_.Clear(); cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x0000007fu) { ::memset(&secondsintoyear_, 0, static_cast<size_t>( reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* ScalarShort::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // required uint32 secondsintoyear = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { _Internal::set_has_secondsintoyear(&has_bits); secondsintoyear_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // required uint32 nano = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) { _Internal::set_has_nano(&has_bits); nano_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // required sint32 val = 3; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 24)) { _Internal::set_has_val(&has_bits); val_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarintZigZag32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional int32 severity = 4 [default = 0]; case 4: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 32)) { _Internal::set_has_severity(&has_bits); severity_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional int32 status = 5 [default = 0]; case 5: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 40)) { _Internal::set_has_status(&has_bits); status_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional uint32 repeatcount = 6; case 6: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 48)) { _Internal::set_has_repeatcount(&has_bits); repeatcount_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // repeated .EPICS.FieldValue fieldvalues = 7; case 7: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 58)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseMessage(_internal_add_fieldvalues(), ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<58>(ptr)); } else goto handle_unusual; continue; // optional bool fieldactualchange = 8; case 8: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 64)) { _Internal::set_has_fieldactualchange(&has_bits); fieldactualchange_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* ScalarShort::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:EPICS.ScalarShort) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required uint32 secondsintoyear = 1; if (cached_has_bits & 0x00000001u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(1, this->_internal_secondsintoyear(), target); } // required uint32 nano = 2; if (cached_has_bits & 0x00000002u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(2, this->_internal_nano(), target); } // required sint32 val = 3; if (cached_has_bits & 0x00000004u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteSInt32ToArray(3, this->_internal_val(), target); } // optional int32 severity = 4 [default = 0]; if (cached_has_bits & 0x00000008u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(4, this->_internal_severity(), target); } // optional int32 status = 5 [default = 0]; if (cached_has_bits & 0x00000010u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(5, this->_internal_status(), target); } // optional uint32 repeatcount = 6; if (cached_has_bits & 0x00000020u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(6, this->_internal_repeatcount(), target); } // repeated .EPICS.FieldValue fieldvalues = 7; for (unsigned int i = 0, n = static_cast<unsigned int>(this->_internal_fieldvalues_size()); i < n; i++) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage(7, this->_internal_fieldvalues(i), target, stream); } // optional bool fieldactualchange = 8; if (cached_has_bits & 0x00000040u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(8, this->_internal_fieldactualchange(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:EPICS.ScalarShort) return target; } size_t ScalarShort::RequiredFieldsByteSizeFallback() const { // @@protoc_insertion_point(required_fields_byte_size_fallback_start:EPICS.ScalarShort) size_t total_size = 0; if (_internal_has_secondsintoyear()) { // required uint32 secondsintoyear = 1; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_secondsintoyear()); } if (_internal_has_nano()) { // required uint32 nano = 2; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_nano()); } if (_internal_has_val()) { // required sint32 val = 3; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SInt32Size( this->_internal_val()); } return total_size; } size_t ScalarShort::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:EPICS.ScalarShort) size_t total_size = 0; if (((_has_bits_[0] & 0x00000007) ^ 0x00000007) == 0) { // All required fields are present. // required uint32 secondsintoyear = 1; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_secondsintoyear()); // required uint32 nano = 2; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_nano()); // required sint32 val = 3; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SInt32Size( this->_internal_val()); } else { total_size += RequiredFieldsByteSizeFallback(); } ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated .EPICS.FieldValue fieldvalues = 7; total_size += 1UL * this->_internal_fieldvalues_size(); for (const auto& msg : this->fieldvalues_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000078u) { // optional int32 severity = 4 [default = 0]; if (cached_has_bits & 0x00000008u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_severity()); } // optional int32 status = 5 [default = 0]; if (cached_has_bits & 0x00000010u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_status()); } // optional uint32 repeatcount = 6; if (cached_has_bits & 0x00000020u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_repeatcount()); } // optional bool fieldactualchange = 8; if (cached_has_bits & 0x00000040u) { total_size += 1 + 1; } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void ScalarShort::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:EPICS.ScalarShort) GOOGLE_DCHECK_NE(&from, this); const ScalarShort* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<ScalarShort>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:EPICS.ScalarShort) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:EPICS.ScalarShort) MergeFrom(*source); } } void ScalarShort::MergeFrom(const ScalarShort& from) { // @@protoc_insertion_point(class_specific_merge_from_start:EPICS.ScalarShort) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; fieldvalues_.MergeFrom(from.fieldvalues_); cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x0000007fu) { if (cached_has_bits & 0x00000001u) { secondsintoyear_ = from.secondsintoyear_; } if (cached_has_bits & 0x00000002u) { nano_ = from.nano_; } if (cached_has_bits & 0x00000004u) { val_ = from.val_; } if (cached_has_bits & 0x00000008u) { severity_ = from.severity_; } if (cached_has_bits & 0x00000010u) { status_ = from.status_; } if (cached_has_bits & 0x00000020u) { repeatcount_ = from.repeatcount_; } if (cached_has_bits & 0x00000040u) { fieldactualchange_ = from.fieldactualchange_; } _has_bits_[0] |= cached_has_bits; } } void ScalarShort::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:EPICS.ScalarShort) if (&from == this) return; Clear(); MergeFrom(from); } void ScalarShort::CopyFrom(const ScalarShort& from) { // @@protoc_insertion_point(class_specific_copy_from_start:EPICS.ScalarShort) if (&from == this) return; Clear(); MergeFrom(from); } bool ScalarShort::IsInitialized() const { if (_Internal::MissingRequiredFields(_has_bits_)) return false; if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(fieldvalues_)) return false; return true; } void ScalarShort::InternalSwap(ScalarShort* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); fieldvalues_.InternalSwap(&other->fieldvalues_); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(ScalarShort, fieldactualchange_) + sizeof(ScalarShort::fieldactualchange_) - PROTOBUF_FIELD_OFFSET(ScalarShort, secondsintoyear_)>( reinterpret_cast<char*>(&secondsintoyear_), reinterpret_cast<char*>(&other->secondsintoyear_)); } ::PROTOBUF_NAMESPACE_ID::Metadata ScalarShort::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_epics_5fevent_2eproto_getter, &descriptor_table_epics_5fevent_2eproto_once, file_level_metadata_epics_5fevent_2eproto[3]); } // =================================================================== class ScalarInt::_Internal { public: using HasBits = decltype(std::declval<ScalarInt>()._has_bits_); static void set_has_secondsintoyear(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_nano(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static void set_has_val(HasBits* has_bits) { (*has_bits)[0] |= 4u; } static void set_has_severity(HasBits* has_bits) { (*has_bits)[0] |= 8u; } static void set_has_status(HasBits* has_bits) { (*has_bits)[0] |= 16u; } static void set_has_repeatcount(HasBits* has_bits) { (*has_bits)[0] |= 32u; } static void set_has_fieldactualchange(HasBits* has_bits) { (*has_bits)[0] |= 64u; } static bool MissingRequiredFields(const HasBits& has_bits) { return ((has_bits[0] & 0x00000007) ^ 0x00000007) != 0; } }; ScalarInt::ScalarInt(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena), fieldvalues_(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:EPICS.ScalarInt) } ScalarInt::ScalarInt(const ScalarInt& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_), fieldvalues_(from.fieldvalues_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::memcpy(&secondsintoyear_, &from.secondsintoyear_, static_cast<size_t>(reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); // @@protoc_insertion_point(copy_constructor:EPICS.ScalarInt) } void ScalarInt::SharedCtor() { ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&secondsintoyear_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); } ScalarInt::~ScalarInt() { // @@protoc_insertion_point(destructor:EPICS.ScalarInt) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void ScalarInt::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); } void ScalarInt::ArenaDtor(void* object) { ScalarInt* _this = reinterpret_cast< ScalarInt* >(object); (void)_this; } void ScalarInt::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void ScalarInt::SetCachedSize(int size) const { _cached_size_.Set(size); } void ScalarInt::Clear() { // @@protoc_insertion_point(message_clear_start:EPICS.ScalarInt) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; fieldvalues_.Clear(); cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x0000007fu) { ::memset(&secondsintoyear_, 0, static_cast<size_t>( reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* ScalarInt::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // required uint32 secondsintoyear = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { _Internal::set_has_secondsintoyear(&has_bits); secondsintoyear_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // required uint32 nano = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) { _Internal::set_has_nano(&has_bits); nano_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // required sfixed32 val = 3; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 29)) { _Internal::set_has_val(&has_bits); val_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::int32>(ptr); ptr += sizeof(::PROTOBUF_NAMESPACE_ID::int32); } else goto handle_unusual; continue; // optional int32 severity = 4 [default = 0]; case 4: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 32)) { _Internal::set_has_severity(&has_bits); severity_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional int32 status = 5 [default = 0]; case 5: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 40)) { _Internal::set_has_status(&has_bits); status_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional uint32 repeatcount = 6; case 6: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 48)) { _Internal::set_has_repeatcount(&has_bits); repeatcount_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // repeated .EPICS.FieldValue fieldvalues = 7; case 7: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 58)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseMessage(_internal_add_fieldvalues(), ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<58>(ptr)); } else goto handle_unusual; continue; // optional bool fieldactualchange = 8; case 8: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 64)) { _Internal::set_has_fieldactualchange(&has_bits); fieldactualchange_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* ScalarInt::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:EPICS.ScalarInt) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required uint32 secondsintoyear = 1; if (cached_has_bits & 0x00000001u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(1, this->_internal_secondsintoyear(), target); } // required uint32 nano = 2; if (cached_has_bits & 0x00000002u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(2, this->_internal_nano(), target); } // required sfixed32 val = 3; if (cached_has_bits & 0x00000004u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteSFixed32ToArray(3, this->_internal_val(), target); } // optional int32 severity = 4 [default = 0]; if (cached_has_bits & 0x00000008u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(4, this->_internal_severity(), target); } // optional int32 status = 5 [default = 0]; if (cached_has_bits & 0x00000010u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(5, this->_internal_status(), target); } // optional uint32 repeatcount = 6; if (cached_has_bits & 0x00000020u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(6, this->_internal_repeatcount(), target); } // repeated .EPICS.FieldValue fieldvalues = 7; for (unsigned int i = 0, n = static_cast<unsigned int>(this->_internal_fieldvalues_size()); i < n; i++) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage(7, this->_internal_fieldvalues(i), target, stream); } // optional bool fieldactualchange = 8; if (cached_has_bits & 0x00000040u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(8, this->_internal_fieldactualchange(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:EPICS.ScalarInt) return target; } size_t ScalarInt::RequiredFieldsByteSizeFallback() const { // @@protoc_insertion_point(required_fields_byte_size_fallback_start:EPICS.ScalarInt) size_t total_size = 0; if (_internal_has_secondsintoyear()) { // required uint32 secondsintoyear = 1; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_secondsintoyear()); } if (_internal_has_nano()) { // required uint32 nano = 2; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_nano()); } if (_internal_has_val()) { // required sfixed32 val = 3; total_size += 1 + 4; } return total_size; } size_t ScalarInt::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:EPICS.ScalarInt) size_t total_size = 0; if (((_has_bits_[0] & 0x00000007) ^ 0x00000007) == 0) { // All required fields are present. // required uint32 secondsintoyear = 1; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_secondsintoyear()); // required uint32 nano = 2; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_nano()); // required sfixed32 val = 3; total_size += 1 + 4; } else { total_size += RequiredFieldsByteSizeFallback(); } ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated .EPICS.FieldValue fieldvalues = 7; total_size += 1UL * this->_internal_fieldvalues_size(); for (const auto& msg : this->fieldvalues_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000078u) { // optional int32 severity = 4 [default = 0]; if (cached_has_bits & 0x00000008u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_severity()); } // optional int32 status = 5 [default = 0]; if (cached_has_bits & 0x00000010u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_status()); } // optional uint32 repeatcount = 6; if (cached_has_bits & 0x00000020u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_repeatcount()); } // optional bool fieldactualchange = 8; if (cached_has_bits & 0x00000040u) { total_size += 1 + 1; } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void ScalarInt::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:EPICS.ScalarInt) GOOGLE_DCHECK_NE(&from, this); const ScalarInt* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<ScalarInt>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:EPICS.ScalarInt) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:EPICS.ScalarInt) MergeFrom(*source); } } void ScalarInt::MergeFrom(const ScalarInt& from) { // @@protoc_insertion_point(class_specific_merge_from_start:EPICS.ScalarInt) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; fieldvalues_.MergeFrom(from.fieldvalues_); cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x0000007fu) { if (cached_has_bits & 0x00000001u) { secondsintoyear_ = from.secondsintoyear_; } if (cached_has_bits & 0x00000002u) { nano_ = from.nano_; } if (cached_has_bits & 0x00000004u) { val_ = from.val_; } if (cached_has_bits & 0x00000008u) { severity_ = from.severity_; } if (cached_has_bits & 0x00000010u) { status_ = from.status_; } if (cached_has_bits & 0x00000020u) { repeatcount_ = from.repeatcount_; } if (cached_has_bits & 0x00000040u) { fieldactualchange_ = from.fieldactualchange_; } _has_bits_[0] |= cached_has_bits; } } void ScalarInt::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:EPICS.ScalarInt) if (&from == this) return; Clear(); MergeFrom(from); } void ScalarInt::CopyFrom(const ScalarInt& from) { // @@protoc_insertion_point(class_specific_copy_from_start:EPICS.ScalarInt) if (&from == this) return; Clear(); MergeFrom(from); } bool ScalarInt::IsInitialized() const { if (_Internal::MissingRequiredFields(_has_bits_)) return false; if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(fieldvalues_)) return false; return true; } void ScalarInt::InternalSwap(ScalarInt* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); fieldvalues_.InternalSwap(&other->fieldvalues_); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(ScalarInt, fieldactualchange_) + sizeof(ScalarInt::fieldactualchange_) - PROTOBUF_FIELD_OFFSET(ScalarInt, secondsintoyear_)>( reinterpret_cast<char*>(&secondsintoyear_), reinterpret_cast<char*>(&other->secondsintoyear_)); } ::PROTOBUF_NAMESPACE_ID::Metadata ScalarInt::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_epics_5fevent_2eproto_getter, &descriptor_table_epics_5fevent_2eproto_once, file_level_metadata_epics_5fevent_2eproto[4]); } // =================================================================== class ScalarEnum::_Internal { public: using HasBits = decltype(std::declval<ScalarEnum>()._has_bits_); static void set_has_secondsintoyear(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_nano(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static void set_has_val(HasBits* has_bits) { (*has_bits)[0] |= 4u; } static void set_has_severity(HasBits* has_bits) { (*has_bits)[0] |= 8u; } static void set_has_status(HasBits* has_bits) { (*has_bits)[0] |= 16u; } static void set_has_repeatcount(HasBits* has_bits) { (*has_bits)[0] |= 32u; } static void set_has_fieldactualchange(HasBits* has_bits) { (*has_bits)[0] |= 64u; } static bool MissingRequiredFields(const HasBits& has_bits) { return ((has_bits[0] & 0x00000007) ^ 0x00000007) != 0; } }; ScalarEnum::ScalarEnum(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena), fieldvalues_(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:EPICS.ScalarEnum) } ScalarEnum::ScalarEnum(const ScalarEnum& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_), fieldvalues_(from.fieldvalues_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::memcpy(&secondsintoyear_, &from.secondsintoyear_, static_cast<size_t>(reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); // @@protoc_insertion_point(copy_constructor:EPICS.ScalarEnum) } void ScalarEnum::SharedCtor() { ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&secondsintoyear_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); } ScalarEnum::~ScalarEnum() { // @@protoc_insertion_point(destructor:EPICS.ScalarEnum) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void ScalarEnum::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); } void ScalarEnum::ArenaDtor(void* object) { ScalarEnum* _this = reinterpret_cast< ScalarEnum* >(object); (void)_this; } void ScalarEnum::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void ScalarEnum::SetCachedSize(int size) const { _cached_size_.Set(size); } void ScalarEnum::Clear() { // @@protoc_insertion_point(message_clear_start:EPICS.ScalarEnum) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; fieldvalues_.Clear(); cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x0000007fu) { ::memset(&secondsintoyear_, 0, static_cast<size_t>( reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* ScalarEnum::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // required uint32 secondsintoyear = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { _Internal::set_has_secondsintoyear(&has_bits); secondsintoyear_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // required uint32 nano = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) { _Internal::set_has_nano(&has_bits); nano_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // required sint32 val = 3; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 24)) { _Internal::set_has_val(&has_bits); val_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarintZigZag32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional int32 severity = 4 [default = 0]; case 4: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 32)) { _Internal::set_has_severity(&has_bits); severity_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional int32 status = 5 [default = 0]; case 5: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 40)) { _Internal::set_has_status(&has_bits); status_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional uint32 repeatcount = 6; case 6: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 48)) { _Internal::set_has_repeatcount(&has_bits); repeatcount_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // repeated .EPICS.FieldValue fieldvalues = 7; case 7: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 58)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseMessage(_internal_add_fieldvalues(), ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<58>(ptr)); } else goto handle_unusual; continue; // optional bool fieldactualchange = 8; case 8: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 64)) { _Internal::set_has_fieldactualchange(&has_bits); fieldactualchange_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* ScalarEnum::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:EPICS.ScalarEnum) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required uint32 secondsintoyear = 1; if (cached_has_bits & 0x00000001u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(1, this->_internal_secondsintoyear(), target); } // required uint32 nano = 2; if (cached_has_bits & 0x00000002u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(2, this->_internal_nano(), target); } // required sint32 val = 3; if (cached_has_bits & 0x00000004u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteSInt32ToArray(3, this->_internal_val(), target); } // optional int32 severity = 4 [default = 0]; if (cached_has_bits & 0x00000008u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(4, this->_internal_severity(), target); } // optional int32 status = 5 [default = 0]; if (cached_has_bits & 0x00000010u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(5, this->_internal_status(), target); } // optional uint32 repeatcount = 6; if (cached_has_bits & 0x00000020u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(6, this->_internal_repeatcount(), target); } // repeated .EPICS.FieldValue fieldvalues = 7; for (unsigned int i = 0, n = static_cast<unsigned int>(this->_internal_fieldvalues_size()); i < n; i++) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage(7, this->_internal_fieldvalues(i), target, stream); } // optional bool fieldactualchange = 8; if (cached_has_bits & 0x00000040u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(8, this->_internal_fieldactualchange(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:EPICS.ScalarEnum) return target; } size_t ScalarEnum::RequiredFieldsByteSizeFallback() const { // @@protoc_insertion_point(required_fields_byte_size_fallback_start:EPICS.ScalarEnum) size_t total_size = 0; if (_internal_has_secondsintoyear()) { // required uint32 secondsintoyear = 1; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_secondsintoyear()); } if (_internal_has_nano()) { // required uint32 nano = 2; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_nano()); } if (_internal_has_val()) { // required sint32 val = 3; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SInt32Size( this->_internal_val()); } return total_size; } size_t ScalarEnum::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:EPICS.ScalarEnum) size_t total_size = 0; if (((_has_bits_[0] & 0x00000007) ^ 0x00000007) == 0) { // All required fields are present. // required uint32 secondsintoyear = 1; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_secondsintoyear()); // required uint32 nano = 2; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_nano()); // required sint32 val = 3; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SInt32Size( this->_internal_val()); } else { total_size += RequiredFieldsByteSizeFallback(); } ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated .EPICS.FieldValue fieldvalues = 7; total_size += 1UL * this->_internal_fieldvalues_size(); for (const auto& msg : this->fieldvalues_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000078u) { // optional int32 severity = 4 [default = 0]; if (cached_has_bits & 0x00000008u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_severity()); } // optional int32 status = 5 [default = 0]; if (cached_has_bits & 0x00000010u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_status()); } // optional uint32 repeatcount = 6; if (cached_has_bits & 0x00000020u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_repeatcount()); } // optional bool fieldactualchange = 8; if (cached_has_bits & 0x00000040u) { total_size += 1 + 1; } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void ScalarEnum::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:EPICS.ScalarEnum) GOOGLE_DCHECK_NE(&from, this); const ScalarEnum* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<ScalarEnum>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:EPICS.ScalarEnum) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:EPICS.ScalarEnum) MergeFrom(*source); } } void ScalarEnum::MergeFrom(const ScalarEnum& from) { // @@protoc_insertion_point(class_specific_merge_from_start:EPICS.ScalarEnum) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; fieldvalues_.MergeFrom(from.fieldvalues_); cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x0000007fu) { if (cached_has_bits & 0x00000001u) { secondsintoyear_ = from.secondsintoyear_; } if (cached_has_bits & 0x00000002u) { nano_ = from.nano_; } if (cached_has_bits & 0x00000004u) { val_ = from.val_; } if (cached_has_bits & 0x00000008u) { severity_ = from.severity_; } if (cached_has_bits & 0x00000010u) { status_ = from.status_; } if (cached_has_bits & 0x00000020u) { repeatcount_ = from.repeatcount_; } if (cached_has_bits & 0x00000040u) { fieldactualchange_ = from.fieldactualchange_; } _has_bits_[0] |= cached_has_bits; } } void ScalarEnum::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:EPICS.ScalarEnum) if (&from == this) return; Clear(); MergeFrom(from); } void ScalarEnum::CopyFrom(const ScalarEnum& from) { // @@protoc_insertion_point(class_specific_copy_from_start:EPICS.ScalarEnum) if (&from == this) return; Clear(); MergeFrom(from); } bool ScalarEnum::IsInitialized() const { if (_Internal::MissingRequiredFields(_has_bits_)) return false; if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(fieldvalues_)) return false; return true; } void ScalarEnum::InternalSwap(ScalarEnum* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); fieldvalues_.InternalSwap(&other->fieldvalues_); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(ScalarEnum, fieldactualchange_) + sizeof(ScalarEnum::fieldactualchange_) - PROTOBUF_FIELD_OFFSET(ScalarEnum, secondsintoyear_)>( reinterpret_cast<char*>(&secondsintoyear_), reinterpret_cast<char*>(&other->secondsintoyear_)); } ::PROTOBUF_NAMESPACE_ID::Metadata ScalarEnum::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_epics_5fevent_2eproto_getter, &descriptor_table_epics_5fevent_2eproto_once, file_level_metadata_epics_5fevent_2eproto[5]); } // =================================================================== class ScalarFloat::_Internal { public: using HasBits = decltype(std::declval<ScalarFloat>()._has_bits_); static void set_has_secondsintoyear(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_nano(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static void set_has_val(HasBits* has_bits) { (*has_bits)[0] |= 4u; } static void set_has_severity(HasBits* has_bits) { (*has_bits)[0] |= 8u; } static void set_has_status(HasBits* has_bits) { (*has_bits)[0] |= 16u; } static void set_has_repeatcount(HasBits* has_bits) { (*has_bits)[0] |= 32u; } static void set_has_fieldactualchange(HasBits* has_bits) { (*has_bits)[0] |= 64u; } static bool MissingRequiredFields(const HasBits& has_bits) { return ((has_bits[0] & 0x00000007) ^ 0x00000007) != 0; } }; ScalarFloat::ScalarFloat(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena), fieldvalues_(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:EPICS.ScalarFloat) } ScalarFloat::ScalarFloat(const ScalarFloat& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_), fieldvalues_(from.fieldvalues_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::memcpy(&secondsintoyear_, &from.secondsintoyear_, static_cast<size_t>(reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); // @@protoc_insertion_point(copy_constructor:EPICS.ScalarFloat) } void ScalarFloat::SharedCtor() { ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&secondsintoyear_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); } ScalarFloat::~ScalarFloat() { // @@protoc_insertion_point(destructor:EPICS.ScalarFloat) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void ScalarFloat::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); } void ScalarFloat::ArenaDtor(void* object) { ScalarFloat* _this = reinterpret_cast< ScalarFloat* >(object); (void)_this; } void ScalarFloat::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void ScalarFloat::SetCachedSize(int size) const { _cached_size_.Set(size); } void ScalarFloat::Clear() { // @@protoc_insertion_point(message_clear_start:EPICS.ScalarFloat) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; fieldvalues_.Clear(); cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x0000007fu) { ::memset(&secondsintoyear_, 0, static_cast<size_t>( reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* ScalarFloat::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // required uint32 secondsintoyear = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { _Internal::set_has_secondsintoyear(&has_bits); secondsintoyear_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // required uint32 nano = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) { _Internal::set_has_nano(&has_bits); nano_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // required float val = 3; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 29)) { _Internal::set_has_val(&has_bits); val_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr); ptr += sizeof(float); } else goto handle_unusual; continue; // optional int32 severity = 4 [default = 0]; case 4: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 32)) { _Internal::set_has_severity(&has_bits); severity_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional int32 status = 5 [default = 0]; case 5: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 40)) { _Internal::set_has_status(&has_bits); status_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional uint32 repeatcount = 6; case 6: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 48)) { _Internal::set_has_repeatcount(&has_bits); repeatcount_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // repeated .EPICS.FieldValue fieldvalues = 7; case 7: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 58)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseMessage(_internal_add_fieldvalues(), ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<58>(ptr)); } else goto handle_unusual; continue; // optional bool fieldactualchange = 8; case 8: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 64)) { _Internal::set_has_fieldactualchange(&has_bits); fieldactualchange_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* ScalarFloat::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:EPICS.ScalarFloat) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required uint32 secondsintoyear = 1; if (cached_has_bits & 0x00000001u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(1, this->_internal_secondsintoyear(), target); } // required uint32 nano = 2; if (cached_has_bits & 0x00000002u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(2, this->_internal_nano(), target); } // required float val = 3; if (cached_has_bits & 0x00000004u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteFloatToArray(3, this->_internal_val(), target); } // optional int32 severity = 4 [default = 0]; if (cached_has_bits & 0x00000008u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(4, this->_internal_severity(), target); } // optional int32 status = 5 [default = 0]; if (cached_has_bits & 0x00000010u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(5, this->_internal_status(), target); } // optional uint32 repeatcount = 6; if (cached_has_bits & 0x00000020u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(6, this->_internal_repeatcount(), target); } // repeated .EPICS.FieldValue fieldvalues = 7; for (unsigned int i = 0, n = static_cast<unsigned int>(this->_internal_fieldvalues_size()); i < n; i++) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage(7, this->_internal_fieldvalues(i), target, stream); } // optional bool fieldactualchange = 8; if (cached_has_bits & 0x00000040u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(8, this->_internal_fieldactualchange(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:EPICS.ScalarFloat) return target; } size_t ScalarFloat::RequiredFieldsByteSizeFallback() const { // @@protoc_insertion_point(required_fields_byte_size_fallback_start:EPICS.ScalarFloat) size_t total_size = 0; if (_internal_has_secondsintoyear()) { // required uint32 secondsintoyear = 1; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_secondsintoyear()); } if (_internal_has_nano()) { // required uint32 nano = 2; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_nano()); } if (_internal_has_val()) { // required float val = 3; total_size += 1 + 4; } return total_size; } size_t ScalarFloat::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:EPICS.ScalarFloat) size_t total_size = 0; if (((_has_bits_[0] & 0x00000007) ^ 0x00000007) == 0) { // All required fields are present. // required uint32 secondsintoyear = 1; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_secondsintoyear()); // required uint32 nano = 2; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_nano()); // required float val = 3; total_size += 1 + 4; } else { total_size += RequiredFieldsByteSizeFallback(); } ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated .EPICS.FieldValue fieldvalues = 7; total_size += 1UL * this->_internal_fieldvalues_size(); for (const auto& msg : this->fieldvalues_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000078u) { // optional int32 severity = 4 [default = 0]; if (cached_has_bits & 0x00000008u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_severity()); } // optional int32 status = 5 [default = 0]; if (cached_has_bits & 0x00000010u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_status()); } // optional uint32 repeatcount = 6; if (cached_has_bits & 0x00000020u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_repeatcount()); } // optional bool fieldactualchange = 8; if (cached_has_bits & 0x00000040u) { total_size += 1 + 1; } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void ScalarFloat::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:EPICS.ScalarFloat) GOOGLE_DCHECK_NE(&from, this); const ScalarFloat* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<ScalarFloat>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:EPICS.ScalarFloat) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:EPICS.ScalarFloat) MergeFrom(*source); } } void ScalarFloat::MergeFrom(const ScalarFloat& from) { // @@protoc_insertion_point(class_specific_merge_from_start:EPICS.ScalarFloat) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; fieldvalues_.MergeFrom(from.fieldvalues_); cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x0000007fu) { if (cached_has_bits & 0x00000001u) { secondsintoyear_ = from.secondsintoyear_; } if (cached_has_bits & 0x00000002u) { nano_ = from.nano_; } if (cached_has_bits & 0x00000004u) { val_ = from.val_; } if (cached_has_bits & 0x00000008u) { severity_ = from.severity_; } if (cached_has_bits & 0x00000010u) { status_ = from.status_; } if (cached_has_bits & 0x00000020u) { repeatcount_ = from.repeatcount_; } if (cached_has_bits & 0x00000040u) { fieldactualchange_ = from.fieldactualchange_; } _has_bits_[0] |= cached_has_bits; } } void ScalarFloat::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:EPICS.ScalarFloat) if (&from == this) return; Clear(); MergeFrom(from); } void ScalarFloat::CopyFrom(const ScalarFloat& from) { // @@protoc_insertion_point(class_specific_copy_from_start:EPICS.ScalarFloat) if (&from == this) return; Clear(); MergeFrom(from); } bool ScalarFloat::IsInitialized() const { if (_Internal::MissingRequiredFields(_has_bits_)) return false; if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(fieldvalues_)) return false; return true; } void ScalarFloat::InternalSwap(ScalarFloat* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); fieldvalues_.InternalSwap(&other->fieldvalues_); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(ScalarFloat, fieldactualchange_) + sizeof(ScalarFloat::fieldactualchange_) - PROTOBUF_FIELD_OFFSET(ScalarFloat, secondsintoyear_)>( reinterpret_cast<char*>(&secondsintoyear_), reinterpret_cast<char*>(&other->secondsintoyear_)); } ::PROTOBUF_NAMESPACE_ID::Metadata ScalarFloat::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_epics_5fevent_2eproto_getter, &descriptor_table_epics_5fevent_2eproto_once, file_level_metadata_epics_5fevent_2eproto[6]); } // =================================================================== class ScalarDouble::_Internal { public: using HasBits = decltype(std::declval<ScalarDouble>()._has_bits_); static void set_has_secondsintoyear(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_nano(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static void set_has_val(HasBits* has_bits) { (*has_bits)[0] |= 4u; } static void set_has_severity(HasBits* has_bits) { (*has_bits)[0] |= 8u; } static void set_has_status(HasBits* has_bits) { (*has_bits)[0] |= 16u; } static void set_has_repeatcount(HasBits* has_bits) { (*has_bits)[0] |= 32u; } static void set_has_fieldactualchange(HasBits* has_bits) { (*has_bits)[0] |= 64u; } static bool MissingRequiredFields(const HasBits& has_bits) { return ((has_bits[0] & 0x00000007) ^ 0x00000007) != 0; } }; ScalarDouble::ScalarDouble(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena), fieldvalues_(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:EPICS.ScalarDouble) } ScalarDouble::ScalarDouble(const ScalarDouble& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_), fieldvalues_(from.fieldvalues_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::memcpy(&secondsintoyear_, &from.secondsintoyear_, static_cast<size_t>(reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); // @@protoc_insertion_point(copy_constructor:EPICS.ScalarDouble) } void ScalarDouble::SharedCtor() { ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&secondsintoyear_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); } ScalarDouble::~ScalarDouble() { // @@protoc_insertion_point(destructor:EPICS.ScalarDouble) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void ScalarDouble::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); } void ScalarDouble::ArenaDtor(void* object) { ScalarDouble* _this = reinterpret_cast< ScalarDouble* >(object); (void)_this; } void ScalarDouble::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void ScalarDouble::SetCachedSize(int size) const { _cached_size_.Set(size); } void ScalarDouble::Clear() { // @@protoc_insertion_point(message_clear_start:EPICS.ScalarDouble) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; fieldvalues_.Clear(); cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x0000007fu) { ::memset(&secondsintoyear_, 0, static_cast<size_t>( reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* ScalarDouble::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // required uint32 secondsintoyear = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { _Internal::set_has_secondsintoyear(&has_bits); secondsintoyear_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // required uint32 nano = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) { _Internal::set_has_nano(&has_bits); nano_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // required double val = 3; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 25)) { _Internal::set_has_val(&has_bits); val_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<double>(ptr); ptr += sizeof(double); } else goto handle_unusual; continue; // optional int32 severity = 4 [default = 0]; case 4: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 32)) { _Internal::set_has_severity(&has_bits); severity_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional int32 status = 5 [default = 0]; case 5: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 40)) { _Internal::set_has_status(&has_bits); status_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional uint32 repeatcount = 6; case 6: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 48)) { _Internal::set_has_repeatcount(&has_bits); repeatcount_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // repeated .EPICS.FieldValue fieldvalues = 7; case 7: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 58)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseMessage(_internal_add_fieldvalues(), ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<58>(ptr)); } else goto handle_unusual; continue; // optional bool fieldactualchange = 8; case 8: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 64)) { _Internal::set_has_fieldactualchange(&has_bits); fieldactualchange_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* ScalarDouble::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:EPICS.ScalarDouble) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required uint32 secondsintoyear = 1; if (cached_has_bits & 0x00000001u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(1, this->_internal_secondsintoyear(), target); } // required uint32 nano = 2; if (cached_has_bits & 0x00000002u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(2, this->_internal_nano(), target); } // required double val = 3; if (cached_has_bits & 0x00000004u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteDoubleToArray(3, this->_internal_val(), target); } // optional int32 severity = 4 [default = 0]; if (cached_has_bits & 0x00000008u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(4, this->_internal_severity(), target); } // optional int32 status = 5 [default = 0]; if (cached_has_bits & 0x00000010u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(5, this->_internal_status(), target); } // optional uint32 repeatcount = 6; if (cached_has_bits & 0x00000020u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(6, this->_internal_repeatcount(), target); } // repeated .EPICS.FieldValue fieldvalues = 7; for (unsigned int i = 0, n = static_cast<unsigned int>(this->_internal_fieldvalues_size()); i < n; i++) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage(7, this->_internal_fieldvalues(i), target, stream); } // optional bool fieldactualchange = 8; if (cached_has_bits & 0x00000040u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(8, this->_internal_fieldactualchange(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:EPICS.ScalarDouble) return target; } size_t ScalarDouble::RequiredFieldsByteSizeFallback() const { // @@protoc_insertion_point(required_fields_byte_size_fallback_start:EPICS.ScalarDouble) size_t total_size = 0; if (_internal_has_secondsintoyear()) { // required uint32 secondsintoyear = 1; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_secondsintoyear()); } if (_internal_has_nano()) { // required uint32 nano = 2; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_nano()); } if (_internal_has_val()) { // required double val = 3; total_size += 1 + 8; } return total_size; } size_t ScalarDouble::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:EPICS.ScalarDouble) size_t total_size = 0; if (((_has_bits_[0] & 0x00000007) ^ 0x00000007) == 0) { // All required fields are present. // required uint32 secondsintoyear = 1; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_secondsintoyear()); // required uint32 nano = 2; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_nano()); // required double val = 3; total_size += 1 + 8; } else { total_size += RequiredFieldsByteSizeFallback(); } ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated .EPICS.FieldValue fieldvalues = 7; total_size += 1UL * this->_internal_fieldvalues_size(); for (const auto& msg : this->fieldvalues_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000078u) { // optional int32 severity = 4 [default = 0]; if (cached_has_bits & 0x00000008u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_severity()); } // optional int32 status = 5 [default = 0]; if (cached_has_bits & 0x00000010u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_status()); } // optional uint32 repeatcount = 6; if (cached_has_bits & 0x00000020u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_repeatcount()); } // optional bool fieldactualchange = 8; if (cached_has_bits & 0x00000040u) { total_size += 1 + 1; } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void ScalarDouble::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:EPICS.ScalarDouble) GOOGLE_DCHECK_NE(&from, this); const ScalarDouble* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<ScalarDouble>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:EPICS.ScalarDouble) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:EPICS.ScalarDouble) MergeFrom(*source); } } void ScalarDouble::MergeFrom(const ScalarDouble& from) { // @@protoc_insertion_point(class_specific_merge_from_start:EPICS.ScalarDouble) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; fieldvalues_.MergeFrom(from.fieldvalues_); cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x0000007fu) { if (cached_has_bits & 0x00000001u) { secondsintoyear_ = from.secondsintoyear_; } if (cached_has_bits & 0x00000002u) { nano_ = from.nano_; } if (cached_has_bits & 0x00000004u) { val_ = from.val_; } if (cached_has_bits & 0x00000008u) { severity_ = from.severity_; } if (cached_has_bits & 0x00000010u) { status_ = from.status_; } if (cached_has_bits & 0x00000020u) { repeatcount_ = from.repeatcount_; } if (cached_has_bits & 0x00000040u) { fieldactualchange_ = from.fieldactualchange_; } _has_bits_[0] |= cached_has_bits; } } void ScalarDouble::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:EPICS.ScalarDouble) if (&from == this) return; Clear(); MergeFrom(from); } void ScalarDouble::CopyFrom(const ScalarDouble& from) { // @@protoc_insertion_point(class_specific_copy_from_start:EPICS.ScalarDouble) if (&from == this) return; Clear(); MergeFrom(from); } bool ScalarDouble::IsInitialized() const { if (_Internal::MissingRequiredFields(_has_bits_)) return false; if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(fieldvalues_)) return false; return true; } void ScalarDouble::InternalSwap(ScalarDouble* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); fieldvalues_.InternalSwap(&other->fieldvalues_); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(ScalarDouble, fieldactualchange_) + sizeof(ScalarDouble::fieldactualchange_) - PROTOBUF_FIELD_OFFSET(ScalarDouble, secondsintoyear_)>( reinterpret_cast<char*>(&secondsintoyear_), reinterpret_cast<char*>(&other->secondsintoyear_)); } ::PROTOBUF_NAMESPACE_ID::Metadata ScalarDouble::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_epics_5fevent_2eproto_getter, &descriptor_table_epics_5fevent_2eproto_once, file_level_metadata_epics_5fevent_2eproto[7]); } // =================================================================== class VectorString::_Internal { public: using HasBits = decltype(std::declval<VectorString>()._has_bits_); static void set_has_secondsintoyear(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_nano(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static void set_has_severity(HasBits* has_bits) { (*has_bits)[0] |= 4u; } static void set_has_status(HasBits* has_bits) { (*has_bits)[0] |= 8u; } static void set_has_repeatcount(HasBits* has_bits) { (*has_bits)[0] |= 16u; } static void set_has_fieldactualchange(HasBits* has_bits) { (*has_bits)[0] |= 32u; } static bool MissingRequiredFields(const HasBits& has_bits) { return ((has_bits[0] & 0x00000003) ^ 0x00000003) != 0; } }; VectorString::VectorString(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena), val_(arena), fieldvalues_(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:EPICS.VectorString) } VectorString::VectorString(const VectorString& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_), val_(from.val_), fieldvalues_(from.fieldvalues_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::memcpy(&secondsintoyear_, &from.secondsintoyear_, static_cast<size_t>(reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); // @@protoc_insertion_point(copy_constructor:EPICS.VectorString) } void VectorString::SharedCtor() { ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&secondsintoyear_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); } VectorString::~VectorString() { // @@protoc_insertion_point(destructor:EPICS.VectorString) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void VectorString::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); } void VectorString::ArenaDtor(void* object) { VectorString* _this = reinterpret_cast< VectorString* >(object); (void)_this; } void VectorString::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void VectorString::SetCachedSize(int size) const { _cached_size_.Set(size); } void VectorString::Clear() { // @@protoc_insertion_point(message_clear_start:EPICS.VectorString) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; val_.Clear(); fieldvalues_.Clear(); cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x0000003fu) { ::memset(&secondsintoyear_, 0, static_cast<size_t>( reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* VectorString::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // required uint32 secondsintoyear = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { _Internal::set_has_secondsintoyear(&has_bits); secondsintoyear_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // required uint32 nano = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) { _Internal::set_has_nano(&has_bits); nano_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // repeated string val = 3; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) { ptr -= 1; do { ptr += 1; auto str = _internal_add_val(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); #ifndef NDEBUG ::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "EPICS.VectorString.val"); #endif // !NDEBUG CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<26>(ptr)); } else goto handle_unusual; continue; // optional int32 severity = 4 [default = 0]; case 4: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 32)) { _Internal::set_has_severity(&has_bits); severity_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional int32 status = 5 [default = 0]; case 5: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 40)) { _Internal::set_has_status(&has_bits); status_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional uint32 repeatcount = 6; case 6: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 48)) { _Internal::set_has_repeatcount(&has_bits); repeatcount_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // repeated .EPICS.FieldValue fieldvalues = 7; case 7: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 58)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseMessage(_internal_add_fieldvalues(), ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<58>(ptr)); } else goto handle_unusual; continue; // optional bool fieldactualchange = 8; case 8: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 64)) { _Internal::set_has_fieldactualchange(&has_bits); fieldactualchange_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* VectorString::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:EPICS.VectorString) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required uint32 secondsintoyear = 1; if (cached_has_bits & 0x00000001u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(1, this->_internal_secondsintoyear(), target); } // required uint32 nano = 2; if (cached_has_bits & 0x00000002u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(2, this->_internal_nano(), target); } // repeated string val = 3; for (int i = 0, n = this->_internal_val_size(); i < n; i++) { const auto& s = this->_internal_val(i); ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( s.data(), static_cast<int>(s.length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "EPICS.VectorString.val"); target = stream->WriteString(3, s, target); } // optional int32 severity = 4 [default = 0]; if (cached_has_bits & 0x00000004u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(4, this->_internal_severity(), target); } // optional int32 status = 5 [default = 0]; if (cached_has_bits & 0x00000008u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(5, this->_internal_status(), target); } // optional uint32 repeatcount = 6; if (cached_has_bits & 0x00000010u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(6, this->_internal_repeatcount(), target); } // repeated .EPICS.FieldValue fieldvalues = 7; for (unsigned int i = 0, n = static_cast<unsigned int>(this->_internal_fieldvalues_size()); i < n; i++) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage(7, this->_internal_fieldvalues(i), target, stream); } // optional bool fieldactualchange = 8; if (cached_has_bits & 0x00000020u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(8, this->_internal_fieldactualchange(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:EPICS.VectorString) return target; } size_t VectorString::RequiredFieldsByteSizeFallback() const { // @@protoc_insertion_point(required_fields_byte_size_fallback_start:EPICS.VectorString) size_t total_size = 0; if (_internal_has_secondsintoyear()) { // required uint32 secondsintoyear = 1; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_secondsintoyear()); } if (_internal_has_nano()) { // required uint32 nano = 2; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_nano()); } return total_size; } size_t VectorString::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:EPICS.VectorString) size_t total_size = 0; if (((_has_bits_[0] & 0x00000003) ^ 0x00000003) == 0) { // All required fields are present. // required uint32 secondsintoyear = 1; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_secondsintoyear()); // required uint32 nano = 2; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_nano()); } else { total_size += RequiredFieldsByteSizeFallback(); } ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated string val = 3; total_size += 1 * ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(val_.size()); for (int i = 0, n = val_.size(); i < n; i++) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( val_.Get(i)); } // repeated .EPICS.FieldValue fieldvalues = 7; total_size += 1UL * this->_internal_fieldvalues_size(); for (const auto& msg : this->fieldvalues_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x0000003cu) { // optional int32 severity = 4 [default = 0]; if (cached_has_bits & 0x00000004u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_severity()); } // optional int32 status = 5 [default = 0]; if (cached_has_bits & 0x00000008u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_status()); } // optional uint32 repeatcount = 6; if (cached_has_bits & 0x00000010u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_repeatcount()); } // optional bool fieldactualchange = 8; if (cached_has_bits & 0x00000020u) { total_size += 1 + 1; } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void VectorString::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:EPICS.VectorString) GOOGLE_DCHECK_NE(&from, this); const VectorString* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<VectorString>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:EPICS.VectorString) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:EPICS.VectorString) MergeFrom(*source); } } void VectorString::MergeFrom(const VectorString& from) { // @@protoc_insertion_point(class_specific_merge_from_start:EPICS.VectorString) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; val_.MergeFrom(from.val_); fieldvalues_.MergeFrom(from.fieldvalues_); cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x0000003fu) { if (cached_has_bits & 0x00000001u) { secondsintoyear_ = from.secondsintoyear_; } if (cached_has_bits & 0x00000002u) { nano_ = from.nano_; } if (cached_has_bits & 0x00000004u) { severity_ = from.severity_; } if (cached_has_bits & 0x00000008u) { status_ = from.status_; } if (cached_has_bits & 0x00000010u) { repeatcount_ = from.repeatcount_; } if (cached_has_bits & 0x00000020u) { fieldactualchange_ = from.fieldactualchange_; } _has_bits_[0] |= cached_has_bits; } } void VectorString::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:EPICS.VectorString) if (&from == this) return; Clear(); MergeFrom(from); } void VectorString::CopyFrom(const VectorString& from) { // @@protoc_insertion_point(class_specific_copy_from_start:EPICS.VectorString) if (&from == this) return; Clear(); MergeFrom(from); } bool VectorString::IsInitialized() const { if (_Internal::MissingRequiredFields(_has_bits_)) return false; if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(fieldvalues_)) return false; return true; } void VectorString::InternalSwap(VectorString* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); val_.InternalSwap(&other->val_); fieldvalues_.InternalSwap(&other->fieldvalues_); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(VectorString, fieldactualchange_) + sizeof(VectorString::fieldactualchange_) - PROTOBUF_FIELD_OFFSET(VectorString, secondsintoyear_)>( reinterpret_cast<char*>(&secondsintoyear_), reinterpret_cast<char*>(&other->secondsintoyear_)); } ::PROTOBUF_NAMESPACE_ID::Metadata VectorString::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_epics_5fevent_2eproto_getter, &descriptor_table_epics_5fevent_2eproto_once, file_level_metadata_epics_5fevent_2eproto[8]); } // =================================================================== class VectorChar::_Internal { public: using HasBits = decltype(std::declval<VectorChar>()._has_bits_); static void set_has_secondsintoyear(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static void set_has_nano(HasBits* has_bits) { (*has_bits)[0] |= 4u; } static void set_has_val(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_severity(HasBits* has_bits) { (*has_bits)[0] |= 8u; } static void set_has_status(HasBits* has_bits) { (*has_bits)[0] |= 16u; } static void set_has_repeatcount(HasBits* has_bits) { (*has_bits)[0] |= 32u; } static void set_has_fieldactualchange(HasBits* has_bits) { (*has_bits)[0] |= 64u; } static bool MissingRequiredFields(const HasBits& has_bits) { return ((has_bits[0] & 0x00000007) ^ 0x00000007) != 0; } }; VectorChar::VectorChar(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena), fieldvalues_(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:EPICS.VectorChar) } VectorChar::VectorChar(const VectorChar& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_), fieldvalues_(from.fieldvalues_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); val_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_val()) { val_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_val(), GetArenaForAllocation()); } ::memcpy(&secondsintoyear_, &from.secondsintoyear_, static_cast<size_t>(reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); // @@protoc_insertion_point(copy_constructor:EPICS.VectorChar) } void VectorChar::SharedCtor() { val_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&secondsintoyear_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); } VectorChar::~VectorChar() { // @@protoc_insertion_point(destructor:EPICS.VectorChar) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void VectorChar::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); val_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } void VectorChar::ArenaDtor(void* object) { VectorChar* _this = reinterpret_cast< VectorChar* >(object); (void)_this; } void VectorChar::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void VectorChar::SetCachedSize(int size) const { _cached_size_.Set(size); } void VectorChar::Clear() { // @@protoc_insertion_point(message_clear_start:EPICS.VectorChar) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; fieldvalues_.Clear(); cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000001u) { val_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x0000007eu) { ::memset(&secondsintoyear_, 0, static_cast<size_t>( reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* VectorChar::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // required uint32 secondsintoyear = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { _Internal::set_has_secondsintoyear(&has_bits); secondsintoyear_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // required uint32 nano = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) { _Internal::set_has_nano(&has_bits); nano_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // required bytes val = 3; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) { auto str = _internal_mutable_val(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; // optional int32 severity = 4 [default = 0]; case 4: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 32)) { _Internal::set_has_severity(&has_bits); severity_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional int32 status = 5 [default = 0]; case 5: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 40)) { _Internal::set_has_status(&has_bits); status_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional uint32 repeatcount = 6; case 6: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 48)) { _Internal::set_has_repeatcount(&has_bits); repeatcount_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // repeated .EPICS.FieldValue fieldvalues = 7; case 7: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 58)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseMessage(_internal_add_fieldvalues(), ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<58>(ptr)); } else goto handle_unusual; continue; // optional bool fieldactualchange = 8; case 8: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 64)) { _Internal::set_has_fieldactualchange(&has_bits); fieldactualchange_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* VectorChar::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:EPICS.VectorChar) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required uint32 secondsintoyear = 1; if (cached_has_bits & 0x00000002u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(1, this->_internal_secondsintoyear(), target); } // required uint32 nano = 2; if (cached_has_bits & 0x00000004u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(2, this->_internal_nano(), target); } // required bytes val = 3; if (cached_has_bits & 0x00000001u) { target = stream->WriteBytesMaybeAliased( 3, this->_internal_val(), target); } // optional int32 severity = 4 [default = 0]; if (cached_has_bits & 0x00000008u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(4, this->_internal_severity(), target); } // optional int32 status = 5 [default = 0]; if (cached_has_bits & 0x00000010u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(5, this->_internal_status(), target); } // optional uint32 repeatcount = 6; if (cached_has_bits & 0x00000020u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(6, this->_internal_repeatcount(), target); } // repeated .EPICS.FieldValue fieldvalues = 7; for (unsigned int i = 0, n = static_cast<unsigned int>(this->_internal_fieldvalues_size()); i < n; i++) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage(7, this->_internal_fieldvalues(i), target, stream); } // optional bool fieldactualchange = 8; if (cached_has_bits & 0x00000040u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(8, this->_internal_fieldactualchange(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:EPICS.VectorChar) return target; } size_t VectorChar::RequiredFieldsByteSizeFallback() const { // @@protoc_insertion_point(required_fields_byte_size_fallback_start:EPICS.VectorChar) size_t total_size = 0; if (_internal_has_val()) { // required bytes val = 3; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::BytesSize( this->_internal_val()); } if (_internal_has_secondsintoyear()) { // required uint32 secondsintoyear = 1; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_secondsintoyear()); } if (_internal_has_nano()) { // required uint32 nano = 2; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_nano()); } return total_size; } size_t VectorChar::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:EPICS.VectorChar) size_t total_size = 0; if (((_has_bits_[0] & 0x00000007) ^ 0x00000007) == 0) { // All required fields are present. // required bytes val = 3; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::BytesSize( this->_internal_val()); // required uint32 secondsintoyear = 1; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_secondsintoyear()); // required uint32 nano = 2; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_nano()); } else { total_size += RequiredFieldsByteSizeFallback(); } ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated .EPICS.FieldValue fieldvalues = 7; total_size += 1UL * this->_internal_fieldvalues_size(); for (const auto& msg : this->fieldvalues_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000078u) { // optional int32 severity = 4 [default = 0]; if (cached_has_bits & 0x00000008u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_severity()); } // optional int32 status = 5 [default = 0]; if (cached_has_bits & 0x00000010u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_status()); } // optional uint32 repeatcount = 6; if (cached_has_bits & 0x00000020u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_repeatcount()); } // optional bool fieldactualchange = 8; if (cached_has_bits & 0x00000040u) { total_size += 1 + 1; } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void VectorChar::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:EPICS.VectorChar) GOOGLE_DCHECK_NE(&from, this); const VectorChar* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<VectorChar>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:EPICS.VectorChar) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:EPICS.VectorChar) MergeFrom(*source); } } void VectorChar::MergeFrom(const VectorChar& from) { // @@protoc_insertion_point(class_specific_merge_from_start:EPICS.VectorChar) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; fieldvalues_.MergeFrom(from.fieldvalues_); cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x0000007fu) { if (cached_has_bits & 0x00000001u) { _internal_set_val(from._internal_val()); } if (cached_has_bits & 0x00000002u) { secondsintoyear_ = from.secondsintoyear_; } if (cached_has_bits & 0x00000004u) { nano_ = from.nano_; } if (cached_has_bits & 0x00000008u) { severity_ = from.severity_; } if (cached_has_bits & 0x00000010u) { status_ = from.status_; } if (cached_has_bits & 0x00000020u) { repeatcount_ = from.repeatcount_; } if (cached_has_bits & 0x00000040u) { fieldactualchange_ = from.fieldactualchange_; } _has_bits_[0] |= cached_has_bits; } } void VectorChar::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:EPICS.VectorChar) if (&from == this) return; Clear(); MergeFrom(from); } void VectorChar::CopyFrom(const VectorChar& from) { // @@protoc_insertion_point(class_specific_copy_from_start:EPICS.VectorChar) if (&from == this) return; Clear(); MergeFrom(from); } bool VectorChar::IsInitialized() const { if (_Internal::MissingRequiredFields(_has_bits_)) return false; if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(fieldvalues_)) return false; return true; } void VectorChar::InternalSwap(VectorChar* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); fieldvalues_.InternalSwap(&other->fieldvalues_); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), &val_, GetArenaForAllocation(), &other->val_, other->GetArenaForAllocation() ); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(VectorChar, fieldactualchange_) + sizeof(VectorChar::fieldactualchange_) - PROTOBUF_FIELD_OFFSET(VectorChar, secondsintoyear_)>( reinterpret_cast<char*>(&secondsintoyear_), reinterpret_cast<char*>(&other->secondsintoyear_)); } ::PROTOBUF_NAMESPACE_ID::Metadata VectorChar::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_epics_5fevent_2eproto_getter, &descriptor_table_epics_5fevent_2eproto_once, file_level_metadata_epics_5fevent_2eproto[9]); } // =================================================================== class VectorShort::_Internal { public: using HasBits = decltype(std::declval<VectorShort>()._has_bits_); static void set_has_secondsintoyear(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_nano(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static void set_has_severity(HasBits* has_bits) { (*has_bits)[0] |= 4u; } static void set_has_status(HasBits* has_bits) { (*has_bits)[0] |= 8u; } static void set_has_repeatcount(HasBits* has_bits) { (*has_bits)[0] |= 16u; } static void set_has_fieldactualchange(HasBits* has_bits) { (*has_bits)[0] |= 32u; } static bool MissingRequiredFields(const HasBits& has_bits) { return ((has_bits[0] & 0x00000003) ^ 0x00000003) != 0; } }; VectorShort::VectorShort(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena), val_(arena), fieldvalues_(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:EPICS.VectorShort) } VectorShort::VectorShort(const VectorShort& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_), val_(from.val_), fieldvalues_(from.fieldvalues_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::memcpy(&secondsintoyear_, &from.secondsintoyear_, static_cast<size_t>(reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); // @@protoc_insertion_point(copy_constructor:EPICS.VectorShort) } void VectorShort::SharedCtor() { ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&secondsintoyear_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); } VectorShort::~VectorShort() { // @@protoc_insertion_point(destructor:EPICS.VectorShort) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void VectorShort::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); } void VectorShort::ArenaDtor(void* object) { VectorShort* _this = reinterpret_cast< VectorShort* >(object); (void)_this; } void VectorShort::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void VectorShort::SetCachedSize(int size) const { _cached_size_.Set(size); } void VectorShort::Clear() { // @@protoc_insertion_point(message_clear_start:EPICS.VectorShort) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; val_.Clear(); fieldvalues_.Clear(); cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x0000003fu) { ::memset(&secondsintoyear_, 0, static_cast<size_t>( reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* VectorShort::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // required uint32 secondsintoyear = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { _Internal::set_has_secondsintoyear(&has_bits); secondsintoyear_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // required uint32 nano = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) { _Internal::set_has_nano(&has_bits); nano_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // repeated sint32 val = 3 [packed = true]; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) { ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedSInt32Parser(_internal_mutable_val(), ptr, ctx); CHK_(ptr); } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 24) { _internal_add_val(::PROTOBUF_NAMESPACE_ID::internal::ReadVarintZigZag32(&ptr)); CHK_(ptr); } else goto handle_unusual; continue; // optional int32 severity = 4 [default = 0]; case 4: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 32)) { _Internal::set_has_severity(&has_bits); severity_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional int32 status = 5 [default = 0]; case 5: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 40)) { _Internal::set_has_status(&has_bits); status_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional uint32 repeatcount = 6; case 6: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 48)) { _Internal::set_has_repeatcount(&has_bits); repeatcount_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // repeated .EPICS.FieldValue fieldvalues = 7; case 7: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 58)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseMessage(_internal_add_fieldvalues(), ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<58>(ptr)); } else goto handle_unusual; continue; // optional bool fieldactualchange = 8; case 8: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 64)) { _Internal::set_has_fieldactualchange(&has_bits); fieldactualchange_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* VectorShort::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:EPICS.VectorShort) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required uint32 secondsintoyear = 1; if (cached_has_bits & 0x00000001u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(1, this->_internal_secondsintoyear(), target); } // required uint32 nano = 2; if (cached_has_bits & 0x00000002u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(2, this->_internal_nano(), target); } // repeated sint32 val = 3 [packed = true]; { int byte_size = _val_cached_byte_size_.load(std::memory_order_relaxed); if (byte_size > 0) { target = stream->WriteSInt32Packed( 3, _internal_val(), byte_size, target); } } // optional int32 severity = 4 [default = 0]; if (cached_has_bits & 0x00000004u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(4, this->_internal_severity(), target); } // optional int32 status = 5 [default = 0]; if (cached_has_bits & 0x00000008u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(5, this->_internal_status(), target); } // optional uint32 repeatcount = 6; if (cached_has_bits & 0x00000010u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(6, this->_internal_repeatcount(), target); } // repeated .EPICS.FieldValue fieldvalues = 7; for (unsigned int i = 0, n = static_cast<unsigned int>(this->_internal_fieldvalues_size()); i < n; i++) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage(7, this->_internal_fieldvalues(i), target, stream); } // optional bool fieldactualchange = 8; if (cached_has_bits & 0x00000020u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(8, this->_internal_fieldactualchange(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:EPICS.VectorShort) return target; } size_t VectorShort::RequiredFieldsByteSizeFallback() const { // @@protoc_insertion_point(required_fields_byte_size_fallback_start:EPICS.VectorShort) size_t total_size = 0; if (_internal_has_secondsintoyear()) { // required uint32 secondsintoyear = 1; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_secondsintoyear()); } if (_internal_has_nano()) { // required uint32 nano = 2; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_nano()); } return total_size; } size_t VectorShort::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:EPICS.VectorShort) size_t total_size = 0; if (((_has_bits_[0] & 0x00000003) ^ 0x00000003) == 0) { // All required fields are present. // required uint32 secondsintoyear = 1; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_secondsintoyear()); // required uint32 nano = 2; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_nano()); } else { total_size += RequiredFieldsByteSizeFallback(); } ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated sint32 val = 3 [packed = true]; { size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: SInt32Size(this->val_); if (data_size > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size)); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(data_size); _val_cached_byte_size_.store(cached_size, std::memory_order_relaxed); total_size += data_size; } // repeated .EPICS.FieldValue fieldvalues = 7; total_size += 1UL * this->_internal_fieldvalues_size(); for (const auto& msg : this->fieldvalues_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x0000003cu) { // optional int32 severity = 4 [default = 0]; if (cached_has_bits & 0x00000004u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_severity()); } // optional int32 status = 5 [default = 0]; if (cached_has_bits & 0x00000008u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_status()); } // optional uint32 repeatcount = 6; if (cached_has_bits & 0x00000010u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_repeatcount()); } // optional bool fieldactualchange = 8; if (cached_has_bits & 0x00000020u) { total_size += 1 + 1; } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void VectorShort::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:EPICS.VectorShort) GOOGLE_DCHECK_NE(&from, this); const VectorShort* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<VectorShort>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:EPICS.VectorShort) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:EPICS.VectorShort) MergeFrom(*source); } } void VectorShort::MergeFrom(const VectorShort& from) { // @@protoc_insertion_point(class_specific_merge_from_start:EPICS.VectorShort) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; val_.MergeFrom(from.val_); fieldvalues_.MergeFrom(from.fieldvalues_); cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x0000003fu) { if (cached_has_bits & 0x00000001u) { secondsintoyear_ = from.secondsintoyear_; } if (cached_has_bits & 0x00000002u) { nano_ = from.nano_; } if (cached_has_bits & 0x00000004u) { severity_ = from.severity_; } if (cached_has_bits & 0x00000008u) { status_ = from.status_; } if (cached_has_bits & 0x00000010u) { repeatcount_ = from.repeatcount_; } if (cached_has_bits & 0x00000020u) { fieldactualchange_ = from.fieldactualchange_; } _has_bits_[0] |= cached_has_bits; } } void VectorShort::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:EPICS.VectorShort) if (&from == this) return; Clear(); MergeFrom(from); } void VectorShort::CopyFrom(const VectorShort& from) { // @@protoc_insertion_point(class_specific_copy_from_start:EPICS.VectorShort) if (&from == this) return; Clear(); MergeFrom(from); } bool VectorShort::IsInitialized() const { if (_Internal::MissingRequiredFields(_has_bits_)) return false; if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(fieldvalues_)) return false; return true; } void VectorShort::InternalSwap(VectorShort* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); val_.InternalSwap(&other->val_); fieldvalues_.InternalSwap(&other->fieldvalues_); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(VectorShort, fieldactualchange_) + sizeof(VectorShort::fieldactualchange_) - PROTOBUF_FIELD_OFFSET(VectorShort, secondsintoyear_)>( reinterpret_cast<char*>(&secondsintoyear_), reinterpret_cast<char*>(&other->secondsintoyear_)); } ::PROTOBUF_NAMESPACE_ID::Metadata VectorShort::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_epics_5fevent_2eproto_getter, &descriptor_table_epics_5fevent_2eproto_once, file_level_metadata_epics_5fevent_2eproto[10]); } // =================================================================== class VectorInt::_Internal { public: using HasBits = decltype(std::declval<VectorInt>()._has_bits_); static void set_has_secondsintoyear(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_nano(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static void set_has_severity(HasBits* has_bits) { (*has_bits)[0] |= 4u; } static void set_has_status(HasBits* has_bits) { (*has_bits)[0] |= 8u; } static void set_has_repeatcount(HasBits* has_bits) { (*has_bits)[0] |= 16u; } static void set_has_fieldactualchange(HasBits* has_bits) { (*has_bits)[0] |= 32u; } static bool MissingRequiredFields(const HasBits& has_bits) { return ((has_bits[0] & 0x00000003) ^ 0x00000003) != 0; } }; VectorInt::VectorInt(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena), val_(arena), fieldvalues_(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:EPICS.VectorInt) } VectorInt::VectorInt(const VectorInt& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_), val_(from.val_), fieldvalues_(from.fieldvalues_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::memcpy(&secondsintoyear_, &from.secondsintoyear_, static_cast<size_t>(reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); // @@protoc_insertion_point(copy_constructor:EPICS.VectorInt) } void VectorInt::SharedCtor() { ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&secondsintoyear_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); } VectorInt::~VectorInt() { // @@protoc_insertion_point(destructor:EPICS.VectorInt) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void VectorInt::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); } void VectorInt::ArenaDtor(void* object) { VectorInt* _this = reinterpret_cast< VectorInt* >(object); (void)_this; } void VectorInt::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void VectorInt::SetCachedSize(int size) const { _cached_size_.Set(size); } void VectorInt::Clear() { // @@protoc_insertion_point(message_clear_start:EPICS.VectorInt) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; val_.Clear(); fieldvalues_.Clear(); cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x0000003fu) { ::memset(&secondsintoyear_, 0, static_cast<size_t>( reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* VectorInt::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // required uint32 secondsintoyear = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { _Internal::set_has_secondsintoyear(&has_bits); secondsintoyear_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // required uint32 nano = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) { _Internal::set_has_nano(&has_bits); nano_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // repeated sfixed32 val = 3 [packed = true]; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) { ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedSFixed32Parser(_internal_mutable_val(), ptr, ctx); CHK_(ptr); } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 29) { _internal_add_val(::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::int32>(ptr)); ptr += sizeof(::PROTOBUF_NAMESPACE_ID::int32); } else goto handle_unusual; continue; // optional int32 severity = 4 [default = 0]; case 4: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 32)) { _Internal::set_has_severity(&has_bits); severity_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional int32 status = 5 [default = 0]; case 5: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 40)) { _Internal::set_has_status(&has_bits); status_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional uint32 repeatcount = 6; case 6: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 48)) { _Internal::set_has_repeatcount(&has_bits); repeatcount_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // repeated .EPICS.FieldValue fieldvalues = 7; case 7: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 58)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseMessage(_internal_add_fieldvalues(), ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<58>(ptr)); } else goto handle_unusual; continue; // optional bool fieldactualchange = 8; case 8: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 64)) { _Internal::set_has_fieldactualchange(&has_bits); fieldactualchange_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* VectorInt::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:EPICS.VectorInt) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required uint32 secondsintoyear = 1; if (cached_has_bits & 0x00000001u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(1, this->_internal_secondsintoyear(), target); } // required uint32 nano = 2; if (cached_has_bits & 0x00000002u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(2, this->_internal_nano(), target); } // repeated sfixed32 val = 3 [packed = true]; if (this->_internal_val_size() > 0) { target = stream->WriteFixedPacked(3, _internal_val(), target); } // optional int32 severity = 4 [default = 0]; if (cached_has_bits & 0x00000004u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(4, this->_internal_severity(), target); } // optional int32 status = 5 [default = 0]; if (cached_has_bits & 0x00000008u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(5, this->_internal_status(), target); } // optional uint32 repeatcount = 6; if (cached_has_bits & 0x00000010u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(6, this->_internal_repeatcount(), target); } // repeated .EPICS.FieldValue fieldvalues = 7; for (unsigned int i = 0, n = static_cast<unsigned int>(this->_internal_fieldvalues_size()); i < n; i++) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage(7, this->_internal_fieldvalues(i), target, stream); } // optional bool fieldactualchange = 8; if (cached_has_bits & 0x00000020u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(8, this->_internal_fieldactualchange(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:EPICS.VectorInt) return target; } size_t VectorInt::RequiredFieldsByteSizeFallback() const { // @@protoc_insertion_point(required_fields_byte_size_fallback_start:EPICS.VectorInt) size_t total_size = 0; if (_internal_has_secondsintoyear()) { // required uint32 secondsintoyear = 1; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_secondsintoyear()); } if (_internal_has_nano()) { // required uint32 nano = 2; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_nano()); } return total_size; } size_t VectorInt::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:EPICS.VectorInt) size_t total_size = 0; if (((_has_bits_[0] & 0x00000003) ^ 0x00000003) == 0) { // All required fields are present. // required uint32 secondsintoyear = 1; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_secondsintoyear()); // required uint32 nano = 2; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_nano()); } else { total_size += RequiredFieldsByteSizeFallback(); } ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated sfixed32 val = 3 [packed = true]; { unsigned int count = static_cast<unsigned int>(this->_internal_val_size()); size_t data_size = 4UL * count; if (data_size > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size)); } total_size += data_size; } // repeated .EPICS.FieldValue fieldvalues = 7; total_size += 1UL * this->_internal_fieldvalues_size(); for (const auto& msg : this->fieldvalues_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x0000003cu) { // optional int32 severity = 4 [default = 0]; if (cached_has_bits & 0x00000004u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_severity()); } // optional int32 status = 5 [default = 0]; if (cached_has_bits & 0x00000008u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_status()); } // optional uint32 repeatcount = 6; if (cached_has_bits & 0x00000010u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_repeatcount()); } // optional bool fieldactualchange = 8; if (cached_has_bits & 0x00000020u) { total_size += 1 + 1; } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void VectorInt::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:EPICS.VectorInt) GOOGLE_DCHECK_NE(&from, this); const VectorInt* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<VectorInt>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:EPICS.VectorInt) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:EPICS.VectorInt) MergeFrom(*source); } } void VectorInt::MergeFrom(const VectorInt& from) { // @@protoc_insertion_point(class_specific_merge_from_start:EPICS.VectorInt) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; val_.MergeFrom(from.val_); fieldvalues_.MergeFrom(from.fieldvalues_); cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x0000003fu) { if (cached_has_bits & 0x00000001u) { secondsintoyear_ = from.secondsintoyear_; } if (cached_has_bits & 0x00000002u) { nano_ = from.nano_; } if (cached_has_bits & 0x00000004u) { severity_ = from.severity_; } if (cached_has_bits & 0x00000008u) { status_ = from.status_; } if (cached_has_bits & 0x00000010u) { repeatcount_ = from.repeatcount_; } if (cached_has_bits & 0x00000020u) { fieldactualchange_ = from.fieldactualchange_; } _has_bits_[0] |= cached_has_bits; } } void VectorInt::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:EPICS.VectorInt) if (&from == this) return; Clear(); MergeFrom(from); } void VectorInt::CopyFrom(const VectorInt& from) { // @@protoc_insertion_point(class_specific_copy_from_start:EPICS.VectorInt) if (&from == this) return; Clear(); MergeFrom(from); } bool VectorInt::IsInitialized() const { if (_Internal::MissingRequiredFields(_has_bits_)) return false; if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(fieldvalues_)) return false; return true; } void VectorInt::InternalSwap(VectorInt* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); val_.InternalSwap(&other->val_); fieldvalues_.InternalSwap(&other->fieldvalues_); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(VectorInt, fieldactualchange_) + sizeof(VectorInt::fieldactualchange_) - PROTOBUF_FIELD_OFFSET(VectorInt, secondsintoyear_)>( reinterpret_cast<char*>(&secondsintoyear_), reinterpret_cast<char*>(&other->secondsintoyear_)); } ::PROTOBUF_NAMESPACE_ID::Metadata VectorInt::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_epics_5fevent_2eproto_getter, &descriptor_table_epics_5fevent_2eproto_once, file_level_metadata_epics_5fevent_2eproto[11]); } // =================================================================== class VectorEnum::_Internal { public: using HasBits = decltype(std::declval<VectorEnum>()._has_bits_); static void set_has_secondsintoyear(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_nano(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static void set_has_severity(HasBits* has_bits) { (*has_bits)[0] |= 4u; } static void set_has_status(HasBits* has_bits) { (*has_bits)[0] |= 8u; } static void set_has_repeatcount(HasBits* has_bits) { (*has_bits)[0] |= 16u; } static void set_has_fieldactualchange(HasBits* has_bits) { (*has_bits)[0] |= 32u; } static bool MissingRequiredFields(const HasBits& has_bits) { return ((has_bits[0] & 0x00000003) ^ 0x00000003) != 0; } }; VectorEnum::VectorEnum(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena), val_(arena), fieldvalues_(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:EPICS.VectorEnum) } VectorEnum::VectorEnum(const VectorEnum& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_), val_(from.val_), fieldvalues_(from.fieldvalues_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::memcpy(&secondsintoyear_, &from.secondsintoyear_, static_cast<size_t>(reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); // @@protoc_insertion_point(copy_constructor:EPICS.VectorEnum) } void VectorEnum::SharedCtor() { ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&secondsintoyear_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); } VectorEnum::~VectorEnum() { // @@protoc_insertion_point(destructor:EPICS.VectorEnum) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void VectorEnum::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); } void VectorEnum::ArenaDtor(void* object) { VectorEnum* _this = reinterpret_cast< VectorEnum* >(object); (void)_this; } void VectorEnum::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void VectorEnum::SetCachedSize(int size) const { _cached_size_.Set(size); } void VectorEnum::Clear() { // @@protoc_insertion_point(message_clear_start:EPICS.VectorEnum) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; val_.Clear(); fieldvalues_.Clear(); cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x0000003fu) { ::memset(&secondsintoyear_, 0, static_cast<size_t>( reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* VectorEnum::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // required uint32 secondsintoyear = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { _Internal::set_has_secondsintoyear(&has_bits); secondsintoyear_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // required uint32 nano = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) { _Internal::set_has_nano(&has_bits); nano_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // repeated sint32 val = 3 [packed = true]; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) { ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedSInt32Parser(_internal_mutable_val(), ptr, ctx); CHK_(ptr); } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 24) { _internal_add_val(::PROTOBUF_NAMESPACE_ID::internal::ReadVarintZigZag32(&ptr)); CHK_(ptr); } else goto handle_unusual; continue; // optional int32 severity = 4 [default = 0]; case 4: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 32)) { _Internal::set_has_severity(&has_bits); severity_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional int32 status = 5 [default = 0]; case 5: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 40)) { _Internal::set_has_status(&has_bits); status_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional uint32 repeatcount = 6; case 6: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 48)) { _Internal::set_has_repeatcount(&has_bits); repeatcount_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // repeated .EPICS.FieldValue fieldvalues = 7; case 7: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 58)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseMessage(_internal_add_fieldvalues(), ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<58>(ptr)); } else goto handle_unusual; continue; // optional bool fieldactualchange = 8; case 8: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 64)) { _Internal::set_has_fieldactualchange(&has_bits); fieldactualchange_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* VectorEnum::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:EPICS.VectorEnum) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required uint32 secondsintoyear = 1; if (cached_has_bits & 0x00000001u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(1, this->_internal_secondsintoyear(), target); } // required uint32 nano = 2; if (cached_has_bits & 0x00000002u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(2, this->_internal_nano(), target); } // repeated sint32 val = 3 [packed = true]; { int byte_size = _val_cached_byte_size_.load(std::memory_order_relaxed); if (byte_size > 0) { target = stream->WriteSInt32Packed( 3, _internal_val(), byte_size, target); } } // optional int32 severity = 4 [default = 0]; if (cached_has_bits & 0x00000004u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(4, this->_internal_severity(), target); } // optional int32 status = 5 [default = 0]; if (cached_has_bits & 0x00000008u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(5, this->_internal_status(), target); } // optional uint32 repeatcount = 6; if (cached_has_bits & 0x00000010u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(6, this->_internal_repeatcount(), target); } // repeated .EPICS.FieldValue fieldvalues = 7; for (unsigned int i = 0, n = static_cast<unsigned int>(this->_internal_fieldvalues_size()); i < n; i++) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage(7, this->_internal_fieldvalues(i), target, stream); } // optional bool fieldactualchange = 8; if (cached_has_bits & 0x00000020u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(8, this->_internal_fieldactualchange(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:EPICS.VectorEnum) return target; } size_t VectorEnum::RequiredFieldsByteSizeFallback() const { // @@protoc_insertion_point(required_fields_byte_size_fallback_start:EPICS.VectorEnum) size_t total_size = 0; if (_internal_has_secondsintoyear()) { // required uint32 secondsintoyear = 1; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_secondsintoyear()); } if (_internal_has_nano()) { // required uint32 nano = 2; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_nano()); } return total_size; } size_t VectorEnum::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:EPICS.VectorEnum) size_t total_size = 0; if (((_has_bits_[0] & 0x00000003) ^ 0x00000003) == 0) { // All required fields are present. // required uint32 secondsintoyear = 1; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_secondsintoyear()); // required uint32 nano = 2; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_nano()); } else { total_size += RequiredFieldsByteSizeFallback(); } ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated sint32 val = 3 [packed = true]; { size_t data_size = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: SInt32Size(this->val_); if (data_size > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size)); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(data_size); _val_cached_byte_size_.store(cached_size, std::memory_order_relaxed); total_size += data_size; } // repeated .EPICS.FieldValue fieldvalues = 7; total_size += 1UL * this->_internal_fieldvalues_size(); for (const auto& msg : this->fieldvalues_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x0000003cu) { // optional int32 severity = 4 [default = 0]; if (cached_has_bits & 0x00000004u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_severity()); } // optional int32 status = 5 [default = 0]; if (cached_has_bits & 0x00000008u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_status()); } // optional uint32 repeatcount = 6; if (cached_has_bits & 0x00000010u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_repeatcount()); } // optional bool fieldactualchange = 8; if (cached_has_bits & 0x00000020u) { total_size += 1 + 1; } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void VectorEnum::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:EPICS.VectorEnum) GOOGLE_DCHECK_NE(&from, this); const VectorEnum* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<VectorEnum>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:EPICS.VectorEnum) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:EPICS.VectorEnum) MergeFrom(*source); } } void VectorEnum::MergeFrom(const VectorEnum& from) { // @@protoc_insertion_point(class_specific_merge_from_start:EPICS.VectorEnum) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; val_.MergeFrom(from.val_); fieldvalues_.MergeFrom(from.fieldvalues_); cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x0000003fu) { if (cached_has_bits & 0x00000001u) { secondsintoyear_ = from.secondsintoyear_; } if (cached_has_bits & 0x00000002u) { nano_ = from.nano_; } if (cached_has_bits & 0x00000004u) { severity_ = from.severity_; } if (cached_has_bits & 0x00000008u) { status_ = from.status_; } if (cached_has_bits & 0x00000010u) { repeatcount_ = from.repeatcount_; } if (cached_has_bits & 0x00000020u) { fieldactualchange_ = from.fieldactualchange_; } _has_bits_[0] |= cached_has_bits; } } void VectorEnum::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:EPICS.VectorEnum) if (&from == this) return; Clear(); MergeFrom(from); } void VectorEnum::CopyFrom(const VectorEnum& from) { // @@protoc_insertion_point(class_specific_copy_from_start:EPICS.VectorEnum) if (&from == this) return; Clear(); MergeFrom(from); } bool VectorEnum::IsInitialized() const { if (_Internal::MissingRequiredFields(_has_bits_)) return false; if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(fieldvalues_)) return false; return true; } void VectorEnum::InternalSwap(VectorEnum* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); val_.InternalSwap(&other->val_); fieldvalues_.InternalSwap(&other->fieldvalues_); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(VectorEnum, fieldactualchange_) + sizeof(VectorEnum::fieldactualchange_) - PROTOBUF_FIELD_OFFSET(VectorEnum, secondsintoyear_)>( reinterpret_cast<char*>(&secondsintoyear_), reinterpret_cast<char*>(&other->secondsintoyear_)); } ::PROTOBUF_NAMESPACE_ID::Metadata VectorEnum::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_epics_5fevent_2eproto_getter, &descriptor_table_epics_5fevent_2eproto_once, file_level_metadata_epics_5fevent_2eproto[12]); } // =================================================================== class VectorFloat::_Internal { public: using HasBits = decltype(std::declval<VectorFloat>()._has_bits_); static void set_has_secondsintoyear(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_nano(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static void set_has_severity(HasBits* has_bits) { (*has_bits)[0] |= 4u; } static void set_has_status(HasBits* has_bits) { (*has_bits)[0] |= 8u; } static void set_has_repeatcount(HasBits* has_bits) { (*has_bits)[0] |= 16u; } static void set_has_fieldactualchange(HasBits* has_bits) { (*has_bits)[0] |= 32u; } static bool MissingRequiredFields(const HasBits& has_bits) { return ((has_bits[0] & 0x00000003) ^ 0x00000003) != 0; } }; VectorFloat::VectorFloat(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena), val_(arena), fieldvalues_(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:EPICS.VectorFloat) } VectorFloat::VectorFloat(const VectorFloat& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_), val_(from.val_), fieldvalues_(from.fieldvalues_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::memcpy(&secondsintoyear_, &from.secondsintoyear_, static_cast<size_t>(reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); // @@protoc_insertion_point(copy_constructor:EPICS.VectorFloat) } void VectorFloat::SharedCtor() { ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&secondsintoyear_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); } VectorFloat::~VectorFloat() { // @@protoc_insertion_point(destructor:EPICS.VectorFloat) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void VectorFloat::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); } void VectorFloat::ArenaDtor(void* object) { VectorFloat* _this = reinterpret_cast< VectorFloat* >(object); (void)_this; } void VectorFloat::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void VectorFloat::SetCachedSize(int size) const { _cached_size_.Set(size); } void VectorFloat::Clear() { // @@protoc_insertion_point(message_clear_start:EPICS.VectorFloat) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; val_.Clear(); fieldvalues_.Clear(); cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x0000003fu) { ::memset(&secondsintoyear_, 0, static_cast<size_t>( reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* VectorFloat::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // required uint32 secondsintoyear = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { _Internal::set_has_secondsintoyear(&has_bits); secondsintoyear_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // required uint32 nano = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) { _Internal::set_has_nano(&has_bits); nano_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // repeated float val = 3 [packed = true]; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) { ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedFloatParser(_internal_mutable_val(), ptr, ctx); CHK_(ptr); } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 29) { _internal_add_val(::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr)); ptr += sizeof(float); } else goto handle_unusual; continue; // optional int32 severity = 4 [default = 0]; case 4: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 32)) { _Internal::set_has_severity(&has_bits); severity_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional int32 status = 5 [default = 0]; case 5: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 40)) { _Internal::set_has_status(&has_bits); status_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional uint32 repeatcount = 6; case 6: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 48)) { _Internal::set_has_repeatcount(&has_bits); repeatcount_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // repeated .EPICS.FieldValue fieldvalues = 7; case 7: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 58)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseMessage(_internal_add_fieldvalues(), ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<58>(ptr)); } else goto handle_unusual; continue; // optional bool fieldactualchange = 8; case 8: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 64)) { _Internal::set_has_fieldactualchange(&has_bits); fieldactualchange_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* VectorFloat::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:EPICS.VectorFloat) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required uint32 secondsintoyear = 1; if (cached_has_bits & 0x00000001u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(1, this->_internal_secondsintoyear(), target); } // required uint32 nano = 2; if (cached_has_bits & 0x00000002u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(2, this->_internal_nano(), target); } // repeated float val = 3 [packed = true]; if (this->_internal_val_size() > 0) { target = stream->WriteFixedPacked(3, _internal_val(), target); } // optional int32 severity = 4 [default = 0]; if (cached_has_bits & 0x00000004u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(4, this->_internal_severity(), target); } // optional int32 status = 5 [default = 0]; if (cached_has_bits & 0x00000008u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(5, this->_internal_status(), target); } // optional uint32 repeatcount = 6; if (cached_has_bits & 0x00000010u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(6, this->_internal_repeatcount(), target); } // repeated .EPICS.FieldValue fieldvalues = 7; for (unsigned int i = 0, n = static_cast<unsigned int>(this->_internal_fieldvalues_size()); i < n; i++) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage(7, this->_internal_fieldvalues(i), target, stream); } // optional bool fieldactualchange = 8; if (cached_has_bits & 0x00000020u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(8, this->_internal_fieldactualchange(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:EPICS.VectorFloat) return target; } size_t VectorFloat::RequiredFieldsByteSizeFallback() const { // @@protoc_insertion_point(required_fields_byte_size_fallback_start:EPICS.VectorFloat) size_t total_size = 0; if (_internal_has_secondsintoyear()) { // required uint32 secondsintoyear = 1; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_secondsintoyear()); } if (_internal_has_nano()) { // required uint32 nano = 2; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_nano()); } return total_size; } size_t VectorFloat::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:EPICS.VectorFloat) size_t total_size = 0; if (((_has_bits_[0] & 0x00000003) ^ 0x00000003) == 0) { // All required fields are present. // required uint32 secondsintoyear = 1; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_secondsintoyear()); // required uint32 nano = 2; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_nano()); } else { total_size += RequiredFieldsByteSizeFallback(); } ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated float val = 3 [packed = true]; { unsigned int count = static_cast<unsigned int>(this->_internal_val_size()); size_t data_size = 4UL * count; if (data_size > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size)); } total_size += data_size; } // repeated .EPICS.FieldValue fieldvalues = 7; total_size += 1UL * this->_internal_fieldvalues_size(); for (const auto& msg : this->fieldvalues_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x0000003cu) { // optional int32 severity = 4 [default = 0]; if (cached_has_bits & 0x00000004u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_severity()); } // optional int32 status = 5 [default = 0]; if (cached_has_bits & 0x00000008u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_status()); } // optional uint32 repeatcount = 6; if (cached_has_bits & 0x00000010u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_repeatcount()); } // optional bool fieldactualchange = 8; if (cached_has_bits & 0x00000020u) { total_size += 1 + 1; } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void VectorFloat::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:EPICS.VectorFloat) GOOGLE_DCHECK_NE(&from, this); const VectorFloat* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<VectorFloat>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:EPICS.VectorFloat) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:EPICS.VectorFloat) MergeFrom(*source); } } void VectorFloat::MergeFrom(const VectorFloat& from) { // @@protoc_insertion_point(class_specific_merge_from_start:EPICS.VectorFloat) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; val_.MergeFrom(from.val_); fieldvalues_.MergeFrom(from.fieldvalues_); cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x0000003fu) { if (cached_has_bits & 0x00000001u) { secondsintoyear_ = from.secondsintoyear_; } if (cached_has_bits & 0x00000002u) { nano_ = from.nano_; } if (cached_has_bits & 0x00000004u) { severity_ = from.severity_; } if (cached_has_bits & 0x00000008u) { status_ = from.status_; } if (cached_has_bits & 0x00000010u) { repeatcount_ = from.repeatcount_; } if (cached_has_bits & 0x00000020u) { fieldactualchange_ = from.fieldactualchange_; } _has_bits_[0] |= cached_has_bits; } } void VectorFloat::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:EPICS.VectorFloat) if (&from == this) return; Clear(); MergeFrom(from); } void VectorFloat::CopyFrom(const VectorFloat& from) { // @@protoc_insertion_point(class_specific_copy_from_start:EPICS.VectorFloat) if (&from == this) return; Clear(); MergeFrom(from); } bool VectorFloat::IsInitialized() const { if (_Internal::MissingRequiredFields(_has_bits_)) return false; if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(fieldvalues_)) return false; return true; } void VectorFloat::InternalSwap(VectorFloat* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); val_.InternalSwap(&other->val_); fieldvalues_.InternalSwap(&other->fieldvalues_); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(VectorFloat, fieldactualchange_) + sizeof(VectorFloat::fieldactualchange_) - PROTOBUF_FIELD_OFFSET(VectorFloat, secondsintoyear_)>( reinterpret_cast<char*>(&secondsintoyear_), reinterpret_cast<char*>(&other->secondsintoyear_)); } ::PROTOBUF_NAMESPACE_ID::Metadata VectorFloat::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_epics_5fevent_2eproto_getter, &descriptor_table_epics_5fevent_2eproto_once, file_level_metadata_epics_5fevent_2eproto[13]); } // =================================================================== class VectorDouble::_Internal { public: using HasBits = decltype(std::declval<VectorDouble>()._has_bits_); static void set_has_secondsintoyear(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_nano(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static void set_has_severity(HasBits* has_bits) { (*has_bits)[0] |= 4u; } static void set_has_status(HasBits* has_bits) { (*has_bits)[0] |= 8u; } static void set_has_repeatcount(HasBits* has_bits) { (*has_bits)[0] |= 16u; } static void set_has_fieldactualchange(HasBits* has_bits) { (*has_bits)[0] |= 32u; } static bool MissingRequiredFields(const HasBits& has_bits) { return ((has_bits[0] & 0x00000003) ^ 0x00000003) != 0; } }; VectorDouble::VectorDouble(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena), val_(arena), fieldvalues_(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:EPICS.VectorDouble) } VectorDouble::VectorDouble(const VectorDouble& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_), val_(from.val_), fieldvalues_(from.fieldvalues_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::memcpy(&secondsintoyear_, &from.secondsintoyear_, static_cast<size_t>(reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); // @@protoc_insertion_point(copy_constructor:EPICS.VectorDouble) } void VectorDouble::SharedCtor() { ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&secondsintoyear_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); } VectorDouble::~VectorDouble() { // @@protoc_insertion_point(destructor:EPICS.VectorDouble) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void VectorDouble::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); } void VectorDouble::ArenaDtor(void* object) { VectorDouble* _this = reinterpret_cast< VectorDouble* >(object); (void)_this; } void VectorDouble::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void VectorDouble::SetCachedSize(int size) const { _cached_size_.Set(size); } void VectorDouble::Clear() { // @@protoc_insertion_point(message_clear_start:EPICS.VectorDouble) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; val_.Clear(); fieldvalues_.Clear(); cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x0000003fu) { ::memset(&secondsintoyear_, 0, static_cast<size_t>( reinterpret_cast<char*>(&fieldactualchange_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(fieldactualchange_)); } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* VectorDouble::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // required uint32 secondsintoyear = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { _Internal::set_has_secondsintoyear(&has_bits); secondsintoyear_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // required uint32 nano = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) { _Internal::set_has_nano(&has_bits); nano_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // repeated double val = 3 [packed = true]; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) { ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedDoubleParser(_internal_mutable_val(), ptr, ctx); CHK_(ptr); } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 25) { _internal_add_val(::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<double>(ptr)); ptr += sizeof(double); } else goto handle_unusual; continue; // optional int32 severity = 4 [default = 0]; case 4: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 32)) { _Internal::set_has_severity(&has_bits); severity_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional int32 status = 5 [default = 0]; case 5: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 40)) { _Internal::set_has_status(&has_bits); status_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional uint32 repeatcount = 6; case 6: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 48)) { _Internal::set_has_repeatcount(&has_bits); repeatcount_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // repeated .EPICS.FieldValue fieldvalues = 7; case 7: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 58)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseMessage(_internal_add_fieldvalues(), ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<58>(ptr)); } else goto handle_unusual; continue; // optional bool fieldactualchange = 8; case 8: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 64)) { _Internal::set_has_fieldactualchange(&has_bits); fieldactualchange_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* VectorDouble::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:EPICS.VectorDouble) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required uint32 secondsintoyear = 1; if (cached_has_bits & 0x00000001u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(1, this->_internal_secondsintoyear(), target); } // required uint32 nano = 2; if (cached_has_bits & 0x00000002u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(2, this->_internal_nano(), target); } // repeated double val = 3 [packed = true]; if (this->_internal_val_size() > 0) { target = stream->WriteFixedPacked(3, _internal_val(), target); } // optional int32 severity = 4 [default = 0]; if (cached_has_bits & 0x00000004u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(4, this->_internal_severity(), target); } // optional int32 status = 5 [default = 0]; if (cached_has_bits & 0x00000008u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(5, this->_internal_status(), target); } // optional uint32 repeatcount = 6; if (cached_has_bits & 0x00000010u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(6, this->_internal_repeatcount(), target); } // repeated .EPICS.FieldValue fieldvalues = 7; for (unsigned int i = 0, n = static_cast<unsigned int>(this->_internal_fieldvalues_size()); i < n; i++) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage(7, this->_internal_fieldvalues(i), target, stream); } // optional bool fieldactualchange = 8; if (cached_has_bits & 0x00000020u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(8, this->_internal_fieldactualchange(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:EPICS.VectorDouble) return target; } size_t VectorDouble::RequiredFieldsByteSizeFallback() const { // @@protoc_insertion_point(required_fields_byte_size_fallback_start:EPICS.VectorDouble) size_t total_size = 0; if (_internal_has_secondsintoyear()) { // required uint32 secondsintoyear = 1; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_secondsintoyear()); } if (_internal_has_nano()) { // required uint32 nano = 2; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_nano()); } return total_size; } size_t VectorDouble::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:EPICS.VectorDouble) size_t total_size = 0; if (((_has_bits_[0] & 0x00000003) ^ 0x00000003) == 0) { // All required fields are present. // required uint32 secondsintoyear = 1; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_secondsintoyear()); // required uint32 nano = 2; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_nano()); } else { total_size += RequiredFieldsByteSizeFallback(); } ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated double val = 3 [packed = true]; { unsigned int count = static_cast<unsigned int>(this->_internal_val_size()); size_t data_size = 8UL * count; if (data_size > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size)); } total_size += data_size; } // repeated .EPICS.FieldValue fieldvalues = 7; total_size += 1UL * this->_internal_fieldvalues_size(); for (const auto& msg : this->fieldvalues_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x0000003cu) { // optional int32 severity = 4 [default = 0]; if (cached_has_bits & 0x00000004u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_severity()); } // optional int32 status = 5 [default = 0]; if (cached_has_bits & 0x00000008u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_status()); } // optional uint32 repeatcount = 6; if (cached_has_bits & 0x00000010u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_repeatcount()); } // optional bool fieldactualchange = 8; if (cached_has_bits & 0x00000020u) { total_size += 1 + 1; } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void VectorDouble::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:EPICS.VectorDouble) GOOGLE_DCHECK_NE(&from, this); const VectorDouble* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<VectorDouble>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:EPICS.VectorDouble) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:EPICS.VectorDouble) MergeFrom(*source); } } void VectorDouble::MergeFrom(const VectorDouble& from) { // @@protoc_insertion_point(class_specific_merge_from_start:EPICS.VectorDouble) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; val_.MergeFrom(from.val_); fieldvalues_.MergeFrom(from.fieldvalues_); cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x0000003fu) { if (cached_has_bits & 0x00000001u) { secondsintoyear_ = from.secondsintoyear_; } if (cached_has_bits & 0x00000002u) { nano_ = from.nano_; } if (cached_has_bits & 0x00000004u) { severity_ = from.severity_; } if (cached_has_bits & 0x00000008u) { status_ = from.status_; } if (cached_has_bits & 0x00000010u) { repeatcount_ = from.repeatcount_; } if (cached_has_bits & 0x00000020u) { fieldactualchange_ = from.fieldactualchange_; } _has_bits_[0] |= cached_has_bits; } } void VectorDouble::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:EPICS.VectorDouble) if (&from == this) return; Clear(); MergeFrom(from); } void VectorDouble::CopyFrom(const VectorDouble& from) { // @@protoc_insertion_point(class_specific_copy_from_start:EPICS.VectorDouble) if (&from == this) return; Clear(); MergeFrom(from); } bool VectorDouble::IsInitialized() const { if (_Internal::MissingRequiredFields(_has_bits_)) return false; if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(fieldvalues_)) return false; return true; } void VectorDouble::InternalSwap(VectorDouble* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); val_.InternalSwap(&other->val_); fieldvalues_.InternalSwap(&other->fieldvalues_); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(VectorDouble, fieldactualchange_) + sizeof(VectorDouble::fieldactualchange_) - PROTOBUF_FIELD_OFFSET(VectorDouble, secondsintoyear_)>( reinterpret_cast<char*>(&secondsintoyear_), reinterpret_cast<char*>(&other->secondsintoyear_)); } ::PROTOBUF_NAMESPACE_ID::Metadata VectorDouble::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_epics_5fevent_2eproto_getter, &descriptor_table_epics_5fevent_2eproto_once, file_level_metadata_epics_5fevent_2eproto[14]); } // =================================================================== class V4GenericBytes::_Internal { public: using HasBits = decltype(std::declval<V4GenericBytes>()._has_bits_); static void set_has_secondsintoyear(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static void set_has_nano(HasBits* has_bits) { (*has_bits)[0] |= 4u; } static void set_has_val(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_severity(HasBits* has_bits) { (*has_bits)[0] |= 8u; } static void set_has_status(HasBits* has_bits) { (*has_bits)[0] |= 16u; } static void set_has_repeatcount(HasBits* has_bits) { (*has_bits)[0] |= 32u; } static void set_has_fieldactualchange(HasBits* has_bits) { (*has_bits)[0] |= 64u; } static void set_has_usertag(HasBits* has_bits) { (*has_bits)[0] |= 128u; } static bool MissingRequiredFields(const HasBits& has_bits) { return ((has_bits[0] & 0x00000007) ^ 0x00000007) != 0; } }; V4GenericBytes::V4GenericBytes(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena), fieldvalues_(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:EPICS.V4GenericBytes) } V4GenericBytes::V4GenericBytes(const V4GenericBytes& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_), fieldvalues_(from.fieldvalues_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); val_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_val()) { val_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_val(), GetArenaForAllocation()); } ::memcpy(&secondsintoyear_, &from.secondsintoyear_, static_cast<size_t>(reinterpret_cast<char*>(&usertag_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(usertag_)); // @@protoc_insertion_point(copy_constructor:EPICS.V4GenericBytes) } void V4GenericBytes::SharedCtor() { val_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&secondsintoyear_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&usertag_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(usertag_)); } V4GenericBytes::~V4GenericBytes() { // @@protoc_insertion_point(destructor:EPICS.V4GenericBytes) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void V4GenericBytes::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); val_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } void V4GenericBytes::ArenaDtor(void* object) { V4GenericBytes* _this = reinterpret_cast< V4GenericBytes* >(object); (void)_this; } void V4GenericBytes::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void V4GenericBytes::SetCachedSize(int size) const { _cached_size_.Set(size); } void V4GenericBytes::Clear() { // @@protoc_insertion_point(message_clear_start:EPICS.V4GenericBytes) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; fieldvalues_.Clear(); cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000001u) { val_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x000000feu) { ::memset(&secondsintoyear_, 0, static_cast<size_t>( reinterpret_cast<char*>(&usertag_) - reinterpret_cast<char*>(&secondsintoyear_)) + sizeof(usertag_)); } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* V4GenericBytes::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // required uint32 secondsintoyear = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { _Internal::set_has_secondsintoyear(&has_bits); secondsintoyear_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // required uint32 nano = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 16)) { _Internal::set_has_nano(&has_bits); nano_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // required bytes val = 3; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) { auto str = _internal_mutable_val(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; // optional int32 severity = 4 [default = 0]; case 4: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 32)) { _Internal::set_has_severity(&has_bits); severity_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional int32 status = 5 [default = 0]; case 5: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 40)) { _Internal::set_has_status(&has_bits); status_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional uint32 repeatcount = 6; case 6: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 48)) { _Internal::set_has_repeatcount(&has_bits); repeatcount_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // repeated .EPICS.FieldValue fieldvalues = 7; case 7: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 58)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseMessage(_internal_add_fieldvalues(), ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<58>(ptr)); } else goto handle_unusual; continue; // optional bool fieldactualchange = 8; case 8: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 64)) { _Internal::set_has_fieldactualchange(&has_bits); fieldactualchange_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional uint32 userTag = 9; case 9: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 72)) { _Internal::set_has_usertag(&has_bits); usertag_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* V4GenericBytes::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:EPICS.V4GenericBytes) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required uint32 secondsintoyear = 1; if (cached_has_bits & 0x00000002u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(1, this->_internal_secondsintoyear(), target); } // required uint32 nano = 2; if (cached_has_bits & 0x00000004u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(2, this->_internal_nano(), target); } // required bytes val = 3; if (cached_has_bits & 0x00000001u) { target = stream->WriteBytesMaybeAliased( 3, this->_internal_val(), target); } // optional int32 severity = 4 [default = 0]; if (cached_has_bits & 0x00000008u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(4, this->_internal_severity(), target); } // optional int32 status = 5 [default = 0]; if (cached_has_bits & 0x00000010u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(5, this->_internal_status(), target); } // optional uint32 repeatcount = 6; if (cached_has_bits & 0x00000020u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(6, this->_internal_repeatcount(), target); } // repeated .EPICS.FieldValue fieldvalues = 7; for (unsigned int i = 0, n = static_cast<unsigned int>(this->_internal_fieldvalues_size()); i < n; i++) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage(7, this->_internal_fieldvalues(i), target, stream); } // optional bool fieldactualchange = 8; if (cached_has_bits & 0x00000040u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(8, this->_internal_fieldactualchange(), target); } // optional uint32 userTag = 9; if (cached_has_bits & 0x00000080u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteUInt32ToArray(9, this->_internal_usertag(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:EPICS.V4GenericBytes) return target; } size_t V4GenericBytes::RequiredFieldsByteSizeFallback() const { // @@protoc_insertion_point(required_fields_byte_size_fallback_start:EPICS.V4GenericBytes) size_t total_size = 0; if (_internal_has_val()) { // required bytes val = 3; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::BytesSize( this->_internal_val()); } if (_internal_has_secondsintoyear()) { // required uint32 secondsintoyear = 1; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_secondsintoyear()); } if (_internal_has_nano()) { // required uint32 nano = 2; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_nano()); } return total_size; } size_t V4GenericBytes::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:EPICS.V4GenericBytes) size_t total_size = 0; if (((_has_bits_[0] & 0x00000007) ^ 0x00000007) == 0) { // All required fields are present. // required bytes val = 3; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::BytesSize( this->_internal_val()); // required uint32 secondsintoyear = 1; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_secondsintoyear()); // required uint32 nano = 2; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_nano()); } else { total_size += RequiredFieldsByteSizeFallback(); } ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated .EPICS.FieldValue fieldvalues = 7; total_size += 1UL * this->_internal_fieldvalues_size(); for (const auto& msg : this->fieldvalues_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x000000f8u) { // optional int32 severity = 4 [default = 0]; if (cached_has_bits & 0x00000008u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_severity()); } // optional int32 status = 5 [default = 0]; if (cached_has_bits & 0x00000010u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_status()); } // optional uint32 repeatcount = 6; if (cached_has_bits & 0x00000020u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_repeatcount()); } // optional bool fieldactualchange = 8; if (cached_has_bits & 0x00000040u) { total_size += 1 + 1; } // optional uint32 userTag = 9; if (cached_has_bits & 0x00000080u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::UInt32Size( this->_internal_usertag()); } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void V4GenericBytes::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:EPICS.V4GenericBytes) GOOGLE_DCHECK_NE(&from, this); const V4GenericBytes* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<V4GenericBytes>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:EPICS.V4GenericBytes) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:EPICS.V4GenericBytes) MergeFrom(*source); } } void V4GenericBytes::MergeFrom(const V4GenericBytes& from) { // @@protoc_insertion_point(class_specific_merge_from_start:EPICS.V4GenericBytes) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; fieldvalues_.MergeFrom(from.fieldvalues_); cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x000000ffu) { if (cached_has_bits & 0x00000001u) { _internal_set_val(from._internal_val()); } if (cached_has_bits & 0x00000002u) { secondsintoyear_ = from.secondsintoyear_; } if (cached_has_bits & 0x00000004u) { nano_ = from.nano_; } if (cached_has_bits & 0x00000008u) { severity_ = from.severity_; } if (cached_has_bits & 0x00000010u) { status_ = from.status_; } if (cached_has_bits & 0x00000020u) { repeatcount_ = from.repeatcount_; } if (cached_has_bits & 0x00000040u) { fieldactualchange_ = from.fieldactualchange_; } if (cached_has_bits & 0x00000080u) { usertag_ = from.usertag_; } _has_bits_[0] |= cached_has_bits; } } void V4GenericBytes::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:EPICS.V4GenericBytes) if (&from == this) return; Clear(); MergeFrom(from); } void V4GenericBytes::CopyFrom(const V4GenericBytes& from) { // @@protoc_insertion_point(class_specific_copy_from_start:EPICS.V4GenericBytes) if (&from == this) return; Clear(); MergeFrom(from); } bool V4GenericBytes::IsInitialized() const { if (_Internal::MissingRequiredFields(_has_bits_)) return false; if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(fieldvalues_)) return false; return true; } void V4GenericBytes::InternalSwap(V4GenericBytes* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); fieldvalues_.InternalSwap(&other->fieldvalues_); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), &val_, GetArenaForAllocation(), &other->val_, other->GetArenaForAllocation() ); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(V4GenericBytes, usertag_) + sizeof(V4GenericBytes::usertag_) - PROTOBUF_FIELD_OFFSET(V4GenericBytes, secondsintoyear_)>( reinterpret_cast<char*>(&secondsintoyear_), reinterpret_cast<char*>(&other->secondsintoyear_)); } ::PROTOBUF_NAMESPACE_ID::Metadata V4GenericBytes::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_epics_5fevent_2eproto_getter, &descriptor_table_epics_5fevent_2eproto_once, file_level_metadata_epics_5fevent_2eproto[15]); } // =================================================================== class PayloadInfo::_Internal { public: using HasBits = decltype(std::declval<PayloadInfo>()._has_bits_); static void set_has_type(HasBits* has_bits) { (*has_bits)[0] |= 4u; } static void set_has_pvname(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_year(HasBits* has_bits) { (*has_bits)[0] |= 8u; } static void set_has_elementcount(HasBits* has_bits) { (*has_bits)[0] |= 8192u; } static void set_has_unused00(HasBits* has_bits) { (*has_bits)[0] |= 16u; } static void set_has_unused01(HasBits* has_bits) { (*has_bits)[0] |= 32u; } static void set_has_unused02(HasBits* has_bits) { (*has_bits)[0] |= 64u; } static void set_has_unused03(HasBits* has_bits) { (*has_bits)[0] |= 128u; } static void set_has_unused04(HasBits* has_bits) { (*has_bits)[0] |= 256u; } static void set_has_unused05(HasBits* has_bits) { (*has_bits)[0] |= 512u; } static void set_has_unused06(HasBits* has_bits) { (*has_bits)[0] |= 1024u; } static void set_has_unused07(HasBits* has_bits) { (*has_bits)[0] |= 2048u; } static void set_has_unused08(HasBits* has_bits) { (*has_bits)[0] |= 4096u; } static void set_has_unused09(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static bool MissingRequiredFields(const HasBits& has_bits) { return ((has_bits[0] & 0x0000000d) ^ 0x0000000d) != 0; } }; PayloadInfo::PayloadInfo(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena), headers_(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:EPICS.PayloadInfo) } PayloadInfo::PayloadInfo(const PayloadInfo& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_), headers_(from.headers_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); pvname_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_pvname()) { pvname_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_pvname(), GetArenaForAllocation()); } unused09_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_unused09()) { unused09_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_unused09(), GetArenaForAllocation()); } ::memcpy(&type_, &from.type_, static_cast<size_t>(reinterpret_cast<char*>(&elementcount_) - reinterpret_cast<char*>(&type_)) + sizeof(elementcount_)); // @@protoc_insertion_point(copy_constructor:EPICS.PayloadInfo) } void PayloadInfo::SharedCtor() { pvname_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); unused09_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&type_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&elementcount_) - reinterpret_cast<char*>(&type_)) + sizeof(elementcount_)); } PayloadInfo::~PayloadInfo() { // @@protoc_insertion_point(destructor:EPICS.PayloadInfo) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void PayloadInfo::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); pvname_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); unused09_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } void PayloadInfo::ArenaDtor(void* object) { PayloadInfo* _this = reinterpret_cast< PayloadInfo* >(object); (void)_this; } void PayloadInfo::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void PayloadInfo::SetCachedSize(int size) const { _cached_size_.Set(size); } void PayloadInfo::Clear() { // @@protoc_insertion_point(message_clear_start:EPICS.PayloadInfo) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; headers_.Clear(); cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { pvname_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { unused09_.ClearNonDefaultToEmpty(); } } if (cached_has_bits & 0x000000fcu) { ::memset(&type_, 0, static_cast<size_t>( reinterpret_cast<char*>(&unused03_) - reinterpret_cast<char*>(&type_)) + sizeof(unused03_)); } if (cached_has_bits & 0x00003f00u) { ::memset(&unused04_, 0, static_cast<size_t>( reinterpret_cast<char*>(&elementcount_) - reinterpret_cast<char*>(&unused04_)) + sizeof(elementcount_)); } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* PayloadInfo::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // required .EPICS.PayloadType type = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { ::PROTOBUF_NAMESPACE_ID::uint64 val = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); if (PROTOBUF_PREDICT_TRUE(::EPICS::PayloadType_IsValid(val))) { _internal_set_type(static_cast<::EPICS::PayloadType>(val)); } else { ::PROTOBUF_NAMESPACE_ID::internal::WriteVarint(1, val, mutable_unknown_fields()); } } else goto handle_unusual; continue; // required string pvname = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { auto str = _internal_mutable_pvname(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); #ifndef NDEBUG ::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "EPICS.PayloadInfo.pvname"); #endif // !NDEBUG CHK_(ptr); } else goto handle_unusual; continue; // required int32 year = 3; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 24)) { _Internal::set_has_year(&has_bits); year_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional int32 elementCount = 4; case 4: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 32)) { _Internal::set_has_elementcount(&has_bits); elementcount_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional double unused00 = 5; case 5: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 41)) { _Internal::set_has_unused00(&has_bits); unused00_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<double>(ptr); ptr += sizeof(double); } else goto handle_unusual; continue; // optional double unused01 = 6; case 6: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 49)) { _Internal::set_has_unused01(&has_bits); unused01_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<double>(ptr); ptr += sizeof(double); } else goto handle_unusual; continue; // optional double unused02 = 7; case 7: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 57)) { _Internal::set_has_unused02(&has_bits); unused02_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<double>(ptr); ptr += sizeof(double); } else goto handle_unusual; continue; // optional double unused03 = 8; case 8: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 65)) { _Internal::set_has_unused03(&has_bits); unused03_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<double>(ptr); ptr += sizeof(double); } else goto handle_unusual; continue; // optional double unused04 = 9; case 9: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 73)) { _Internal::set_has_unused04(&has_bits); unused04_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<double>(ptr); ptr += sizeof(double); } else goto handle_unusual; continue; // optional double unused05 = 10; case 10: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 81)) { _Internal::set_has_unused05(&has_bits); unused05_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<double>(ptr); ptr += sizeof(double); } else goto handle_unusual; continue; // optional double unused06 = 11; case 11: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 89)) { _Internal::set_has_unused06(&has_bits); unused06_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<double>(ptr); ptr += sizeof(double); } else goto handle_unusual; continue; // optional double unused07 = 12; case 12: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 97)) { _Internal::set_has_unused07(&has_bits); unused07_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<double>(ptr); ptr += sizeof(double); } else goto handle_unusual; continue; // optional double unused08 = 13; case 13: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 105)) { _Internal::set_has_unused08(&has_bits); unused08_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<double>(ptr); ptr += sizeof(double); } else goto handle_unusual; continue; // optional string unused09 = 14; case 14: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 114)) { auto str = _internal_mutable_unused09(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); #ifndef NDEBUG ::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "EPICS.PayloadInfo.unused09"); #endif // !NDEBUG CHK_(ptr); } else goto handle_unusual; continue; // repeated .EPICS.FieldValue headers = 15; case 15: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 122)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseMessage(_internal_add_headers(), ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<122>(ptr)); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* PayloadInfo::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:EPICS.PayloadInfo) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required .EPICS.PayloadType type = 1; if (cached_has_bits & 0x00000004u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteEnumToArray( 1, this->_internal_type(), target); } // required string pvname = 2; if (cached_has_bits & 0x00000001u) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->_internal_pvname().data(), static_cast<int>(this->_internal_pvname().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "EPICS.PayloadInfo.pvname"); target = stream->WriteStringMaybeAliased( 2, this->_internal_pvname(), target); } // required int32 year = 3; if (cached_has_bits & 0x00000008u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(3, this->_internal_year(), target); } // optional int32 elementCount = 4; if (cached_has_bits & 0x00002000u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(4, this->_internal_elementcount(), target); } // optional double unused00 = 5; if (cached_has_bits & 0x00000010u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteDoubleToArray(5, this->_internal_unused00(), target); } // optional double unused01 = 6; if (cached_has_bits & 0x00000020u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteDoubleToArray(6, this->_internal_unused01(), target); } // optional double unused02 = 7; if (cached_has_bits & 0x00000040u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteDoubleToArray(7, this->_internal_unused02(), target); } // optional double unused03 = 8; if (cached_has_bits & 0x00000080u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteDoubleToArray(8, this->_internal_unused03(), target); } // optional double unused04 = 9; if (cached_has_bits & 0x00000100u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteDoubleToArray(9, this->_internal_unused04(), target); } // optional double unused05 = 10; if (cached_has_bits & 0x00000200u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteDoubleToArray(10, this->_internal_unused05(), target); } // optional double unused06 = 11; if (cached_has_bits & 0x00000400u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteDoubleToArray(11, this->_internal_unused06(), target); } // optional double unused07 = 12; if (cached_has_bits & 0x00000800u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteDoubleToArray(12, this->_internal_unused07(), target); } // optional double unused08 = 13; if (cached_has_bits & 0x00001000u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteDoubleToArray(13, this->_internal_unused08(), target); } // optional string unused09 = 14; if (cached_has_bits & 0x00000002u) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->_internal_unused09().data(), static_cast<int>(this->_internal_unused09().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "EPICS.PayloadInfo.unused09"); target = stream->WriteStringMaybeAliased( 14, this->_internal_unused09(), target); } // repeated .EPICS.FieldValue headers = 15; for (unsigned int i = 0, n = static_cast<unsigned int>(this->_internal_headers_size()); i < n; i++) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage(15, this->_internal_headers(i), target, stream); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:EPICS.PayloadInfo) return target; } size_t PayloadInfo::RequiredFieldsByteSizeFallback() const { // @@protoc_insertion_point(required_fields_byte_size_fallback_start:EPICS.PayloadInfo) size_t total_size = 0; if (_internal_has_pvname()) { // required string pvname = 2; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_pvname()); } if (_internal_has_type()) { // required .EPICS.PayloadType type = 1; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->_internal_type()); } if (_internal_has_year()) { // required int32 year = 3; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_year()); } return total_size; } size_t PayloadInfo::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:EPICS.PayloadInfo) size_t total_size = 0; if (((_has_bits_[0] & 0x0000000d) ^ 0x0000000d) == 0) { // All required fields are present. // required string pvname = 2; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_pvname()); // required .EPICS.PayloadType type = 1; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::EnumSize(this->_internal_type()); // required int32 year = 3; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_year()); } else { total_size += RequiredFieldsByteSizeFallback(); } ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated .EPICS.FieldValue headers = 15; total_size += 1UL * this->_internal_headers_size(); for (const auto& msg : this->headers_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } // optional string unused09 = 14; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000002u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_unused09()); } if (cached_has_bits & 0x000000f0u) { // optional double unused00 = 5; if (cached_has_bits & 0x00000010u) { total_size += 1 + 8; } // optional double unused01 = 6; if (cached_has_bits & 0x00000020u) { total_size += 1 + 8; } // optional double unused02 = 7; if (cached_has_bits & 0x00000040u) { total_size += 1 + 8; } // optional double unused03 = 8; if (cached_has_bits & 0x00000080u) { total_size += 1 + 8; } } if (cached_has_bits & 0x00003f00u) { // optional double unused04 = 9; if (cached_has_bits & 0x00000100u) { total_size += 1 + 8; } // optional double unused05 = 10; if (cached_has_bits & 0x00000200u) { total_size += 1 + 8; } // optional double unused06 = 11; if (cached_has_bits & 0x00000400u) { total_size += 1 + 8; } // optional double unused07 = 12; if (cached_has_bits & 0x00000800u) { total_size += 1 + 8; } // optional double unused08 = 13; if (cached_has_bits & 0x00001000u) { total_size += 1 + 8; } // optional int32 elementCount = 4; if (cached_has_bits & 0x00002000u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_elementcount()); } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void PayloadInfo::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:EPICS.PayloadInfo) GOOGLE_DCHECK_NE(&from, this); const PayloadInfo* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<PayloadInfo>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:EPICS.PayloadInfo) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:EPICS.PayloadInfo) MergeFrom(*source); } } void PayloadInfo::MergeFrom(const PayloadInfo& from) { // @@protoc_insertion_point(class_specific_merge_from_start:EPICS.PayloadInfo) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; headers_.MergeFrom(from.headers_); cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x000000ffu) { if (cached_has_bits & 0x00000001u) { _internal_set_pvname(from._internal_pvname()); } if (cached_has_bits & 0x00000002u) { _internal_set_unused09(from._internal_unused09()); } if (cached_has_bits & 0x00000004u) { type_ = from.type_; } if (cached_has_bits & 0x00000008u) { year_ = from.year_; } if (cached_has_bits & 0x00000010u) { unused00_ = from.unused00_; } if (cached_has_bits & 0x00000020u) { unused01_ = from.unused01_; } if (cached_has_bits & 0x00000040u) { unused02_ = from.unused02_; } if (cached_has_bits & 0x00000080u) { unused03_ = from.unused03_; } _has_bits_[0] |= cached_has_bits; } if (cached_has_bits & 0x00003f00u) { if (cached_has_bits & 0x00000100u) { unused04_ = from.unused04_; } if (cached_has_bits & 0x00000200u) { unused05_ = from.unused05_; } if (cached_has_bits & 0x00000400u) { unused06_ = from.unused06_; } if (cached_has_bits & 0x00000800u) { unused07_ = from.unused07_; } if (cached_has_bits & 0x00001000u) { unused08_ = from.unused08_; } if (cached_has_bits & 0x00002000u) { elementcount_ = from.elementcount_; } _has_bits_[0] |= cached_has_bits; } } void PayloadInfo::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:EPICS.PayloadInfo) if (&from == this) return; Clear(); MergeFrom(from); } void PayloadInfo::CopyFrom(const PayloadInfo& from) { // @@protoc_insertion_point(class_specific_copy_from_start:EPICS.PayloadInfo) if (&from == this) return; Clear(); MergeFrom(from); } bool PayloadInfo::IsInitialized() const { if (_Internal::MissingRequiredFields(_has_bits_)) return false; if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(headers_)) return false; return true; } void PayloadInfo::InternalSwap(PayloadInfo* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); headers_.InternalSwap(&other->headers_); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), &pvname_, GetArenaForAllocation(), &other->pvname_, other->GetArenaForAllocation() ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), &unused09_, GetArenaForAllocation(), &other->unused09_, other->GetArenaForAllocation() ); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(PayloadInfo, elementcount_) + sizeof(PayloadInfo::elementcount_) - PROTOBUF_FIELD_OFFSET(PayloadInfo, type_)>( reinterpret_cast<char*>(&type_), reinterpret_cast<char*>(&other->type_)); } ::PROTOBUF_NAMESPACE_ID::Metadata PayloadInfo::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_epics_5fevent_2eproto_getter, &descriptor_table_epics_5fevent_2eproto_once, file_level_metadata_epics_5fevent_2eproto[16]); } // @@protoc_insertion_point(namespace_scope) } // namespace EPICS PROTOBUF_NAMESPACE_OPEN template<> PROTOBUF_NOINLINE ::EPICS::FieldValue* Arena::CreateMaybeMessage< ::EPICS::FieldValue >(Arena* arena) { return Arena::CreateMessageInternal< ::EPICS::FieldValue >(arena); } template<> PROTOBUF_NOINLINE ::EPICS::ScalarString* Arena::CreateMaybeMessage< ::EPICS::ScalarString >(Arena* arena) { return Arena::CreateMessageInternal< ::EPICS::ScalarString >(arena); } template<> PROTOBUF_NOINLINE ::EPICS::ScalarByte* Arena::CreateMaybeMessage< ::EPICS::ScalarByte >(Arena* arena) { return Arena::CreateMessageInternal< ::EPICS::ScalarByte >(arena); } template<> PROTOBUF_NOINLINE ::EPICS::ScalarShort* Arena::CreateMaybeMessage< ::EPICS::ScalarShort >(Arena* arena) { return Arena::CreateMessageInternal< ::EPICS::ScalarShort >(arena); } template<> PROTOBUF_NOINLINE ::EPICS::ScalarInt* Arena::CreateMaybeMessage< ::EPICS::ScalarInt >(Arena* arena) { return Arena::CreateMessageInternal< ::EPICS::ScalarInt >(arena); } template<> PROTOBUF_NOINLINE ::EPICS::ScalarEnum* Arena::CreateMaybeMessage< ::EPICS::ScalarEnum >(Arena* arena) { return Arena::CreateMessageInternal< ::EPICS::ScalarEnum >(arena); } template<> PROTOBUF_NOINLINE ::EPICS::ScalarFloat* Arena::CreateMaybeMessage< ::EPICS::ScalarFloat >(Arena* arena) { return Arena::CreateMessageInternal< ::EPICS::ScalarFloat >(arena); } template<> PROTOBUF_NOINLINE ::EPICS::ScalarDouble* Arena::CreateMaybeMessage< ::EPICS::ScalarDouble >(Arena* arena) { return Arena::CreateMessageInternal< ::EPICS::ScalarDouble >(arena); } template<> PROTOBUF_NOINLINE ::EPICS::VectorString* Arena::CreateMaybeMessage< ::EPICS::VectorString >(Arena* arena) { return Arena::CreateMessageInternal< ::EPICS::VectorString >(arena); } template<> PROTOBUF_NOINLINE ::EPICS::VectorChar* Arena::CreateMaybeMessage< ::EPICS::VectorChar >(Arena* arena) { return Arena::CreateMessageInternal< ::EPICS::VectorChar >(arena); } template<> PROTOBUF_NOINLINE ::EPICS::VectorShort* Arena::CreateMaybeMessage< ::EPICS::VectorShort >(Arena* arena) { return Arena::CreateMessageInternal< ::EPICS::VectorShort >(arena); } template<> PROTOBUF_NOINLINE ::EPICS::VectorInt* Arena::CreateMaybeMessage< ::EPICS::VectorInt >(Arena* arena) { return Arena::CreateMessageInternal< ::EPICS::VectorInt >(arena); } template<> PROTOBUF_NOINLINE ::EPICS::VectorEnum* Arena::CreateMaybeMessage< ::EPICS::VectorEnum >(Arena* arena) { return Arena::CreateMessageInternal< ::EPICS::VectorEnum >(arena); } template<> PROTOBUF_NOINLINE ::EPICS::VectorFloat* Arena::CreateMaybeMessage< ::EPICS::VectorFloat >(Arena* arena) { return Arena::CreateMessageInternal< ::EPICS::VectorFloat >(arena); } template<> PROTOBUF_NOINLINE ::EPICS::VectorDouble* Arena::CreateMaybeMessage< ::EPICS::VectorDouble >(Arena* arena) { return Arena::CreateMessageInternal< ::EPICS::VectorDouble >(arena); } template<> PROTOBUF_NOINLINE ::EPICS::V4GenericBytes* Arena::CreateMaybeMessage< ::EPICS::V4GenericBytes >(Arena* arena) { return Arena::CreateMessageInternal< ::EPICS::V4GenericBytes >(arena); } template<> PROTOBUF_NOINLINE ::EPICS::PayloadInfo* Arena::CreateMaybeMessage< ::EPICS::PayloadInfo >(Arena* arena) { return Arena::CreateMessageInternal< ::EPICS::PayloadInfo >(arena); } PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc>
37.569393
178
0.70138
[ "object" ]
4ef530605b290c45ef02594bfd123b448d913102
2,234
cpp
C++
src/pseudo-sc.cpp
nowar-fonts/Psuedo-SC
3d241b563fab73e0f702ebbfba399b7b5cb63820
[ "MIT" ]
5
2020-10-17T09:48:48.000Z
2021-12-25T02:22:03.000Z
src/pseudo-sc.cpp
nowar-fonts/Psuedo-SC
3d241b563fab73e0f702ebbfba399b7b5cb63820
[ "MIT" ]
null
null
null
src/pseudo-sc.cpp
nowar-fonts/Psuedo-SC
3d241b563fab73e0f702ebbfba399b7b5cb63820
[ "MIT" ]
4
2020-10-29T07:44:59.000Z
2021-11-27T12:27:09.000Z
#include <algorithm> #include <cmath> #include <cstdio> #include <streambuf> #include <string> #include <vector> #include <nlohmann/json.hpp> #include <nowide/args.hpp> #include <nowide/cstdio.hpp> #include <nowide/fstream.hpp> #include <nowide/iostream.hpp> #include "opencc-t2s.h" const char *usage = reinterpret_cast<const char *>(u8"用法:\n\t%s font.otd\n"); const char *loadfilefail = reinterpret_cast<const char *>(u8"读取文件 %s 失败\n"); using json = nlohmann::json; std::string LoadFile(char *u8filename) { static char u8buffer[4096]; nowide::ifstream file(u8filename); if (!file) { snprintf(u8buffer, sizeof u8buffer, loadfilefail, u8filename); nowide::cerr << u8buffer << std::endl; throw std::runtime_error("failed to load file"); } std::string result{std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()}; return result; } void Rename(json &base) { for (auto &nameTuple : base["name"]) { uint16_t nameId = nameTuple["nameID"]; switch (nameId) { case 1: case 3: case 4: case 16: case 18: case 21: nameTuple["nameString"] = std::string(nameTuple["nameString"]) + " (Pseudo-SC)"; break; case 6: case 20: nameTuple["nameString"] = std::string(nameTuple["nameString"]) + "Pseudo-SC"; break; default: break; } } } void Remap(json &base) { auto &cmap = base["cmap"]; for (auto &[trad, simp] : OpenCC_T2S) { auto usimp = std::to_string(simp); if (cmap.find(usimp) != cmap.end()) { auto utrad = std::to_string(trad); cmap[utrad] = cmap[usimp]; } } } int main(int argc, char *u8argv[]) { static char u8buffer[4096]; nowide::args _{argc, u8argv}; if (argc != 2) { snprintf(u8buffer, sizeof u8buffer, usage, u8argv[0]); nowide::cout << u8buffer << std::endl; return EXIT_FAILURE; } json base; bool basecff; try { auto s = LoadFile(u8argv[1]); base = json::parse(s); } catch (std::runtime_error) { return EXIT_FAILURE; } Rename(base); Remap(base); std::string out = base.dump(); FILE *outfile = nowide::fopen(u8argv[1], "wb"); fwrite(out.c_str(), 1, out.size(), outfile); fclose(outfile); return 0; }
23.515789
84
0.629364
[ "vector" ]
4ef572ba693b3e667ea40b10e1917de919745ec8
2,240
cpp
C++
src/shadereditor/src/shadereditor/solver/chlsl_solver_baserange.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/shadereditor/src/shadereditor/solver/chlsl_solver_baserange.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/shadereditor/src/shadereditor/solver/chlsl_solver_baserange.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
 #include "cbase.h" #include "editorCommon.h" void CHLSL_Solver_BaseRange::OnWriteFXC(bool bIsPixelShader, WriteContext_FXC &context) { Assert(0); } void CHLSL_Solver_BaseRange::Render(Preview2DContext &c) { int OP = GetRenderOperator(); int type0 = GetSourceVar(0)->GetType(); int type1 = GetSourceVar(1)->GetType(); int type2 = GetSourceVar(2)->GetType(); SetUVParamBySourceVar(OP, 0, 0); SetUVParamBySourceVar(OP, 1, 1); SetUVParamBySourceVar(OP, 2, 2); IMaterialVar *var_3 = pEditorRoot->GetUVTargetParam(OP, 3); IMaterialVar *var_4 = pEditorRoot->GetUVTargetParam(OP, 4); //IMaterialVar *var_5 = pEditorRoot->GetUVTargetParam( OP, 5 ); var_3->SetVecValue(0, 0, 0, 0); var_4->SetVecValue(0, 0, 0, 0); //var_5->SetVecValue( 0, 0, 0, 0 ); int maxSlots = ::GetSlotsFromTypeFlag(type2); if (type2 != type0) var_3->SetVecValue(maxSlots >= 2, maxSlots >= 3, maxSlots >= 4, 0); if (type2 != type1) var_4->SetVecValue(maxSlots >= 2, maxSlots >= 3, maxSlots >= 4, 0); pEditorRoot->GetUVTargetParam(OP, 5)->SetVecValue(maxSlots >= 2, maxSlots >= 3, maxSlots >= 4, 0); CNodeView::RenderSingleSolver(c, pEditorRoot->GetOperatorMaterial(OP)); UpdateTargetVarToReflectMapIndex(0); } void CHLSL_Solver_Smoothstep::OnWriteFXC(bool bIsPixelShader, WriteContext_FXC &context) { CHLSL_Var *tg = GetTargetVar(0); tg->DeclareMe(context); CHLSL_Var *src1 = GetSourceVar(0); CHLSL_Var *src2 = GetSourceVar(1); CHLSL_Var *src3 = GetSourceVar(2); char tmp[MAXTARGC]; Q_snprintf(tmp, MAXTARGC, "%s = smoothstep( %s, %s, %s );\n", tg->GetName(), src1->GetName(), src2->GetName(), src3->GetName()); context.buf_code.PutString(tmp); } void CHLSL_Solver_Clamp::OnWriteFXC(bool bIsPixelShader, WriteContext_FXC &context) { CHLSL_Var *tg = GetTargetVar(0); tg->DeclareMe(context); CHLSL_Var *src1 = GetSourceVar(0); CHLSL_Var *src2 = GetSourceVar(1); CHLSL_Var *src3 = GetSourceVar(2); char tmp[MAXTARGC]; Q_snprintf(tmp, MAXTARGC, "%s = clamp( %s, %s, %s );\n", tg->GetName(), src3->GetName(), src1->GetName(), src2->GetName()); context.buf_code.PutString(tmp); }
35
102
0.6625
[ "render" ]
4ef8d78f2f2d20f417b4d053ccb267aa59621629
655
cpp
C++
min-stack/solution-0.cpp
tsenmu/leetcode
6f6d11dec4e5ee0fbc0c59fd6fa97b2c556e05ee
[ "Apache-2.0" ]
null
null
null
min-stack/solution-0.cpp
tsenmu/leetcode
6f6d11dec4e5ee0fbc0c59fd6fa97b2c556e05ee
[ "Apache-2.0" ]
null
null
null
min-stack/solution-0.cpp
tsenmu/leetcode
6f6d11dec4e5ee0fbc0c59fd6fa97b2c556e05ee
[ "Apache-2.0" ]
null
null
null
class MinStack { protected: stack<int> m_list; stack<int> m_min; public: /** initialize your data structure here. */ MinStack() { } void push(int x) { m_list.push(x); m_min.push(m_min.empty() ? x : min(m_min.top(), x)); } void pop() { m_list.pop(); m_min.pop(); } int top() { return m_list.top(); } int getMin() { return m_min.top(); } }; /** * Your MinStack object will be instantiated and called as such: * MinStack obj = new MinStack(); * obj.push(x); * obj.pop(); * int param_3 = obj.top(); * int param_4 = obj.getMin(); */
18.194444
64
0.517557
[ "object" ]
4efd0da9e311b3de754caafc6abf5cf27aea6617
26,699
cpp
C++
IntermediateCode.cpp
migu4917/Simple-C0-Compiler
3d454402f6f1152de60be972f844f69ef95bdc8e
[ "MIT" ]
2
2020-09-15T11:18:58.000Z
2020-09-21T01:57:12.000Z
IntermediateCode.cpp
migu4917/Simple-C0-Compiler
3d454402f6f1152de60be972f844f69ef95bdc8e
[ "MIT" ]
null
null
null
IntermediateCode.cpp
migu4917/Simple-C0-Compiler
3d454402f6f1152de60be972f844f69ef95bdc8e
[ "MIT" ]
2
2020-09-21T01:57:17.000Z
2020-09-27T16:38:01.000Z
#include <sstream> #include <map> #include <algorithm> #include <climits> #include <iostream> #include <set> #include "IntermediateCode.h" #include "lexicalAnalysis.h" #include "util.h" using std::map; using std::ostringstream; using std::swap; using std::stoi; using std::to_string; using std::cout; using std::endl; using std::set; int FourItemExpr::id = 0; static map<Sym, string> type2string = { {INTTK, "int"}, {CHARTK, "char"}, {VOIDTK, "void"} }; vector<FourItemExpr> IntermediateCode::imExprList; map< string, vector<FourItemExpr> > IntermediateCode::func2im; map<string, string> IntermediateCode::str2name; unsigned int IntermediateCode::tempVarMark = 0; bool IntermediateCode::skip = false; extern SymbolTable symbolTable; void IntermediateCode::addConstantDef(ConstantItem& item) { if (item.isEmpty()) { return; } ostringstream ostr; Sym type = item.getType(); if (type == CHARTK) { ostr << '\'' << (char)item.getValue() << '\''; } else { ostr << item.getValue(); } add4ItemExpr(opConst, type2string.at(type), item.getName(), ostr.str()); } void IntermediateCode::add4ItemExpr(IMOper imop, string result, string first, string second) { if (skip) { return; } FourItemExpr imExpr(imop, result, first, second); if (imExprList.size() > 0) { FourItemExpr lastExpr = *(imExprList.end() - 1); IMOper lastOp = lastExpr.op; if ((lastOp == opAdd || lastOp == opSub || lastOp == opMul || lastOp == opDiv || lastOp == opLoadArray) && (imExpr.op == opAssign && imExpr.first == lastExpr.result) && (isTempVariable(lastExpr.result) || (imExpr.result == func_RetVar && symbolTable.isLocalVariable(lastExpr.result)))) { lastExpr.result = imExpr.result; imExpr = lastExpr; imExprList.pop_back(); } } imExprList.push_back(imExpr); } void IntermediateCode::addFunctionDef(FunctionItem& item) { if (item.isEmpty()) { return; } symbolTable.setNowFunctionItem(item.getName()); string type = type2string[item.getType()]; add4ItemExpr(opFunc, type, item.getName()); } void IntermediateCode::addVariableDef(VariableItem& item) { if (item.isEmpty()) { return; } string type = type2string[item.getType()]; if (item.getArrayLength() > 0) { add4ItemExpr(opVar, type, item.getName(), "[" + std::to_string(item.getArrayLength()) + "]"); } else { add4ItemExpr(opVar, type, item.getName()); } } void IntermediateCode::addParameter(vector<VariableItem*>& parameters) { for (auto i = parameters.begin(); i != parameters.end(); i++) { VariableItem item = **i; string type = type2string[item.getType()]; add4ItemExpr(opPara, type, item.getName()); } } void IntermediateCode::scanfFunction(Item& item) { if (item.isEmpty()) { return; } string type = type2string[item.getType()]; add4ItemExpr(opScanf, item.getName(), type); } void IntermediateCode::printfFunction(string str, string result, string type) { if (str.length() > 0 && result.length() > 0) { add4ItemExpr(opPrintf, str2name[str], result, type); } else if (str.length() > 0) { add4ItemExpr(opPrintf, str2name[str]); } else { add4ItemExpr(opPrintf, result, type); } } void IntermediateCode::functionReturn(string result) { if (result.length() > 0) { add4ItemExpr(opAssign, func_RetVar, result); add4ItemExpr(opReturn, ""); return; } add4ItemExpr(opReturn, result); } void IntermediateCode::callFunction(string funcName) { add4ItemExpr(opCall, funcName); } void IntermediateCode::getReturnValue(string result) { add4ItemExpr(opGetRetVal, result); } void IntermediateCode::pushParameter(string result, string funcName) { add4ItemExpr(opPush, result, funcName); } void IntermediateCode::setLabel(string label) { add4ItemExpr(opSetLabel, label); } void IntermediateCode::addString(string str) { static unsigned int cnt = 0; if (str2name.find(str) == str2name.end()) { string name = string("STRING_" + std::to_string(cnt++)); str2name[str] = name; } } void IntermediateCode::toFunctionBlock() { string funcName = ""; for (auto i = imExprList.begin(); i != imExprList.end(); i++) { if (i->op == opFunc) { funcName = i->first; func2im[funcName].clear(); } if (funcName.length() > 0) { func2im[funcName].push_back(*i); } } } void IntermediateCode::toTotalList() { imExprList.clear(); for (auto i = func2im.begin(); i != func2im.end(); i++) { auto& func2im = i->second; for (auto j = func2im.begin(); j < func2im.end(); j++) { imExprList.push_back(*j); } } } void IntermediateCode::removeUseless() { for (auto i = func2im.begin(); i != func2im.end(); i++) { symbolTable.setNowFunctionItem(i->first); set<string> localVarUse; auto& list = i->second; for (auto j = list.begin(); j < list.end(); j++) { if (j->op == opFunc || j->op == opVar || j->op == opConst || j->op == opPara) { continue; } if (j->op == opScanf || j->op == opPush || j->op == opStore2Array) { localVarUse.insert(j->result); } else if (j->op == opPrintf) { if (symbolTable.isLocalVariable(j->result)) { localVarUse.insert(j->result); } if (symbolTable.isLocalVariable(j->first)) { localVarUse.insert(j->first); } } else { if (symbolTable.isLocalVariable(j->first)) { localVarUse.insert(j->first); } if (symbolTable.isLocalVariable(j->second)) { localVarUse.insert(j->second); } } //if (j->op == opDiv && j->result == "#TEMP_VAR_1" && j->first == "j" && j->second == "i") { // j = list.erase(j); //} } for (auto j = list.begin(); j < list.end(); j++) { if (!(j->op == opAdd || j->op == opSub || j->op == opMul || j->op == opDiv || j->op == opMod || j->op == opAssign || j->op == opGetRetVal)) { continue; } if (symbolTable.isLocalVariable(j->result) && !isTempVariable(j->result) && !isNumberValue(j->result) && localVarUse.find(j->result) == localVarUse.end()) { j = list.erase(j); } } } } void IntermediateCode::optimization() { smallAdjust(); #ifdef OPT_REDUNDANT_JUMP removeRedundantJump(); #endif // REDUNDANT_JUMP toFunctionBlock(); #ifdef OPT_INLINE map<string, bool> func2inline; for (auto i = func2im.begin(); i != func2im.end(); i++) { symbolTable.setNowFunctionItem(i->first); auto& imList = i->second; bool canBeInline = true; for (auto j = imList.begin(); j < imList.end(); j++) { switch (j->op) { case opAdd: case opSub: case opMul: case opDiv: case opMod: case opAssign: if (!symbolTable.isLocalVariable(j->result) || !symbolTable.isLocalVariable(j->first) || !symbolTable.isLocalVariable(j->second)) { canBeInline = false; } break; //case opLss: case opLeq: case opGre: case opGeq: case opEql: case opNeq: //case opBeq: case opBne: case opBlt: case opBle: case opBgt: case opBge: //case opSetLabel: case opGoto: case opBNZ: case opBZ: case opPush: case opCall: case opGetRetVal: case opScanf: case opVar: case opStore2Array: case opLoadArray: canBeInline = false; break; case opPrintf: if (!symbolTable.isLocalVariable(j->result)) { canBeInline = false; } if (j->second.length() > 0 && !symbolTable.isLocalVariable(j->first)) { canBeInline = false; } break; case opReturn: case opFunc: case opPara: case opConst: default: break; } } if (symbolTable.getParaCount(i->first) > INLINE_PARA_CNT_LIMIT) { canBeInline = false; } func2inline[i->first] = canBeInline; #ifdef DEBUG cout << i->first << "\t" << canBeInline << "\n"; #endif // DEBUG } const string INLINE_VAR = "INLINE_"; for (auto i = func2im.begin(); i != func2im.end(); i++) { auto& imList = i->second; if (func2inline[i->first]) { continue; } for (auto j = imList.begin(); j < imList.end(); j++) { auto start = j; if (j->op == opCall || j->op == opPush) { string inlineFunc = (j->op == opCall ? j->result : j->first); if (!func2inline[inlineFunc]) { continue; } map<string, string> formal2real; auto& formalParas = ((FunctionItem*)symbolTable.getItem(inlineFunc))->parameters; for (; j->op != opCall; j++) { formal2real[formalParas[formal2real.size()]->getName()] = j->result; } j++; // now, j->op == opCall if (j->op == opGetRetVal) { // use the result variable to replace func_RetVar formal2real[func_RetVar] = j->result; j++; } else { //if (symbolTable.getType(inlineFunc) != VOIDTK) { // //j--; // continue; //} } j = imList.erase(start, j); // delete call and return code releaseTempVar(); string inlineEndLabel = getNewLabel(); for (FourItemExpr k : func2im[inlineFunc]) { FourItemExpr temp = k; auto op = temp.op; if (op == opPara || op == opFunc || op == opConst || op == opReturn) { if (op == opReturn) { j = imList.insert(j, FourItemExpr(opGoto, inlineEndLabel)) + 1; } continue; } // rename label if (op == opGoto || op == opBNZ || op == opBZ || op == opSetLabel || op == opBeq || op == opBne || op == opBlt || op == opBle || op == opBgt || op == opBge) { if (formal2real.find(temp.result) == formal2real.end()) { formal2real[temp.result] = getNewLabel(); } } if (op == opPrintf) { if (isStringName(temp.result)) { formal2real[temp.result] = temp.result; } } string* codeVar[] = { &temp.first, &temp.second, &temp.result }; for (int p = 0; p < 3; p++) { if (isTempVariable(*codeVar[p]) && *codeVar[p] != func_RetVar) { codeVar[p]->insert(1, INLINE_VAR); } else { // when modify a para but the real para is a number // replace the number by a temp var if (p == 2 && isNumberValue(formal2real[*codeVar[p]]) && op != opPrintf) { string inlineTempVar = getTempVar().insert(1, "INLINE_PARA_"); formal2real[*codeVar[p]] = inlineTempVar; } if (formal2real.find(*codeVar[p]) != formal2real.end() && !isNumberValue(*codeVar[p])) { *codeVar[p] = formal2real[*codeVar[p]]; } } } j = imList.insert(j, temp) + 1; } j = imList.insert(j, FourItemExpr(opSetLabel, inlineEndLabel)); } } } toTotalList(); removeRedundantJump(); smallAdjust(); removeRedundantJump(); smallAdjust(); removeRedundantJump(); smallAdjust(); toFunctionBlock(); //removeUseless(); toTotalList(); #endif // DO_INLINE } void IntermediateCode::removeRedundantJump() { map<string, int> label2addr; map<string, int> label2cnt; map<FourItemExpr, int> code2addr; int addr = 0; for (auto i = imExprList.begin(); i != imExprList.end(); i++) { if (i->op == opSetLabel) { label2addr[i->result] = addr; } else { if (i->op == opGoto || i->op == opBZ || i->op == opBNZ || i->op == opBeq || i->op == opBne || i->op == opBlt || i->op == opBle || i->op == opBgt || i->op == opBge) { label2cnt[i->result]++; } code2addr[*i] = addr++; } } for (auto i = imExprList.begin(); i != imExprList.end();) { if ((i->op == opGoto || i->op == opBZ || i->op == opBNZ || i->op == opBeq || i->op == opBne || i->op == opBlt || i->op == opBle || i->op == opBgt || i->op == opBge) && code2addr[*i] + 1 == label2addr[i->result]) { label2cnt[i->result]--; i = imExprList.erase(i); } else { i++; } } for (auto i = imExprList.begin(); i != imExprList.end(); i++) { if (i->op == opSetLabel && label2cnt[i->result] == 0) { i = imExprList.erase(i); } } } IMOper reverseOp(IMOper op) { switch (op) { case opLss: return opGre; break; case opLeq: return opGeq; break; case opGre: return opLss; break; case opGeq: return opLeq; break; case opEql: case opNeq: return op; break; default: return op; break; } } void IntermediateCode::smallAdjust() { set<string> localVarUse; for (auto i = imExprList.begin(); i != imExprList.end(); i++) { if ((i->op == opAdd || i->op == opMul || i->op == opEql || i->op == opNeq) && isNumberValue(i->first)) { swap(i->first, i->second); } if ((i->op == opGre || i->op == opGeq || i->op == opLss || i->op == opLeq) && isNumberValue(i->first)) { swap(i->first, i->second); i->op = reverseOp(i->op); } if (i->op == opSub && isNumberValue(i->second)) { int value = stoi(i->second); if (value > INT_MIN) { i->op = opAdd; i->second = to_string(-value); } } if (i->op == opAssign && i->result == i->first) { i = imExprList.erase(i); } if (symbolTable.isLocalVariable(i->first)) { localVarUse.insert(i->first); } if (symbolTable.isLocalVariable(i->second)) { localVarUse.insert(i->second); } } for (auto i = imExprList.begin() + 1; i != imExprList.end(); i++) { FourItemExpr& prev = *(i - 1); FourItemExpr& now = *i; if (prev.op == opFunc) { symbolTable.setNowFunctionItem(prev.first); } if (!isTempVariable(prev.result)) { continue; } if ((prev.op == opAdd || prev.op == opMul) && prev.op == now.op && prev.result == now.first && isNumberValue(prev.second) && isNumberValue(now.second)) { int num1 = stoi(prev.second); int num2 = stoi(now.second); int result; if (prev.op == opAdd) { result = num1 + num2; } else { result = num1 * num2; } i->first = prev.first; if (result != 0) { i->second = to_string(result); } else { i->op = opAssign; i->second = ""; } i = imExprList.erase(i - 1); } if ((prev.op == opEql || prev.op == opNeq|| prev.op == opLss || prev.op == opLeq || prev.op == opGre || prev.op == opGeq) && prev.result == now.first && (now.op == opBZ || now.op == opBNZ)) { IMOper op = prev.op; switch (op) { case opLss: if (now.op == opBZ) { now.op = opBge; } else { now.op = opBlt; } break; case opLeq: if (now.op == opBZ) { now.op = opBgt; } else { now.op = opBle; } break; case opGre: if (now.op == opBZ) { now.op = opBle; } else { now.op = opBgt; } break; case opGeq: if (now.op == opBZ) { now.op = opBlt; } else { now.op = opBge; } break; case opEql: if (now.op == opBZ) { now.op = opBne; } else { now.op = opBeq; } break; case opNeq: if (now.op == opBZ) { now.op = opBeq; } else { now.op = opBne; } break; default: break; } now.first = prev.first; now.second = prev.second; i = imExprList.erase(i - 1); } } for (auto i = imExprList.begin() + 1; i != imExprList.end(); i++) { if (isNumberValue(i->first) && isNumberValue(i->second)) { int first = stoi(i->first); int second = stoi(i->second); switch (i->op) { case opAdd: *i = FourItemExpr(opAssign, i->result, to_string(first + second)); break; case opSub: *i = FourItemExpr(opAssign, i->result, to_string(first - second)); break; case opMul: *i = FourItemExpr(opAssign, i->result, to_string(first * second)); break; case opDiv: if (second != 0) { *i = FourItemExpr(opAssign, i->result, to_string(first / second)); } break; case opMod: if (second != 0) { *i = FourItemExpr(opAssign, i->result, to_string(first % second)); } break; case opBeq: if (first == second) { *i = FourItemExpr(opGoto, i->result); } else { i = imExprList.erase(i); } break; case opBne: if (first != second) { *i = FourItemExpr(opGoto, i->result); } else { i = imExprList.erase(i); } break; case opBlt: if (first < second) { *i = FourItemExpr(opGoto, i->result); } else { i = imExprList.erase(i); } break; case opBle: if (first <= second) { *i = FourItemExpr(opGoto, i->result); } else { i = imExprList.erase(i); } break; case opBgt: if (first > second) { *i = FourItemExpr(opGoto, i->result); } else { i = imExprList.erase(i); } break; case opBge: if (first >= second) { *i = FourItemExpr(opGoto, i->result); } else { i = imExprList.erase(i); } break; default: break; } } } for (auto i = imExprList.begin() + 1; i < imExprList.end(); i++) { auto prev = i - 1; auto now = i; if (prev->op == opFunc) { symbolTable.setNowFunctionItem(prev->first); } if ((prev->op == opAdd || prev->op == opMul || prev->op == opDiv || prev->op == opSub || prev->op == opMod || prev->op == opGetRetVal || prev->op == opAssign) && now->op == opAssign && prev->result == now->first && isTempVariable(prev->result)) { prev->result = now->result; i = imExprList.erase(i); } } //#TEMP_VAR_0 = x / y //#TEMP_VAR_1 = #TEMP_VAR_0 * y //var = x - #TEMP_VAR_1 // result: var = x % y #ifdef OPT_MOD for (auto i = imExprList.begin() + 2; i < imExprList.end(); i++) { auto expr1 = i - 2; auto expr2 = i - 1; auto expr3 = i; if (expr1->op == opFunc) { symbolTable.setNowFunctionItem(expr1->first); } if (!symbolTable.isLocalVariable(expr1->result) || !symbolTable.isLocalVariable(expr1->first) || !symbolTable.isLocalVariable(expr1->second) || !symbolTable.isLocalVariable(expr2->result) || !symbolTable.isLocalVariable(expr2->first) || !symbolTable.isLocalVariable(expr2->second) || !symbolTable.isLocalVariable(expr3->result) || !symbolTable.isLocalVariable(expr3->first) || !symbolTable.isLocalVariable(expr3->second)) { continue; } if ((!isTempVariable(expr1->result) || !isTempVariable(expr2->result)) && expr3->result != func_RetVar) { continue; } if (expr1->op == opDiv && expr2->op == opMul && expr3->op == opSub) { string quotient = expr1->result; string dividend = expr1->first; string divisor = expr1->second; if (((quotient == expr2->first && divisor == expr2->second) || (quotient == expr2->second && divisor == expr2->first)) && expr3->first == dividend && expr3->second == expr2->result) { expr1->op = opMod; expr1->result = expr3->result; i = imExprList.erase(i - 1, i + 1); } } } #endif // OPT_MOD } string FourItemExpr::toString() { static map<IMOper, string> op2string = { {opAdd,"+" }, {opSub,"-"}, {opMul,"*"}, {opDiv, "/"}, {opAssign, "="}, {opLoadArray, "[]"}, {opStore2Array, "[]="}, {opSetLabel, "setLabel"}, {opPush, "push"}, {opCall, "call"}, {opLss, "<"}, {opLeq, "<="}, {opGre, ">" }, {opGeq,">="}, {opEql, "=="}, {opNeq, "!="}, {opGoto, "goto"}, {opBNZ, "BNZ"}, {opBZ, "BZ"}, {opScanf, "scanf"}, {opPrintf, "printf"}, {opReturn, "return"}, {opGetRetVal, "retValue"}, {opFunc, "function"} , {opVar, "var"}, {opPara, "para"}, {opConst, "const"}, {opBeq, "beq"}, {opBne, "bne"}, {opBlt, "blt"}, {opBle, "ble"}, {opBgt, "bgt"}, {opBge, "bge"}, {opMod, "%"}, }; ostringstream ostr; switch (op) { case opAdd: case opSub: case opMul: case opDiv: case opAssign: case opMod: case opLss: case opLeq: case opGre: case opGeq: case opEql: case opNeq: ostr << "\t"; if (result.length() > 0) { ostr << result << "\t"; } ostr << "=\t"; ostr << first << "\t"; if (second.length() > 0) { ostr << op2string[op] << "\t"; ostr << second; } break; case opLoadArray: ostr << "\t"; ostr << result << "\t=\t"; ostr << first << "[" << second << "]"; break; case opStore2Array: ostr << "\t" << first; ostr << "[" << second << "]" << "\t=\t"; ostr << result; break; case opSetLabel: ostr << result << ":"; break; case opBNZ: case opBZ: case opGoto: case opBeq: case opBne: case opBlt: case opBle: case opBgt: case opBge: ostr << "\t"; ostr << op2string[op] << "\t"; if (first.length() > 0) { ostr << first << "\t"; } if (second.length() > 0) { ostr << second << "\t"; } if (result.length() > 0) { ostr << result; } break; case opPush: ostr << "\t" << op2string[op] << "\t" << result; break; case opCall: case opScanf: case opPrintf: case opReturn: case opGetRetVal: case opFunc: case opVar: case opPara: case opConst: if (op != opFunc) { ostr << "\t"; } ostr << op2string[op] << "\t"; if (result.length() > 0) { ostr << result << "\t"; } if (first.length() > 0) { ostr << first << "\t"; } if (op == opConst) { ostr << "=\t"; } if (second.length() > 0) { ostr << second; } if (op == opFunc) { ostr << "()"; } break; default: break; } return ostr.str(); } void IntermediateCode::dumpCode2File(FILE* file) { for (auto i = imExprList.begin(); i != imExprList.end(); i++) { fprintf(file, "%s\n", i->toString().c_str()); } } string IntermediateCode::getTempVar() { string var = string("#TEMP_VAR_" + std::to_string(tempVarMark++)); return var; } void IntermediateCode::releaseTempVar() { tempVarMark = 0; } string IntermediateCode::getNewLabel() { static unsigned int cnt = 0; string label = string("LABEL_" + std::to_string(cnt++)); return label; }
35.98248
112
0.46395
[ "vector" ]
f6000e9fce2d63892fc6f5c495c3b9ac905a9e84
2,527
hpp
C++
ThirdParty/oglplus-develop/include/oglplus/exposed.hpp
vif/3D-STG
721402e76a9b9b99b88ba3eb06beb6abb17a9254
[ "MIT" ]
null
null
null
ThirdParty/oglplus-develop/include/oglplus/exposed.hpp
vif/3D-STG
721402e76a9b9b99b88ba3eb06beb6abb17a9254
[ "MIT" ]
null
null
null
ThirdParty/oglplus-develop/include/oglplus/exposed.hpp
vif/3D-STG
721402e76a9b9b99b88ba3eb06beb6abb17a9254
[ "MIT" ]
null
null
null
/** * @file oglplus/exposed.hpp * @brief Special object wrapper for exposing Object's OpenGL name * * @author Matus Chochlik * * Copyright 2010-2013 Matus Chochlik. 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 #ifndef OGLPLUS_EXPOSED_1107121519_HPP #define OGLPLUS_EXPOSED_1107121519_HPP #include <oglplus/config.hpp> #include <oglplus/friend_of.hpp> #include <oglplus/object.hpp> namespace oglplus { #ifdef Expose #undef Expose #endif #if OGLPLUS_DOCUMENTATION_ONLY /// This template class can ba used to get the OpenGL name of the Object /** Exposing the object's name can be useful when calling an OpenGL function * which is not wrapped by @OGLplus and which requires the name of an object. * * @note The instance of Object from which the instance of Exposed<Object> * was created must be kept alive at least as long as the instance of Exposed. * * @see Managed * @see Expose * * @ingroup utility_classes */ template <class Object> class Exposed : public Managed<Object> { public: Exposed(const Object& object); /// Returns the OpenGL name of the wrapped object GLuint Name(void) const; }; #else template <class ObjectOps_> class Exposed : public Managed<ObjectOps_> { public: Exposed(const ObjectOps_& object) : Managed<ObjectOps_>(object) { } GLuint Name(void) const { return FriendOf<ObjectOps_>::GetName(*this); } }; #endif #if OGLPLUS_DOCUMENTATION_ONLY /// Function that creates an Exposed wrapper for the object passed as argument /** This function provides a more convenient way of exposing an Object's name * than manually instantiating the Exposed class. * * Example: * @code * Program program; * // initialize program here * glProgramParameteri(Expose(program).Name(), GL_PROGRAM_SEPARABLE, GL_TRUE); * @endcode * @see Exposed * * @ingroup utility_classes */ template <class Object> inline Exposed<Object> Expose(const Object& object) #endif template <class ObjectOps_> inline Exposed<ObjectOps_> Expose(const Object<ObjectOps_>& object) { return Exposed<ObjectOps_>(object); } template <class ObjectOps_> inline Exposed<ObjectOps_> Expose(const Managed<Object<ObjectOps_> >& object) { return Exposed<ObjectOps_>(object); } template <class ObjectOps_> inline Exposed<ObjectOps_> Expose(const Managed<ObjectOps_>& object) { return Exposed<ObjectOps_>(object); } } // namespace oglplus #endif // include guard
23.616822
79
0.745944
[ "object" ]