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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b456b0940256fdbbaea932b0f979ccdf7668f611 | 8,694 | cpp | C++ | src/ros_viz_tools.cpp | qpc001/ros_viz_tools | 0e377004b0439ae7a276c5aa25dba09a28d826e4 | [
"MIT"
] | 12 | 2019-11-25T01:20:59.000Z | 2022-03-30T15:54:16.000Z | src/ros_viz_tools.cpp | Magic-wei/ros_viz_tools | 57fcf3e94bc586224f13106f83fd7b98bce86086 | [
"MIT"
] | null | null | null | src/ros_viz_tools.cpp | Magic-wei/ros_viz_tools | 57fcf3e94bc586224f13106f83fd7b98bce86086 | [
"MIT"
] | 8 | 2019-11-25T00:56:57.000Z | 2021-09-14T01:43:35.000Z | // Copyright (C) 2019 Wei Wang (wei.wang.bit@outlook.com)
#include "ros_viz_tools/ros_viz_tools.h"
namespace ros_viz_tools {
RosVizTools::RosVizTools(const ros::NodeHandle &nh, const std::string &topic) :
nh(nh), topic(topic) {
initPublisher();
}
void RosVizTools::initPublisher() {
rviz_pub = this->nh.advertise<visualization_msgs::MarkerArray>(topic, 1);
}
void RosVizTools::publish() {
rviz_pub.publish(this->rviz_marker_array);
}
void RosVizTools::clear() {
this->rviz_marker_array.markers.clear();
}
void RosVizTools::append(const Marker &marker) {
this->rviz_marker_array.markers.push_back(marker);
}
Marker RosVizTools::newMaker(const geometry_msgs::Vector3 &scale,
const geometry_msgs::Pose &pose,
const std::string &ns,
const int32_t &id,
const ColorRGBA &color,
const std::string &frame_id,
const int32_t &type) {
Marker marker;
// Set marker frame and timestamp.
marker.header.frame_id = frame_id;
marker.header.stamp = ros::Time::now();
// Set the namespace and id for this marker.
marker.ns = ns;
marker.id = id;
// Set the marker type.
marker.type = type;
// Set the marker action.
marker.action = visualization_msgs::Marker::ADD;
// Set the pose of the marker.
marker.pose = pose;
// Set the scale and color of the marker.
marker.scale = scale;
marker.color = color;
return marker;
}
Marker RosVizTools::newCubeList(double scale,
const std::string &ns,
const int32_t &id,
const ColorRGBA &color,
const std::string &frame_id) {
geometry_msgs::Vector3 vec_scale;
vec_scale.x = scale;
vec_scale.y = scale;
vec_scale.z = scale;
return newMaker(vec_scale, defaultPose(), ns, id, color, frame_id, visualization_msgs::Marker::CUBE_LIST);
}
Marker RosVizTools::newSphereList(const double &scale,
const std::string &ns,
const int32_t &id,
const ColorRGBA &color,
const std::string &frame_id) {
geometry_msgs::Vector3 vec_scale;
vec_scale.x = scale;
vec_scale.y = scale;
vec_scale.z = scale;
return newMaker(vec_scale, defaultPose(), ns, id, color, frame_id, visualization_msgs::Marker::SPHERE_LIST);
}
Marker RosVizTools::newLineStrip(const double &scale,
const std::string &ns,
const int32_t &id,
const ColorRGBA &color,
const std::string &frame_id) {
geometry_msgs::Vector3 vec_scale;
vec_scale.x = scale;
vec_scale.y = 1.0;
vec_scale.z = 1.0;
return newMaker(vec_scale, defaultPose(), ns, id, color, frame_id, visualization_msgs::Marker::LINE_STRIP);
}
Marker RosVizTools::newLineList(const double &scale,
const std::string &ns,
const int32_t &id,
const ColorRGBA &color,
const std::string &frame_id) {
geometry_msgs::Vector3 vec_scale;
vec_scale.x = scale;
vec_scale.y = 1.0;
vec_scale.z = 1.0;
return newMaker(vec_scale, defaultPose(), ns, id, color, frame_id, visualization_msgs::Marker::LINE_LIST);
}
Marker RosVizTools::newCylinder(const geometry_msgs::Vector3 &scale,
const geometry_msgs::Pose &pose,
const std::string &ns,
const int32_t &id,
const ColorRGBA &color,
const std::string &frame_id) {
return newMaker(scale, pose, ns, id, color, frame_id, visualization_msgs::Marker::CYLINDER);
}
Marker RosVizTools::newCube(const double &scale,
const geometry_msgs::Pose &pose,
const std::string &ns,
const int32_t &id,
const ColorRGBA &color,
const std::string &frame_id) {
geometry_msgs::Vector3 vec_scale;
vec_scale.x = scale;
vec_scale.y = scale;
vec_scale.z = scale;
return newMaker(vec_scale, pose, ns, id, color, frame_id, visualization_msgs::Marker::CUBE);
}
Marker RosVizTools::newSphere(const double &scale,
const geometry_msgs::Pose &pose,
const std::string &ns,
const int32_t &id,
const ColorRGBA &color,
const std::string &frame_id) {
geometry_msgs::Vector3 vec_scale;
vec_scale.x = scale;
vec_scale.y = scale;
vec_scale.z = scale;
return newMaker(vec_scale, pose, ns, id, color, frame_id, visualization_msgs::Marker::SPHERE);
}
Marker RosVizTools::newArrow(const geometry_msgs::Vector3 &scale,
const geometry_msgs::Pose &pose,
const std::string &ns,
const int32_t &id,
const ColorRGBA &color,
const std::string &frame_id) {
return newMaker(scale, pose, ns, id, color, frame_id, visualization_msgs::Marker::ARROW);
}
Marker RosVizTools::newText(const double &scale,
const geometry_msgs::Pose &pose,
const std::string &ns,
const int32_t &id,
const ColorRGBA &color,
const std::string &frame_id) {
geometry_msgs::Vector3 vec_scale;
vec_scale.x = 1.0;
vec_scale.y = 1.0;
vec_scale.z = scale;
return newMaker(vec_scale, pose, ns, id, color, frame_id, visualization_msgs::Marker::TEXT_VIEW_FACING);
}
Marker RosVizTools::newFrame(const double &width,
const double &length,
const geometry_msgs::Pose &pose,
const std::string &ns,
const int32_t &id,
const std::string &frame_id) {
// line list marker
Marker frame = newLineList(width, ns, id, ros_viz_tools::WHITE, frame_id);
// transform matrix - world origin to frame origin
tf2::Transform trans_world_ori;
tf2::convert(pose, trans_world_ori);
// transform matrix - frame origin to key point of x, y, z axes
tf2::Matrix3x3 mat(tf2::Quaternion(0, 0, 0, 1));
tf2::Vector3 pos_x(length, 0, 0);
tf2::Vector3 pos_y(0, length, 0);
tf2::Vector3 pos_z(0, 0, length);
tf2::Transform trans_ori_x(mat, pos_x);
tf2::Transform trans_ori_y(mat, pos_y);
tf2::Transform trans_ori_z(mat, pos_z);
// transform matrix - world origin to key point of x, y, z axes
tf2::Transform trans_world_x = trans_world_ori * trans_ori_x;
tf2::Transform trans_world_y = trans_world_ori * trans_ori_y;
tf2::Transform trans_world_z = trans_world_ori * trans_ori_z;
geometry_msgs::Point p;
// x axis
p.x = pose.position.x;
p.y = pose.position.y;
p.z = pose.position.z;
frame.points.push_back(p);
frame.colors.push_back(RED);
tf2::Vector3 r_wx = trans_world_x.getOrigin();
p.x = r_wx[0];
p.y = r_wx[1];
p.z = r_wx[2];
frame.points.push_back(p);
frame.colors.push_back(RED);
// y axis
p.x = pose.position.x;
p.y = pose.position.y;
p.z = pose.position.z;
frame.points.push_back(p);
frame.colors.push_back(GREEN);
tf2::Vector3 r_wy = trans_world_y.getOrigin();
p.x = r_wy[0];
p.y = r_wy[1];
p.z = r_wy[2];
frame.points.push_back(p);
frame.colors.push_back(GREEN);
// z axis
p.x = pose.position.x;
p.y = pose.position.y;
p.z = pose.position.z;
frame.points.push_back(p);
frame.colors.push_back(BLUE);
tf2::Vector3 r_wz = trans_world_z.getOrigin();
p.x = r_wz[0];
p.y = r_wz[1];
p.z = r_wz[2];
frame.points.push_back(p);
frame.colors.push_back(BLUE);
return frame;
}
geometry_msgs::Pose RosVizTools::defaultPose() {
geometry_msgs::Pose pose;
pose.position.x = 0.0;
pose.position.y = 0.0;
pose.position.z = 0.0;
pose.orientation.x = 0.0;
pose.orientation.y = 0.0;
pose.orientation.z = 0.0;
pose.orientation.w = 1.0;
return pose;
}
} // namespace ros_viz_tools | 35.485714 | 112 | 0.567058 | [
"transform"
] |
b45795a6421634595c3c1ca06ec50d3a2ce3c980 | 3,598 | cpp | C++ | src/QuickVtk-Core/Vtk/Internal/quickVtkFboOffscreenWindow.cpp | jayavardhanravi/QuickVtk | 4e899221daa6057c89193d079fa31435af89b296 | [
"BSD-3-Clause"
] | 1 | 2020-02-16T00:51:36.000Z | 2020-02-16T00:51:36.000Z | src/QuickVtk-Core/Vtk/Internal/quickVtkFboOffscreenWindow.cpp | jayavardhanravi/QuickVtk | 4e899221daa6057c89193d079fa31435af89b296 | [
"BSD-3-Clause"
] | null | null | null | src/QuickVtk-Core/Vtk/Internal/quickVtkFboOffscreenWindow.cpp | jayavardhanravi/QuickVtk | 4e899221daa6057c89193d079fa31435af89b296 | [
"BSD-3-Clause"
] | null | null | null | #include "quickVtkFboOffscreenWindow.hpp"
#include "quickVtkFboRenderer.hpp"
#include <vtkOpenGLState.h>
namespace quick {
namespace Vtk {
FboOffscreenWindow::FboOffscreenWindow() : QtParentRenderer(0) {
this->OffScreenRenderingOn();
}
auto FboOffscreenWindow::New() -> FboOffscreenWindow* {
return new FboOffscreenWindow();
}
auto FboOffscreenWindow::OpenGLInitState() -> void {
this->MakeCurrent();
initializeOpenGLFunctions();
// Get OpenGL viewport size as configured by QtQuick
int glViewport[4];
glGetIntegerv(GL_VIEWPORT, glViewport);
//std::cout << "FboOffscreenWindow::OpenGLInitState - glViewport: " << glViewport[0] << "," << glViewport[1] << "," << glViewport[2] << "," << glViewport[3] << "\n";
// Do not know why exactly we need this, but it seems to help with syncing the Qt-VTK OpenGL states
this->State->Initialize(this);
// We now check the viewport size in vtkOpenGLState
int vtkGLViewport[4];
this->State->vtkglGetIntegerv(GL_VIEWPORT, vtkGLViewport);
//std::cout << "FboOffscreenWindow::OpenGLInitState - vtkGLViewport: " << vtkGLViewport[0] << "," << vtkGLViewport[1] << "," << vtkGLViewport[2] << "," << vtkGLViewport[3] << "\n";
// We adjust if they went out of sync
if (vtkGLViewport[2] != glViewport[2] || vtkGLViewport[3] != glViewport[3])
{
//std::cout << "Need to adjust viewport..\n";
if (glViewport[2] > 1 && glViewport[3] > 1)
this->State->vtkglViewport(0, 0, glViewport[2], glViewport[3]);
}
// We can now reset the GL state based on the VTK state
Superclass::OpenGLInitState();
glUseProgram(0);
glEnable(GL_BLEND);
// This one throws an invalid enum
//glHint(GL_CLIP_VOLUME_CLIPPING_HINT_EXT, GL_FASTEST);
//NOTE:
// disabling the call to glDepthMask fixed an exception on windows
// occured only if opacity (vtkProperty) is < 1.0.
// this works fine on macOS & windows, not sure about Linux...
//glDepthMask(GL_TRUE);
}
auto FboOffscreenWindow::Render() -> void {
if (this->QtParentRenderer) {
this->QtParentRenderer->update();
}
}
auto FboOffscreenWindow::InternalRender() -> void {
Superclass::Render();
}
auto FboOffscreenWindow::SetFramebufferObject(QOpenGLFramebufferObject *fbo) -> void {
this->BackLeftBuffer = this->FrontLeftBuffer = this->BackBuffer = this->FrontBuffer = static_cast<unsigned int>(GL_COLOR_ATTACHMENT0);
auto size = fbo->size();
this->Size[0] = size.width();
this->Size[1] = size.height();
this->NumberOfFrameBuffers = 1;
this->FrameBufferObject = static_cast<unsigned int>(fbo->handle());
this->DepthRenderBufferObject = 0;
this->TextureObjects[0] = static_cast<unsigned int>(fbo->texture());
this->OffScreenRendering = 1;
this->OffScreenUseFrameBuffer = 1;
this->Modified();
}
FboOffscreenWindow::~FboOffscreenWindow() {
this->OffScreenRendering = 0;
}
}
}
| 39.977778 | 192 | 0.553641 | [
"render"
] |
b458cb8da6cc0ce4dc853ef61ca46de45faa04e0 | 46,000 | cpp | C++ | fpsgame/graphics/MapReader.cpp | mrlitong/CPP-Game-engine-usage | 95697c4bfb507cfb38dbe0f632740e2a7eac71fb | [
"MIT"
] | 186 | 2017-07-26T12:53:29.000Z | 2021-09-10T04:00:39.000Z | fpsgame/graphics/MapReader.cpp | mrlitong/CPP-Game-engine-usage | 95697c4bfb507cfb38dbe0f632740e2a7eac71fb | [
"MIT"
] | 1 | 2017-08-15T13:12:27.000Z | 2017-08-16T06:14:57.000Z | fpsgame/graphics/MapReader.cpp | mrlitong/CPP-Game-engine-usage | 95697c4bfb507cfb38dbe0f632740e2a7eac71fb | [
"MIT"
] | 6 | 2017-02-15T10:19:26.000Z | 2017-03-15T03:17:15.000Z | /* Copyright (C) 2016 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* 0 A.D. 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 0 A.D. If not, see <http://www.gnu.org/licenses/>.
*/
#include "precompiled.h"
#include "MapReader.h"
#include "graphics/Camera.h"
#include "graphics/CinemaManager.h"
#include "graphics/Entity.h"
#include "graphics/GameView.h"
#include "graphics/MapGenerator.h"
#include "graphics/Patch.h"
#include "graphics/Terrain.h"
#include "graphics/TerrainTextureEntry.h"
#include "graphics/TerrainTextureManager.h"
#include "lib/timer.h"
#include "lib/external_libraries/libsdl.h"
#include "maths/MathUtil.h"
#include "ps/CLogger.h"
#include "ps/Loader.h"
#include "ps/LoaderThunks.h"
#include "ps/World.h"
#include "ps/XML/Xeromyces.h"
#include "renderer/PostprocManager.h"
#include "renderer/SkyManager.h"
#include "renderer/WaterManager.h"
#include "simulation2/Simulation2.h"
#include "simulation2/components/ICmpObstruction.h"
#include "simulation2/components/ICmpOwnership.h"
#include "simulation2/components/ICmpPlayer.h"
#include "simulation2/components/ICmpPlayerManager.h"
#include "simulation2/components/ICmpPosition.h"
#include "simulation2/components/ICmpTerrain.h"
#include "simulation2/components/ICmpVisual.h"
#include "simulation2/components/ICmpWaterManager.h"
#include <boost/algorithm/string/predicate.hpp>
CMapReader::CMapReader()
: xml_reader(0), m_PatchesPerSide(0), m_MapGen(0)
{
cur_terrain_tex = 0; // important - resets generator state
// Maps that don't override the default probably want the old lighting model
//m_LightEnv.SetLightingModel("old");
//pPostproc->SetPostEffect(L"default");
}
// LoadMap: try to load the map from given file; reinitialise the scene to new data if successful
void CMapReader::LoadMap(const VfsPath& pathname, JSRuntime* rt, JS::HandleValue settings, CTerrain *pTerrain_,
WaterManager* pWaterMan_, SkyManager* pSkyMan_,
CLightEnv *pLightEnv_, CGameView *pGameView_, CCinemaManager* pCinema_, CTriggerManager* pTrigMan_, CPostprocManager* pPostproc_,
CSimulation2 *pSimulation2_, const CSimContext* pSimContext_, int playerID_, bool skipEntities)
{
// latch parameters (held until DelayedLoadFinished)
pTerrain = pTerrain_;
pLightEnv = pLightEnv_;
pGameView = pGameView_;
pWaterMan = pWaterMan_;
pSkyMan = pSkyMan_;
pCinema = pCinema_;
pTrigMan = pTrigMan_;
pPostproc = pPostproc_;
pSimulation2 = pSimulation2_;
pSimContext = pSimContext_;
m_PlayerID = playerID_;
m_SkipEntities = skipEntities;
m_StartingCameraTarget = INVALID_ENTITY;
m_ScriptSettings.init(rt, settings);
filename_xml = pathname.ChangeExtension(L".xml");
// In some cases (particularly tests) we don't want to bother storing a large
// mostly-empty .pmp file, so we let the XML file specify basic terrain instead.
// If there's an .xml file and no .pmp, then we're probably in this XML-only mode
only_xml = false;
if (!VfsFileExists(pathname) && VfsFileExists(filename_xml))
{
only_xml = true;
}
file_format_version = CMapIO::FILE_VERSION; // default if there's no .pmp
if (!only_xml)
{
// [25ms]
unpacker.Read(pathname, "PSMP");
file_format_version = unpacker.GetVersion();
}
// check oldest supported version
if (file_format_version < FILE_READ_VERSION)
throw PSERROR_File_InvalidVersion();
// delete all existing entities
if (pSimulation2)
pSimulation2->ResetState();
// reset post effects
if (pPostproc)
pPostproc->SetPostEffect(L"default");
// load map or script settings script
if (settings.isUndefined())
RegMemFun(this, &CMapReader::LoadScriptSettings, L"CMapReader::LoadScriptSettings", 50);
else
RegMemFun(this, &CMapReader::LoadRMSettings, L"CMapReader::LoadRMSettings", 50);
// load player settings script (must be done before reading map)
RegMemFun(this, &CMapReader::LoadPlayerSettings, L"CMapReader::LoadPlayerSettings", 50);
// unpack the data
if (!only_xml)
RegMemFun(this, &CMapReader::UnpackMap, L"CMapReader::UnpackMap", 1200);
// read the corresponding XML file
RegMemFun(this, &CMapReader::ReadXML, L"CMapReader::ReadXML", 50);
// apply terrain data to the world
RegMemFun(this, &CMapReader::ApplyTerrainData, L"CMapReader::ApplyTerrainData", 5);
// read entities
RegMemFun(this, &CMapReader::ReadXMLEntities, L"CMapReader::ReadXMLEntities", 5800);
// apply misc data to the world
RegMemFun(this, &CMapReader::ApplyData, L"CMapReader::ApplyData", 5);
// load map settings script (must be done after reading map)
RegMemFun(this, &CMapReader::LoadMapSettings, L"CMapReader::LoadMapSettings", 5);
RegMemFun(this, &CMapReader::DelayLoadFinished, L"CMapReader::DelayLoadFinished", 5);
}
// LoadRandomMap: try to load the map data; reinitialise the scene to new data if successful
void CMapReader::LoadRandomMap(const CStrW& scriptFile, JSRuntime* rt, JS::HandleValue settings, CTerrain *pTerrain_,
WaterManager* pWaterMan_, SkyManager* pSkyMan_,
CLightEnv *pLightEnv_, CGameView *pGameView_, CCinemaManager* pCinema_, CTriggerManager* pTrigMan_, CPostprocManager* pPostproc_,
CSimulation2 *pSimulation2_, int playerID_)
{
// latch parameters (held until DelayedLoadFinished)
m_ScriptFile = scriptFile;
pSimulation2 = pSimulation2_;
pSimContext = pSimulation2 ? &pSimulation2->GetSimContext() : NULL;
m_ScriptSettings.init(rt, settings);
pTerrain = pTerrain_;
pLightEnv = pLightEnv_;
pGameView = pGameView_;
pWaterMan = pWaterMan_;
pSkyMan = pSkyMan_;
pCinema = pCinema_;
pTrigMan = pTrigMan_;
pPostproc = pPostproc_;
m_PlayerID = playerID_;
m_SkipEntities = false;
m_StartingCameraTarget = INVALID_ENTITY;
// delete all existing entities
if (pSimulation2)
pSimulation2->ResetState();
only_xml = false;
// copy random map settings (before entity creation)
RegMemFun(this, &CMapReader::LoadRMSettings, L"CMapReader::LoadRMSettings", 50);
// load player settings script (must be done before reading map)
RegMemFun(this, &CMapReader::LoadPlayerSettings, L"CMapReader::LoadPlayerSettings", 50);
// load map generator with random map script
RegMemFun(this, &CMapReader::GenerateMap, L"CMapReader::GenerateMap", 5000);
// parse RMS results into terrain structure
RegMemFun(this, &CMapReader::ParseTerrain, L"CMapReader::ParseTerrain", 500);
// parse RMS results into environment settings
RegMemFun(this, &CMapReader::ParseEnvironment, L"CMapReader::ParseEnvironment", 5);
// parse RMS results into camera settings
RegMemFun(this, &CMapReader::ParseCamera, L"CMapReader::ParseCamera", 5);
// apply terrain data to the world
RegMemFun(this, &CMapReader::ApplyTerrainData, L"CMapReader::ApplyTerrainData", 5);
// parse RMS results into entities
RegMemFun(this, &CMapReader::ParseEntities, L"CMapReader::ParseEntities", 1000);
// apply misc data to the world
RegMemFun(this, &CMapReader::ApplyData, L"CMapReader::ApplyData", 5);
// load map settings script (must be done after reading map)
RegMemFun(this, &CMapReader::LoadMapSettings, L"CMapReader::LoadMapSettings", 5);
RegMemFun(this, &CMapReader::DelayLoadFinished, L"CMapReader::DelayLoadFinished", 5);
}
// UnpackMap: unpack the given data from the raw data stream into local variables
int CMapReader::UnpackMap()
{
// now unpack everything into local data
int ret = UnpackTerrain();
if (ret != 0) // failed or timed out
{
return ret;
}
return 0;
}
// UnpackTerrain: unpack the terrain from the end of the input data stream
// - data: map size, heightmap, list of textures used by map, texture tile assignments
int CMapReader::UnpackTerrain()
{
// yield after this time is reached. balances increased progress bar
// smoothness vs. slowing down loading.
const double end_time = timer_Time() + 200e-3;
// first call to generator (this is skipped after first call,
// i.e. when the loop below was interrupted)
if (cur_terrain_tex == 0)
{
m_PatchesPerSide = (ssize_t)unpacker.UnpackSize();
// unpack heightmap [600us]
size_t verticesPerSide = m_PatchesPerSide*PATCH_SIZE+1;
m_Heightmap.resize(SQR(verticesPerSide));
unpacker.UnpackRaw(&m_Heightmap[0], SQR(verticesPerSide)*sizeof(u16));
// unpack # textures
num_terrain_tex = unpacker.UnpackSize();
m_TerrainTextures.reserve(num_terrain_tex);
}
// unpack texture names; find handle for each texture.
// interruptible.
while (cur_terrain_tex < num_terrain_tex)
{
CStr texturename;
unpacker.UnpackString(texturename);
ENSURE(CTerrainTextureManager::IsInitialised()); // we need this for the terrain properties (even when graphics are disabled)
CTerrainTextureEntry* texentry = g_TexMan.FindTexture(texturename);
m_TerrainTextures.push_back(texentry);
cur_terrain_tex++;
LDR_CHECK_TIMEOUT(cur_terrain_tex, num_terrain_tex);
}
// unpack tile data [3ms]
ssize_t tilesPerSide = m_PatchesPerSide*PATCH_SIZE;
m_Tiles.resize(size_t(SQR(tilesPerSide)));
unpacker.UnpackRaw(&m_Tiles[0], sizeof(STileDesc)*m_Tiles.size());
// reset generator state.
cur_terrain_tex = 0;
return 0;
}
int CMapReader::ApplyTerrainData()
{
if (m_PatchesPerSide == 0)
{
// we'll probably crash when trying to use this map later
throw PSERROR_Game_World_MapLoadFailed("Error loading map: no terrain data.\nCheck application log for details.");
}
if (!only_xml)
{
// initialise the terrain
pTerrain->Initialize(m_PatchesPerSide, &m_Heightmap[0]);
// setup the textures on the minipatches
STileDesc* tileptr = &m_Tiles[0];
for (ssize_t j=0; j<m_PatchesPerSide; j++) {
for (ssize_t i=0; i<m_PatchesPerSide; i++) {
for (ssize_t m=0; m<PATCH_SIZE; m++) {
for (ssize_t k=0; k<PATCH_SIZE; k++) {
CMiniPatch& mp = pTerrain->GetPatch(i,j)->m_MiniPatches[m][k]; // can't fail
mp.Tex = m_TerrainTextures[tileptr->m_Tex1Index];
mp.Priority = tileptr->m_Priority;
tileptr++;
}
}
}
}
}
CmpPtr<ICmpTerrain> cmpTerrain(*pSimContext, SYSTEM_ENTITY);
if (cmpTerrain)
cmpTerrain->ReloadTerrain();
return 0;
}
// ApplyData: take all the input data, and rebuild the scene from it
int CMapReader::ApplyData()
{
// copy over the lighting parameters
if (pLightEnv)
*pLightEnv = m_LightEnv;
CmpPtr<ICmpPlayerManager> cmpPlayerManager(*pSimContext, SYSTEM_ENTITY);
if (pGameView && cmpPlayerManager)
{
// Default to global camera (with constraints)
pGameView->ResetCameraTarget(pGameView->GetCamera()->GetFocus());
// TODO: Starting rotation?
CmpPtr<ICmpPlayer> cmpPlayer(*pSimContext, cmpPlayerManager->GetPlayerByID(m_PlayerID));
if (cmpPlayer && cmpPlayer->HasStartingCamera())
{
// Use player starting camera
CFixedVector3D pos = cmpPlayer->GetStartingCameraPos();
pGameView->ResetCameraTarget(CVector3D(pos.X.ToFloat(), pos.Y.ToFloat(), pos.Z.ToFloat()));
}
else if (m_StartingCameraTarget != INVALID_ENTITY)
{
// Point camera at entity
CmpPtr<ICmpPosition> cmpPosition(*pSimContext, m_StartingCameraTarget);
if (cmpPosition)
{
CFixedVector3D pos = cmpPosition->GetPosition();
pGameView->ResetCameraTarget(CVector3D(pos.X.ToFloat(), pos.Y.ToFloat(), pos.Z.ToFloat()));
}
}
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
PSRETURN CMapSummaryReader::LoadMap(const VfsPath& pathname)
{
VfsPath filename_xml = pathname.ChangeExtension(L".xml");
CXeromyces xmb_file;
if (xmb_file.Load(g_VFS, filename_xml, "scenario") != PSRETURN_OK)
return PSRETURN_File_ReadFailed;
// Define all the relevant elements used in the XML file
#define EL(x) int el_##x = xmb_file.GetElementID(#x)
#define AT(x) int at_##x = xmb_file.GetAttributeID(#x)
EL(scenario);
EL(scriptsettings);
#undef AT
#undef EL
XMBElement root = xmb_file.GetRoot();
ENSURE(root.GetNodeName() == el_scenario);
XERO_ITER_EL(root, child)
{
int child_name = child.GetNodeName();
if (child_name == el_scriptsettings)
{
m_ScriptSettings = child.GetText();
}
}
return PSRETURN_OK;
}
void CMapSummaryReader::GetMapSettings(ScriptInterface& scriptInterface, JS::MutableHandleValue ret)
{
JSContext* cx = scriptInterface.GetContext();
JSAutoRequest rq(cx);
scriptInterface.Eval("({})", ret);
if (m_ScriptSettings.empty())
return;
JS::RootedValue scriptSettingsVal(cx);
scriptInterface.ParseJSON(m_ScriptSettings, &scriptSettingsVal);
scriptInterface.SetProperty(ret, "settings", scriptSettingsVal, false);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Holds various state data while reading maps, so that loading can be
// interrupted (e.g. to update the progress display) then later resumed.
class CXMLReader
{
NONCOPYABLE(CXMLReader);
public:
CXMLReader(const VfsPath& xml_filename, CMapReader& mapReader)
: m_MapReader(mapReader), nodes(NULL, 0, NULL)
{
Init(xml_filename);
}
CStr ReadScriptSettings();
// read everything except for entities
void ReadXML();
// return semantics: see Loader.cpp!LoadFunc.
int ProgressiveReadEntities();
private:
CXeromyces xmb_file;
CMapReader& m_MapReader;
int el_entity;
int el_tracks;
int el_template, el_player;
int el_position, el_orientation, el_obstruction;
int el_actor;
int at_x, at_y, at_z;
int at_group, at_group2;
int at_angle;
int at_uid;
int at_seed;
XMBElementList nodes; // children of root
// loop counters
size_t node_idx;
size_t entity_idx;
// # entities+nonentities processed and total (for progress calc)
int completed_jobs, total_jobs;
// maximum used entity ID, so we can safely allocate new ones
entity_id_t max_uid;
void Init(const VfsPath& xml_filename);
void ReadTerrain(XMBElement parent);
void ReadEnvironment(XMBElement parent);
void ReadCamera(XMBElement parent);
void ReadPaths(XMBElement parent);
void ReadTriggers(XMBElement parent);
int ReadEntities(XMBElement parent, double end_time);
};
void CXMLReader::Init(const VfsPath& xml_filename)
{
// must only assign once, so do it here
node_idx = entity_idx = 0;
if (xmb_file.Load(g_VFS, xml_filename, "scenario") != PSRETURN_OK)
throw PSERROR_File_ReadFailed();
// define the elements and attributes that are frequently used in the XML file,
// so we don't need to do lots of string construction and comparison when
// reading the data.
// (Needs to be synchronised with the list in CXMLReader - ugh)
#define EL(x) el_##x = xmb_file.GetElementID(#x)
#define AT(x) at_##x = xmb_file.GetAttributeID(#x)
EL(entity);
EL(tracks);
EL(template);
EL(player);
EL(position);
EL(orientation);
EL(obstruction);
EL(actor);
AT(x); AT(y); AT(z);
AT(group); AT(group2);
AT(angle);
AT(uid);
AT(seed);
#undef AT
#undef EL
XMBElement root = xmb_file.GetRoot();
ENSURE(xmb_file.GetElementString(root.GetNodeName()) == "Scenario");
nodes = root.GetChildNodes();
// find out total number of entities+nonentities
// (used when calculating progress)
completed_jobs = 0;
total_jobs = 0;
for (XMBElement node : nodes)
total_jobs += node.GetChildNodes().size();
// Find the maximum entity ID, so we can safely allocate new IDs without conflicts
max_uid = SYSTEM_ENTITY;
XMBElement ents = nodes.GetFirstNamedItem(xmb_file.GetElementID("Entities"));
XERO_ITER_EL(ents, ent)
{
CStr uid = ent.GetAttributes().GetNamedItem(at_uid);
max_uid = std::max(max_uid, (entity_id_t)uid.ToUInt());
}
}
CStr CXMLReader::ReadScriptSettings()
{
XMBElement root = xmb_file.GetRoot();
ENSURE(xmb_file.GetElementString(root.GetNodeName()) == "Scenario");
nodes = root.GetChildNodes();
XMBElement settings = nodes.GetFirstNamedItem(xmb_file.GetElementID("ScriptSettings"));
return settings.GetText();
}
void CXMLReader::ReadTerrain(XMBElement parent)
{
#define AT(x) int at_##x = xmb_file.GetAttributeID(#x)
AT(patches);
AT(texture);
AT(priority);
AT(height);
#undef AT
ssize_t patches = 9;
CStr texture = "grass1_spring";
int priority = 0;
u16 height = 16384;
XERO_ITER_ATTR(parent, attr)
{
if (attr.Name == at_patches)
patches = attr.Value.ToInt();
else if (attr.Name == at_texture)
texture = attr.Value;
else if (attr.Name == at_priority)
priority = attr.Value.ToInt();
else if (attr.Name == at_height)
height = (u16)attr.Value.ToInt();
}
m_MapReader.m_PatchesPerSide = patches;
// Load the texture
ENSURE(CTerrainTextureManager::IsInitialised()); // we need this for the terrain properties (even when graphics are disabled)
CTerrainTextureEntry* texentry = g_TexMan.FindTexture(texture);
m_MapReader.pTerrain->Initialize(patches, NULL);
// Fill the heightmap
u16* heightmap = m_MapReader.pTerrain->GetHeightMap();
ssize_t verticesPerSide = m_MapReader.pTerrain->GetVerticesPerSide();
for (ssize_t i = 0; i < SQR(verticesPerSide); ++i)
heightmap[i] = height;
// Fill the texture map
for (ssize_t pz = 0; pz < patches; ++pz)
{
for (ssize_t px = 0; px < patches; ++px)
{
CPatch* patch = m_MapReader.pTerrain->GetPatch(px, pz); // can't fail
for (ssize_t z = 0; z < PATCH_SIZE; ++z)
{
for (ssize_t x = 0; x < PATCH_SIZE; ++x)
{
patch->m_MiniPatches[z][x].Tex = texentry;
patch->m_MiniPatches[z][x].Priority = priority;
}
}
}
}
}
void CXMLReader::ReadEnvironment(XMBElement parent)
{
#define EL(x) int el_##x = xmb_file.GetElementID(#x)
#define AT(x) int at_##x = xmb_file.GetAttributeID(#x)
EL(lightingmodel);
EL(posteffect);
EL(skyset);
EL(suncolor);
EL(sunelevation);
EL(sunrotation);
EL(terrainambientcolor);
EL(unitsambientcolor);
EL(water);
EL(waterbody);
EL(type);
EL(color);
EL(tint);
EL(height);
EL(shininess); // for compatibility
EL(waviness);
EL(murkiness);
EL(windangle);
EL(reflectiontint); // for compatibility
EL(reflectiontintstrength); // for compatibility
EL(fog);
EL(fogcolor);
EL(fogfactor);
EL(fogthickness);
EL(postproc);
EL(brightness);
EL(contrast);
EL(saturation);
EL(bloom);
AT(r); AT(g); AT(b);
#undef AT
#undef EL
XERO_ITER_EL(parent, element)
{
int element_name = element.GetNodeName();
XMBAttributeList attrs = element.GetAttributes();
if (element_name == el_lightingmodel)
{
// NOP - obsolete.
}
else if (element_name == el_skyset)
{
if (m_MapReader.pSkyMan)
m_MapReader.pSkyMan->SetSkySet(element.GetText().FromUTF8());
}
else if (element_name == el_suncolor)
{
m_MapReader.m_LightEnv.m_SunColor = RGBColor(
attrs.GetNamedItem(at_r).ToFloat(),
attrs.GetNamedItem(at_g).ToFloat(),
attrs.GetNamedItem(at_b).ToFloat());
}
else if (element_name == el_sunelevation)
{
m_MapReader.m_LightEnv.m_Elevation = attrs.GetNamedItem(at_angle).ToFloat();
}
else if (element_name == el_sunrotation)
{
m_MapReader.m_LightEnv.m_Rotation = attrs.GetNamedItem(at_angle).ToFloat();
}
else if (element_name == el_terrainambientcolor)
{
m_MapReader.m_LightEnv.m_TerrainAmbientColor = RGBColor(
attrs.GetNamedItem(at_r).ToFloat(),
attrs.GetNamedItem(at_g).ToFloat(),
attrs.GetNamedItem(at_b).ToFloat());
}
else if (element_name == el_unitsambientcolor)
{
m_MapReader.m_LightEnv.m_UnitsAmbientColor = RGBColor(
attrs.GetNamedItem(at_r).ToFloat(),
attrs.GetNamedItem(at_g).ToFloat(),
attrs.GetNamedItem(at_b).ToFloat());
}
else if (element_name == el_fog)
{
XERO_ITER_EL(element, fog)
{
int element_name = fog.GetNodeName();
if (element_name == el_fogcolor)
{
XMBAttributeList attrs = fog.GetAttributes();
m_MapReader.m_LightEnv.m_FogColor = RGBColor(
attrs.GetNamedItem(at_r).ToFloat(),
attrs.GetNamedItem(at_g).ToFloat(),
attrs.GetNamedItem(at_b).ToFloat());
}
else if (element_name == el_fogfactor)
{
m_MapReader.m_LightEnv.m_FogFactor = fog.GetText().ToFloat();
}
else if (element_name == el_fogthickness)
{
m_MapReader.m_LightEnv.m_FogMax = fog.GetText().ToFloat();
}
}
}
else if (element_name == el_postproc)
{
XERO_ITER_EL(element, postproc)
{
int element_name = postproc.GetNodeName();
if (element_name == el_brightness)
{
m_MapReader.m_LightEnv.m_Brightness = postproc.GetText().ToFloat();
}
else if (element_name == el_contrast)
{
m_MapReader.m_LightEnv.m_Contrast = postproc.GetText().ToFloat();
}
else if (element_name == el_saturation)
{
m_MapReader.m_LightEnv.m_Saturation = postproc.GetText().ToFloat();
}
else if (element_name == el_bloom)
{
m_MapReader.m_LightEnv.m_Bloom = postproc.GetText().ToFloat();
}
else if (element_name == el_posteffect)
{
if (m_MapReader.pPostproc)
m_MapReader.pPostproc->SetPostEffect(postproc.GetText().FromUTF8());
}
}
}
else if (element_name == el_water)
{
XERO_ITER_EL(element, waterbody)
{
ENSURE(waterbody.GetNodeName() == el_waterbody);
XERO_ITER_EL(waterbody, waterelement)
{
int element_name = waterelement.GetNodeName();
if (element_name == el_height)
{
CmpPtr<ICmpWaterManager> cmpWaterManager(*m_MapReader.pSimContext, SYSTEM_ENTITY);
ENSURE(cmpWaterManager);
cmpWaterManager->SetWaterLevel(entity_pos_t::FromString(waterelement.GetText()));
continue;
}
// The rest are purely graphical effects, and should be ignored if
// graphics are disabled
if (!m_MapReader.pWaterMan)
continue;
if (element_name == el_type)
{
if (waterelement.GetText() == "default")
m_MapReader.pWaterMan->m_WaterType = L"ocean";
else
m_MapReader.pWaterMan->m_WaterType = waterelement.GetText().FromUTF8();
}
else if (element_name == el_shininess || element_name == el_reflectiontint || element_name == el_reflectiontintstrength)
{
// deprecated.
}
#define READ_COLOR(el, out) \
else if (element_name == el) \
{ \
XMBAttributeList attrs = waterelement.GetAttributes(); \
out = CColor( \
attrs.GetNamedItem(at_r).ToFloat(), \
attrs.GetNamedItem(at_g).ToFloat(), \
attrs.GetNamedItem(at_b).ToFloat(), \
1.f); \
}
#define READ_FLOAT(el, out) \
else if (element_name == el) \
{ \
out = waterelement.GetText().ToFloat(); \
} \
READ_COLOR(el_color, m_MapReader.pWaterMan->m_WaterColor)
READ_COLOR(el_tint, m_MapReader.pWaterMan->m_WaterTint)
READ_FLOAT(el_waviness, m_MapReader.pWaterMan->m_Waviness)
READ_FLOAT(el_murkiness, m_MapReader.pWaterMan->m_Murkiness)
READ_FLOAT(el_windangle, m_MapReader.pWaterMan->m_WindAngle)
#undef READ_FLOAT
#undef READ_COLOR
else
debug_warn(L"Invalid map XML data");
}
}
}
else
debug_warn(L"Invalid map XML data");
}
m_MapReader.m_LightEnv.CalculateSunDirection();
}
void CXMLReader::ReadCamera(XMBElement parent)
{
// defaults if we don't find player starting camera
#define EL(x) int el_##x = xmb_file.GetElementID(#x)
#define AT(x) int at_##x = xmb_file.GetAttributeID(#x)
EL(declination);
EL(rotation);
EL(position);
AT(angle);
AT(x); AT(y); AT(z);
#undef AT
#undef EL
float declination = DEGTORAD(30.f), rotation = DEGTORAD(-45.f);
CVector3D translation = CVector3D(100, 150, -100);
XERO_ITER_EL(parent, element)
{
int element_name = element.GetNodeName();
XMBAttributeList attrs = element.GetAttributes();
if (element_name == el_declination)
{
declination = attrs.GetNamedItem(at_angle).ToFloat();
}
else if (element_name == el_rotation)
{
rotation = attrs.GetNamedItem(at_angle).ToFloat();
}
else if (element_name == el_position)
{
translation = CVector3D(
attrs.GetNamedItem(at_x).ToFloat(),
attrs.GetNamedItem(at_y).ToFloat(),
attrs.GetNamedItem(at_z).ToFloat());
}
else
debug_warn(L"Invalid map XML data");
}
if (m_MapReader.pGameView)
{
m_MapReader.pGameView->GetCamera()->m_Orientation.SetXRotation(declination);
m_MapReader.pGameView->GetCamera()->m_Orientation.RotateY(rotation);
m_MapReader.pGameView->GetCamera()->m_Orientation.Translate(translation);
m_MapReader.pGameView->GetCamera()->UpdateFrustum();
}
}
void CXMLReader::ReadPaths(XMBElement parent)
{
#define EL(x) int el_##x = xmb_file.GetElementID(#x)
#define AT(x) int at_##x = xmb_file.GetAttributeID(#x)
EL(path);
EL(rotation);
EL(node);
EL(position);
EL(target);
AT(name);
AT(timescale);
AT(orientation);
AT(mode);
AT(style);
AT(x);
AT(y);
AT(z);
AT(deltatime);
#undef EL
#undef AT
XERO_ITER_EL(parent, element)
{
int elementName = element.GetNodeName();
if (elementName == el_path)
{
CCinemaData pathData;
XMBAttributeList attrs = element.GetAttributes();
CStrW pathName(attrs.GetNamedItem(at_name).FromUTF8());
pathData.m_Timescale = fixed::FromString(attrs.GetNamedItem(at_timescale));
TNSpline pathSpline, targetSpline;
fixed lastTargetTime = fixed::Zero();
pathData.m_Name = pathName;
pathData.m_Orientation = attrs.GetNamedItem(at_orientation).FromUTF8();
pathData.m_Mode = attrs.GetNamedItem(at_mode).FromUTF8();
pathData.m_Style = attrs.GetNamedItem(at_style).FromUTF8();
XERO_ITER_EL(element, pathChild)
{
elementName = pathChild.GetNodeName();
attrs = pathChild.GetAttributes();
// Load node data used for spline
if (elementName == el_node)
{
bool positionDeclared = false;
SplineData data;
data.Distance = fixed::FromString(attrs.GetNamedItem(at_deltatime));
lastTargetTime += fixed::FromString(attrs.GetNamedItem(at_deltatime));
XERO_ITER_EL(pathChild, nodeChild)
{
elementName = nodeChild.GetNodeName();
attrs = nodeChild.GetAttributes();
if (elementName == el_position)
{
data.Position.X = fixed::FromString(attrs.GetNamedItem(at_x));
data.Position.Y = fixed::FromString(attrs.GetNamedItem(at_y));
data.Position.Z = fixed::FromString(attrs.GetNamedItem(at_z));
positionDeclared = true;
}
else if (elementName == el_rotation)
{
data.Rotation.X = fixed::FromString(attrs.GetNamedItem(at_x));
data.Rotation.Y = fixed::FromString(attrs.GetNamedItem(at_y));
data.Rotation.Z = fixed::FromString(attrs.GetNamedItem(at_z));
}
else if (elementName == el_target)
{
CFixedVector3D targetPosition;
targetPosition.X = fixed::FromString(attrs.GetNamedItem(at_x));
targetPosition.Y = fixed::FromString(attrs.GetNamedItem(at_y));
targetPosition.Z = fixed::FromString(attrs.GetNamedItem(at_z));
targetSpline.AddNode(targetPosition, CFixedVector3D(), lastTargetTime);
lastTargetTime = fixed::Zero();
}
else
LOGWARNING("Invalid cinematic element for node child");
}
// Skip the node if no position
if (positionDeclared)
pathSpline.AddNode(data.Position, data.Rotation, data.Distance);
}
else
LOGWARNING("Invalid cinematic element for path child");
}
// Construct cinema path with data gathered
CCinemaPath path(pathData, pathSpline, targetSpline);
if (path.Empty())
{
LOGWARNING("Path with name '%s' is empty", pathName.ToUTF8());
return;
}
if (!m_MapReader.pCinema->HasPath(pathName))
m_MapReader.pCinema->AddPath(pathName, path);
else
LOGWARNING("Path with name '%s' already exists", pathName.ToUTF8());
}
else
LOGWARNING("Invalid path child with name '%s'", element.GetText());
}
}
void CXMLReader::ReadTriggers(XMBElement UNUSED(parent))
{
}
int CXMLReader::ReadEntities(XMBElement parent, double end_time)
{
XMBElementList entities = parent.GetChildNodes();
ENSURE(m_MapReader.pSimulation2);
CSimulation2& sim = *m_MapReader.pSimulation2;
CmpPtr<ICmpPlayerManager> cmpPlayerManager(sim, SYSTEM_ENTITY);
while (entity_idx < entities.size())
{
// all new state at this scope and below doesn't need to be
// wrapped, since we only yield after a complete iteration.
XMBElement entity = entities[entity_idx++];
ENSURE(entity.GetNodeName() == el_entity);
XMBAttributeList attrs = entity.GetAttributes();
CStr uid = attrs.GetNamedItem(at_uid);
ENSURE(!uid.empty());
int EntityUid = uid.ToInt();
CStrW TemplateName;
int PlayerID = 0;
CFixedVector3D Position;
CFixedVector3D Orientation;
long Seed = -1;
// Obstruction control groups.
entity_id_t ControlGroup = INVALID_ENTITY;
entity_id_t ControlGroup2 = INVALID_ENTITY;
XERO_ITER_EL(entity, setting)
{
int element_name = setting.GetNodeName();
// <template>
if (element_name == el_template)
{
TemplateName = setting.GetText().FromUTF8();
}
// <player>
else if (element_name == el_player)
{
PlayerID = setting.GetText().ToInt();
}
// <position>
else if (element_name == el_position)
{
XMBAttributeList attrs = setting.GetAttributes();
Position = CFixedVector3D(
fixed::FromString(attrs.GetNamedItem(at_x)),
fixed::FromString(attrs.GetNamedItem(at_y)),
fixed::FromString(attrs.GetNamedItem(at_z)));
}
// <orientation>
else if (element_name == el_orientation)
{
XMBAttributeList attrs = setting.GetAttributes();
Orientation = CFixedVector3D(
fixed::FromString(attrs.GetNamedItem(at_x)),
fixed::FromString(attrs.GetNamedItem(at_y)),
fixed::FromString(attrs.GetNamedItem(at_z)));
// TODO: what happens if some attributes are missing?
}
// <obstruction>
else if (element_name == el_obstruction)
{
XMBAttributeList attrs = setting.GetAttributes();
ControlGroup = attrs.GetNamedItem(at_group).ToInt();
ControlGroup2 = attrs.GetNamedItem(at_group2).ToInt();
}
// <actor>
else if (element_name == el_actor)
{
XMBAttributeList attrs = setting.GetAttributes();
CStr seedStr = attrs.GetNamedItem(at_seed);
if (!seedStr.empty())
{
Seed = seedStr.ToLong();
ENSURE(Seed >= 0);
}
}
else
debug_warn(L"Invalid map XML data");
}
entity_id_t ent = sim.AddEntity(TemplateName, EntityUid);
entity_id_t player = cmpPlayerManager->GetPlayerByID(PlayerID);
if (ent == INVALID_ENTITY || player == INVALID_ENTITY)
{ // Don't add entities with invalid player IDs
LOGERROR("Failed to load entity template '%s'", utf8_from_wstring(TemplateName));
}
else
{
CmpPtr<ICmpPosition> cmpPosition(sim, ent);
if (cmpPosition)
{
cmpPosition->JumpTo(Position.X, Position.Z);
cmpPosition->SetYRotation(Orientation.Y);
// TODO: other parts of the position
}
CmpPtr<ICmpOwnership> cmpOwnership(sim, ent);
if (cmpOwnership)
cmpOwnership->SetOwner(PlayerID);
CmpPtr<ICmpObstruction> cmpObstruction(sim, ent);
if (cmpObstruction)
{
if (ControlGroup != INVALID_ENTITY)
cmpObstruction->SetControlGroup(ControlGroup);
if (ControlGroup2 != INVALID_ENTITY)
cmpObstruction->SetControlGroup2(ControlGroup2);
cmpObstruction->ResolveFoundationCollisions();
}
CmpPtr<ICmpVisual> cmpVisual(sim, ent);
if (cmpVisual)
{
if (Seed != -1)
cmpVisual->SetActorSeed((u32)Seed);
// TODO: variation/selection strings
}
if (PlayerID == m_MapReader.m_PlayerID && (boost::algorithm::ends_with(TemplateName, L"civil_centre") || m_MapReader.m_StartingCameraTarget == INVALID_ENTITY))
{
// Focus on civil centre or first entity owned by player
m_MapReader.m_StartingCameraTarget = ent;
}
}
completed_jobs++;
LDR_CHECK_TIMEOUT(completed_jobs, total_jobs);
}
return 0;
}
void CXMLReader::ReadXML()
{
for (XMBElement node : nodes)
{
CStr name = xmb_file.GetElementString(node.GetNodeName());
if (name == "Terrain")
{
ReadTerrain(node);
}
else if (name == "Environment")
{
ReadEnvironment(node);
}
else if (name == "Camera")
{
ReadCamera(node);
}
else if (name == "ScriptSettings")
{
// Already loaded - this is to prevent an assertion
}
else if (name == "Entities")
{
// Handled by ProgressiveReadEntities instead
}
else if (name == "Paths")
{
ReadPaths(node);
}
else if (name == "Triggers")
{
ReadTriggers(node);
}
else if (name == "Script")
{
if (m_MapReader.pSimulation2)
m_MapReader.pSimulation2->SetStartupScript(node.GetText());
}
else
{
debug_printf("Invalid XML element in map file: %s\n", name.c_str());
debug_warn(L"Invalid map XML data");
}
}
}
int CXMLReader::ProgressiveReadEntities()
{
// yield after this time is reached. balances increased progress bar
// smoothness vs. slowing down loading.
const double end_time = timer_Time() + 200e-3;
int ret;
while (node_idx < nodes.size())
{
XMBElement node = nodes[node_idx];
CStr name = xmb_file.GetElementString(node.GetNodeName());
if (name == "Entities")
{
if (!m_MapReader.m_SkipEntities)
{
ret = ReadEntities(node, end_time);
if (ret != 0) // error or timed out
return ret;
}
}
node_idx++;
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// load script settings from map
int CMapReader::LoadScriptSettings()
{
if (!xml_reader)
xml_reader = new CXMLReader(filename_xml, *this);
// parse the script settings
if (pSimulation2)
pSimulation2->SetMapSettings(xml_reader->ReadScriptSettings());
return 0;
}
// load player settings script
int CMapReader::LoadPlayerSettings()
{
if (pSimulation2)
pSimulation2->LoadPlayerSettings(true);
return 0;
}
// load map settings script
int CMapReader::LoadMapSettings()
{
if (pSimulation2)
pSimulation2->LoadMapSettings();
return 0;
}
int CMapReader::ReadXML()
{
if (!xml_reader)
xml_reader = new CXMLReader(filename_xml, *this);
xml_reader->ReadXML();
return 0;
}
// progressive
int CMapReader::ReadXMLEntities()
{
if (!xml_reader)
xml_reader = new CXMLReader(filename_xml, *this);
int ret = xml_reader->ProgressiveReadEntities();
// finished or failed
if (ret <= 0)
{
SAFE_DELETE(xml_reader);
}
return ret;
}
int CMapReader::DelayLoadFinished()
{
// we were dynamically allocated by CWorld::Initialize
delete this;
return 0;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int CMapReader::LoadRMSettings()
{
// copy random map settings over to sim
ENSURE(pSimulation2);
pSimulation2->SetMapSettings(m_ScriptSettings);
return 0;
}
int CMapReader::GenerateMap()
{
JSContext* cx = pSimulation2->GetScriptInterface().GetContext();
JSAutoRequest rq(cx);
if (!m_MapGen)
{
// Initialize map generator
m_MapGen = new CMapGenerator();
VfsPath scriptPath;
if (m_ScriptFile.length())
scriptPath = L"maps/random/"+m_ScriptFile;
// Stringify settings to pass across threads
std::string scriptSettings = pSimulation2->GetScriptInterface().StringifyJSON(&m_ScriptSettings);
// Try to generate map
m_MapGen->GenerateMap(scriptPath, scriptSettings);
}
// Check status
int progress = m_MapGen->GetProgress();
if (progress < 0)
{
// RMS failed - return to main menu
throw PSERROR_Game_World_MapLoadFailed("Error generating random map.\nCheck application log for details.");
}
else if (progress == 0)
{
// Finished, get results as StructuredClone object, which must be read to obtain the JS val
shared_ptr<ScriptInterface::StructuredClone> results = m_MapGen->GetResults();
// Parse data into simulation context
JS::RootedValue data(cx);
pSimulation2->GetScriptInterface().ReadStructuredClone(results, &data);
if (data.isUndefined())
{
// RMS failed - return to main menu
throw PSERROR_Game_World_MapLoadFailed("Error generating random map.\nCheck application log for details.");
}
else
{
m_MapData.init(cx, data);
}
}
else
{
// Still working
// Sleep for a while, slowing down the rendering thread
// to allow more CPU for the map generator thread
SDL_Delay(100);
}
// return progress
return progress;
};
int CMapReader::ParseTerrain()
{
TIMER(L"ParseTerrain");
JSContext* cx = pSimulation2->GetScriptInterface().GetContext();
JSAutoRequest rq(cx);
// parse terrain from map data
// an error here should stop the loading process
#define GET_TERRAIN_PROPERTY(val, prop, out)\
if (!pSimulation2->GetScriptInterface().GetProperty(val, #prop, out))\
{ LOGERROR("CMapReader::ParseTerrain() failed to get '%s' property", #prop);\
throw PSERROR_Game_World_MapLoadFailed("Error parsing terrain data.\nCheck application log for details"); }
u32 size;
GET_TERRAIN_PROPERTY(m_MapData, size, size)
m_PatchesPerSide = size / PATCH_SIZE;
// flat heightmap of u16 data
GET_TERRAIN_PROPERTY(m_MapData, height, m_Heightmap)
// load textures
std::vector<std::string> textureNames;
GET_TERRAIN_PROPERTY(m_MapData, textureNames, textureNames)
num_terrain_tex = textureNames.size();
while (cur_terrain_tex < num_terrain_tex)
{
ENSURE(CTerrainTextureManager::IsInitialised()); // we need this for the terrain properties (even when graphics are disabled)
CTerrainTextureEntry* texentry = g_TexMan.FindTexture(textureNames[cur_terrain_tex]);
m_TerrainTextures.push_back(texentry);
cur_terrain_tex++;
}
// build tile data
m_Tiles.resize(SQR(size));
JS::RootedValue tileData(cx);
GET_TERRAIN_PROPERTY(m_MapData, tileData, &tileData)
// parse tile data object into flat arrays
std::vector<u16> tileIndex;
std::vector<u16> tilePriority;
GET_TERRAIN_PROPERTY(tileData, index, tileIndex);
GET_TERRAIN_PROPERTY(tileData, priority, tilePriority);
ENSURE(SQR(size) == tileIndex.size() && SQR(size) == tilePriority.size());
// reorder by patches and store
for (size_t x = 0; x < size; ++x)
{
size_t patchX = x / PATCH_SIZE;
size_t offX = x % PATCH_SIZE;
for (size_t y = 0; y < size; ++y)
{
size_t patchY = y / PATCH_SIZE;
size_t offY = y % PATCH_SIZE;
STileDesc tile;
tile.m_Tex1Index = tileIndex[y*size + x];
tile.m_Tex2Index = 0xFFFF;
tile.m_Priority = tilePriority[y*size + x];
m_Tiles[(patchY * m_PatchesPerSide + patchX) * SQR(PATCH_SIZE) + (offY * PATCH_SIZE + offX)] = tile;
}
}
// reset generator state
cur_terrain_tex = 0;
#undef GET_TERRAIN_PROPERTY
return 0;
}
int CMapReader::ParseEntities()
{
TIMER(L"ParseEntities");
JSContext* cx = pSimulation2->GetScriptInterface().GetContext();
JSAutoRequest rq(cx);
// parse entities from map data
std::vector<Entity> entities;
if (!pSimulation2->GetScriptInterface().GetProperty(m_MapData, "entities", entities))
LOGWARNING("CMapReader::ParseEntities() failed to get 'entities' property");
CSimulation2& sim = *pSimulation2;
CmpPtr<ICmpPlayerManager> cmpPlayerManager(sim, SYSTEM_ENTITY);
size_t entity_idx = 0;
size_t num_entities = entities.size();
Entity currEnt;
while (entity_idx < num_entities)
{
// Get current entity struct
currEnt = entities[entity_idx];
entity_id_t ent = pSimulation2->AddEntity(currEnt.templateName, currEnt.entityID);
entity_id_t player = cmpPlayerManager->GetPlayerByID(currEnt.playerID);
if (ent == INVALID_ENTITY || player == INVALID_ENTITY)
{ // Don't add entities with invalid player IDs
LOGERROR("Failed to load entity template '%s'", utf8_from_wstring(currEnt.templateName));
}
else
{
CmpPtr<ICmpPosition> cmpPosition(sim, ent);
if (cmpPosition)
{
cmpPosition->JumpTo(currEnt.position.X, currEnt.position.Z);
cmpPosition->SetYRotation(currEnt.rotation.Y);
// TODO: other parts of the position
}
CmpPtr<ICmpOwnership> cmpOwnership(sim, ent);
if (cmpOwnership)
cmpOwnership->SetOwner(currEnt.playerID);
// Detect and fix collisions between foundation-blocking entities.
// This presently serves to copy wall tower control groups to wall
// segments, allowing players to expand RMS-generated walls.
CmpPtr<ICmpObstruction> cmpObstruction(sim, ent);
if (cmpObstruction)
cmpObstruction->ResolveFoundationCollisions();
if (currEnt.playerID == m_PlayerID && (boost::algorithm::ends_with(currEnt.templateName, L"civil_centre") || m_StartingCameraTarget == INVALID_ENTITY))
{
// Focus on civil centre or first entity owned by player
m_StartingCameraTarget = currEnt.entityID;
}
}
entity_idx++;
}
return 0;
}
int CMapReader::ParseEnvironment()
{
// parse environment settings from map data
JSContext* cx = pSimulation2->GetScriptInterface().GetContext();
JSAutoRequest rq(cx);
#define GET_ENVIRONMENT_PROPERTY(val, prop, out)\
if (!pSimulation2->GetScriptInterface().GetProperty(val, #prop, out))\
LOGWARNING("CMapReader::ParseEnvironment() failed to get '%s' property", #prop);
JS::RootedValue envObj(cx);
GET_ENVIRONMENT_PROPERTY(m_MapData, Environment, &envObj)
if (envObj.isUndefined())
{
LOGWARNING("CMapReader::ParseEnvironment(): Environment settings not found");
return 0;
}
//m_LightEnv.SetLightingModel("standard");
if (pPostproc)
pPostproc->SetPostEffect(L"default");
std::wstring skySet;
GET_ENVIRONMENT_PROPERTY(envObj, SkySet, skySet)
if (pSkyMan)
pSkyMan->SetSkySet(skySet);
CColor sunColor;
GET_ENVIRONMENT_PROPERTY(envObj, SunColor, sunColor)
m_LightEnv.m_SunColor = RGBColor(sunColor.r, sunColor.g, sunColor.b);
GET_ENVIRONMENT_PROPERTY(envObj, SunElevation, m_LightEnv.m_Elevation)
GET_ENVIRONMENT_PROPERTY(envObj, SunRotation, m_LightEnv.m_Rotation)
CColor terrainAmbientColor;
GET_ENVIRONMENT_PROPERTY(envObj, TerrainAmbientColor, terrainAmbientColor)
m_LightEnv.m_TerrainAmbientColor = RGBColor(terrainAmbientColor.r, terrainAmbientColor.g, terrainAmbientColor.b);
CColor unitsAmbientColor;
GET_ENVIRONMENT_PROPERTY(envObj, UnitsAmbientColor, unitsAmbientColor)
m_LightEnv.m_UnitsAmbientColor = RGBColor(unitsAmbientColor.r, unitsAmbientColor.g, unitsAmbientColor.b);
// Water properties
JS::RootedValue waterObj(cx);
GET_ENVIRONMENT_PROPERTY(envObj, Water, &waterObj)
JS::RootedValue waterBodyObj(cx);
GET_ENVIRONMENT_PROPERTY(waterObj, WaterBody, &waterBodyObj)
// Water level - necessary
float waterHeight;
GET_ENVIRONMENT_PROPERTY(waterBodyObj, Height, waterHeight)
CmpPtr<ICmpWaterManager> cmpWaterManager(*pSimulation2, SYSTEM_ENTITY);
ENSURE(cmpWaterManager);
cmpWaterManager->SetWaterLevel(entity_pos_t::FromFloat(waterHeight));
// If we have graphics, get rest of settings
if (pWaterMan)
{
GET_ENVIRONMENT_PROPERTY(waterBodyObj, Type, pWaterMan->m_WaterType)
if (pWaterMan->m_WaterType == L"default")
pWaterMan->m_WaterType = L"ocean";
GET_ENVIRONMENT_PROPERTY(waterBodyObj, Color, pWaterMan->m_WaterColor)
GET_ENVIRONMENT_PROPERTY(waterBodyObj, Tint, pWaterMan->m_WaterTint)
GET_ENVIRONMENT_PROPERTY(waterBodyObj, Waviness, pWaterMan->m_Waviness)
GET_ENVIRONMENT_PROPERTY(waterBodyObj, Murkiness, pWaterMan->m_Murkiness)
GET_ENVIRONMENT_PROPERTY(waterBodyObj, WindAngle, pWaterMan->m_WindAngle)
}
JS::RootedValue fogObject(cx);
GET_ENVIRONMENT_PROPERTY(envObj, Fog, &fogObject);
GET_ENVIRONMENT_PROPERTY(fogObject, FogFactor, m_LightEnv.m_FogFactor);
GET_ENVIRONMENT_PROPERTY(fogObject, FogThickness, m_LightEnv.m_FogMax);
CColor fogColor;
GET_ENVIRONMENT_PROPERTY(fogObject, FogColor, fogColor);
m_LightEnv.m_FogColor = RGBColor(fogColor.r, fogColor.g, fogColor.b);
JS::RootedValue postprocObject(cx);
GET_ENVIRONMENT_PROPERTY(envObj, Postproc, &postprocObject);
std::wstring postProcEffect;
GET_ENVIRONMENT_PROPERTY(postprocObject, PostprocEffect, postProcEffect);
if (pPostproc)
pPostproc->SetPostEffect(postProcEffect);
GET_ENVIRONMENT_PROPERTY(postprocObject, Brightness, m_LightEnv.m_Brightness);
GET_ENVIRONMENT_PROPERTY(postprocObject, Contrast, m_LightEnv.m_Contrast);
GET_ENVIRONMENT_PROPERTY(postprocObject, Saturation, m_LightEnv.m_Saturation);
GET_ENVIRONMENT_PROPERTY(postprocObject, Bloom, m_LightEnv.m_Bloom);
m_LightEnv.CalculateSunDirection();
#undef GET_ENVIRONMENT_PROPERTY
return 0;
}
int CMapReader::ParseCamera()
{
JSContext* cx = pSimulation2->GetScriptInterface().GetContext();
JSAutoRequest rq(cx);
// parse camera settings from map data
// defaults if we don't find player starting camera
float declination = DEGTORAD(30.f), rotation = DEGTORAD(-45.f);
CVector3D translation = CVector3D(100, 150, -100);
#define GET_CAMERA_PROPERTY(val, prop, out)\
if (!pSimulation2->GetScriptInterface().GetProperty(val, #prop, out))\
LOGWARNING("CMapReader::ParseCamera() failed to get '%s' property", #prop);
JS::RootedValue cameraObj(cx);
GET_CAMERA_PROPERTY(m_MapData, Camera, &cameraObj)
if (!cameraObj.isUndefined())
{ // If camera property exists, read values
CFixedVector3D pos;
GET_CAMERA_PROPERTY(cameraObj, Position, pos)
translation = pos;
GET_CAMERA_PROPERTY(cameraObj, Rotation, rotation)
GET_CAMERA_PROPERTY(cameraObj, Declination, declination)
}
#undef GET_CAMERA_PROPERTY
if (pGameView)
{
pGameView->GetCamera()->m_Orientation.SetXRotation(declination);
pGameView->GetCamera()->m_Orientation.RotateY(rotation);
pGameView->GetCamera()->m_Orientation.Translate(translation);
pGameView->GetCamera()->UpdateFrustum();
}
return 0;
}
CMapReader::~CMapReader()
{
// Cleaup objects
delete xml_reader;
delete m_MapGen;
}
| 28.732042 | 162 | 0.709913 | [
"object",
"vector",
"model"
] |
b45a78db2abb39d04a7be7e5fc9bd4a32f6bbe67 | 370 | cpp | C++ | goodies/main.cpp | xtianhb/modern_cpp | 0b39fe1663a69795a5cfa13c73ed849a74c4121f | [
"MIT"
] | null | null | null | goodies/main.cpp | xtianhb/modern_cpp | 0b39fe1663a69795a5cfa13c73ed849a74c4121f | [
"MIT"
] | null | null | null | goodies/main.cpp | xtianhb/modern_cpp | 0b39fe1663a69795a5cfa13c73ed849a74c4121f | [
"MIT"
] | null | null | null |
#include <iostream>
#include <goodies.hpp>
int main()
{
std::cout << "//GOODIES>>" << std::endl;
//enums();
//strings();
//modern_strings();
//mstrings();
//Stream_Strings();
//literals();
//const_expr();
//init_list();
//vector();
//unions();
my_union();
std::cout << ">>GOODIES//" << std::endl;
return 0;
} | 14.8 | 44 | 0.494595 | [
"vector"
] |
b45e6ec05894c7648ffab7f7338a7af318934ae9 | 6,325 | cpp | C++ | test/basic_interface_rfft.cpp | michaelbacci/xtensor-fftw | 0c463ab759d7664a9b25c4382987138151ad74c3 | [
"BSD-3-Clause"
] | 13 | 2019-12-13T08:38:55.000Z | 2021-06-18T09:01:23.000Z | test/basic_interface_rfft.cpp | michaelbacci/xtensor-fftw | 0c463ab759d7664a9b25c4382987138151ad74c3 | [
"BSD-3-Clause"
] | 13 | 2019-11-07T12:15:38.000Z | 2022-02-23T14:33:00.000Z | test/basic_interface_rfft.cpp | michaelbacci/xtensor-fftw | 0c463ab759d7664a9b25c4382987138151ad74c3 | [
"BSD-3-Clause"
] | 5 | 2019-11-07T11:57:36.000Z | 2021-05-15T22:38:37.000Z | /*
* xtensor-fftw
* Copyright (c) 2017, Patrick Bos
*
* Distributed under the terms of the BSD 3-Clause License.
*
* The full license is in the file LICENSE, distributed with this software.
*/
#include <xtensor-fftw/basic_option.hpp>
#include "basic_interface.hpp"
///////////////////////////////////////////////////////////////////////////////
// Setup
///////////////////////////////////////////////////////////////////////////////
// GoogleTest fixture class
template <typename T>
class TransformAndInvert_realFFT : public ::testing::Test {};
TYPED_TEST_CASE(TransformAndInvert_realFFT, MyTypes);
///////////////////////////////////////////////////////////////////////////////
// Real FFT (real input)
///////////////////////////////////////////////////////////////////////////////
////
// Real FFT: xarray
////
TYPED_TEST(TransformAndInvert_realFFT, realFFT_1D_xarray) {
xt::xarray<TypeParam, xt::layout_type::row_major> a = generate_data<TypeParam, 1>(4);
auto a_fourier = xt::fftw::rfft(a);
// std::cout << "fourier transform of input before ifft (which is destructive!): " << a_fourier << std::endl;
auto should_be_a = xt::fftw::irfft(a_fourier);
assert_results(a, a_fourier, should_be_a);
}
TYPED_TEST(TransformAndInvert_realFFT, realFFT_2D_xarray) {
xt::xarray<TypeParam, xt::layout_type::row_major> a = generate_data<TypeParam, 2>(4);
auto a_fourier = xt::fftw::rfft2(a);
// std::cout << "fourier transform of input before ifft (which is destructive!): " << a_fourier << std::endl;
auto should_be_a = xt::fftw::irfft2(a_fourier);
assert_results(a, a_fourier, should_be_a);
}
TYPED_TEST(TransformAndInvert_realFFT, realFFT_3D_xarray) {
xt::xarray<TypeParam> a = generate_data<TypeParam, 3>(4);
auto a_fourier = xt::fftw::rfft3(a);
// std::cout << "fourier transform of input before ifft (which is destructive!): " << a_fourier << std::endl;
auto should_be_a = xt::fftw::irfft3(a_fourier);
assert_results(a, a_fourier, should_be_a);
}
TYPED_TEST(TransformAndInvert_realFFT, realFFT_nD_n_equals_4_xarray) {
xt::xarray<TypeParam> a = generate_data<TypeParam, 4>(4);
auto a_fourier = xt::fftw::rfftn<4>(a);
// std::cout << "fourier transform of input before ifft (which is destructive!): " << a_fourier << std::endl;
auto should_be_a = xt::fftw::irfftn<4>(a_fourier);
assert_results(a, a_fourier, should_be_a);
}
TYPED_TEST(TransformAndInvert_realFFT, realFFT_nD_n_equals_1_xarray) {
xt::xarray<TypeParam> a = generate_data<TypeParam, 1>(4);
auto a_fourier = xt::fftw::rfftn<1>(a);
// std::cout << "fourier transform of input before ifft (which is destructive!): " << a_fourier << std::endl;
auto should_be_a = xt::fftw::irfftn<1>(a_fourier);
assert_results(a, a_fourier, should_be_a);
}
// odd data sizes
TYPED_TEST(TransformAndInvert_realFFT, realFFT_1D_oddsize_xarray) {
xt::xarray<TypeParam, xt::layout_type::row_major> a = generate_data<TypeParam, 1>(5);
auto a_fourier = xt::fftw::rfft(a);
std::cout << "fourier transform of input before ifft (which is destructive!): " << a_fourier << std::endl;
auto should_be_a = xt::fftw::irfft(a_fourier, true);
assert_results(a, a_fourier, should_be_a, true);
}
TYPED_TEST(TransformAndInvert_realFFT, realFFT_2D_oddsize_xarray) {
xt::xarray<TypeParam, xt::layout_type::row_major> a = generate_data<TypeParam, 2>(5);
auto a_fourier = xt::fftw::rfft2(a);
// std::cout << "fourier transform of input before ifft (which is destructive!): " << a_fourier << std::endl;
auto should_be_a = xt::fftw::irfft2(a_fourier, true);
assert_results(a, a_fourier, should_be_a);
}
TYPED_TEST(TransformAndInvert_realFFT, realFFT_3D_oddsize_xarray) {
xt::xarray<TypeParam> a = generate_data<TypeParam, 3>(5);
auto a_fourier = xt::fftw::rfft3(a);
// std::cout << "fourier transform of input before ifft (which is destructive!): " << a_fourier << std::endl;
auto should_be_a = xt::fftw::irfft3(a_fourier, true);
assert_results(a, a_fourier, should_be_a);
}
TYPED_TEST(TransformAndInvert_realFFT, realFFT_nD_n_equals_4_oddsize_xarray) {
xt::xarray<TypeParam> a = generate_data<TypeParam, 4>(5);
auto a_fourier = xt::fftw::rfftn<4>(a);
// std::cout << "fourier transform of input before ifft (which is destructive!): " << a_fourier << std::endl;
auto should_be_a = xt::fftw::irfftn<4>(a_fourier, true);
assert_results(a, a_fourier, should_be_a);
}
TYPED_TEST(TransformAndInvert_realFFT, realFFT_nD_n_equals_1_oddsize_xarray) {
xt::xarray<TypeParam> a = generate_data<TypeParam, 1>(5);
auto a_fourier = xt::fftw::rfftn<1>(a);
// std::cout << "fourier transform of input before ifft (which is destructive!): " << a_fourier << std::endl;
auto should_be_a = xt::fftw::irfftn<1>(a_fourier, true);
assert_results(a, a_fourier, should_be_a);
}
/*
////
// Real FFT: xtensor
////
TYPED_TEST(TransformAndInvert_realFFT, realFFT_1D_xtensor) {
xt::xtensor<TypeParam, 1> a = generate_data<TypeParam, 1>(4);
auto a_fourier = xt::fftw::rfft(a);
// std::cout << "fourier transform of input before ifft (which is destructive!): " << a_fourier << std::endl;
auto should_be_a = xt::fftw::irfft(a_fourier);
assert_results(a, a_fourier, should_be_a);
}
TYPED_TEST(TransformAndInvert_realFFT, realFFT_2D_xtensor) {
xt::xtensor<TypeParam, 2> a = generate_data<TypeParam, 2>(4);
auto a_fourier = xt::fftw::rfft2(a);
// std::cout << "fourier transform of input before ifft (which is destructive!): " << a_fourier << std::endl;
auto should_be_a = xt::fftw::irfft2(a_fourier);
assert_results(a, a_fourier, should_be_a);
}
TYPED_TEST(TransformAndInvert_realFFT, realFFT_3D_xtensor) {
xt::xtensor<TypeParam, 3> a = generate_data<TypeParam, 3>(4);
auto a_fourier = xt::fftw::rfft3(a);
// std::cout << "fourier transform of input before ifft (which is destructive!): " << a_fourier << std::endl;
auto should_be_a = xt::fftw::irfft3(a_fourier);
assert_results(a, a_fourier, should_be_a);
}
TYPED_TEST(TransformAndInvert_realFFT, realFFT_4D_xtensor) {
xt::xtensor<TypeParam, 4> a = generate_data<TypeParam, 4>(4);
auto a_fourier = xt::fftw::rfftn(a);
// std::cout << "fourier transform of input before ifft (which is destructive!): " << a_fourier << std::endl;
auto should_be_a = xt::fftw::irfftn(a_fourier);
assert_results(a, a_fourier, should_be_a);
}
*/
| 40.544872 | 111 | 0.681897 | [
"transform"
] |
b462128d467acd8e9285699f5c3bbce12245444a | 36,302 | cc | C++ | chrome/browser/views/extensions/extension_shelf.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | 11 | 2015-03-20T04:08:08.000Z | 2021-11-15T15:51:36.000Z | chrome/browser/views/extensions/extension_shelf.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | null | null | null | chrome/browser/views/extensions/extension_shelf.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/views/extensions/extension_shelf.h"
#include <algorithm>
#include "app/resource_bundle.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/stl_util-inl.h"
#include "base/string_util.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_theme_provider.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/views/extensions/extension_view.h"
#include "chrome/browser/view_ids.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/pref_names.h"
#include "views/controls/label.h"
#include "views/screen.h"
#include "views/widget/root_view.h"
namespace {
// This is the slight padding that is there around the edge of the browser. This
// has been determined empirically.
// TODO(sidchat): Compute this value from the root view of the extension shelf.
static const int kExtensionShelfPaddingOnLeft = 4;
// Margins around the content.
static const int kTopMarginWhenExtensionsOnTop = 1;
static const int kTopMarginWhenExtensionsOnBottom = 2;
static const int kBottomMargin = 2;
static const int kLeftMargin = 0;
static const int kRightMargin = 0;
// Padding on left and right side of an extension toolstrip.
static const int kToolstripPadding = 2;
// Width of the toolstrip divider.
static const int kToolstripDividerWidth = 2;
// Preferred height of the ExtensionShelf.
static const int kShelfHeight = 29;
// Preferred height of the Extension shelf when only shown on the new tab page.
const int kNewtabShelfHeight = 58;
// How inset the extension shelf is when displayed on the new tab page. This is
// in addition to the margins above.
static const int kNewtabHorizontalPadding = 8;
static const int kNewtabVerticalPadding = 12;
// We need an extra margin to the left of all the toolstrips in detached mode,
// so that the first toolstrip doesn't look so squished against the rounded
// corners of the extension shelf.
static const int kNewtabExtraHorMargin = 2;
static const int kNewtabExtraVerMargin = 2;
// Padding for the title inside the handle.
static const int kHandlePadding = 4;
// Inset for the extension view when displayed either dragging or expanded.
static const int kWindowInset = 1;
// Delays for showing and hiding the shelf handle.
static const int kShowDelayMs = 500;
static const int kHideDelayMs = 300;
} // namespace
// A view that holds the place for a toolstrip in the shelf while the toolstrip
// is being dragged or moved.
// TODO(erikkay) this should draw a dimmed out version of the toolstrip.
class ExtensionShelf::PlaceholderView : public views::View {
public:
PlaceholderView() {}
void SetWidth(int width) {
SetBounds(x(), y(), width, height());
PreferredSizeChanged();
}
// ExtensionShelf resizes its views to their preferred size at layout,
// so just always prefer the current size.
gfx::Size GetPreferredSize() { return size(); }
private:
DISALLOW_COPY_AND_ASSIGN(PlaceholderView);
};
// A wrapper class for the ExtensionHost displayed as a toolstrip.
// The class itself also acts as the View for the handle of the toolstrip
// it represents.
class ExtensionShelf::Toolstrip : public views::View,
public BrowserBubble::Delegate,
public AnimationDelegate {
public:
Toolstrip(ExtensionShelf* shelf, ExtensionHost* host,
const Extension::ToolstripInfo& info);
virtual ~Toolstrip();
// Convenience to calculate just the size of the handle.
gfx::Size GetHandlePreferredSize();
// View methods:
virtual void Paint(gfx::Canvas* canvas);
virtual gfx::Size GetPreferredSize();
virtual void Layout();
virtual void OnMouseEntered(const views::MouseEvent& event);
virtual void OnMouseExited(const views::MouseEvent& event);
virtual bool OnMousePressed(const views::MouseEvent& event);
virtual bool OnMouseDragged(const views::MouseEvent& event);
virtual void OnMouseReleased(const views::MouseEvent& event, bool canceled);
virtual bool IsFocusable() const { return true; }
virtual void ChildPreferredSizeChanged(View* child);
// Adjust the size and position of the window/handle.
void LayoutWindow();
// Is the toolstrip window visible (not necessarily the handle).
bool window_visible() { return (window_.get() && window_->visible()); }
// Is the handle for this toolstrip currently visible.
bool handle_visible() { return (window_visible() && handle_visible_); }
// Is the toolstrip opened in expanded mode.
bool expanded() { return expanded_; }
// Is the toolstrip being dragged.
bool dragging() { return dragging_; }
// Accessors for the host and its view.
ExtensionHost* host() const { return host_; }
ExtensionView* view() const { return host_->view(); }
// The view that's currently displayed in the shelf. This could be
// either the ExtensionView or |placeholder_view_| depending on the
// current state.
View* GetShelfView() const {
if (placeholder_view_)
return placeholder_view_;
return view();
}
// Detaching the toolstrip from the shelf means that the ExtensionView is
// displayed inside of the BrowserBubble rather than the shelf. This may
// still visually appear to be part of the shelf (expanded) or completely
// separate (dragging).
// If |browser| is true, it also will detach/attach to the browser window.
void DetachFromShelf(bool browser);
void AttachToShelf(bool browser);
// Show / Hide the shelf handle.
void ShowShelfHandle();
void DoShowShelfHandle();
void HideShelfHandle(int delay_ms);
void DoHideShelfHandle();
void StopHandleTimer();
void HideWindow();
void ShowWindow();
// Expand / Collapse
void Expand(int height, const GURL& url);
void Collapse(const GURL& url);
// BrowserBubble::Delegate
virtual void BubbleBrowserWindowMoved(BrowserBubble* bubble);
virtual void BubbleBrowserWindowClosing(BrowserBubble* bubble);
// AnimationDelegate
virtual void AnimationProgressed(const Animation* animation);
virtual void AnimationEnded(const Animation* animation);
private:
// The actual renderer that this toolstrip contains.
ExtensionHost* host_;
// Manifest definition of this toolstrip.
Extension::ToolstripInfo info_;
// A window that can be logically attached to the browser window. This is
// used for two purposes: a handle that sits above the toolstrip when it's
// collapsed and not dragging, and as a container for the toolstrip when it's
// dragging or expanded.
scoped_ptr<BrowserBubble> window_;
// Used for drawing the name of the extension in the handle.
scoped_ptr<views::Label> title_;
// Pointer back to the containing shelf.
ExtensionShelf* shelf_;
// When dragging, a placeholder view is put into the shelf to hold space
// for the ExtensionView. This view is parent owned when it's in the view
// hierarchy, so there's no ownership issues here.
PlaceholderView* placeholder_view_;
// Current state of the toolstrip, currently can't both be expanded and
// dragging.
// TODO(erikkay) Support dragging while expanded.
bool dragging_;
bool expanded_;
bool handle_visible_;
// The target expanded height of the toolstrip (used for animation).
int expanded_height_;
// If dragging, where did the drag start from.
gfx::Point initial_drag_location_;
// We have to remember the initial drag point in screen coordinates, because
// later, when the toolstrip is being dragged around, there is no good way of
// computing the screen coordinates given the initial drag view coordinates.
gfx::Point initial_drag_screen_point_;
// Timers for tracking mouse hovering.
ScopedRunnableMethodFactory<ExtensionShelf::Toolstrip> timer_factory_;
// Animate opening and closing the mole.
scoped_ptr<SlideAnimation> mole_animation_;
DISALLOW_COPY_AND_ASSIGN(Toolstrip);
};
ExtensionShelf::Toolstrip::Toolstrip(ExtensionShelf* shelf,
ExtensionHost* host,
const Extension::ToolstripInfo& info)
: host_(host),
info_(info),
shelf_(shelf),
placeholder_view_(NULL),
dragging_(false),
expanded_(false),
handle_visible_(false),
expanded_height_(0),
ALLOW_THIS_IN_INITIALIZER_LIST(timer_factory_(this)) {
DCHECK(host->view());
// We're owned by shelf_, not the bubble that we get inserted in and out of.
set_parent_owned(false);
mole_animation_.reset(new SlideAnimation(this));
std::wstring name = UTF8ToWide(host_->extension()->name());
// |title_| isn't actually put in the view hierarchy. We just use it
// to draw in place. The reason for this is so that we can properly handle
// the various mouse events necessary for hovering and dragging.
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
title_.reset(new views::Label(name, rb.GetFont(ResourceBundle::BaseFont)));
title_->SetBounds(kHandlePadding, kHandlePadding, 100, 100);
title_->SizeToPreferredSize();
SizeToPreferredSize();
}
ExtensionShelf::Toolstrip::~Toolstrip() {
if (window_.get() && window_->attached())
window_->DetachFromBrowser();
}
void ExtensionShelf::Toolstrip::Paint(gfx::Canvas* canvas) {
// Paint the background.
SkColor theme_toolbar_color =
shelf_->GetThemeProvider()->GetColor(BrowserThemeProvider::COLOR_TOOLBAR);
canvas->FillRectInt(theme_toolbar_color, 0, 0, width(), height());
// Paints the handle for the toolstrip (only called on mouse-hover).
SkColor border_color = ResourceBundle::toolbar_separator_color;
canvas->FillRectInt(border_color, 0, 0, width(), 1);
canvas->FillRectInt(border_color, 0, 0, 1, height() - 1);
canvas->FillRectInt(border_color, width() - 1, 0, 1, height() - 1);
int ext_width = view()->width() + kToolstripPadding +
kToolstripDividerWidth;
if (ext_width < width()) {
canvas->FillRectInt(border_color, ext_width, height() - 1,
width() - ext_width, 1);
}
if (handle_visible_) {
// Draw the title using a Label as a stamp.
// See constructor for comment about this.
title_->ProcessPaint(canvas);
if (dragging_) {
// When we're dragging, draw the bottom border.
canvas->FillRectInt(border_color, 0, height() - 1, width(), 1);
}
}
}
gfx::Size ExtensionShelf::Toolstrip::GetHandlePreferredSize() {
gfx::Size sz;
if (handle_visible_) {
sz = title_->GetPreferredSize();
sz.set_width(std::max(view()->width(), sz.width()));
sz.Enlarge(2 + kHandlePadding * 2, kHandlePadding * 2);
}
return sz;
}
gfx::Size ExtensionShelf::Toolstrip::GetPreferredSize() {
gfx::Size sz;
if (handle_visible_)
sz = GetHandlePreferredSize();
if (view()->GetParent() == this) {
gfx::Size extension_size = view()->GetPreferredSize();
sz.Enlarge(0, extension_size.height());
sz.set_width(extension_size.width());
}
// The view is inset slightly when displayed in the window.
sz.Enlarge(kWindowInset * 2, kWindowInset * 2);
return sz;
}
void ExtensionShelf::Toolstrip::Layout() {
if (view()->GetParent() == this) {
int view_y = kWindowInset;
if (handle_visible_)
view_y += GetHandlePreferredSize().height();
view()->SetBounds(kWindowInset, view_y, view()->width(), view()->height());
}
}
void ExtensionShelf::Toolstrip::OnMouseEntered(const views::MouseEvent& event) {
if (dragging_)
return;
ShowShelfHandle();
}
void ExtensionShelf::Toolstrip::OnMouseExited(const views::MouseEvent& event) {
if (dragging_)
return;
HideShelfHandle(kHideDelayMs);
}
bool ExtensionShelf::Toolstrip::OnMousePressed(const views::MouseEvent& event) {
initial_drag_location_ = event.location();
initial_drag_screen_point_ = views::Screen::GetCursorScreenPoint();
return true;
}
bool ExtensionShelf::Toolstrip::OnMouseDragged(const views::MouseEvent& event) {
if (expanded_) {
// Do nothing for now.
} else if (!dragging_) {
int y_delta = abs(initial_drag_location_.y() - event.location().y());
int x_delta = abs(initial_drag_location_.x() - event.location().x());
if (y_delta > GetVerticalDragThreshold() ||
x_delta > GetHorizontalDragThreshold()) {
dragging_ = true;
StopHandleTimer();
DetachFromShelf(true);
}
} else {
// When freely dragging a window, you can really only trust the
// actual screen point. Local coordinate conversions don't work.
gfx::Point screen = views::Screen::GetCursorScreenPoint();
// However, the handle is actually a child of the browser window
// so we need to convert it back to local coordinates.
gfx::Point origin(0, 0);
views::View::ConvertPointToScreen(shelf_->GetRootView(), &origin);
int screen_x = screen.x() - initial_drag_location_.x() - origin.x();
// Restrict the horizontal and vertical motions of the toolstrip so that it
// cannot be dragged out of the extension shelf. If the extension shelf is
// on the top along with the bookmark bar, the toolstrip cannot be dragged
// into the space allocated for bookmarks. The toolstrip cannot be dragged
// out of the browser window.
if (screen_x < kExtensionShelfPaddingOnLeft) {
screen_x = kExtensionShelfPaddingOnLeft;
} else if (screen_x > shelf_->width() - width() +
kExtensionShelfPaddingOnLeft) {
screen_x = shelf_->width() - width() + kExtensionShelfPaddingOnLeft;
}
screen.set_x(screen_x);
screen.set_y(initial_drag_screen_point_.y() - origin.y() -
initial_drag_location_.y());
// TODO(erikkay) as this gets dragged around, update the placeholder view
// on the shelf to show where it will get dropped to.
window_->MoveTo(screen.x(), screen.y());
}
return true;
}
void ExtensionShelf::Toolstrip::OnMouseReleased(const views::MouseEvent& event,
bool canceled) {
StopHandleTimer();
if (dragging_) {
// Drop the toolstrip roughly where it is now.
views::View::OnMouseReleased(event, canceled);
dragging_ = false;
// |this| and |shelf_| are in different view hierarchies, so we need to
// convert to screen coordinates and back again to map locations.
gfx::Point loc = event.location();
View::ConvertPointToScreen(this, &loc);
View::ConvertPointToView(NULL, shelf_, &loc);
shelf_->DropExtension(this, loc, canceled);
AttachToShelf(true);
} else if (!canceled) {
// Toggle mole to either expanded or collapsed.
// TODO(erikkay) If there's no valid URL in the manifest, should we
// post an event to the toolstrip in this case?
if (expanded_) {
if (info_.toolstrip.is_valid())
shelf_->CollapseToolstrip(host_, info_.toolstrip);
} else {
if (info_.mole.is_valid())
shelf_->ExpandToolstrip(host_, info_.mole, info_.mole_height);
}
}
}
void ExtensionShelf::Toolstrip::LayoutWindow() {
if (!window_visible() && !handle_visible_ && !expanded_)
return;
if (!window_.get()) {
window_.reset(new BrowserBubble(this, shelf_->GetWidget(),
gfx::Point(0, 0)));
window_->set_delegate(this);
}
gfx::Size window_size = GetPreferredSize();
if (mole_animation_->IsAnimating()) {
// We only want to animate the body of the mole window. When we're
// expanding, this is everything except for the handle. When we're
// collapsing, this is everything except for the handle and the toolstrip.
// We subtract this amount from the target height, figure out the step in
// the animation from the rest, and then add it back in.
int window_offset = shelf_->height();
if (!mole_animation_->IsShowing())
window_offset += GetPreferredSize().height();
else
window_offset += GetHandlePreferredSize().height();
int h = expanded_height_ - window_offset;
window_size.set_height(window_offset +
static_cast<int>(h * mole_animation_->GetCurrentValue()));
} else if (!expanded_ && !dragging_) {
window_size.set_height(GetHandlePreferredSize().height());
}
// Now figure out where to place the window on the screen. Since it's a top-
// level widget, we need to do some coordinate conversion to get this right.
gfx::Point origin(-kToolstripPadding, 0);
if (expanded_ || mole_animation_->IsAnimating()) {
if (shelf_->IsOnTop()) {
if (handle_visible_)
origin.set_y(-GetHandlePreferredSize().height());
else
origin.set_y(0);
} else {
origin.set_y(GetShelfView()->height() - window_size.height());
}
views::View::ConvertPointToView(GetShelfView(), shelf_->GetRootView(),
&origin);
} else {
origin.set_y(-(window_size.height() + kToolstripPadding - 1));
views::View::ConvertPointToWidget(view(), &origin);
}
SetBounds(0, 0, window_size.width(), window_size.height());
window_->SetBounds(origin.x(), origin.y(),
window_size.width(), window_size.height());
}
void ExtensionShelf::Toolstrip::ChildPreferredSizeChanged(View* child) {
if (child == view()) {
child->SizeToPreferredSize();
Layout();
if (window_visible())
LayoutWindow();
if (expanded_) {
placeholder_view_->SetWidth(child->width());
shelf_->Layout();
}
}
}
void ExtensionShelf::Toolstrip::BubbleBrowserWindowMoved(
BrowserBubble* bubble) {
if (!expanded_)
HideWindow();
}
void ExtensionShelf::Toolstrip::BubbleBrowserWindowClosing(
BrowserBubble* bubble) {
HideWindow();
}
void ExtensionShelf::Toolstrip::AnimationProgressed(
const Animation* animation) {
LayoutWindow();
}
void ExtensionShelf::Toolstrip::AnimationEnded(const Animation* animation) {
if (window_visible())
LayoutWindow();
if (!expanded_) {
AttachToShelf(false);
HideShelfHandle(kHideDelayMs);
}
}
void ExtensionShelf::Toolstrip::DetachFromShelf(bool browserDetach) {
DCHECK(window_.get());
DCHECK(!placeholder_view_);
if (browserDetach && window_->attached())
window_->DetachFromBrowser();
// Construct a placeholder view to replace the view.
placeholder_view_ = new PlaceholderView();
placeholder_view_->SetBounds(view()->bounds());
shelf_->AddChildView(placeholder_view_);
AddChildView(view());
SizeToPreferredSize();
window_->ResizeToView();
Layout();
}
void ExtensionShelf::Toolstrip::AttachToShelf(bool browserAttach) {
DCHECK(window_.get());
DCHECK(placeholder_view_);
if (browserAttach && !window_->attached())
window_->AttachToBrowser();
// Move the view back into the shelf and remove the old placeholder.
shelf_->AddChildView(view());
// The size of the view may have changed, so just set the position.
view()->SetX(placeholder_view_->x());
view()->SetY(placeholder_view_->y());
// Remove the old placeholder.
shelf_->RemoveChildView(placeholder_view_);
delete placeholder_view_;
placeholder_view_ = NULL;
SizeToPreferredSize();
Layout();
shelf_->Layout();
}
void ExtensionShelf::Toolstrip::DoShowShelfHandle() {
if (!handle_visible()) {
handle_visible_ = true;
// Make sure the text color for the title matches the theme colors.
title_->SetColor(
shelf_->GetThemeProvider()->GetColor(
BrowserThemeProvider::COLOR_BOOKMARK_TEXT));
ShowWindow();
}
}
void ExtensionShelf::Toolstrip::HideWindow() {
if (!window_visible())
return;
handle_visible_ = false;
window_->Hide();
if (expanded_) {
if (info_.toolstrip.is_valid())
shelf_->CollapseToolstrip(host_, info_.toolstrip);
else
shelf_->CollapseToolstrip(host_, GURL());
}
if (window_->attached())
window_->DetachFromBrowser();
window_.reset(NULL);
shelf_->Layout();
}
void ExtensionShelf::Toolstrip::ShowWindow() {
DCHECK(handle_visible_ || expanded_);
LayoutWindow();
if (!window_visible())
window_->Show(false); // |false| means show, but don't activate.
}
void ExtensionShelf::Toolstrip::DoHideShelfHandle() {
if (!handle_visible())
return;
handle_visible_ = false;
if (expanded_) {
LayoutWindow();
Layout();
} else {
HideWindow();
}
}
void ExtensionShelf::Toolstrip::StopHandleTimer() {
if (!timer_factory_.empty())
timer_factory_.RevokeAll();
}
void ExtensionShelf::Toolstrip::Expand(int height, const GURL& url) {
DCHECK(!expanded_);
expanded_ = true;
ShowWindow();
bool navigate = (!url.is_empty() && url != host_->GetURL());
if (navigate)
host_->NavigateToURL(url);
StopHandleTimer();
DetachFromShelf(false);
mole_animation_->Show();
gfx::Size extension_size = view()->GetPreferredSize();
extension_size.set_height(height);
view()->SetPreferredSize(extension_size);
expanded_height_ = GetPreferredSize().height();
// This is to prevent flickering as the page loads and lays out.
// Once the navigation is finished, ExtensionView will wind up setting
// visibility to true.
if (navigate)
view()->SetVisible(false);
}
void ExtensionShelf::Toolstrip::Collapse(const GURL& url) {
DCHECK(expanded_);
expanded_ = false;
if (window_visible())
mole_animation_->Hide();
gfx::Size extension_size = view()->GetPreferredSize();
extension_size.set_height(
kShelfHeight - (shelf_->top_margin() + kBottomMargin));
view()->SetPreferredSize(extension_size);
if (!url.is_empty() && url != host_->GetURL()) {
host_->NavigateToURL(url);
// This is to prevent flickering as the page loads and lays out.
// Once the navigation is finished, ExtensionView will wind up setting
// visibility to true.
view()->SetVisible(false);
}
if (!window_visible())
AnimationEnded(NULL);
}
void ExtensionShelf::Toolstrip::ShowShelfHandle() {
StopHandleTimer();
if (handle_visible())
return;
MessageLoop::current()->PostDelayedTask(FROM_HERE,
timer_factory_.NewRunnableMethod(
&ExtensionShelf::Toolstrip::DoShowShelfHandle),
kShowDelayMs);
}
void ExtensionShelf::Toolstrip::HideShelfHandle(int delay_ms) {
StopHandleTimer();
if (!handle_visible() || dragging_ || mole_animation_->IsAnimating())
return;
if (delay_ms) {
MessageLoop::current()->PostDelayedTask(FROM_HERE,
timer_factory_.NewRunnableMethod(
&ExtensionShelf::Toolstrip::DoHideShelfHandle),
delay_ms);
} else {
DoHideShelfHandle();
}
}
////////////////////////////////////////////////////////////////////////////////
ExtensionShelf::ExtensionShelf(Browser* browser)
: background_needs_repaint_(true),
browser_(browser),
model_(browser->extension_shelf_model()),
fullscreen_(false) {
SetID(VIEW_ID_DEV_EXTENSION_SHELF);
if (IsOnTop())
top_margin_ = kTopMarginWhenExtensionsOnTop;
else
top_margin_ = kTopMarginWhenExtensionsOnBottom;
model_->AddObserver(this);
LoadFromModel();
EnableCanvasFlippingForRTLUI(true);
registrar_.Add(this,
NotificationType::EXTENSION_SHELF_VISIBILITY_PREF_CHANGED,
NotificationService::AllSources());
size_animation_.reset(new SlideAnimation(this));
if (IsAlwaysShown())
size_animation_->Reset(1);
else
size_animation_->Reset(0);
}
ExtensionShelf::~ExtensionShelf() {
if (model_) {
int count = model_->count();
for (int i = 0; i < count; ++i) {
delete ToolstripAtIndex(i);
model_->SetToolstripDataAt(i, NULL);
}
model_->RemoveObserver(this);
}
}
void ExtensionShelf::PaintChildren(gfx::Canvas* canvas) {
InitBackground(canvas);
int max_x = width();
if (IsDetached())
max_x -= 2 * kNewtabHorizontalPadding;
// Draw vertical dividers between Toolstrip items in the Extension shelf.
int count = GetChildViewCount();
for (int i = 0; i < count; ++i) {
int right = GetChildViewAt(i)->bounds().right() + kToolstripPadding;
if (right >= max_x)
break;
int vertical_padding = IsDetached() ? (height() - kShelfHeight) / 2 : 1;
DetachableToolbarView::PaintVerticalDivider(
canvas, right, height(), vertical_padding,
DetachableToolbarView::kEdgeDividerColor,
DetachableToolbarView::kMiddleDividerColor,
GetThemeProvider()->GetColor(BrowserThemeProvider::COLOR_TOOLBAR));
}
}
// static
void ExtensionShelf::ToggleWhenExtensionShelfVisible(Profile* profile) {
PrefService* prefs = profile->GetPrefs();
const bool always_show = !prefs->GetBoolean(prefs::kShowExtensionShelf);
// The user changed when the Extension Shelf is shown, update the
// preferences.
prefs->SetBoolean(prefs::kShowExtensionShelf, always_show);
prefs->ScheduleSavePersistentPrefs();
// And notify the notification service.
Source<Profile> source(profile);
NotificationService::current()->Notify(
NotificationType::EXTENSION_SHELF_VISIBILITY_PREF_CHANGED,
source,
NotificationService::NoDetails());
}
gfx::Size ExtensionShelf::GetPreferredSize() {
return LayoutItems(true);
}
void ExtensionShelf::ChildPreferredSizeChanged(View* child) {
PreferredSizeChanged();
}
void ExtensionShelf::Layout() {
LayoutItems(false);
}
void ExtensionShelf::OnMouseEntered(const views::MouseEvent& event) {
}
void ExtensionShelf::OnMouseExited(const views::MouseEvent& event) {
}
bool ExtensionShelf::GetAccessibleRole(AccessibilityTypes::Role* role) {
DCHECK(role);
*role = AccessibilityTypes::ROLE_TOOLBAR;
return true;
}
bool ExtensionShelf::GetAccessibleName(std::wstring* name) {
DCHECK(name);
if (!accessible_name_.empty()) {
name->assign(accessible_name_);
return true;
}
return false;
}
void ExtensionShelf::SetAccessibleName(const std::wstring& name) {
accessible_name_.assign(name);
}
void ExtensionShelf::ThemeChanged() {
// Refresh the CSS to update toolstrip text colors from theme.
int count = model_->count();
for (int i = 0; i < count; ++i)
ToolstripAtIndex(i)->view()->host()->InsertThemeCSS();
Layout();
}
void ExtensionShelf::ToolstripInsertedAt(ExtensionHost* host,
int index) {
model_->SetToolstripDataAt(index,
new Toolstrip(this, host, model_->ToolstripAt(index).info));
bool had_views = GetChildViewCount() > 0;
ExtensionView* view = host->view();
AddChildView(view);
view->SetContainer(this);
if (!had_views)
PreferredSizeChanged();
Layout();
}
void ExtensionShelf::ToolstripRemovingAt(ExtensionHost* host, int index) {
// Delete the Toolstrip view and remove it from the model.
Toolstrip* toolstrip = ToolstripAtIndex(index);
View* view = toolstrip->GetShelfView();
RemoveChildView(view);
delete toolstrip;
model_->SetToolstripDataAt(index, NULL);
// Technically, the toolstrip is still in the model at this point, but
// the Layout code handles this case.
Layout();
}
void ExtensionShelf::ToolstripDraggingFrom(ExtensionHost* host, int index) {
}
void ExtensionShelf::ToolstripMoved(ExtensionHost* host, int from_index,
int to_index) {
Layout();
}
void ExtensionShelf::ToolstripChanged(ExtensionShelfModel::iterator toolstrip) {
Toolstrip* t = static_cast<Toolstrip*>(toolstrip->data);
if (toolstrip->height > 0) {
if (!t->expanded()) {
t->Expand(toolstrip->height, toolstrip->url);
}
} else if (t->expanded()) {
t->Collapse(toolstrip->url);
}
}
void ExtensionShelf::ExtensionShelfEmpty() {
PreferredSizeChanged();
}
void ExtensionShelf::ShelfModelReloaded() {
// None of the child views are parent owned, so nothing is being leaked here.
RemoveAllChildViews(false);
LoadFromModel();
}
void ExtensionShelf::ShelfModelDeleting() {
int count = model_->count();
for (int i = 0; i < count; ++i) {
delete ToolstripAtIndex(i);
model_->SetToolstripDataAt(i, NULL);
}
model_->RemoveObserver(this);
model_ = NULL;
}
void ExtensionShelf::AnimationProgressed(const Animation* animation) {
if (browser_)
browser_->ExtensionShelfSizeChanged();
}
void ExtensionShelf::AnimationEnded(const Animation* animation) {
if (browser_)
browser_->ExtensionShelfSizeChanged();
Layout();
}
void ExtensionShelf::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type.value) {
case NotificationType::EXTENSION_SHELF_VISIBILITY_PREF_CHANGED: {
if (fullscreen_)
break;
if (IsAlwaysShown())
size_animation_->Show();
else
size_animation_->Hide();
break;
}
default:
NOTREACHED();
break;
}
}
void ExtensionShelf::OnExtensionMouseEvent(ExtensionView* view) {
Toolstrip *toolstrip = ToolstripForView(view);
if (toolstrip)
toolstrip->ShowShelfHandle();
}
void ExtensionShelf::OnExtensionMouseLeave(ExtensionView* view) {
Toolstrip *toolstrip = ToolstripForView(view);
if (toolstrip)
toolstrip->HideShelfHandle(kHideDelayMs);
}
void ExtensionShelf::DropExtension(Toolstrip* toolstrip, const gfx::Point& pt,
bool cancel) {
Toolstrip* dest_toolstrip = ToolstripAtX(pt.x());
if (!dest_toolstrip) {
if (pt.x() > 0)
dest_toolstrip = ToolstripAtIndex(model_->count() - 1);
else
dest_toolstrip = ToolstripAtIndex(0);
}
if (toolstrip == dest_toolstrip)
return;
int from = model_->IndexOfHost(toolstrip->host());
int to = model_->IndexOfHost(dest_toolstrip->host());
DCHECK(from != to);
model_->MoveToolstripAt(from, to);
}
void ExtensionShelf::ExpandToolstrip(ExtensionHost* host, const GURL& url,
int height) {
ExtensionShelfModel::iterator toolstrip = model_->ToolstripForHost(host);
model_->ExpandToolstrip(toolstrip, url, height);
}
void ExtensionShelf::CollapseToolstrip(ExtensionHost* host, const GURL& url) {
ExtensionShelfModel::iterator toolstrip = model_->ToolstripForHost(host);
model_->CollapseToolstrip(toolstrip, url);
}
void ExtensionShelf::InitBackground(gfx::Canvas* canvas) {
if (!background_needs_repaint_)
return;
// Capture a background bitmap to give to the toolstrips.
SkRect background_rect = {
SkIntToScalar(0),
SkIntToScalar(0),
SkIntToScalar(width()),
SkIntToScalar(height())
};
// Tell all extension views about the new background.
int count = model_->count();
for (int i = 0; i < count; ++i) {
ExtensionView* view = ToolstripAtIndex(i)->view();
const SkBitmap& background = canvas->getDevice()->accessBitmap(false);
SkRect mapped_subset = background_rect;
gfx::Rect view_bounds = view->bounds();
mapped_subset.offset(SkIntToScalar(view_bounds.x()),
SkIntToScalar(view_bounds.y()));
bool result = canvas->getTotalMatrix().mapRect(&mapped_subset);
DCHECK(result);
SkIRect isubset;
mapped_subset.round(&isubset);
SkBitmap subset_bitmap;
// This will create another bitmap that just references pixels in the
// actual bitmap.
result = background.extractSubset(&subset_bitmap, isubset);
if (!result)
return;
// We do a deep copy because extractSubset() returns a bitmap that
// references pixels in the original one and we want to actually make a
// smaller copy that will have a long lifetime.
SkBitmap smaller_copy;
if (!subset_bitmap.copyTo(&smaller_copy, SkBitmap::kARGB_8888_Config))
return;
DCHECK(smaller_copy.readyToDraw());
view->SetBackground(smaller_copy);
}
background_needs_repaint_ = false;
}
ExtensionShelf::Toolstrip* ExtensionShelf::ToolstripAtX(int x) {
int count = model_->count();
if (count == 0)
return NULL;
if (x < 0)
return NULL;
for (int i = 0; i < count; ++i) {
Toolstrip* toolstrip = ToolstripAtIndex(i);
View* view = toolstrip->GetShelfView();
int x_mirrored = view->GetRootView()->MirroredXCoordinateInsideView(x);
if (x_mirrored > view->x() + view->width() + kToolstripPadding)
continue;
return toolstrip;
}
return NULL;
}
ExtensionShelf::Toolstrip* ExtensionShelf::ToolstripAtIndex(int index) {
return static_cast<Toolstrip*>(model_->ToolstripAt(index).data);
}
ExtensionShelf::Toolstrip* ExtensionShelf::ToolstripForView(
ExtensionView* view) {
int count = model_->count();
for (int i = 0; i < count; ++i) {
Toolstrip* toolstrip = ToolstripAtIndex(i);
if (view == toolstrip->view())
return toolstrip;
}
return NULL;
}
void ExtensionShelf::LoadFromModel() {
int count = model_->count();
for (int i = 0; i < count; ++i)
ToolstripInsertedAt(model_->ToolstripAt(i).host, i);
}
gfx::Size ExtensionShelf::LayoutItems(bool compute_bounds_only) {
if (!GetParent() || !model_ || !model_->count())
return gfx::Size(0, 0);
gfx::Size prefsize;
int x = kLeftMargin;
int y = top_margin_;
int content_height = kShelfHeight - top_margin_ - kBottomMargin;
int max_x = width() - kRightMargin;
if (OnNewTabPage()) {
double current_state = 1 - size_animation_->GetCurrentValue();
x += static_cast<int>(static_cast<double>
(kNewtabHorizontalPadding + kNewtabExtraHorMargin) * current_state);
y += static_cast<int>(static_cast<double>
(kNewtabVerticalPadding + kNewtabExtraVerMargin) * current_state);
max_x -= static_cast<int>(static_cast<double>
(2 * kNewtabHorizontalPadding) * current_state);
}
int count = model_->count();
for (int i = 0; i < count; ++i) {
x += kToolstripPadding; // Left padding.
Toolstrip* toolstrip = ToolstripAtIndex(i);
if (!toolstrip) // Can be NULL while in the process of removing.
continue;
View* view = toolstrip->GetShelfView();
gfx::Size pref = view->GetPreferredSize();
// |next_x| is the x value for where the next toolstrip in the list will be.
int next_x = x + pref.width() + kToolstripPadding; // Right padding.
if (!compute_bounds_only) {
bool clipped = next_x >= max_x;
if (clipped)
pref.set_width(std::max(0, max_x - x));
if (view == toolstrip->view())
toolstrip->view()->SetIsClipped(clipped);
view->SetBounds(x, y, pref.width(), content_height);
view->Layout();
if (toolstrip->window_visible())
toolstrip->LayoutWindow();
}
x = next_x + kToolstripDividerWidth;
}
if (!compute_bounds_only) {
background_needs_repaint_ = true;
SchedulePaint();
} else {
if (OnNewTabPage()) {
prefsize.set_height(kShelfHeight + static_cast<int>(static_cast<double>
(kNewtabShelfHeight - kShelfHeight) *
(1 - size_animation_->GetCurrentValue())));
} else {
prefsize.set_height(static_cast<int>(static_cast<double>(kShelfHeight) *
size_animation_->GetCurrentValue()));
}
x += kRightMargin;
prefsize.set_width(x);
}
return prefsize;
}
bool ExtensionShelf::IsOnTop() const {
static bool is_on_top = CommandLine::ForCurrentProcess()->HasSwitch(
switches::kShowExtensionsOnTop);
return is_on_top;
}
bool ExtensionShelf::IsDetached() const {
return OnNewTabPage() && (size_animation_->GetCurrentValue() != 1);
}
bool ExtensionShelf::IsAlwaysShown() const {
Profile* profile = browser_->profile();
return profile->GetPrefs()->GetBoolean(prefs::kShowExtensionShelf);
}
bool ExtensionShelf::OnNewTabPage() const {
return (browser_ && browser_->GetSelectedTabContents() &&
browser_->GetSelectedTabContents()->IsExtensionShelfAlwaysVisible());
}
void ExtensionShelf::OnFullscreenToggled(bool fullscreen) {
if (fullscreen == fullscreen_)
return;
fullscreen_ = fullscreen;
if (!IsAlwaysShown() || IsOnTop())
return;
if (fullscreen_)
size_animation_->Hide();
else
size_animation_->Show();
}
| 31.92788 | 80 | 0.695664 | [
"model"
] |
b462666a5b19dfdf5f7e6dc75108c43871ccd444 | 3,730 | hpp | C++ | Middlewares/ST/touchgfx/framework/include/touchgfx/widgets/canvas/AbstractPainterABGR2222.hpp | xlord13/vescUserInterface | ff26bc1245ec35cb545042fe01ce3111c92ef80f | [
"MIT"
] | 15 | 2021-09-21T13:55:54.000Z | 2022-03-08T14:05:39.000Z | Software/STM32CubeDemo/MenuDemo/Middlewares/ST/touchgfx/framework/include/touchgfx/widgets/canvas/AbstractPainterABGR2222.hpp | DynamixYANG/Roendi | 2f6703d63922071fd0dfc8e4d2c9bba95ea04f08 | [
"MIT"
] | 7 | 2021-09-22T07:56:52.000Z | 2022-03-21T17:39:34.000Z | Software/STM32CubeDemo/MenuDemo/Middlewares/ST/touchgfx/framework/include/touchgfx/widgets/canvas/AbstractPainterABGR2222.hpp | DynamixYANG/Roendi | 2f6703d63922071fd0dfc8e4d2c9bba95ea04f08 | [
"MIT"
] | 1 | 2022-03-07T07:51:50.000Z | 2022-03-07T07:51:50.000Z | /******************************************************************************
* Copyright (c) 2018(-2021) STMicroelectronics.
* All rights reserved.
*
* This file is part of the TouchGFX 4.18.0 distribution.
*
* This software is licensed under terms that can be found in the LICENSE file in
* the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
*******************************************************************************/
/**
* @file touchgfx/widgets/canvas/AbstractPainterABGR2222.hpp
*
* Declares the touchgfx::AbstractPainterABGR2222 class.
*/
#ifndef TOUCHGFX_ABSTRACTPAINTERABGR2222_HPP
#define TOUCHGFX_ABSTRACTPAINTERABGR2222_HPP
#include <touchgfx/hal/Types.hpp>
#include <touchgfx/Bitmap.hpp>
#include <touchgfx/lcd/LCD.hpp>
#include <touchgfx/widgets/canvas/AbstractPainter.hpp>
#include <platform/driver/lcd/LCD8bpp_ABGR2222.hpp>
namespace touchgfx
{
/**
* The AbstractPainterABGR2222 class is an abstract class for creating a painter to draw on a
* ABGR2222 display using CanvasWidgetRenderer.
*
* @see AbstractPainter
*/
class AbstractPainterABGR2222 : public AbstractPainter
{
public:
AbstractPainterABGR2222()
: AbstractPainter(), currentX(0), currentY(0)
{
assert(compatibleFramebuffer(Bitmap::ABGR2222) && "The chosen painter only works with ABGR2222 displays");
}
virtual void render(uint8_t* ptr, int x, int xAdjust, int y, unsigned count, const uint8_t* covers);
/**
* @copydoc AbstractPainterRGB565::mixColors(uint16_t,uint16_t,uint8_t)
*/
FORCE_INLINE_FUNCTION uint8_t mixColors(uint8_t newpix, uint8_t bufpix, uint8_t alpha)
{
return mixColors(LCD8bpp_ABGR2222::getRedFromNativeColor(newpix),
LCD8bpp_ABGR2222::getGreenFromNativeColor(newpix),
LCD8bpp_ABGR2222::getBlueFromNativeColor(newpix), bufpix, alpha);
}
/**
* @copybrief AbstractPainterRGB565::mixColors(uint16_t,uint16_t,uint16_t,uint16_t,uint8_t)
*
* @param R The red color.
* @param G The green color.
* @param B The blue color.
* @param bufpix The buffer pixel value.
* @param alpha The alpha of the R,G,B.
*
* @return The result of blending the two colors into a new color.
*/
FORCE_INLINE_FUNCTION uint8_t mixColors(uint8_t R, uint8_t G, uint8_t B, uint8_t bufpix, uint8_t alpha)
{
const uint8_t ialpha = 0xFF - alpha;
const uint8_t p_red = LCD8bpp_ABGR2222::getRedFromNativeColor(bufpix);
const uint8_t p_green = LCD8bpp_ABGR2222::getGreenFromNativeColor(bufpix);
const uint8_t p_blue = LCD8bpp_ABGR2222::getBlueFromNativeColor(bufpix);
const uint8_t red = LCD::div255(R * alpha + p_red * ialpha);
const uint8_t green = LCD::div255(G * alpha + p_green * ialpha);
const uint8_t blue = LCD::div255(B * alpha + p_blue * ialpha);
return LCD8bpp_ABGR2222::getNativeColorFromRGB(red, green, blue);
}
protected:
/**
* @copydoc AbstractPainterRGB565::renderInit
*/
virtual bool renderInit()
{
return true;
}
/**
* @copydoc AbstractPainterRGB565::renderNext
*/
virtual bool renderNext(uint8_t& red, uint8_t& green, uint8_t& blue, uint8_t& alpha)
{
return false;
}
/**
* @copydoc AbstractPainterRGB565::renderPixel
*/
virtual void renderPixel(uint8_t* p, uint8_t red, uint8_t green, uint8_t blue);
int currentX; ///< Current x coordinate relative to the widget
int currentY; ///< Current y coordinate relative to the widget
};
} // namespace touchgfx
#endif // TOUCHGFX_ABSTRACTPAINTERABGR2222_HPP
| 34.537037 | 114 | 0.665684 | [
"render"
] |
b4669e5e0aa04750f27c9dc59e04fce61deb0db5 | 56,059 | cpp | C++ | deps/libgdal/gdal/ogr/ogrsf_frmts/edigeo/ogredigeodatasource.cpp | blairdgeo/node-gdal | a9bb3c082b30605ed1668dd9fe49afd25a7bb9d6 | [
"Apache-2.0"
] | 1 | 2015-07-04T20:09:20.000Z | 2015-07-04T20:09:20.000Z | deps/libgdal/gdal/ogr/ogrsf_frmts/edigeo/ogredigeodatasource.cpp | blairdgeo/node-gdal | a9bb3c082b30605ed1668dd9fe49afd25a7bb9d6 | [
"Apache-2.0"
] | null | null | null | deps/libgdal/gdal/ogr/ogrsf_frmts/edigeo/ogredigeodatasource.cpp | blairdgeo/node-gdal | a9bb3c082b30605ed1668dd9fe49afd25a7bb9d6 | [
"Apache-2.0"
] | null | null | null | /******************************************************************************
* $Id: ogredigeodatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $
*
* Project: EDIGEO Translator
* Purpose: Implements OGREDIGEODataSource class
* Author: Even Rouault, even dot rouault at mines dash paris dot org
*
******************************************************************************
* Copyright (c) 2011, Even Rouault <even dot rouault at mines-paris dot org>
*
* 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 "ogr_edigeo.h"
#include "cpl_conv.h"
#include "cpl_string.h"
CPL_CVSID("$Id: ogredigeodatasource.cpp 27729 2014-09-24 00:40:16Z goatbar $");
#ifndef M_PI
# define M_PI 3.1415926535897932384626433832795
#endif
/************************************************************************/
/* OGREDIGEODataSource() */
/************************************************************************/
OGREDIGEODataSource::OGREDIGEODataSource()
{
papoLayers = NULL;
nLayers = 0;
pszName = NULL;
poSRS = NULL;
bExtentValid = FALSE;
dfMinX = dfMinY = dfMaxX = dfMaxY = 0;
fpTHF = NULL;
bHasReadEDIGEO = FALSE;
bIncludeFontFamily = CSLTestBoolean(CPLGetConfigOption(
"OGR_EDIGEO_INCLUDE_FONT_FAMILY", "YES"));
iATR = iDI3 = iDI4 = iHEI = iFON = -1;
iATR_VAL = iANGLE = iSIZE = iOBJ_LNK = iOBJ_LNK_LAYER = -1;
dfSizeFactor = atof(CPLGetConfigOption("OGR_EDIGEO_FONT_SIZE_FACTOR", "2"));
if (dfSizeFactor <= 0 || dfSizeFactor >= 100)
dfSizeFactor = 2;
bRecodeToUTF8 = CSLTestBoolean(CPLGetConfigOption(
"OGR_EDIGEO_RECODE_TO_UTF8", "YES"));
bHasUTF8ContentOnly = TRUE;
}
/************************************************************************/
/* ~OGREDIGEODataSource() */
/************************************************************************/
OGREDIGEODataSource::~OGREDIGEODataSource()
{
for( int i = 0; i < nLayers; i++ )
delete papoLayers[i];
CPLFree( papoLayers );
CPLFree( pszName );
if (fpTHF)
VSIFCloseL(fpTHF);
if (poSRS)
poSRS->Release();
}
/************************************************************************/
/* TestCapability() */
/************************************************************************/
int OGREDIGEODataSource::TestCapability( CPL_UNUSED const char * pszCap )
{
return FALSE;
}
/************************************************************************/
/* GetLayer() */
/************************************************************************/
OGRLayer *OGREDIGEODataSource::GetLayer( int iLayer )
{
ReadEDIGEO();
if( iLayer < 0 || iLayer >= nLayers )
return NULL;
else
return papoLayers[iLayer];
}
/************************************************************************/
/* GetLayerCount() */
/************************************************************************/
int OGREDIGEODataSource::GetLayerCount()
{
ReadEDIGEO();
return nLayers;
}
/************************************************************************/
/* ReadTHF() */
/************************************************************************/
int OGREDIGEODataSource::ReadTHF(VSILFILE* fp)
{
const char* pszLine;
while((pszLine = CPLReadLine2L(fp, 81, NULL)) != NULL)
{
if (strlen(pszLine) < 8 || pszLine[7] != ':')
continue;
/* Cf Z 52000 tableau 56 for field list*/
if (strncmp(pszLine, "LONSA", 5) == 0)
{
if (osLON.size() != 0)
{
CPLDebug("EDIGEO", "We only handle one lot per THF file");
break;
}
osLON = pszLine + 8;
}
else if (strncmp(pszLine, "GNNSA", 5) == 0)
osGNN = pszLine + 8;
else if (strncmp(pszLine, "GONSA", 5) == 0)
osGON = pszLine + 8;
else if (strncmp(pszLine, "QANSA", 5) == 0)
osQAN = pszLine + 8;
else if (strncmp(pszLine, "DINSA", 5) == 0)
osDIN = pszLine + 8;
else if (strncmp(pszLine, "SCNSA", 5) == 0)
osSCN = pszLine + 8;
else if (strncmp(pszLine, "GDNSA", 5) == 0)
aosGDN.push_back(pszLine + 8);
}
if (osLON.size() == 0)
{
CPLDebug("EDIGEO", "LON field missing");
return 0;
}
if (osGON.size() == 0)
{
CPLDebug("EDIGEO", "GON field missing");
return 0;
}
if (osDIN.size() == 0)
{
CPLDebug("EDIGEO", "DIN field missing");
return 0;
}
if (osSCN.size() == 0)
{
CPLDebug("EDIGEO", "SCN field missing");
return FALSE;
}
CPLDebug("EDIGEO", "LON = %s", osLON.c_str());
CPLDebug("EDIGEO", "GNN = %s", osGNN.c_str());
CPLDebug("EDIGEO", "GON = %s", osGON.c_str());
CPLDebug("EDIGEO", "QAN = %s", osQAN.c_str());
CPLDebug("EDIGEO", "DIN = %s", osDIN.c_str());
CPLDebug("EDIGEO", "SCN = %s", osSCN.c_str());
for(int i=0;i<(int)aosGDN.size();i++)
CPLDebug("EDIGEO", "GDN[%d] = %s", i, aosGDN[i].c_str());
return TRUE;
}
/************************************************************************/
/* OpenFile() */
/************************************************************************/
VSILFILE* OGREDIGEODataSource::OpenFile(const char *pszType,
const CPLString& osExt)
{
CPLString osTmp = osLON + pszType;
CPLString osFilename = CPLFormCIFilename(CPLGetPath(pszName),
osTmp.c_str(), osExt.c_str());
VSILFILE* fp = VSIFOpenL(osFilename, "rb");
if (fp == NULL)
{
CPLString osExtLower = osExt;
for(int i=0;i<(int)osExt.size();i++)
osExtLower[i] = (char)tolower(osExt[i]);
CPLString osFilename2 = CPLFormCIFilename(CPLGetPath(pszName),
osTmp.c_str(), osExtLower.c_str());
fp = VSIFOpenL(osFilename2, "rb");
if (fp == NULL)
{
CPLDebug("EDIGEO", "Cannot open %s", osFilename.c_str());
}
}
return fp;
}
/************************************************************************/
/* ReadGEO() */
/************************************************************************/
int OGREDIGEODataSource::ReadGEO()
{
VSILFILE* fp = OpenFile(osGON, "GEO");
if (fp == NULL)
return FALSE;
const char* pszLine;
while((pszLine = CPLReadLine2L(fp, 81, NULL)) != NULL)
{
if (strlen(pszLine) < 8 || pszLine[7] != ':')
continue;
if (strncmp(pszLine, "RELSA", 5) == 0)
{
osREL = pszLine + 8;
CPLDebug("EDIGEO", "REL = %s", osREL.c_str());
break;
}
}
VSIFCloseL(fp);
if (osREL.size() == 0)
{
CPLDebug("EDIGEO", "REL field missing");
return FALSE;
}
/* All the SRS names mentionned in B.8.2.3 and B.8.3.1 are in the IGN file */
poSRS = new OGRSpatialReference();
CPLString osProj4Str = "+init=IGNF:" + osREL;
if (poSRS->SetFromUserInput(osProj4Str.c_str()) != OGRERR_NONE)
{
/* Hard code a few common cases */
if (osREL == "LAMB1")
poSRS->importFromProj4("+proj=lcc +lat_1=49.5 +lat_0=49.5 +lon_0=0 +k_0=0.99987734 +x_0=600000 +y_0=200000 +a=6378249.2 +b=6356514.999978254 +nadgrids=ntf_r93.gsb,null +pm=paris +units=m +no_defs");
else if (osREL == "LAMB2")
poSRS->importFromProj4("+proj=lcc +lat_1=46.8 +lat_0=46.8 +lon_0=0 +k_0=0.99987742 +x_0=600000 +y_0=200000 +a=6378249.2 +b=6356514.999978254 +nadgrids=ntf_r93.gsb,null +pm=paris +units=m +no_defs");
else if (osREL == "LAMB3")
poSRS->importFromProj4("+proj=lcc +lat_1=44.1 +lat_0=44.1 +lon_0=0 +k_0=0.9998775 +x_0=600000 +y_0=200000 +a=6378249.2 +b=6356514.999978254 +nadgrids=ntf_r93.gsb,null +pm=paris +units=m +no_defs");
else if (osREL == "LAMB4")
poSRS->importFromProj4("+proj=lcc +lat_1=42.165 +lat_0=42.165 +lon_0=0 +k_0=0.99994471 +x_0=234.358 +y_0=185861.369 +a=6378249.2 +b=6356514.999978254 +nadgrids=ntf_r93.gsb,null +pm=paris +units=m +no_defs");
else if (osREL == "LAMB93")
poSRS->importFromProj4("+proj=lcc +lat_1=44 +lat_2=49 +lat_0=46.5 +lon_0=3 +x_0=700000 +y_0=6600000 +ellps=GRS81 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs");
else
{
CPLDebug("EDIGEO", "Cannot resolve %s SRS. Check that the IGNF file is in the directory of PROJ.4 ressource files", osREL.c_str());
delete poSRS;
poSRS = NULL;
}
}
return TRUE;
}
/************************************************************************/
/* ReadGEN() */
/************************************************************************/
int OGREDIGEODataSource::ReadGEN()
{
VSILFILE* fp = OpenFile(osGNN, "GEN");
if (fp == NULL)
return FALSE;
const char* pszLine;
CPLString osCM1, osCM2;
while((pszLine = CPLReadLine2L(fp, 81, NULL)) != NULL)
{
if (strlen(pszLine) < 8 || pszLine[7] != ':')
continue;
if (strncmp(pszLine, "CM1CC", 5) == 0)
{
osCM1 = pszLine + 8;
}
else if (strncmp(pszLine, "CM2CC", 5) == 0)
{
osCM2 = pszLine + 8;
}
}
VSIFCloseL(fp);
if (osCM1.size() == 0 || osCM2.size() == 0)
return FALSE;
char** papszTokens1 = CSLTokenizeString2(osCM1.c_str(), ";", 0);
char** papszTokens2 = CSLTokenizeString2(osCM2.c_str(), ";", 0);
if (CSLCount(papszTokens1) == 2 && CSLCount(papszTokens2) == 2)
{
bExtentValid = TRUE;
dfMinX = atof(papszTokens1[0]);
dfMinY = atof(papszTokens1[1]);
dfMaxX = atof(papszTokens2[0]);
dfMaxY = atof(papszTokens2[1]);
}
CSLDestroy(papszTokens1);
CSLDestroy(papszTokens2);
return bExtentValid;
}
/************************************************************************/
/* ReadDIC() */
/************************************************************************/
int OGREDIGEODataSource::ReadDIC()
{
VSILFILE* fp = OpenFile(osDIN, "DIC");
if (fp == NULL)
return FALSE;
const char* pszLine;
CPLString osRTY, osRID, osLAB, osTYP;
while(TRUE)
{
pszLine = CPLReadLine2L(fp, 81, NULL);
if (pszLine != NULL)
{
if (strlen(pszLine) < 8 || pszLine[7] != ':')
continue;
}
if (pszLine == NULL || strncmp(pszLine, "RTYSA", 5) == 0)
{
if (osRTY == "DID")
{
//CPLDebug("EDIGEO", "Object %s = %s",
// osRID.c_str(), osLAB.c_str());
mapObjects[osRID] = osLAB;
}
else if (osRTY == "DIA")
{
//CPLDebug("EDIGEO", "Attribute %s = %s, %s",
// osRID.c_str(), osLAB.c_str(), osTYP.c_str());
OGREDIGEOAttributeDef sAttributeDef;
sAttributeDef.osLAB = osLAB;
sAttributeDef.osTYP = osTYP;
mapAttributes[osRID] = sAttributeDef;
}
if (pszLine == NULL)
break;
osRTY = pszLine + 8;
osRID = "";
osLAB = "";
osTYP = "";
}
if (strncmp(pszLine, "RIDSA", 5) == 0)
osRID = pszLine + 8;
else if (strncmp(pszLine, "LABSA", 5) == 0)
osLAB = pszLine + 8;
else if (strncmp(pszLine, "TYPSA", 5) == 0)
osTYP = pszLine + 8;
}
VSIFCloseL(fp);
return TRUE;
}
/************************************************************************/
/* ReadSCD() */
/************************************************************************/
int OGREDIGEODataSource::ReadSCD()
{
VSILFILE* fp = OpenFile(osSCN, "SCD");
if (fp == NULL)
return FALSE;
const char* pszLine;
CPLString osRTY, osRID, osNameRID, osKND;
strListType aosAttrRID;
int nWidth = 0;
while(TRUE)
{
pszLine = CPLReadLine2L(fp, 81, NULL);
if (pszLine != NULL)
{
if (strlen(pszLine) < 8 || pszLine[7] != ':')
continue;
}
if (pszLine == NULL || strncmp(pszLine, "RTYSA", 5) == 0)
{
if (osRTY == "OBJ")
{
if (mapObjects.find(osNameRID) == mapObjects.end())
{
CPLDebug("EDIGEO", "Cannot find object %s",
osNameRID.c_str());
}
else
{
OGREDIGEOObjectDescriptor objDesc;
objDesc.osRID = osRID;
objDesc.osNameRID = osNameRID;
objDesc.osKND = osKND;
objDesc.aosAttrRID = aosAttrRID;
/*CPLDebug("EDIGEO", "Object %s = %s, %s, %d attributes",
osRID.c_str(), osNameRID.c_str(), osKND.c_str(),
(int)aosAttrRID.size());*/
aoObjList.push_back(objDesc);
}
}
else if (osRTY == "ATT")
{
if (mapAttributes.find(osNameRID) == mapAttributes.end())
{
CPLDebug("EDIGEO", "Cannot find attribute %s",
osNameRID.c_str());
}
else
{
OGREDIGEOAttributeDescriptor attDesc;
attDesc.osRID = osRID;
attDesc.osNameRID = osNameRID;
attDesc.nWidth = nWidth;
/*CPLDebug("EDIGEO", "Attribute %s = %s, %d",
osRID.c_str(), osNameRID.c_str(), nWidth);*/
mapAttributesSCD[osRID] = attDesc;
}
}
if (pszLine == NULL)
break;
osRTY = pszLine + 8;
osRID = "";
osNameRID = "";
osKND = "";
aosAttrRID.resize(0);
nWidth = 0;
}
if (strncmp(pszLine, "RIDSA", 5) == 0)
osRID = pszLine + 8;
else if (strncmp(pszLine, "DIPCP", 5) == 0)
{
const char* pszDIP = pszLine + 8;
char** papszTokens = CSLTokenizeString2(pszDIP, ";", 0);
if (CSLCount(papszTokens) == 4)
{
osNameRID = papszTokens[3];
}
CSLDestroy(papszTokens);
}
else if (strncmp(pszLine, "KNDSA", 5) == 0)
osKND = pszLine + 8;
else if (strncmp(pszLine, "AAPCP", 5) == 0)
{
const char* pszAAP = pszLine + 8;
char** papszTokens = CSLTokenizeString2(pszAAP, ";", 0);
if (CSLCount(papszTokens) == 4)
{
const char* pszAttRID = papszTokens[3];
aosAttrRID.push_back(pszAttRID);
}
CSLDestroy(papszTokens);
}
else if (strncmp(pszLine, "CANSN", 5) == 0)
nWidth = atoi(pszLine + 8);
}
VSIFCloseL(fp);
return TRUE;
}
/************************************************************************/
/* ReadQAL() */
/************************************************************************/
int OGREDIGEODataSource::ReadQAL()
{
VSILFILE* fp = OpenFile(osQAN, "QAL");
if (fp == NULL)
return FALSE;
const char* pszLine;
CPLString osRTY, osRID;
int nODA = 0, nUDA = 0;
while(TRUE)
{
pszLine = CPLReadLine2L(fp, 81, NULL);
if (pszLine != NULL)
{
if (strlen(pszLine) < 8 || pszLine[7] != ':')
continue;
}
if (pszLine == NULL || strncmp(pszLine, "RTYSA", 5) == 0)
{
if (osRTY == "QUP")
{
mapQAL[osRID] = intintType(nODA, nUDA);
}
if (pszLine == NULL)
break;
osRTY = pszLine + 8;
osRID = "";
nODA = 0;
nUDA = 0;
}
else if (strncmp(pszLine, "RIDSA", 5) == 0)
osRID = pszLine + 8;
else if (strncmp(pszLine, "ODASD", 5) == 0)
nODA = atoi(pszLine + 8);
else if (strncmp(pszLine, "UDASD", 5) == 0)
nUDA = atoi(pszLine + 8);
}
VSIFCloseL(fp);
return TRUE;
}
/************************************************************************/
/* CreateLayerFromObjectDesc() */
/************************************************************************/
int OGREDIGEODataSource::CreateLayerFromObjectDesc(const OGREDIGEOObjectDescriptor& objDesc)
{
OGRwkbGeometryType eType = wkbUnknown;
if (objDesc.osKND == "ARE")
eType = wkbPolygon;
else if (objDesc.osKND == "LIN")
eType = wkbLineString;
else if (objDesc.osKND == "PCT")
eType = wkbPoint;
else
{
CPLDebug("EDIGEO", "Unknown KND : %s", objDesc.osKND.c_str());
return FALSE;
}
const char* pszLayerName = objDesc.osRID.c_str();
//mapObjects.find(objDesc.osNameRID)->second.c_str();
OGREDIGEOLayer* poLayer = new OGREDIGEOLayer(this, pszLayerName,
eType, poSRS);
poLayer->AddFieldDefn("OBJECT_RID", OFTString, "");
for(int j=0;j<(int)objDesc.aosAttrRID.size();j++)
{
std::map<CPLString,OGREDIGEOAttributeDescriptor>::iterator it =
mapAttributesSCD.find(objDesc.aosAttrRID[j]);
if (it != mapAttributesSCD.end())
{
const OGREDIGEOAttributeDescriptor& attrDesc = it->second;
const OGREDIGEOAttributeDef& attrDef =
mapAttributes[attrDesc.osNameRID];
OGRFieldType eType = OFTString;
if (attrDef.osTYP == "R" || attrDef.osTYP == "E")
eType = OFTReal;
else if (attrDef.osTYP == "I" || attrDef.osTYP == "N")
eType = OFTInteger;
poLayer->AddFieldDefn(attrDef.osLAB, eType, objDesc.aosAttrRID[j]);
}
}
if (strcmp(poLayer->GetName(), "ID_S_OBJ_Z_1_2_2") == 0)
{
OGRFeatureDefn* poFDefn = poLayer->GetLayerDefn();
iATR = poFDefn->GetFieldIndex("ATR");
iDI3 = poFDefn->GetFieldIndex("DI3");
iDI4 = poFDefn->GetFieldIndex("DI4");
iHEI = poFDefn->GetFieldIndex("HEI");
iFON = poFDefn->GetFieldIndex("FON");
poLayer->AddFieldDefn("OGR_OBJ_LNK", OFTString, "");
iOBJ_LNK = poFDefn->GetFieldIndex("OGR_OBJ_LNK");
poLayer->AddFieldDefn("OGR_OBJ_LNK_LAYER", OFTString, "");
iOBJ_LNK_LAYER = poFDefn->GetFieldIndex("OGR_OBJ_LNK_LAYER");
poLayer->AddFieldDefn("OGR_ATR_VAL", OFTString, "");
iATR_VAL = poFDefn->GetFieldIndex("OGR_ATR_VAL");
poLayer->AddFieldDefn("OGR_ANGLE", OFTReal, "");
iANGLE = poFDefn->GetFieldIndex("OGR_ANGLE");
poLayer->AddFieldDefn("OGR_FONT_SIZE", OFTReal, "");
iSIZE = poFDefn->GetFieldIndex("OGR_FONT_SIZE");
}
else if (mapQAL.size() != 0)
{
poLayer->AddFieldDefn("CREAT_DATE", OFTInteger, "");
poLayer->AddFieldDefn("UPDATE_DATE", OFTInteger, "");
}
mapLayer[objDesc.osRID] = poLayer;
papoLayers = (OGRLayer**)
CPLRealloc(papoLayers, (nLayers + 1) * sizeof(OGRLayer*));
papoLayers[nLayers] = poLayer;
nLayers ++;
return TRUE;
}
/************************************************************************/
/* ReadVEC() */
/************************************************************************/
int OGREDIGEODataSource::ReadVEC(const char* pszVECName)
{
VSILFILE* fp = OpenFile(pszVECName, "VEC");
if (fp == NULL)
return FALSE;
const char* pszLine;
CPLString osRTY, osRID;
xyPairListType aXY;
CPLString osLnkStartType, osLnkStartName, osLnkEndType, osLnkEndName;
strListType osLnkEndNameList;
CPLString osAttId;
std::vector< strstrType > aosAttIdVal;
CPLString osSCP;
CPLString osQUP_RID;
int bIso8859_1 = FALSE;
while(TRUE)
{
pszLine = CPLReadLine2L(fp, 81, NULL);
skip_read_next_line:
if (pszLine != NULL)
{
if (strlen(pszLine) < 8 || pszLine[7] != ':')
continue;
}
if (pszLine == NULL || strncmp(pszLine, "RTYSA", 5) == 0)
{
if (osRTY == "PAR")
{
if (aXY.size() < 2)
CPLDebug("EDIGEO", "Error: ARC %s has not enough points",
osRID.c_str());
else
mapPAR[osRID] = aXY;
}
else if (osRTY == "LNK")
{
if (osLnkStartType == "PAR" && osLnkEndType == "PFE")
{
/*CPLDebug("EDIGEO", "PFE[%s] -> PAR[%s]",
osLnkEndName.c_str(), osLnkStartName.c_str());*/
if (mapPFE_PAR.find(osLnkEndName) == mapPFE_PAR.end())
mapPFE_PAR[osLnkEndName].push_back(osLnkStartName);
else
{
int bAlreadyExists = FALSE;
strListType& osPARList = mapPFE_PAR[osLnkEndName];
for(int j=0;j<(int)osPARList.size();j++)
{
if (osPARList[j] == osLnkStartName)
bAlreadyExists = TRUE;
}
if (!bAlreadyExists)
osPARList.push_back(osLnkStartName);
}
}
else if (osLnkStartType == "FEA" && osLnkEndType == "PFE")
{
/*CPLDebug("EDIGEO", "FEA[%s] -> PFE[%s]",
osLnkStartName.c_str(), osLnkEndName.c_str());*/
listFEA_PFE.push_back(strstrType
(osLnkStartName, osLnkEndName));
}
else if (osLnkStartType == "FEA" && osLnkEndType == "PAR")
{
/*CPLDebug("EDIGEO", "FEA[%s] -> PAR[%s]",
osLnkStartName.c_str(), osLnkEndName.c_str());*/
listFEA_PAR.push_back(std::pair<CPLString, strListType >
(osLnkStartName, osLnkEndNameList));
}
else if (osLnkStartType == "FEA" && osLnkEndType == "PNO")
{
/*CPLDebug("EDIGEO", "FEA[%s] -> PNO[%s]",
osLnkStartName.c_str(), osLnkEndName.c_str());*/
listFEA_PNO.push_back(strstrType
(osLnkStartName, osLnkEndName));
}
else if (osLnkStartType == "FEA" && osLnkEndType == "FEA")
{
/*CPLDebug("EDIGEO", "FEA[%s] -> FEA[%s]",
osLnkStartName.c_str(), osLnkEndName.c_str());*/
if (osSCP == "IS_S_REL_IWW")
mapFEA_FEA[osLnkStartName] = osLnkEndName;
}
else if (osLnkStartType == "PAR" && osLnkEndType == "PNO")
{
}
else
{
CPLDebug("EDIGEO", "Unhandled LNK(%s) %s=%s --> %s=%s",
osRID.c_str(),
osLnkStartType.c_str(), osLnkStartName.c_str(),
osLnkEndType.c_str(), osLnkEndName.c_str());
}
}
else if (osRTY == "FEA")
{
OGREDIGEOFEADesc feaDesc;
feaDesc.aosAttIdVal = aosAttIdVal;
feaDesc.osSCP = osSCP;
feaDesc.osQUP_RID = osQUP_RID;
mapFEA[osRID] = feaDesc;
}
else if (osRTY == "PNO")
{
if (aXY.size() == 1)
{
/*CPLDebug("EDIGEO", "PNO[%s] = %f, %f",
osRID.c_str(), aXY[0].first, aXY[0].second);*/
mapPNO[osRID] = aXY[0];
}
}
if (pszLine == NULL)
break;
osRTY = pszLine + 8;
osRID = "";
aXY.resize(0);
osLnkStartType = "";
osLnkStartName = "";
osLnkEndType = "";
osLnkEndName = "";
osAttId = "";
aosAttIdVal.resize(0);
osLnkEndNameList.resize(0);
osSCP = "";
osQUP_RID = "";
bIso8859_1 = FALSE;
}
else if (strncmp(pszLine, "RIDSA", 5) == 0)
osRID = pszLine + 8;
else if (strncmp(pszLine, "CORCC", 5) == 0)
{
const char* pszY = strchr(pszLine+8, ';');
if (pszY)
{
double dfX = atof(pszLine + 8);
double dfY = atof(pszY + 1);
aXY.push_back(xyPairType (dfX, dfY));
}
}
else if (strncmp(pszLine, "FTPCP", 5) == 0)
{
char** papszTokens = CSLTokenizeString2(pszLine + 8, ";", 0);
if (CSLCount(papszTokens) == 4)
{
if (osLnkStartType.size() == 0)
{
osLnkStartType = papszTokens[2];
osLnkStartName = papszTokens[3];
}
else
{
osLnkEndType = papszTokens[2];
osLnkEndName = papszTokens[3];
osLnkEndNameList.push_back(osLnkEndName);
}
}
CSLDestroy(papszTokens);
}
else if (strncmp(pszLine, "SCPCP", 5) == 0)
{
char** papszTokens = CSLTokenizeString2(pszLine + 8, ";", 0);
if (CSLCount(papszTokens) == 4)
{
if (osRTY == "LNK")
{
if (strcmp(papszTokens[2], "ASS") == 0)
osSCP = papszTokens[3];
}
else if (strcmp(papszTokens[2], "OBJ") == 0)
osSCP = papszTokens[3];
}
CSLDestroy(papszTokens);
}
else if (strncmp(pszLine, "ATPCP", 5) == 0)
{
char** papszTokens = CSLTokenizeString2(pszLine + 8, ";", 0);
if (CSLCount(papszTokens) == 4)
{
if (strcmp(papszTokens[2], "ATT") == 0)
osAttId = papszTokens[3];
}
CSLDestroy(papszTokens);
}
else if (strcmp(pszLine, "TEXT 06:8859-1") == 0)
{
bIso8859_1 = TRUE;
}
else if (strncmp(pszLine, "ATVS", 4) == 0)
{
CPLString osAttVal = pszLine + 8;
int bSkipReadNextLine = FALSE;
while(TRUE)
{
pszLine = CPLReadLine2L(fp, 81, NULL);
if (pszLine != NULL &&
strlen(pszLine) >= 8 &&
pszLine[7] == ':' &&
strncmp(pszLine, "NEXT ", 5) == 0)
{
osAttVal += pszLine + 8;
}
else
{
bSkipReadNextLine = TRUE;
break;
}
}
if (bIso8859_1 && bRecodeToUTF8)
{
char* pszNewVal = CPLRecode(osAttVal.c_str(),
CPL_ENC_ISO8859_1, CPL_ENC_UTF8);
osAttVal = pszNewVal;
CPLFree(pszNewVal);
}
else if (bHasUTF8ContentOnly)
{
bHasUTF8ContentOnly = CPLIsUTF8(osAttVal.c_str(), -1);
}
if (osAttId.size() != 0)
aosAttIdVal.push_back( strstrType (osAttId, osAttVal) );
osAttId = "";
bIso8859_1 = FALSE;
if (bSkipReadNextLine)
goto skip_read_next_line;
}
else if (strncmp(pszLine, "ATVCP", 5) == 0)
{
char** papszTokens = CSLTokenizeString2(pszLine + 8, ";", 0);
if (CSLCount(papszTokens) == 4)
{
if (strcmp(papszTokens[2], "ATT") == 0)
{
CPLString osAttVal = papszTokens[3];
if (osAttId.size() != 0)
aosAttIdVal.push_back( strstrType (osAttId, osAttVal) );
osAttId = "";
}
}
CSLDestroy(papszTokens);
}
else if (strncmp(pszLine, "QAPCP", 5) == 0)
{
char** papszTokens = CSLTokenizeString2(pszLine + 8, ";", 0);
if (CSLCount(papszTokens) == 4)
{
if (strcmp(papszTokens[2], "QUP") == 0)
{
osQUP_RID = papszTokens[3];
}
}
CSLDestroy(papszTokens);
}
}
VSIFCloseL(fp);
return TRUE;
}
/************************************************************************/
/* CreateFeature() */
/************************************************************************/
OGRFeature* OGREDIGEODataSource::CreateFeature(const CPLString& osFEA)
{
const std::map< CPLString, OGREDIGEOFEADesc >::iterator itFEA =
mapFEA.find(osFEA);
if (itFEA == mapFEA.end())
{
CPLDebug("EDIGEO", "ERROR: Cannot find FEA %s", osFEA.c_str());
return NULL;
}
const OGREDIGEOFEADesc& fea = itFEA->second;
const std::map<CPLString,OGREDIGEOLayer*>::iterator itLyr =
mapLayer.find(fea.osSCP);
if (itLyr != mapLayer.end())
{
OGREDIGEOLayer* poLayer = itLyr->second;
OGRFeature* poFeature = new OGRFeature(poLayer->GetLayerDefn());
poFeature->SetField(0, itFEA->first.c_str());
for(int i=0;i<(int)fea.aosAttIdVal.size();i++)
{
const CPLString& id = fea.aosAttIdVal[i].first;
const CPLString& val = fea.aosAttIdVal[i].second;
int iIndex = poLayer->GetAttributeIndex(id);
if (iIndex != -1)
poFeature->SetField(iIndex, val.c_str());
else
CPLDebug("EDIGEO",
"ERROR: Cannot find attribute %s", id.c_str());
}
if (strcmp(poLayer->GetName(), "ID_S_OBJ_Z_1_2_2") != 0 &&
mapQAL.size() != 0 && fea.osQUP_RID.size() != 0)
{
const std::map<CPLString, intintType>::iterator itQAL =
mapQAL.find(fea.osQUP_RID);
if (itQAL != mapQAL.end())
{
const intintType& creationUpdateDate = itQAL->second;
if (creationUpdateDate.first != 0)
poFeature->SetField("CREAT_DATE", creationUpdateDate.first);
if (creationUpdateDate.second != 0)
poFeature->SetField("UPDATE_DATE", creationUpdateDate.second);
}
}
poLayer->AddFeature(poFeature);
return poFeature;
}
else
{
CPLDebug("EDIGEO", "ERROR: Cannot find layer %s", fea.osSCP.c_str());
return NULL;
}
}
/************************************************************************/
/* SetStyle() */
/************************************************************************/
int OGREDIGEODataSource::SetStyle(const CPLString& osFEA,
OGRFeature* poFeature)
{
/* EDIGEO PCI specific */
/* See EDIGeO_PCI.pdf, chapter 3 "Principes généraux de */
/* positionnement de la toponymie. */
const char* pszATR = NULL;
if (strcmp(poFeature->GetDefnRef()->GetName(), "ID_S_OBJ_Z_1_2_2") == 0 &&
iATR != -1 && (pszATR = poFeature->GetFieldAsString(iATR)) != NULL)
{
const CPLString osATR = pszATR;
std::map< CPLString, CPLString>::iterator itFEA_FEA =
mapFEA_FEA.find(osFEA);
if (itFEA_FEA != mapFEA_FEA.end())
{
const CPLString& osOBJ_LNK = itFEA_FEA->second;
std::map< CPLString, OGREDIGEOFEADesc >::iterator itFEA_LNK =
mapFEA.find(osOBJ_LNK);
if (itFEA_LNK != mapFEA.end())
{
const OGREDIGEOFEADesc& fea_lnk = itFEA_LNK->second;
for(int j=0;j<(int)fea_lnk.aosAttIdVal.size();j++)
{
if (fea_lnk.aosAttIdVal[j].first == osATR)
{
double dfAngle = 0;
if (iDI3 != -1 && iDI4 != -1)
{
double dfBaseVectorX =
poFeature->GetFieldAsDouble(iDI3);
double dfBaseVectorY =
poFeature->GetFieldAsDouble(iDI4);
dfAngle = atan2(dfBaseVectorY, dfBaseVectorX)
/ M_PI * 180;
if (dfAngle < 0)
dfAngle += 360;
}
double dfSize = 1;
if (iHEI != -1)
dfSize = poFeature->GetFieldAsDouble(iHEI);
if (dfSize <= 0 || dfSize >= 100)
dfSize = 1;
const char* pszFontFamily = NULL;
if (iFON != -1)
pszFontFamily = poFeature->GetFieldAsString(iFON);
CPLString osStyle("LABEL(t:\"");
osStyle += fea_lnk.aosAttIdVal[j].second;
osStyle += "\"";
if (dfAngle != 0)
{
osStyle += ",a:";
osStyle += CPLString().Printf("%.1f", dfAngle);
}
if (pszFontFamily != NULL && bIncludeFontFamily)
{
osStyle += ",f:\"";
osStyle += pszFontFamily;
osStyle += "\"";
}
osStyle += ",s:";
osStyle += CPLString().Printf("%.1f", dfSize);
osStyle += ",c:#000000)";
poFeature->SetStyleString(osStyle);
poFeature->SetField(iATR_VAL,
fea_lnk.aosAttIdVal[j].second);
poFeature->SetField(iANGLE, dfAngle);
poFeature->SetField(iSIZE, dfSize * dfSizeFactor);
poFeature->SetField(iOBJ_LNK, osOBJ_LNK);
poFeature->SetField(iOBJ_LNK_LAYER, fea_lnk.osSCP);
setLayersWithLabels.insert(fea_lnk.osSCP);
break;
}
}
}
}
}
return TRUE;
}
/************************************************************************/
/* BuildPoints() */
/************************************************************************/
int OGREDIGEODataSource::BuildPoints()
{
for(int i=0;i<(int)listFEA_PNO.size();i++)
{
const CPLString& osFEA = listFEA_PNO[i].first;
const CPLString& osPNO = listFEA_PNO[i].second;
const std::map< CPLString, xyPairType >::iterator itPNO =
mapPNO.find(osPNO);
if (itPNO == mapPNO.end())
{
CPLDebug("EDIGEO", "Cannot find PNO %s", osPNO.c_str());
}
else
{
OGRFeature* poFeature = CreateFeature(osFEA);
if (poFeature)
{
const xyPairType& pno = itPNO->second;
OGRPoint* poPoint = new OGRPoint(pno.first, pno.second);
if (poSRS)
poPoint->assignSpatialReference(poSRS);
poFeature->SetGeometryDirectly(poPoint);
SetStyle(osFEA, poFeature);
}
}
}
return TRUE;
}
/************************************************************************/
/* BuildLineStrings() */
/************************************************************************/
int OGREDIGEODataSource::BuildLineStrings()
{
int i, iter;
for(iter=0;iter<(int)listFEA_PAR.size();iter++)
{
const CPLString& osFEA = listFEA_PAR[iter].first;
const strListType & aosPAR = listFEA_PAR[iter].second;
OGRFeature* poFeature = CreateFeature(osFEA);
if (poFeature)
{
OGRMultiLineString* poMulti = NULL;
for(int k=0;k<(int)aosPAR.size();k++)
{
const std::map< CPLString, xyPairListType >::iterator itPAR =
mapPAR.find(aosPAR[k]);
if (itPAR != mapPAR.end())
{
const xyPairListType& arc = itPAR->second;
OGRLineString* poLS = new OGRLineString();
poLS->setNumPoints((int)arc.size());
for(i=0;i<(int)arc.size();i++)
{
poLS->setPoint(i, arc[i].first, arc[i].second);
}
if (poFeature->GetGeometryRef() != NULL)
{
if (poMulti == NULL)
{
OGRLineString* poPrevLS =
(OGRLineString*) poFeature->StealGeometry();
poMulti = new OGRMultiLineString();
poMulti->addGeometryDirectly(poPrevLS);
poFeature->SetGeometryDirectly(poMulti);
}
poMulti->addGeometryDirectly(poLS);
}
else
poFeature->SetGeometryDirectly(poLS);
}
else
CPLDebug("EDIGEO",
"ERROR: Cannot find ARC %s", aosPAR[k].c_str());
}
if (poFeature->GetGeometryRef())
poFeature->GetGeometryRef()->assignSpatialReference(poSRS);
}
}
return TRUE;
}
/************************************************************************/
/* BuildPolygon() */
/************************************************************************/
int OGREDIGEODataSource::BuildPolygon(const CPLString& osFEA,
const CPLString& osPFE)
{
int i;
const std::map< CPLString, strListType >::iterator itPFE_PAR =
mapPFE_PAR.find(osPFE);
if (itPFE_PAR == mapPFE_PAR.end())
{
CPLDebug("EDIGEO", "ERROR: Cannot find PFE %s", osPFE.c_str());
return FALSE;
}
const strListType & aosPARList = itPFE_PAR->second;
/* -------------------------------------------------------------------- */
/* Resolve arc ids to arc coordinate lists. */
/* -------------------------------------------------------------------- */
std::vector< const xyPairListType *> aoPARPtrList;
for(i=0;i<(int)aosPARList.size();i++)
{
const std::map< CPLString, xyPairListType >::iterator itPAR =
mapPAR.find(aosPARList[i]);
if (itPAR != mapPAR.end())
aoPARPtrList.push_back(&(itPAR->second));
else
CPLDebug("EDIGEO",
"ERROR: Cannot find ARC %s", aosPARList[i].c_str());
}
if (aoPARPtrList.size() == 0)
return FALSE;
/* -------------------------------------------------------------------- */
/* Now try to chain all arcs together. */
/* -------------------------------------------------------------------- */
std::vector<xyPairListType> aoXYList;
int j;
for(j=0;j<(int)aoPARPtrList.size();j++)
{
if (aoPARPtrList[j] == NULL)
continue;
const xyPairListType& sFirstRing = *(aoPARPtrList[j]);
const xyPairType* psNext = &(sFirstRing[sFirstRing.size()-1]);
xyPairListType aoXY;
for(i=0;i<(int)sFirstRing.size();i++)
aoXY.push_back(sFirstRing[i]);
aoPARPtrList[j] = NULL;
int nIter = 1;
while(aoXY[aoXY.size()-1] != aoXY[0] && nIter < (int)aoPARPtrList.size())
{
int bFound = FALSE;
int bReverseSecond = FALSE;
for(i=0;i<(int)aoPARPtrList.size();i++)
{
if (aoPARPtrList[i] != NULL)
{
const xyPairListType& sSecondRing = *(aoPARPtrList[i]);
if (*psNext == sSecondRing[0])
{
bFound = TRUE;
bReverseSecond = FALSE;
break;
}
else if (*psNext == sSecondRing[sSecondRing.size()-1])
{
bFound = TRUE;
bReverseSecond = TRUE;
break;
}
}
}
if (!bFound)
{
CPLDebug("EDIGEO", "Cannot find ring for FEA %s / PFE %s",
osFEA.c_str(), osPFE.c_str());
break;
}
else
{
const xyPairListType& secondRing = *(aoPARPtrList[i]);
aoPARPtrList[i] = NULL;
if (!bReverseSecond)
{
for(i=1;i<(int)secondRing.size();i++)
aoXY.push_back(secondRing[i]);
psNext = &secondRing[secondRing.size()-1];
}
else
{
for(i=1;i<(int)secondRing.size();i++)
aoXY.push_back(secondRing[secondRing.size()-1-i]);
psNext = &secondRing[0];
}
}
nIter ++;
}
aoXYList.push_back(aoXY);
}
/* -------------------------------------------------------------------- */
/* Create feature. */
/* -------------------------------------------------------------------- */
OGRFeature* poFeature = CreateFeature(osFEA);
if (poFeature)
{
std::vector<OGRGeometry*> aosPolygons;
for(j=0;j<(int)aoXYList.size();j++)
{
const xyPairListType& aoXY = aoXYList[j];
OGRLinearRing* poLS = new OGRLinearRing();
poLS->setNumPoints((int)aoXY.size());
for(i=0;i<(int)aoXY.size();i++)
poLS->setPoint(i, aoXY[i].first, aoXY[i].second);
poLS->closeRings();
OGRPolygon* poPolygon = new OGRPolygon();
poPolygon->addRingDirectly(poLS);
aosPolygons.push_back(poPolygon);
}
int bIsValidGeometry;
OGRGeometry* poGeom = OGRGeometryFactory::organizePolygons(
&aosPolygons[0], (int)aosPolygons.size(),
&bIsValidGeometry, NULL);
if (poGeom)
{
if (poSRS)
poGeom->assignSpatialReference(poSRS);
poFeature->SetGeometryDirectly(poGeom);
}
}
return TRUE;
}
/************************************************************************/
/* BuildPolygons() */
/************************************************************************/
int OGREDIGEODataSource::BuildPolygons()
{
int iter;
for(iter=0;iter<(int)listFEA_PFE.size();iter++)
{
const CPLString& osFEA = listFEA_PFE[iter].first;
const CPLString& osPFE = listFEA_PFE[iter].second;
BuildPolygon(osFEA, osPFE);
}
return TRUE;
}
/************************************************************************/
/* OGREDIGEOSortForQGIS() */
/************************************************************************/
static int OGREDIGEOSortForQGIS(const void* a, const void* b)
{
OGREDIGEOLayer* poLayerA = *((OGREDIGEOLayer**) a);
OGREDIGEOLayer* poLayerB = *((OGREDIGEOLayer**) b);
int nTypeA, nTypeB;
switch (poLayerA->GetLayerDefn()->GetGeomType())
{
case wkbPoint: nTypeA = 1; break;
case wkbLineString: nTypeA = 2; break;
case wkbPolygon: nTypeA = 3; break;
default: nTypeA = 4; break;
}
switch (poLayerB->GetLayerDefn()->GetGeomType())
{
case wkbPoint: nTypeB = 1; break;
case wkbLineString: nTypeB = 2; break;
case wkbPolygon: nTypeB = 3; break;
default: nTypeB = 4; break;
}
if (nTypeA == nTypeB)
{
int nCmp = strcmp(poLayerA->GetName(), poLayerB->GetName());
if (nCmp == 0)
return 0;
static const char* apszPolyOrder[] =
{ "COMMUNE_id", "LIEUDIT_id", "SECTION_id", "SUBDSECT_id",
"SUBDFISC_id", "PARCELLE_id", "BATIMENT_id" };
for(int i=0;i<(int)(sizeof(apszPolyOrder)/sizeof(char*));i++)
{
if (strcmp(poLayerA->GetName(), apszPolyOrder[i]) == 0)
return -1;
if (strcmp(poLayerB->GetName(), apszPolyOrder[i]) == 0)
return 1;
}
return nCmp;
}
else
return nTypeB - nTypeA;
}
/************************************************************************/
/* Open() */
/************************************************************************/
int OGREDIGEODataSource::Open( const char * pszFilename, int bUpdateIn)
{
if (bUpdateIn)
{
return FALSE;
}
pszName = CPLStrdup( pszFilename );
/* -------------------------------------------------------------------- */
/* Does this appear to be a .THF file? */
/* -------------------------------------------------------------------- */
if( !EQUAL(CPLGetExtension(pszFilename), "thf") )
return FALSE;
fpTHF = VSIFOpenL(pszFilename, "rb");
if (fpTHF == NULL)
return FALSE;
const char* pszLine;
int i = 0;
int bIsEDIGEO = FALSE;
while(i < 100 && (pszLine = CPLReadLine2L(fpTHF, 81, NULL)) != NULL)
{
if (strcmp(pszLine, "RTYSA03:GTS") == 0)
{
bIsEDIGEO = TRUE;
break;
}
i++;
}
if (!bIsEDIGEO)
{
VSIFCloseL(fpTHF);
fpTHF = NULL;
return FALSE;
}
return TRUE;
}
/************************************************************************/
/* ReadEDIGEO() */
/************************************************************************/
void OGREDIGEODataSource::ReadEDIGEO()
{
if (bHasReadEDIGEO)
return;
bHasReadEDIGEO = TRUE;
/* -------------------------------------------------------------------- */
/* Read .THF file */
/* -------------------------------------------------------------------- */
VSIFSeekL(fpTHF, 0, SEEK_SET);
if (!ReadTHF(fpTHF))
{
VSIFCloseL(fpTHF);
fpTHF = NULL;
return;
}
VSIFCloseL(fpTHF);
fpTHF = NULL;
/* -------------------------------------------------------------------- */
/* Read .GEO file */
/* -------------------------------------------------------------------- */
if (!ReadGEO())
return;
/* -------------------------------------------------------------------- */
/* Read .GEN file */
/* -------------------------------------------------------------------- */
if (osGNN.size() != 0)
ReadGEN();
/* -------------------------------------------------------------------- */
/* Read .DIC file */
/* -------------------------------------------------------------------- */
if (!ReadDIC())
return;
/* -------------------------------------------------------------------- */
/* Read .SCD file */
/* -------------------------------------------------------------------- */
if (!ReadSCD())
return;
/* -------------------------------------------------------------------- */
/* Read .QAL file */
/* -------------------------------------------------------------------- */
if (osQAN.size() != 0)
ReadQAL();
/* -------------------------------------------------------------------- */
/* Create layers from SCD definitions */
/* -------------------------------------------------------------------- */
int i;
for(i=0;i<(int)aoObjList.size();i++)
{
CreateLayerFromObjectDesc(aoObjList[i]);
}
/* -------------------------------------------------------------------- */
/* Read .VEC files and create features */
/* -------------------------------------------------------------------- */
for(i=0;i<(int)aosGDN.size();i++)
{
ReadVEC(aosGDN[i]);
BuildPoints();
BuildLineStrings();
BuildPolygons();
mapPNO.clear();
mapPAR.clear();
mapFEA.clear();
mapPFE_PAR.clear();
listFEA_PFE.clear();
listFEA_PAR.clear();
listFEA_PNO.clear();
mapFEA_FEA.clear();
}
mapObjects.clear();
mapAttributes.clear();
mapAttributesSCD.clear();
mapQAL.clear();
/* -------------------------------------------------------------------- */
/* Delete empty layers */
/* -------------------------------------------------------------------- */
for(i=0;i<nLayers;/*nothing*/)
{
if (papoLayers[i]->GetFeatureCount(TRUE) == 0)
{
delete papoLayers[i];
if (i < nLayers - 1)
memmove(papoLayers + i, papoLayers + i + 1,
(nLayers - i - 1) * sizeof(OGREDIGEOLayer*));
nLayers --;
}
else
i++;
}
/* -------------------------------------------------------------------- */
/* When added from QGIS, the layers must be ordered from */
/* bottom (Polygon) to top (Point) to get nice visual effect */
/* -------------------------------------------------------------------- */
if (CSLTestBoolean(CPLGetConfigOption("OGR_EDIGEO_SORT_FOR_QGIS", "YES")))
qsort(papoLayers, nLayers, sizeof(OGREDIGEOLayer*), OGREDIGEOSortForQGIS);
/* -------------------------------------------------------------------- */
/* Create a label layer for each feature layer */
/* -------------------------------------------------------------------- */
if (CSLTestBoolean(CPLGetConfigOption("OGR_EDIGEO_CREATE_LABEL_LAYERS", "YES")))
CreateLabelLayers();
return;
}
/************************************************************************/
/* CreateLabelLayers() */
/************************************************************************/
void OGREDIGEODataSource::CreateLabelLayers()
{
OGRLayer* poLayer = GetLayerByName("ID_S_OBJ_Z_1_2_2");
if (poLayer == NULL)
return;
std::map<CPLString, OGREDIGEOLayer*> mapLayerNameToLayer;
OGRFeature* poFeature;
OGRFeatureDefn* poFeatureDefn = poLayer->GetLayerDefn();
while((poFeature = poLayer->GetNextFeature()) != NULL)
{
const char* pszBelongingLayerName =
poFeature->GetFieldAsString(iOBJ_LNK_LAYER);
if (pszBelongingLayerName)
{
CPLString osBelongingLayerName = pszBelongingLayerName;
std::map<CPLString, OGREDIGEOLayer*>::iterator it =
mapLayerNameToLayer.find(osBelongingLayerName);
OGREDIGEOLayer* poLabelLayer;
if (it == mapLayerNameToLayer.end())
{
/* Create label layer if it does not already exist */
CPLString osLayerLabelName = osBelongingLayerName + "_LABEL";
poLabelLayer = new OGREDIGEOLayer(this, osLayerLabelName.c_str(),
wkbPoint, poSRS);
int i;
OGRFeatureDefn* poLabelFeatureDefn = poLabelLayer->GetLayerDefn();
for(i=0;i<poFeatureDefn->GetFieldCount();i++)
poLabelFeatureDefn->AddFieldDefn(poFeatureDefn->GetFieldDefn(i));
mapLayerNameToLayer[osBelongingLayerName] = poLabelLayer;
papoLayers = (OGRLayer**)
CPLRealloc(papoLayers, (nLayers + 1) * sizeof(OGRLayer*));
papoLayers[nLayers] = poLabelLayer;
nLayers ++;
}
else
poLabelLayer = mapLayerNameToLayer[osBelongingLayerName];
OGRFeature* poNewFeature = new OGRFeature(poLabelLayer->GetLayerDefn());
poNewFeature->SetFrom(poFeature);
poLabelLayer->AddFeature(poNewFeature);
}
delete poFeature;
}
poLayer->ResetReading();
}
| 35.660941 | 219 | 0.422305 | [
"object",
"vector"
] |
b468e9b92d2aeaac38ec50bd382d0efb70d45156 | 41,531 | inl | C++ | include/bolt/cl/detail/reduce_by_key.inl | MattPD/Bolt | ada8cb02fccd9001947ebe592edc1d3a6715b0e7 | [
"BSL-1.0"
] | 2 | 2017-02-25T04:38:03.000Z | 2018-04-07T10:44:48.000Z | include/bolt/cl/detail/reduce_by_key.inl | MattPD/Bolt | ada8cb02fccd9001947ebe592edc1d3a6715b0e7 | [
"BSL-1.0"
] | null | null | null | include/bolt/cl/detail/reduce_by_key.inl | MattPD/Bolt | ada8cb02fccd9001947ebe592edc1d3a6715b0e7 | [
"BSL-1.0"
] | 1 | 2021-03-01T11:16:46.000Z | 2021-03-01T11:16:46.000Z | /***************************************************************************
* Copyright 2012 - 2013 Advanced Micro Devices, 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.
***************************************************************************/
#define KERNEL02WAVES 4
#define KERNEL1WAVES 4
#define WAVESIZE 64
#define LENGTH_TEST 10
#define ENABLE_PRINTS 0
#include <iostream>
#include <fstream>
#if !defined( REDUCE_BY_KEY_INL )
#define REDUCE_BY_KEY_INL
namespace bolt
{
namespace cl
{
/***********************************************************************************************************************
* REDUCE BY KEY
**********************************************************************************************************************/
template<
typename InputIterator1,
typename InputIterator2,
typename OutputIterator1,
typename OutputIterator2,
typename BinaryPredicate,
typename BinaryFunction>
bolt::cl::pair<OutputIterator1, OutputIterator2>
reduce_by_key(
InputIterator1 keys_first,
InputIterator1 keys_last,
InputIterator2 values_first,
OutputIterator1 keys_output,
OutputIterator2 values_output,
BinaryPredicate binary_pred,
BinaryFunction binary_op,
const std::string& user_code )
{
control& ctl = control::getDefault();
return detail::reduce_by_key_detect_random_access(
ctl,
keys_first,
keys_last,
values_first,
keys_output,
values_output,
binary_pred,
binary_op,
user_code,
std::iterator_traits< InputIterator1 >::iterator_category( )
); // return
}
template<
typename InputIterator1,
typename InputIterator2,
typename OutputIterator1,
typename OutputIterator2,
typename BinaryPredicate>
bolt::cl::pair<OutputIterator1, OutputIterator2>
reduce_by_key(
InputIterator1 keys_first,
InputIterator1 keys_last,
InputIterator2 values_first,
OutputIterator1 keys_output,
OutputIterator2 values_output,
BinaryPredicate binary_pred,
const std::string& user_code )
{
typedef std::iterator_traits<OutputIterator2>::value_type ValOType;
control& ctl = control::getDefault();
plus<ValOType> binary_op;
return detail::reduce_by_key_detect_random_access(
ctl,
keys_first,
keys_last,
values_first,
keys_output,
values_output,
binary_pred,
binary_op,
user_code,
std::iterator_traits< InputIterator1 >::iterator_category( )
); // return
}
template<
typename InputIterator1,
typename InputIterator2,
typename OutputIterator1,
typename OutputIterator2>
bolt::cl::pair<OutputIterator1, OutputIterator2>
reduce_by_key(
InputIterator1 keys_first,
InputIterator1 keys_last,
InputIterator2 values_first,
OutputIterator1 keys_output,
OutputIterator2 values_output,
const std::string& user_code )
{
typedef std::iterator_traits<InputIterator1>::value_type kType;
typedef std::iterator_traits<OutputIterator2>::value_type ValOType;
control& ctl = control::getDefault();
equal_to <kType> binary_pred;
plus <ValOType> binary_op;
return detail::reduce_by_key_detect_random_access(
ctl,
keys_first,
keys_last,
values_first,
keys_output,
values_output,
binary_pred,
binary_op,
user_code,
std::iterator_traits< InputIterator1 >::iterator_category( )
); // return
}
///////////////////////////// CTRL ////////////////////////////////////////////
template<
typename InputIterator1,
typename InputIterator2,
typename OutputIterator1,
typename OutputIterator2,
typename BinaryPredicate,
typename BinaryFunction>
bolt::cl::pair<OutputIterator1, OutputIterator2>
reduce_by_key(
control &ctl,
InputIterator1 keys_first,
InputIterator1 keys_last,
InputIterator2 values_first,
OutputIterator1 keys_output,
OutputIterator2 values_output,
BinaryPredicate binary_pred,
BinaryFunction binary_op,
const std::string& user_code )
{
//typedef std::iterator_traits<OutputIterator1>::value_type KeyOType;
//KeyOType init; memset(&init, 0, sizeof(KeyOType) );
return detail::reduce_by_key_detect_random_access(
ctl,
keys_first,
keys_last,
values_first,
keys_output,
values_output,
binary_pred,
binary_op,
user_code,
std::iterator_traits< InputIterator1 >::iterator_category( )
); // return
}
template<
typename InputIterator1,
typename InputIterator2,
typename OutputIterator1,
typename OutputIterator2,
typename BinaryPredicate>
bolt::cl::pair<OutputIterator1, OutputIterator2>
reduce_by_key(
control &ctl,
InputIterator1 keys_first,
InputIterator1 keys_last,
InputIterator2 values_first,
OutputIterator1 keys_output,
OutputIterator2 values_output,
BinaryPredicate binary_pred,
const std::string& user_code )
{
typedef std::iterator_traits<OutputIterator2>::value_type ValOType;
//KeyOType init; memset(&init, 0, sizeof(KeyOType) );
plus<ValOType> binary_op;
return detail::reduce_by_key_detect_random_access(
ctl,
keys_first,
keys_last,
values_first,
keys_output,
values_output,
binary_pred,
binary_op,
user_code,
std::iterator_traits< InputIterator1 >::iterator_category( )
); // return
}
template<
typename InputIterator1,
typename InputIterator2,
typename OutputIterator1,
typename OutputIterator2>
bolt::cl::pair<OutputIterator1, OutputIterator2>
reduce_by_key(
control &ctl,
InputIterator1 keys_first,
InputIterator1 keys_last,
InputIterator2 values_first,
OutputIterator1 keys_output,
OutputIterator2 values_output,
const std::string& user_code )
{
typedef std::iterator_traits<InputIterator1>::value_type kType;
typedef std::iterator_traits<OutputIterator2>::value_type ValOType;
//KeyOType init; memset(&init, 0, sizeof(KeyOType) );
equal_to <kType> binary_pred;
plus<ValOType> binary_op;
return detail::reduce_by_key_detect_random_access(
ctl,
keys_first,
keys_last,
values_first,
keys_output,
values_output,
binary_pred,
binary_op,
user_code,
std::iterator_traits< InputIterator1 >::iterator_category( )
); // return
}
namespace detail
{
/*!
* \internal
* \addtogroup detail
* \ingroup reduction
* \{
*/
enum typeName {e_kType, e_vType, e_koType, e_voType ,e_BinaryPredicate, e_BinaryFunction};
/***********************************************************************************************************************
* Kernel Template Specializer
**********************************************************************************************************************/
class ReduceByKey_KernelTemplateSpecializer : public KernelTemplateSpecializer
{
public:
ReduceByKey_KernelTemplateSpecializer() : KernelTemplateSpecializer()
{
addKernelName("perBlockScanByKey");
addKernelName("intraBlockInclusiveScanByKey");
addKernelName("perBlockAdditionByKey");
addKernelName("keyValueMapping");
}
const ::std::string operator() ( const ::std::vector<::std::string>& typeNames ) const
{
const std::string templateSpecializationString =
"// Dynamic specialization of generic template definition, using user supplied types\n"
"template __attribute__((mangled_name(" + name(0) + "Instantiated)))\n"
"__attribute__((reqd_work_group_size(KERNEL0WORKGROUPSIZE,1,1)))\n"
"__kernel void " + name(0) + "(\n"
"global " + typeNames[e_kType] + "* keys,\n"
"global " + typeNames[e_vType] + "* vals,\n"
"global " + typeNames[e_voType] + "* output,\n"
"global int * output2,\n"
"const uint vecSize,\n"
"local " + typeNames[e_kType] + "* ldsKeys,\n"
"local " + typeNames[e_voType] + "* ldsVals,\n"
"global " + typeNames[e_BinaryPredicate] + "* binaryPred,\n"
"global " + typeNames[e_BinaryFunction] + "* binaryFunct,\n"
"global " + typeNames[e_kType] + "* keyBuffer,\n"
"global " + typeNames[e_voType] + "* valBuffer\n"
");\n\n"
"// Dynamic specialization of generic template definition, using user supplied types\n"
"template __attribute__((mangled_name(" + name(1) + "Instantiated)))\n"
"__attribute__((reqd_work_group_size(KERNEL1WORKGROUPSIZE,1,1)))\n"
"__kernel void " + name(1) + "(\n"
"global " + typeNames[e_kType] + "* keySumArray,\n"
"global " + typeNames[e_voType] + "* preSumArray,\n"
"global " + typeNames[e_voType] + "* postSumArray,\n"
"const uint vecSize,\n"
"local " + typeNames[e_kType] + "* ldsKeys,\n"
"local " + typeNames[e_voType] + "* ldsVals,\n"
"const uint workPerThread,\n"
"global " + typeNames[e_BinaryPredicate] + "* binaryPred,\n"
"global " + typeNames[e_BinaryFunction] + "* binaryFunct\n"
");\n\n"
"// Dynamic specialization of generic template definition, using user supplied types\n"
"template __attribute__((mangled_name(" + name(2) + "Instantiated)))\n"
"__attribute__((reqd_work_group_size(KERNEL2WORKGROUPSIZE,1,1)))\n"
"__kernel void " + name(2) + "(\n"
"global " + typeNames[e_kType] + "* keySumArray,\n"
"global " + typeNames[e_voType] + "* postSumArray,\n"
"global " + typeNames[e_kType] + "* keys,\n"
"global int * output2,\n"
"global " + typeNames[e_voType] + "* output,\n"
"const uint vecSize,\n"
"global " + typeNames[e_BinaryPredicate] + "* binaryPred,\n"
"global " + typeNames[e_BinaryFunction] + "* binaryFunct\n"
");\n\n"
"// Dynamic specialization of generic template definition, using user supplied types\n"
"template __attribute__((mangled_name(" + name(3) + "Instantiated)))\n"
"__attribute__((reqd_work_group_size(KERNEL0WORKGROUPSIZE,1,1)))\n"
"__kernel void " + name(3) + "(\n"
"global " + typeNames[e_kType] + "*keys,\n"
"global " + typeNames[e_koType] + "*keys_output,\n"
"global " + typeNames[e_voType] + "*vals_output,\n"
"global int *offsetArray,\n"
"global " + typeNames[e_voType] + "*offsetValArray,\n"
"const uint vecSize,\n"
"const int numSections\n"
");\n\n";
return templateSpecializationString;
}
};
/***********************************************************************************************************************
* Detect Random Access
**********************************************************************************************************************/
template<
typename InputIterator1,
typename InputIterator2,
typename OutputIterator1,
typename OutputIterator2,
typename BinaryPredicate,
typename BinaryFunction>
bolt::cl::pair<OutputIterator1, OutputIterator2>
reduce_by_key_detect_random_access(
control &ctl,
const InputIterator1 keys_first,
const InputIterator1 keys_last,
const InputIterator2 values_first,
const OutputIterator1 keys_output,
const OutputIterator2 values_output,
const BinaryPredicate binary_pred,
const BinaryFunction binary_op,
const std::string& user_code,
std::input_iterator_tag )
{
// TODO: It should be possible to support non-random_access_iterator_tag iterators, if we copied the data
// to a temporary buffer. Should we?
static_assert( false, "Bolt only supports random access iterator types" );
};
template<
typename InputIterator1,
typename InputIterator2,
typename OutputIterator1,
typename OutputIterator2,
typename BinaryPredicate,
typename BinaryFunction
>
bolt::cl::pair<OutputIterator1, OutputIterator2>
reduce_by_key_detect_random_access(
control &ctl,
const InputIterator1 keys_first,
const InputIterator1 keys_last,
const InputIterator2 values_first,
const OutputIterator1 keys_output,
const OutputIterator2 values_output,
const BinaryPredicate binary_pred,
const BinaryFunction binary_op,
const std::string& user_code,
std::random_access_iterator_tag )
{
return detail::reduce_by_key_pick_iterator( ctl, keys_first, keys_last, values_first, keys_output, values_output,
binary_pred, binary_op, user_code);
}
/*!
* \brief This overload is called strictly for non-device_vector iterators
* \details This template function overload is used to seperate device_vector iterators from all other iterators
*/
template<
typename InputIterator1,
typename InputIterator2,
typename OutputIterator1,
typename OutputIterator2,
typename BinaryPredicate,
typename BinaryFunction >
typename std::enable_if<
!(std::is_base_of<typename device_vector<typename
std::iterator_traits<InputIterator1>::value_type>::iterator,InputIterator1>::value &&
std::is_base_of<typename device_vector<typename
std::iterator_traits<InputIterator2>::value_type>::iterator,InputIterator2>::value &&
std::is_base_of<typename device_vector<typename
std::iterator_traits<OutputIterator1>::value_type>::iterator,OutputIterator2>::value &&
std::is_base_of<typename device_vector<typename
std::iterator_traits<OutputIterator1>::value_type>::iterator,OutputIterator2>::value),
bolt::cl::pair<OutputIterator1, OutputIterator2> >::type
reduce_by_key_pick_iterator(
control& ctl,
const InputIterator1& keys_first,
const InputIterator1& keys_last,
const InputIterator2& values_first,
const OutputIterator1& keys_output,
const OutputIterator2& values_output,
const BinaryPredicate& binary_pred,
const BinaryFunction& binary_op,
const std::string& user_code)
{
typedef typename std::iterator_traits< InputIterator1 >::value_type kType;
typedef typename std::iterator_traits< InputIterator2 >::value_type vType;
typedef typename std::iterator_traits< OutputIterator1 >::value_type koType;
typedef typename std::iterator_traits< OutputIterator2 >::value_type voType;
static_assert( std::is_convertible< vType, voType >::value, "InputValue and Output iterators are incompatible" );
unsigned int numElements = static_cast< unsigned int >( std::distance( keys_first, keys_last ) );
if( numElements == 1 )
return bolt::cl::make_pair( keys_last, values_first+numElements );
bolt::cl::control::e_RunMode runMode = ctl.getForceRunMode(); // could be dynamic choice some day.
if(runMode == bolt::cl::control::Automatic)
{
runMode = ctl.getDefaultPathToRun();
}
unsigned int sizeOfOut;
{
// Map the input iterator to a device_vector
device_vector< kType > dvKeys( keys_first, keys_last, CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, ctl );
device_vector< vType > dvValues( values_first, numElements, CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, true, ctl );
device_vector< koType > dvKOutput( keys_output, numElements, CL_MEM_USE_HOST_PTR | CL_MEM_WRITE_ONLY, false, ctl );
device_vector< voType > dvVOutput( values_output, numElements, CL_MEM_USE_HOST_PTR | CL_MEM_WRITE_ONLY, false, ctl );
//Now call the actual cl algorithm
sizeOfOut = reduce_by_key_enqueue( ctl, dvKeys.begin( ), dvKeys.end( ), dvValues.begin(), dvKOutput.begin( ),dvVOutput.end( ), binary_pred, binary_op, user_code);
// This should immediately map/unmap the buffer
dvKOutput.data( );
dvVOutput.data( );
}
return bolt::cl::make_pair(keys_output+sizeOfOut, values_output+sizeOfOut);
}
/*!
* \brief This overload is called strictly for device_vector iterators
* \details This template function overload is used to seperate device_vector iterators from all other iterators
*/
template<
typename DVInputIterator1,
typename DVInputIterator2,
typename DVOutputIterator1,
typename DVOutputIterator2,
typename BinaryPredicate,
typename BinaryFunction >
typename std::enable_if<
(std::is_base_of<typename device_vector<typename
std::iterator_traits<DVInputIterator1>::value_type>::iterator,DVInputIterator1>::value &&
std::is_base_of<typename device_vector<typename
std::iterator_traits<DVInputIterator2>::value_type>::iterator,DVInputIterator2>::value &&
std::is_base_of<typename device_vector<typename
std::iterator_traits<DVOutputIterator1>::value_type>::iterator,DVOutputIterator1>::value &&
std::is_base_of<typename device_vector<typename
std::iterator_traits<DVOutputIterator2>::value_type>::iterator,DVOutputIterator2>::value),
bolt::cl::pair<DVOutputIterator1, DVOutputIterator2> >::type
reduce_by_key_pick_iterator(
control& ctl,
const DVInputIterator1& keys_first,
const DVInputIterator1& keys_last,
const DVInputIterator2& values_first,
const DVOutputIterator1& keys_output,
const DVOutputIterator2& values_output,
const BinaryPredicate& binary_pred,
const BinaryFunction& binary_op,
const std::string& user_code)
{
typedef typename std::iterator_traits< DVInputIterator1 >::value_type kType;
typedef typename std::iterator_traits< DVInputIterator2 >::value_type vType;
typedef typename std::iterator_traits< DVOutputIterator1 >::value_type koType;
typedef typename std::iterator_traits< DVOutputIterator2 >::value_type voType;
static_assert( std::is_convertible< vType, voType >::value, "InputValue and Output iterators are incompatible" );
unsigned int numElements = static_cast< unsigned int >( std::distance( keys_first, keys_last ) );
if( numElements < 1 )
return void;
const bolt::cl::control::e_RunMode runMode = ctl.forceRunMode( ); // could be dynamic choice some day.
if( runMode == bolt::cl::control::SerialCpu )
{
// TODO: Need access to the device_vector .data method to get a host pointer
throw ::cl::Error( CL_INVALID_DEVICE, "ReduceByKey device_vector CPU device not implemented" );
return void;
}
else if( runMode == bolt::cl::control::MultiCoreCpu )
{
// TODO: Need access to the device_vector .data method to get a host pointer
throw ::cl::Error( CL_INVALID_DEVICE, "ReduceByKey device_vector CPU device not implemented" );
return void;
}
//Now call the actual cl algorithm
unsigned int sizeOfOut = reduce_by_key_enqueue( ctl, keys_first, keys_last, values_first, keys_output,
values_output, binary_pred, binary_op, user_code);
return bolt::cl::make_pair(keys_output+sizeOfOut, values_output+sizeOfOut);
}
// All calls to reduce_by_key end up here, unless an exception was thrown
// This is the function that sets up the kernels to compile (once only) and execute
template<
typename DVInputIterator1,
typename DVInputIterator2,
typename DVOutputIterator1,
typename DVOutputIterator2,
typename BinaryPredicate,
typename BinaryFunction >
unsigned int
reduce_by_key_enqueue(
control& ctl,
const DVInputIterator1& keys_first,
const DVInputIterator1& keys_last,
const DVInputIterator2& values_first,
const DVOutputIterator1& keys_output,
const DVOutputIterator2& values_output,
const BinaryPredicate& binary_pred,
const BinaryFunction& binary_op,
const std::string& user_code)
{
cl_int l_Error;
/**********************************************************************************
* Type Names - used in KernelTemplateSpecializer
*********************************************************************************/
typedef typename std::iterator_traits< DVInputIterator1 >::value_type kType;
typedef typename std::iterator_traits< DVInputIterator2 >::value_type vType;
typedef typename std::iterator_traits< DVOutputIterator1 >::value_type koType;
typedef typename std::iterator_traits< DVOutputIterator2 >::value_type voType;
std::vector<std::string> typeNames(6);
typeNames[e_kType] = TypeName< kType >::get( );
typeNames[e_vType] = TypeName< vType >::get( );
typeNames[e_koType] = TypeName< koType >::get( );
typeNames[e_voType] = TypeName< voType >::get( );
typeNames[e_BinaryPredicate] = TypeName< BinaryPredicate >::get( );
typeNames[e_BinaryFunction] = TypeName< BinaryFunction >::get( );
/**********************************************************************************
* Type Definitions - directly concatenated into kernel string
*********************************************************************************/
/*std::vector<std::string> typeDefs; // try substituting a map
typeDefs.push_back( ClCode< kType >::get() );
if (TypeName< vType >::get() != TypeName< kType >::get())
{
typeDefs.push_back( ClCode< vType >::get() );
}
if (TypeName< oType >::get() != TypeName< kType >::get() &&
TypeName< oType >::get() != TypeName< vType >::get())
{
typeDefs.push_back( ClCode< oType >::get() );
}
typeDefs.push_back( ClCode< BinaryPredicate >::get() );
typeDefs.push_back( ClCode< BinaryFunction >::get() );*/
std::vector<std::string> typeDefs; // typeDefs must be unique and order does matter
PUSH_BACK_UNIQUE( typeDefs, ClCode< kType >::get() )
PUSH_BACK_UNIQUE( typeDefs, ClCode< vType >::get() )
PUSH_BACK_UNIQUE( typeDefs, ClCode< koType >::get() )
PUSH_BACK_UNIQUE( typeDefs, ClCode< voType >::get() )
PUSH_BACK_UNIQUE( typeDefs, ClCode< BinaryPredicate >::get() )
PUSH_BACK_UNIQUE( typeDefs, ClCode< BinaryFunction >::get() )
/**********************************************************************************
* Compile Options
*********************************************************************************/
bool cpuDevice = ctl.getDevice().getInfo<CL_DEVICE_TYPE>() == CL_DEVICE_TYPE_CPU;
//std::cout << "Device is CPU: " << (cpuDevice?"TRUE":"FALSE") << std::endl;
const size_t kernel0_WgSize = (cpuDevice) ? 1 : WAVESIZE*KERNEL02WAVES;
const size_t kernel1_WgSize = (cpuDevice) ? 1 : WAVESIZE*KERNEL1WAVES;
const size_t kernel2_WgSize = (cpuDevice) ? 1 : WAVESIZE*KERNEL02WAVES;
std::string compileOptions;
std::ostringstream oss;
oss << " -DKERNEL0WORKGROUPSIZE=" << kernel0_WgSize;
oss << " -DKERNEL1WORKGROUPSIZE=" << kernel1_WgSize;
oss << " -DKERNEL2WORKGROUPSIZE=" << kernel2_WgSize;
compileOptions = oss.str();
/**********************************************************************************
* Request Compiled Kernels
*********************************************************************************/
ReduceByKey_KernelTemplateSpecializer ts_kts;
std::vector< ::cl::Kernel > kernels = bolt::cl::getKernels(
ctl,
typeNames,
&ts_kts,
typeDefs,
reduce_by_key_kernels,
compileOptions);
// kernels returned in same order as added in KernelTemplaceSpecializer constructor
// for profiling
::cl::Event kernel0Event, kernel1Event, kernel2Event, kernelAEvent, kernel3Event;
// Set up shape of launch grid and buffers:
int computeUnits = ctl.getDevice( ).getInfo< CL_DEVICE_MAX_COMPUTE_UNITS >( );
int wgPerComputeUnit = ctl.getWGPerComputeUnit( );
int resultCnt = computeUnits * wgPerComputeUnit;
// Ceiling function to bump the size of input to the next whole wavefront size
cl_uint numElements = static_cast< cl_uint >( std::distance( keys_first, keys_last ) );
device_vector< kType >::size_type sizeInputBuff = numElements;
size_t modWgSize = (sizeInputBuff & (kernel0_WgSize-1));
if( modWgSize )
{
sizeInputBuff &= ~modWgSize;
sizeInputBuff += kernel0_WgSize;
}
cl_uint numWorkGroupsK0 = static_cast< cl_uint >( sizeInputBuff / kernel0_WgSize );
// Ceiling function to bump the size of the sum array to the next whole wavefront size
device_vector< kType >::size_type sizeScanBuff = numWorkGroupsK0;
modWgSize = (sizeScanBuff & (kernel0_WgSize-1));
if( modWgSize )
{
sizeScanBuff &= ~modWgSize;
sizeScanBuff += kernel0_WgSize;
}
// Create buffer wrappers so we can access the host functors, for read or writing in the kernel
ALIGNED( 256 ) BinaryPredicate aligned_binary_pred( binary_pred );
control::buffPointer binaryPredicateBuffer = ctl.acquireBuffer( sizeof( aligned_binary_pred ),
CL_MEM_USE_HOST_PTR|CL_MEM_READ_ONLY, &aligned_binary_pred );
ALIGNED( 256 ) BinaryFunction aligned_binary_op( binary_op );
control::buffPointer binaryFunctionBuffer = ctl.acquireBuffer( sizeof( aligned_binary_op ),
CL_MEM_USE_HOST_PTR|CL_MEM_READ_ONLY, &aligned_binary_op );
control::buffPointer keySumArray = ctl.acquireBuffer( sizeScanBuff*sizeof( kType ) );
control::buffPointer preSumArray = ctl.acquireBuffer( sizeScanBuff*sizeof( voType ) );
control::buffPointer postSumArray = ctl.acquireBuffer( sizeScanBuff*sizeof( voType ) );
control::buffPointer offsetArray = ctl.acquireBuffer( numElements *sizeof( int ) );
control::buffPointer offsetValArray = ctl.acquireBuffer( numElements *sizeof( voType ) );
cl_uint ldsKeySize, ldsValueSize;
//Fill the buffer with zeros
::cl::Event fillEvent;
ctl.getCommandQueue().enqueueFillBuffer( *offsetArray, 0, 0, numElements *sizeof( int ), NULL, &fillEvent);
bolt::cl::wait(ctl, fillEvent);
/**********************************************************************************
* Kernel 0
*********************************************************************************/
try
{
ldsKeySize = static_cast< cl_uint >( kernel0_WgSize * sizeof( kType ) );
ldsValueSize = static_cast< cl_uint >( kernel0_WgSize * sizeof( voType ) );
V_OPENCL( kernels[0].setArg( 0, keys_first.getBuffer()), "Error setArg kernels[ 0 ]" ); // Input keys
V_OPENCL( kernels[0].setArg( 1, values_first.getBuffer()),"Error setArg kernels[ 0 ]" ); // Input values
V_OPENCL( kernels[0].setArg( 2, *offsetValArray ), "Error setArg kernels[ 0 ]" ); // Output values
V_OPENCL( kernels[0].setArg( 3, *offsetArray ), "Error setArg kernels[ 0 ]" ); // Output keys
V_OPENCL( kernels[0].setArg( 4, numElements ), "Error setArg kernels[ 0 ]" ); // vecSize
V_OPENCL( kernels[0].setArg( 5, ldsKeySize, NULL ), "Error setArg kernels[ 0 ]" ); // Scratch buffer
V_OPENCL( kernels[0].setArg( 6, ldsValueSize, NULL ), "Error setArg kernels[ 0 ]" ); // Scratch buffer
V_OPENCL( kernels[0].setArg( 7, *binaryPredicateBuffer),"Error setArg kernels[ 0 ]" ); // User provided functor
V_OPENCL( kernels[0].setArg( 8, *binaryFunctionBuffer ),"Error setArg kernels[ 0 ]" ); // User provided functor
V_OPENCL( kernels[0].setArg( 9, *keySumArray ), "Error setArg kernels[ 0 ]" ); // Output per block sum
V_OPENCL( kernels[0].setArg( 10, *preSumArray ), "Error setArg kernels[ 0 ]" ); // Output per block sum
l_Error = ctl.getCommandQueue( ).enqueueNDRangeKernel(
kernels[0],
::cl::NullRange,
::cl::NDRange( sizeInputBuff ),
::cl::NDRange( kernel0_WgSize ),
NULL,
&kernel0Event);
V_OPENCL( l_Error, "enqueueNDRangeKernel() failed for kernel[0]" );
}
catch( const ::cl::Error& e)
{
std::cerr << "::cl::enqueueNDRangeKernel( 0 ) in bolt::cl::reduce_by_key_enqueue()" << std::endl;
std::cerr << "Error Code: " << clErrorStringA(e.err()) << " (" << e.err() << ")" << std::endl;
std::cerr << "File: " << __FILE__ << ", line " << __LINE__ << std::endl;
std::cerr << "Error String: " << e.what() << std::endl;
}
/**********************************************************************************
* Kernel 1
*********************************************************************************/
cl_uint workPerThread = static_cast< cl_uint >( sizeScanBuff / kernel1_WgSize );
V_OPENCL( kernels[1].setArg( 0, *keySumArray ), "Error setArg kernels[ 1 ]" ); // Input keys
V_OPENCL( kernels[1].setArg( 1, *preSumArray ), "Error setArg kernels[ 1 ]" ); // Input buffer
V_OPENCL( kernels[1].setArg( 2, *postSumArray ), "Error setArg kernels[ 1 ]" ); // Output buffer
V_OPENCL( kernels[1].setArg( 3, numWorkGroupsK0 ), "Error setArg kernels[ 1 ]" ); // Size of scratch buffer
V_OPENCL( kernels[1].setArg( 4, ldsKeySize, NULL ), "Error setArg kernels[ 1 ]" ); // Scratch buffer
V_OPENCL( kernels[1].setArg( 5, ldsValueSize, NULL ), "Error setArg kernels[ 1 ]" ); // Scratch buffer
V_OPENCL( kernels[1].setArg( 6, workPerThread ), "Error setArg kernels[ 1 ]" ); // Work Per Thread
V_OPENCL( kernels[1].setArg( 7, *binaryPredicateBuffer ),"Error setArg kernels[ 1 ]" ); // User provided functor
V_OPENCL( kernels[1].setArg( 8, *binaryFunctionBuffer ),"Error setArg kernels[ 1 ]" ); // User provided functor
try
{
l_Error = ctl.getCommandQueue( ).enqueueNDRangeKernel(
kernels[1],
::cl::NullRange,
::cl::NDRange( kernel1_WgSize ), // only 1 work-group
::cl::NDRange( kernel1_WgSize ),
NULL,
&kernel1Event);
V_OPENCL( l_Error, "enqueueNDRangeKernel() failed for kernel[1]" );
}
catch( const ::cl::Error& e)
{
std::cerr << "::cl::enqueueNDRangeKernel( 1 ) in bolt::cl::reduce_by_key_enqueue()" << std::endl;
std::cerr << "Error Code: " << clErrorStringA(e.err()) << " (" << e.err() << ")" << std::endl;
std::cerr << "File: " << __FILE__ << ", line " << __LINE__ << std::endl;
std::cerr << "Error String: " << e.what() << std::endl;
}
#if ENABLE_PRINTS
//delete this code -start
bolt::cl::wait(ctl, kernel0Event);
bolt::cl::wait(ctl, kernel1Event);
::cl::Event l_mapEvent_k1;
voType *post_sum_k1= (voType*)ctl.commandQueue().enqueueMapBuffer( *postSumArray,
false,
CL_MAP_READ,
0,
sizeof(voType)*sizeScanBuff,
NULL,
&l_mapEvent_k1,
&l_Error );
V_OPENCL( l_Error, "Error calling map on the result buffer" );
std::cout<<"Myval-------------------------starts"<<std::endl;
std::ofstream postsum("postsum.txt");
for(unsigned int i = 0; i < sizeScanBuff ; i++)
{
postsum<<post_sum_k1[i]<<std::endl;
}
postsum.close();
std::cout<<"Myval-------------------------ends"<<std::endl;
bolt::cl::wait(ctl, l_mapEvent_k1);
//delete this code -end
#endif
/**********************************************************************************
* Kernel 2
*********************************************************************************/
V_OPENCL( kernels[2].setArg( 0, *keySumArray ), "Error setArg kernels[ 2 ]" ); // Input buffer
V_OPENCL( kernels[2].setArg( 1, *postSumArray ), "Error setArg kernels[ 2 ]" ); // Input buffer
V_OPENCL( kernels[2].setArg( 2, keys_first.getBuffer()), "Error setArg kernels[ 2 ]" ); // Output buffer
V_OPENCL( kernels[2].setArg( 3, *offsetArray), "Error setArg kernels[ 2 ]" ); // Output buffer
V_OPENCL( kernels[2].setArg( 4, *offsetValArray), "Error setArg kernels[ 2 ]" ); // Output buffer
V_OPENCL( kernels[2].setArg( 5, numElements ), "Error setArg kernels[ 2 ]" ); // Size of scratch buffer
V_OPENCL( kernels[2].setArg( 6, *binaryPredicateBuffer ),"Error setArg kernels[ 2 ]" ); // User provided functor
V_OPENCL( kernels[2].setArg( 7, *binaryFunctionBuffer ),"Error setArg kernels[ 2 ]" ); // User provided functor
try
{
l_Error = ctl.getCommandQueue( ).enqueueNDRangeKernel(
kernels[2],
::cl::NullRange,
::cl::NDRange( sizeInputBuff ),
::cl::NDRange( kernel2_WgSize ),
NULL,
&kernel2Event );
V_OPENCL( l_Error, "enqueueNDRangeKernel() failed for kernel[2]" );
}
catch( const ::cl::Error& e)
{
std::cerr << "::cl::enqueueNDRangeKernel( 2 ) in bolt::cl::reduce_by_key_enqueue()" << std::endl;
std::cerr << "Error Code: " << clErrorStringA(e.err()) << " (" << e.err() << ")" << std::endl;
std::cerr << "File: " << __FILE__ << ", line " << __LINE__ << std::endl;
std::cerr << "Error String: " << e.what() << std::endl;
}
// wait for results
l_Error = kernel2Event.wait( );
V_OPENCL( l_Error, "post-kernel[2] failed wait" );
//
// Now take the output keys and increment each non-zero value from previous value.
// This is done serially. It doesn't look GPU friendly.
//
::cl::Event l_mapEvent;
int *h_result = (int*)ctl.getCommandQueue().enqueueMapBuffer( *offsetArray,
false,
CL_MAP_READ | CL_MAP_WRITE,
0,
sizeof(int)*numElements,
NULL,
&l_mapEvent,
&l_Error );
V_OPENCL( l_Error, "Error calling map on the result buffer" );
bolt::cl::wait(ctl, l_mapEvent);
#if ENABLE_PRINTS
//delete this code -start
::cl::Event l_mapEvent2;
voType *v_result = (voType*)ctl.commandQueue().enqueueMapBuffer( *offsetValArray,
false,
CL_MAP_READ,
0,
sizeof(voType)*numElements,
NULL,
&l_mapEvent2,
&l_Error );
V_OPENCL( l_Error, "Error calling map on the result buffer" );
std::cout<<"Myval-------------------------starts"<<std::endl;
std::ofstream val_result("offsetValArray.txt");
val_result<<numElements<<std::endl;
for(unsigned int i = 0; i < LENGTH_TEST ; i++)
{
val_result<<v_result[i]<<std::endl;
}
val_result.close();
std::cout<<"Myval-------------------------ends"<<std::endl;
bolt::cl::wait(ctl, l_mapEvent2);
//delete this code -end
std::ofstream result_b4_ser("result_b4_ser.txt");
for(unsigned int i = 0; i < LENGTH_TEST ; i++)
{
//std::cout<<h_result[i]<<std::endl;
result_b4_ser<<h_result[i]<<std::endl;
}
result_b4_ser.close();
#endif
// Doing this serially; Performance killer!!
unsigned int count_number_of_sections = 0;
//h_result [ numElements - 1 ] = 1; //This is a quick fix!
for( unsigned int i = 0; i < numElements; i++ )
{
if(h_result[i]>0)
{
h_result[i] = count_number_of_sections;
count_number_of_sections++;
}
}
#if ENABLE_PRINTS
std::cout<<count_number_of_sections<<std::endl;
std::ofstream result_file("offsetArray.txt");
for(unsigned int i = 0; i < LENGTH_TEST ; i++)
{
result_file<<h_result[i]<<std::endl;
}
result_file.close();
#endif
//
// Now unmap it. We map the indices back to keys_output using "keys_output"
//
::cl::Event l_unmapEvent;
cl_int l_unmapError = CL_SUCCESS;
l_unmapError = ctl.getCommandQueue().enqueueUnmapMemObject( *offsetArray , h_result, NULL, &l_unmapEvent );
V_OPENCL( l_unmapError, "device_vector failed to unmap host memory back to device memory" );
//V_OPENCL( l_unmapEvent.wait( ), "failed to wait for unmap event" );
bolt::cl::wait(ctl, l_unmapEvent);
/**********************************************************************************
* Kernel 3
*********************************************************************************/
V_OPENCL( kernels[3].setArg( 0, keys_first.getBuffer()), "Error setArg kernels[ 3 ]" ); // Input buffer
V_OPENCL( kernels[3].setArg( 1, keys_output.getBuffer() ), "Error setArg kernels[ 3 ]" ); // Output buffer
V_OPENCL( kernels[3].setArg( 2, values_output.getBuffer()), "Error setArg kernels[ 3 ]" ); // Output buffer
V_OPENCL( kernels[3].setArg( 3, *offsetArray), "Error setArg kernels[ 3 ]" ); // Input buffer
V_OPENCL( kernels[3].setArg( 4, *offsetValArray), "Error setArg kernels[ 3 ]" );
V_OPENCL( kernels[3].setArg( 5, numElements ), "Error setArg kernels[ 3 ]" ); // Size of scratch buffer
V_OPENCL( kernels[3].setArg( 6, count_number_of_sections), "Error setArg kernels[ 3 ]" ); // Size of scratch buffer
try
{
l_Error = ctl.getCommandQueue( ).enqueueNDRangeKernel(
kernels[3],
::cl::NullRange,
::cl::NDRange( sizeInputBuff ),
::cl::NDRange( kernel0_WgSize ),
NULL,
&kernel3Event );
V_OPENCL( l_Error, "enqueueNDRangeKernel() failed for kernel[3]" );
}
catch( const ::cl::Error& e)
{
std::cerr << "::cl::enqueueNDRangeKernel( 3 ) in bolt::cl::reduce_by_key_enqueue()" << std::endl;
std::cerr << "Error Code: " << clErrorStringA(e.err()) << " (" << e.err() << ")" << std::endl;
std::cerr << "File: " << __FILE__ << ", line " << __LINE__ << std::endl;
std::cerr << "Error String: " << e.what() << std::endl;
}
// wait for results
l_Error = kernel3Event.wait( );
V_OPENCL( l_Error, "post-kernel[3] failed wait" );
#if ENABLE_PRINTS
//delete this code -start
::cl::Event l_mapEvent3;
voType *v_result2 = (voType*)ctl.commandQueue().enqueueMapBuffer( *offsetValArray,
false,
CL_MAP_READ,
0,
sizeof(voType)*numElements,
NULL,
&l_mapEvent3,
&l_Error );
V_OPENCL( l_Error, "Error calling map on the result buffer" );
std::cout<<"Myval-------------------------starts"<<std::endl;
std::ofstream result_val_after_launch("result_val_after_launch.txt");
for(unsigned int i = 0; i < LENGTH_TEST ; i++)
{
result_val_after_launch<<v_result2[i]<<std::endl;
}
result_val_after_launch.close();
std::cout<<"Myval-------------------------ends"<<std::endl;
bolt::cl::wait(ctl, l_mapEvent3);
//delete this code -end
#endif
return count_number_of_sections;
} //end of reduce_by_key_enqueue( )
/*! \} */
} //namespace detail
} //namespace cl
} //namespace bolt
#endif
| 43.716842 | 170 | 0.584383 | [
"shape",
"vector"
] |
b4691f0b97e888c70699d2f917d581c5aa186202 | 50,894 | cpp | C++ | src/core/thread/mesh_forwarder.cpp | tpmanley/openthread | bc02c6c05cf52884bc6cd9fad8dc8fc16364a147 | [
"BSD-3-Clause"
] | 1 | 2020-05-25T19:19:55.000Z | 2020-05-25T19:19:55.000Z | src/core/thread/mesh_forwarder.cpp | tpmanley/openthread | bc02c6c05cf52884bc6cd9fad8dc8fc16364a147 | [
"BSD-3-Clause"
] | 1 | 2020-02-05T08:54:11.000Z | 2020-02-05T08:54:11.000Z | src/core/thread/mesh_forwarder.cpp | tpmanley/openthread | bc02c6c05cf52884bc6cd9fad8dc8fc16364a147 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2016, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* This file implements mesh forwarding of IPv6/6LoWPAN messages.
*/
#include "mesh_forwarder.hpp"
#include "common/code_utils.hpp"
#include "common/debug.hpp"
#include "common/encoding.hpp"
#include "common/instance.hpp"
#include "common/locator-getters.hpp"
#include "common/logging.hpp"
#include "common/message.hpp"
#include "common/random.hpp"
#include "net/ip6.hpp"
#include "net/ip6_filter.hpp"
#include "net/netif.hpp"
#include "net/tcp.hpp"
#include "net/udp6.hpp"
#include "radio/radio.hpp"
#include "thread/mle.hpp"
#include "thread/mle_router.hpp"
#include "thread/thread_netif.hpp"
using ot::Encoding::BigEndian::HostSwap16;
namespace ot {
MeshForwarder::MeshForwarder(Instance &aInstance)
: InstanceLocator(aInstance)
, mDiscoverTimer(aInstance, &MeshForwarder::HandleDiscoverTimer, this)
, mUpdateTimer(aInstance, &MeshForwarder::HandleUpdateTimer, this)
, mMessageNextOffset(0)
, mSendMessage(NULL)
, mMeshSource()
, mMeshDest()
, mAddMeshHeader(false)
, mSendBusy(false)
, mScheduleTransmissionTask(aInstance, ScheduleTransmissionTask, this)
, mEnabled(false)
, mScanChannels(0)
, mScanChannel(0)
, mRestorePanId(Mac::kPanIdBroadcast)
, mScanning(false)
#if OPENTHREAD_FTD
, mIndirectSender(aInstance)
#endif
, mDataPollSender(aInstance)
{
mFragTag = Random::NonCrypto::GetUint16();
ResetCounters();
#if OPENTHREAD_FTD
memset(mFragmentEntries, 0, sizeof(mFragmentEntries));
#endif
}
void MeshForwarder::Start(void)
{
if (!mEnabled)
{
Get<Mac::Mac>().SetRxOnWhenIdle(true);
#if OPENTHREAD_FTD
mIndirectSender.Start();
#endif
mEnabled = true;
}
}
void MeshForwarder::Stop(void)
{
Message *message;
VerifyOrExit(mEnabled);
mDataPollSender.StopPolling();
mUpdateTimer.Stop();
if (mScanning)
{
HandleDiscoverComplete();
}
while ((message = mSendQueue.GetHead()) != NULL)
{
mSendQueue.Dequeue(*message);
message->Free();
}
while ((message = mReassemblyList.GetHead()) != NULL)
{
mReassemblyList.Dequeue(*message);
message->Free();
}
#if OPENTHREAD_FTD
mIndirectSender.Stop();
memset(mFragmentEntries, 0, sizeof(mFragmentEntries));
#endif
mEnabled = false;
mSendMessage = NULL;
Get<Mac::Mac>().SetRxOnWhenIdle(false);
exit:
return;
}
void MeshForwarder::RemoveMessage(Message &aMessage)
{
#if OPENTHREAD_FTD
for (ChildTable::Iterator iter(GetInstance(), Child::kInStateAnyExceptInvalid); !iter.IsDone(); iter++)
{
IgnoreReturnValue(mIndirectSender.RemoveMessageFromSleepyChild(aMessage, *iter.GetChild()));
}
#endif
if (mSendMessage == &aMessage)
{
mSendMessage = NULL;
}
mSendQueue.Dequeue(aMessage);
LogMessage(kMessageEvict, aMessage, NULL, OT_ERROR_NO_BUFS);
aMessage.Free();
}
void MeshForwarder::ScheduleTransmissionTask(Tasklet &aTasklet)
{
aTasklet.GetOwner<MeshForwarder>().ScheduleTransmissionTask();
}
void MeshForwarder::ScheduleTransmissionTask(void)
{
VerifyOrExit(!mSendBusy);
mSendMessage = GetDirectTransmission();
VerifyOrExit(mSendMessage != NULL);
if (mSendMessage->GetOffset() == 0)
{
mSendMessage->SetTxSuccess(true);
}
Get<Mac::Mac>().RequestDirectFrameTransmission();
exit:
return;
}
otError MeshForwarder::PrepareDiscoverRequest(void)
{
otError error = OT_ERROR_NONE;
VerifyOrExit(!mScanning);
mScanChannel = Mac::ChannelMask::kChannelIteratorFirst;
mRestorePanId = Get<Mac::Mac>().GetPanId();
mScanning = true;
if (mScanChannels.GetNextChannel(mScanChannel) != OT_ERROR_NONE)
{
HandleDiscoverComplete();
ExitNow(error = OT_ERROR_DROP);
}
exit:
return error;
}
Message *MeshForwarder::GetDirectTransmission(void)
{
Message *curMessage, *nextMessage;
otError error = OT_ERROR_NONE;
for (curMessage = mSendQueue.GetHead(); curMessage; curMessage = nextMessage)
{
if (!curMessage->GetDirectTransmission())
{
nextMessage = curMessage->GetNext();
continue;
}
curMessage->SetDoNotEvict(true);
switch (curMessage->GetType())
{
case Message::kTypeIp6:
error = UpdateIp6Route(*curMessage);
if (curMessage->GetSubType() == Message::kSubTypeMleDiscoverRequest)
{
error = PrepareDiscoverRequest();
}
break;
#if OPENTHREAD_FTD
case Message::kType6lowpan:
error = UpdateMeshRoute(*curMessage);
break;
#endif
default:
error = OT_ERROR_DROP;
break;
}
curMessage->SetDoNotEvict(false);
// the next message may have been evicted during processing (e.g. due to Address Solicit)
nextMessage = curMessage->GetNext();
switch (error)
{
case OT_ERROR_NONE:
ExitNow();
#if OPENTHREAD_FTD
case OT_ERROR_ADDRESS_QUERY:
mSendQueue.Dequeue(*curMessage);
mResolvingQueue.Enqueue(*curMessage);
continue;
#endif
default:
mSendQueue.Dequeue(*curMessage);
LogMessage(kMessageDrop, *curMessage, NULL, error);
curMessage->Free();
continue;
}
}
exit:
return curMessage;
}
otError MeshForwarder::UpdateIp6Route(Message &aMessage)
{
Mle::MleRouter &mle = Get<Mle::MleRouter>();
otError error = OT_ERROR_NONE;
Ip6::Header ip6Header;
mAddMeshHeader = false;
aMessage.Read(0, sizeof(ip6Header), &ip6Header);
VerifyOrExit(!ip6Header.GetSource().IsMulticast(), error = OT_ERROR_DROP);
GetMacSourceAddress(ip6Header.GetSource(), mMacSource);
if (mle.GetRole() == OT_DEVICE_ROLE_DISABLED || mle.GetRole() == OT_DEVICE_ROLE_DETACHED)
{
if (ip6Header.GetDestination().IsLinkLocal() || ip6Header.GetDestination().IsLinkLocalMulticast())
{
GetMacDestinationAddress(ip6Header.GetDestination(), mMacDest);
}
else
{
error = OT_ERROR_DROP;
}
ExitNow();
}
if (ip6Header.GetDestination().IsMulticast())
{
// With the exception of MLE multicasts, an End Device
// transmits multicasts, as IEEE 802.15.4 unicasts to its
// parent.
if (mle.GetRole() == OT_DEVICE_ROLE_CHILD && !aMessage.IsSubTypeMle())
{
mMacDest.SetShort(mle.GetNextHop(Mac::kShortAddrBroadcast));
}
else
{
mMacDest.SetShort(Mac::kShortAddrBroadcast);
}
}
else if (ip6Header.GetDestination().IsLinkLocal())
{
GetMacDestinationAddress(ip6Header.GetDestination(), mMacDest);
}
else if (mle.IsMinimalEndDevice())
{
mMacDest.SetShort(mle.GetNextHop(Mac::kShortAddrBroadcast));
}
else
{
#if OPENTHREAD_FTD
error = UpdateIp6RouteFtd(ip6Header);
#else
assert(false);
#endif
}
exit:
return error;
}
bool MeshForwarder::GetRxOnWhenIdle(void) const
{
return Get<Mac::Mac>().GetRxOnWhenIdle();
}
void MeshForwarder::SetRxOnWhenIdle(bool aRxOnWhenIdle)
{
Get<Mac::Mac>().SetRxOnWhenIdle(aRxOnWhenIdle);
if (aRxOnWhenIdle)
{
mDataPollSender.StopPolling();
Get<Utils::SupervisionListener>().Stop();
}
else
{
mDataPollSender.StartPolling();
Get<Utils::SupervisionListener>().Start();
}
}
void MeshForwarder::GetMacSourceAddress(const Ip6::Address &aIp6Addr, Mac::Address &aMacAddr)
{
aIp6Addr.ToExtAddress(aMacAddr);
if (aMacAddr.GetExtended() != Get<Mac::Mac>().GetExtAddress())
{
aMacAddr.SetShort(Get<Mac::Mac>().GetShortAddress());
}
}
void MeshForwarder::GetMacDestinationAddress(const Ip6::Address &aIp6Addr, Mac::Address &aMacAddr)
{
if (aIp6Addr.IsMulticast())
{
aMacAddr.SetShort(Mac::kShortAddrBroadcast);
}
else if (aIp6Addr.mFields.m16[0] == HostSwap16(0xfe80) && aIp6Addr.mFields.m16[1] == HostSwap16(0x0000) &&
aIp6Addr.mFields.m16[2] == HostSwap16(0x0000) && aIp6Addr.mFields.m16[3] == HostSwap16(0x0000) &&
aIp6Addr.mFields.m16[4] == HostSwap16(0x0000) && aIp6Addr.mFields.m16[5] == HostSwap16(0x00ff) &&
aIp6Addr.mFields.m16[6] == HostSwap16(0xfe00))
{
aMacAddr.SetShort(HostSwap16(aIp6Addr.mFields.m16[7]));
}
else if (Get<Mle::MleRouter>().IsRoutingLocator(aIp6Addr))
{
aMacAddr.SetShort(HostSwap16(aIp6Addr.mFields.m16[7]));
}
else
{
aIp6Addr.ToExtAddress(aMacAddr);
}
}
otError MeshForwarder::DecompressIp6Header(const uint8_t * aFrame,
uint16_t aFrameLength,
const Mac::Address &aMacSource,
const Mac::Address &aMacDest,
Ip6::Header & aIp6Header,
uint8_t & aHeaderLength,
bool & aNextHeaderCompressed)
{
otError error = OT_ERROR_NONE;
const uint8_t * start = aFrame;
Lowpan::FragmentHeader fragmentHeader;
uint16_t fragmentHeaderLength;
int headerLength;
if (fragmentHeader.ParseFrom(aFrame, aFrameLength, fragmentHeaderLength) == OT_ERROR_NONE)
{
// Only the first fragment header is followed by a LOWPAN_IPHC header
VerifyOrExit(fragmentHeader.GetDatagramOffset() == 0, error = OT_ERROR_NOT_FOUND);
aFrame += fragmentHeaderLength;
aFrameLength -= fragmentHeaderLength;
}
VerifyOrExit(aFrameLength >= 1 && Lowpan::Lowpan::IsLowpanHc(aFrame), error = OT_ERROR_NOT_FOUND);
headerLength = Get<Lowpan::Lowpan>().DecompressBaseHeader(aIp6Header, aNextHeaderCompressed, aMacSource, aMacDest,
aFrame, aFrameLength);
VerifyOrExit(headerLength > 0, error = OT_ERROR_PARSE);
aHeaderLength = static_cast<uint8_t>(aFrame - start) + static_cast<uint8_t>(headerLength);
exit:
return error;
}
otError MeshForwarder::HandleFrameRequest(Mac::TxFrame &aFrame)
{
otError error = OT_ERROR_NONE;
VerifyOrExit(mEnabled, error = OT_ERROR_ABORT);
VerifyOrExit(mSendMessage != NULL, error = OT_ERROR_ABORT);
mSendBusy = true;
switch (mSendMessage->GetType())
{
case Message::kTypeIp6:
if (mSendMessage->GetSubType() == Message::kSubTypeMleDiscoverRequest)
{
SuccessOrExit(error = Get<Mac::Mac>().SetTemporaryChannel(mScanChannel));
aFrame.SetChannel(mScanChannel);
// In case a specific PAN ID of a Thread Network to be discovered is not known, Discovery
// Request messages MUST have the Destination PAN ID in the IEEE 802.15.4 MAC header set
// to be the Broadcast PAN ID (0xFFFF) and the Source PAN ID set to a randomly generated
// value.
if (mSendMessage->GetPanId() == Mac::kPanIdBroadcast && Get<Mac::Mac>().GetPanId() == Mac::kPanIdBroadcast)
{
Get<Mac::Mac>().SetPanId(Mac::GenerateRandomPanId());
}
}
mMessageNextOffset =
PrepareDataFrame(aFrame, *mSendMessage, mMacSource, mMacDest, mAddMeshHeader, mMeshSource, mMeshDest);
if ((mSendMessage->GetSubType() == Message::kSubTypeMleChildIdRequest) && mSendMessage->IsLinkSecurityEnabled())
{
otLogNoteMac("Child ID Request requires fragmentation, aborting tx");
mMessageNextOffset = mSendMessage->GetLength();
error = OT_ERROR_ABORT;
ExitNow();
}
assert(aFrame.GetLength() != 7);
break;
#if OPENTHREAD_FTD
case Message::kType6lowpan:
SendMesh(*mSendMessage, aFrame);
break;
case Message::kTypeSupervision:
// A direct supervision message is possible in the case where
// a sleepy child switches its mode (becomes non-sleepy) while
// there is a pending indirect supervision message in the send
// queue for it. The message would be then converted to a
// direct tx.
mMessageNextOffset = mSendMessage->GetLength();
error = OT_ERROR_ABORT;
ExitNow();
#endif
}
aFrame.SetIsARetransmission(false);
exit:
return error;
}
// This method constructs a MAC data from from a given IPv6 message.
//
// This method handles generation of MAC header, mesh header (if
// requested), lowpan compression of IPv6 header, lowpan fragmentation
// header (if message requires fragmentation). It uses the message
// offset to construct next fragments. This method enables link security
// when message is MLE type and requires fragmentation. It returns the
// next offset into the message after the prepared frame.
//
uint16_t MeshForwarder::PrepareDataFrame(Mac::TxFrame & aFrame,
Message & aMessage,
const Mac::Address &aMacSource,
const Mac::Address &aMacDest,
bool aAddMeshHeader,
uint16_t aMeshSource,
uint16_t aMeshDest)
{
uint16_t fcf;
uint8_t *payload;
uint8_t headerLength;
uint16_t payloadLength;
uint16_t fragmentLength;
uint16_t dstpan;
uint8_t secCtl;
uint16_t nextOffset;
start:
// Initialize MAC header
fcf = Mac::Frame::kFcfFrameData;
#if OPENTHREAD_CONFIG_TIME_SYNC_ENABLE
if (aMessage.IsTimeSync())
{
fcf |= Mac::Frame::kFcfFrameVersion2015 | Mac::Frame::kFcfIePresent;
}
else
#endif
{
fcf |= Mac::Frame::kFcfFrameVersion2006;
}
fcf |= (aMacDest.IsShort()) ? Mac::Frame::kFcfDstAddrShort : Mac::Frame::kFcfDstAddrExt;
fcf |= (aMacSource.IsShort()) ? Mac::Frame::kFcfSrcAddrShort : Mac::Frame::kFcfSrcAddrExt;
// All unicast frames request ACK
if (aMacDest.IsExtended() || !aMacDest.IsBroadcast())
{
fcf |= Mac::Frame::kFcfAckRequest;
}
if (aMessage.IsLinkSecurityEnabled())
{
fcf |= Mac::Frame::kFcfSecurityEnabled;
switch (aMessage.GetSubType())
{
case Message::kSubTypeJoinerEntrust:
secCtl = static_cast<uint8_t>(Mac::Frame::kKeyIdMode0);
break;
case Message::kSubTypeMleAnnounce:
secCtl = static_cast<uint8_t>(Mac::Frame::kKeyIdMode2);
break;
default:
secCtl = static_cast<uint8_t>(Mac::Frame::kKeyIdMode1);
break;
}
secCtl |= Mac::Frame::kSecEncMic32;
}
else
{
secCtl = Mac::Frame::kSecNone;
}
dstpan = Get<Mac::Mac>().GetPanId();
switch (aMessage.GetSubType())
{
case Message::kSubTypeMleAnnounce:
aFrame.SetChannel(aMessage.GetChannel());
dstpan = Mac::kPanIdBroadcast;
break;
case Message::kSubTypeMleDiscoverRequest:
case Message::kSubTypeMleDiscoverResponse:
dstpan = aMessage.GetPanId();
break;
default:
break;
}
if (dstpan == Get<Mac::Mac>().GetPanId())
{
#if OPENTHREAD_CONFIG_MAC_HEADER_IE_SUPPORT
// Handle a special case in IEEE 802.15.4-2015, when PAN ID
// Compression is 0, but Src PAN ID is not present:
// Dest Address: Extended
// Src Address: Extended
// Dest Pan ID: Present
// Src Pan ID: Not Present
// Pan ID Compression: 0
if ((fcf & Mac::Frame::kFcfFrameVersionMask) != Mac::Frame::kFcfFrameVersion2015 ||
(fcf & Mac::Frame::kFcfDstAddrMask) != Mac::Frame::kFcfDstAddrExt ||
(fcf & Mac::Frame::kFcfSrcAddrMask) != Mac::Frame::kFcfSrcAddrExt)
#endif
{
fcf |= Mac::Frame::kFcfPanidCompression;
}
}
aFrame.InitMacHeader(fcf, secCtl);
aFrame.SetDstPanId(dstpan);
aFrame.SetSrcPanId(Get<Mac::Mac>().GetPanId());
aFrame.SetDstAddr(aMacDest);
aFrame.SetSrcAddr(aMacSource);
#if OPENTHREAD_CONFIG_TIME_SYNC_ENABLE
if (aMessage.IsTimeSync())
{
Mac::TimeIe * ie;
uint8_t * cur = NULL;
Mac::HeaderIe ieList[2];
ieList[0].Init();
ieList[0].SetId(Mac::Frame::kHeaderIeVendor);
ieList[0].SetLength(sizeof(Mac::TimeIe));
ieList[1].Init();
ieList[1].SetId(Mac::Frame::kHeaderIeTermination2);
ieList[1].SetLength(0);
aFrame.AppendHeaderIe(ieList, 2);
cur = aFrame.GetHeaderIe(Mac::Frame::kHeaderIeVendor);
ie = reinterpret_cast<Mac::TimeIe *>(cur + sizeof(Mac::HeaderIe));
ie->Init();
}
#endif
payload = aFrame.GetPayload();
headerLength = 0;
#if OPENTHREAD_FTD
// Initialize Mesh header
if (aAddMeshHeader)
{
Mle::MleRouter & mle = Get<Mle::MleRouter>();
Lowpan::MeshHeader meshHeader;
uint16_t meshHeaderLength;
uint8_t hopsLeft;
if (mle.GetRole() == OT_DEVICE_ROLE_CHILD)
{
// REED sets hopsLeft to max (16) + 1. It does not know the route cost.
hopsLeft = Mle::kMaxRouteCost + 1;
}
else
{
// Calculate the number of predicted hops.
hopsLeft = mle.GetRouteCost(aMeshDest);
if (hopsLeft != Mle::kMaxRouteCost)
{
hopsLeft += mle.GetLinkCost(Mle::Mle::RouterIdFromRloc16(mle.GetNextHop(aMeshDest)));
}
else
{
// In case there is no route to the destination router (only link).
hopsLeft = mle.GetLinkCost(Mle::Mle::RouterIdFromRloc16(aMeshDest));
}
}
// The hopsLft field MUST be incremented by one if the
// destination RLOC16 is not that of an active Router.
if (!Mle::Mle::IsActiveRouter(aMeshDest))
{
hopsLeft += 1;
}
meshHeader.Init(aMeshSource, aMeshDest, hopsLeft + Lowpan::MeshHeader::kAdditionalHopsLeft);
meshHeaderLength = meshHeader.WriteTo(payload);
payload += meshHeaderLength;
headerLength += meshHeaderLength;
}
#endif
// Compress IPv6 Header
if (aMessage.GetOffset() == 0)
{
Lowpan::BufferWriter buffer(payload, aFrame.GetMaxPayloadLength() - headerLength -
Lowpan::FragmentHeader::kFirstFragmentHeaderSize);
uint8_t hcLength;
Mac::Address meshSource, meshDest;
otError error;
if (aAddMeshHeader)
{
meshSource.SetShort(aMeshSource);
meshDest.SetShort(aMeshDest);
}
else
{
meshSource = aMacSource;
meshDest = aMacDest;
}
error = Get<Lowpan::Lowpan>().Compress(aMessage, meshSource, meshDest, buffer);
assert(error == OT_ERROR_NONE);
hcLength = static_cast<uint8_t>(buffer.GetWritePointer() - payload);
headerLength += hcLength;
payloadLength = aMessage.GetLength() - aMessage.GetOffset();
fragmentLength = aFrame.GetMaxPayloadLength() - headerLength;
if (payloadLength > fragmentLength)
{
Lowpan::FragmentHeader fragmentHeader;
if ((!aMessage.IsLinkSecurityEnabled()) && aMessage.IsSubTypeMle())
{
// Enable security and try again.
aMessage.SetOffset(0);
aMessage.SetLinkSecurityEnabled(true);
goto start;
}
// Write Fragment header
if (aMessage.GetDatagramTag() == 0)
{
// Avoid using datagram tag value 0, which indicates the tag has not been set
if (mFragTag == 0)
{
mFragTag++;
}
aMessage.SetDatagramTag(mFragTag++);
}
memmove(payload + Lowpan::FragmentHeader::kFirstFragmentHeaderSize, payload, hcLength);
fragmentHeader.InitFirstFragment(aMessage.GetLength(), static_cast<uint16_t>(aMessage.GetDatagramTag()));
fragmentHeader.WriteTo(payload);
payload += Lowpan::FragmentHeader::kFirstFragmentHeaderSize;
headerLength += Lowpan::FragmentHeader::kFirstFragmentHeaderSize;
payloadLength = (aFrame.GetMaxPayloadLength() - headerLength) & ~0x7;
}
payload += hcLength;
// copy IPv6 Payload
aMessage.Read(aMessage.GetOffset(), payloadLength, payload);
aFrame.SetPayloadLength(headerLength + payloadLength);
nextOffset = aMessage.GetOffset() + payloadLength;
aMessage.SetOffset(0);
}
else
{
Lowpan::FragmentHeader fragmentHeader;
uint16_t fragmentHeaderLength;
payloadLength = aMessage.GetLength() - aMessage.GetOffset();
// Write Fragment header
fragmentHeader.Init(aMessage.GetLength(), static_cast<uint16_t>(aMessage.GetDatagramTag()),
aMessage.GetOffset());
fragmentHeaderLength = fragmentHeader.WriteTo(payload);
payload += fragmentHeaderLength;
headerLength += fragmentHeaderLength;
fragmentLength = (aFrame.GetMaxPayloadLength() - headerLength) & ~0x7;
if (payloadLength > fragmentLength)
{
payloadLength = fragmentLength;
}
// Copy IPv6 Payload
aMessage.Read(aMessage.GetOffset(), payloadLength, payload);
aFrame.SetPayloadLength(headerLength + payloadLength);
nextOffset = aMessage.GetOffset() + payloadLength;
}
if (nextOffset < aMessage.GetLength())
{
aFrame.SetFramePending(true);
#if OPENTHREAD_CONFIG_TIME_SYNC_ENABLE
aMessage.SetTimeSync(false);
#endif
}
return nextOffset;
}
Neighbor *MeshForwarder::UpdateNeighborOnSentFrame(Mac::TxFrame &aFrame, otError aError, const Mac::Address &aMacDest)
{
Neighbor *neighbor = NULL;
VerifyOrExit(mEnabled);
neighbor = Get<Mle::MleRouter>().GetNeighbor(aMacDest);
VerifyOrExit(neighbor != NULL);
VerifyOrExit(aFrame.GetAckRequest());
if (aError == OT_ERROR_NONE)
{
neighbor->ResetLinkFailures();
}
else if (aError == OT_ERROR_NO_ACK)
{
neighbor->IncrementLinkFailures();
VerifyOrExit(Mle::Mle::IsActiveRouter(neighbor->GetRloc16()));
if (neighbor->GetLinkFailures() >= Mle::kFailedRouterTransmissions)
{
Get<Mle::MleRouter>().RemoveNeighbor(*neighbor);
}
}
exit:
return neighbor;
}
void MeshForwarder::HandleSentFrame(Mac::TxFrame &aFrame, otError aError)
{
Neighbor * neighbor = NULL;
Mac::Address macDest;
assert((aError == OT_ERROR_NONE) || (aError == OT_ERROR_CHANNEL_ACCESS_FAILURE) || (aError == OT_ERROR_ABORT) ||
(aError == OT_ERROR_NO_ACK));
mSendBusy = false;
VerifyOrExit(mEnabled);
if (!aFrame.IsEmpty())
{
aFrame.GetDstAddr(macDest);
neighbor = UpdateNeighborOnSentFrame(aFrame, aError, macDest);
}
VerifyOrExit(mSendMessage != NULL);
assert(mSendMessage->GetDirectTransmission());
if (aError != OT_ERROR_NONE)
{
// If the transmission of any fragment frame fails,
// the overall message transmission is considered
// as failed
mSendMessage->SetTxSuccess(false);
#if OPENTHREAD_CONFIG_DROP_MESSAGE_ON_FRAGMENT_TX_FAILURE
// We set the NextOffset to end of message to avoid sending
// any remaining fragments in the message.
mMessageNextOffset = mSendMessage->GetLength();
#endif
}
if (mMessageNextOffset < mSendMessage->GetLength())
{
mSendMessage->SetOffset(mMessageNextOffset);
}
else
{
otError txError = aError;
mSendMessage->ClearDirectTransmission();
mSendMessage->SetOffset(0);
if (neighbor != NULL)
{
neighbor->GetLinkInfo().AddMessageTxStatus(mSendMessage->GetTxSuccess());
}
#if !OPENTHREAD_CONFIG_DROP_MESSAGE_ON_FRAGMENT_TX_FAILURE
// When `CONFIG_DROP_MESSAGE_ON_FRAGMENT_TX_FAILURE` is
// disabled, all fragment frames of a larger message are
// sent even if the transmission of an earlier fragment fail.
// Note that `GetTxSuccess() tracks the tx success of the
// entire message, while `aError` represents the error
// status of the last fragment frame transmission.
if (!mSendMessage->GetTxSuccess() && (txError == OT_ERROR_NONE))
{
txError = OT_ERROR_FAILED;
}
#endif
LogMessage(kMessageTransmit, *mSendMessage, &macDest, txError);
if (mSendMessage->GetType() == Message::kTypeIp6)
{
if (mSendMessage->GetTxSuccess())
{
mIpCounters.mTxSuccess++;
}
else
{
mIpCounters.mTxFailure++;
}
}
}
if (mSendMessage->GetSubType() == Message::kSubTypeMleDiscoverRequest)
{
mSendBusy = true;
mDiscoverTimer.Start(static_cast<uint16_t>(Mac::kScanDurationDefault));
ExitNow();
}
if (!mSendMessage->GetDirectTransmission() && !mSendMessage->IsChildPending())
{
if (mSendMessage->GetSubType() == Message::kSubTypeMleChildIdRequest && mSendMessage->IsLinkSecurityEnabled())
{
// If the Child ID Request requires fragmentation and therefore
// link layer security, the frame transmission will be aborted.
// When the message is being freed, we signal to MLE to prepare a
// shorter Child ID Request message (by only including mesh-local
// address in the Address Registration TLV).
otLogInfoMac("Requesting shorter `Child ID Request`");
Get<Mle::Mle>().RequestShorterChildIdRequest();
}
mSendQueue.Dequeue(*mSendMessage);
mSendMessage->Free();
mSendMessage = NULL;
mMessageNextOffset = 0;
}
exit:
if (mEnabled)
{
mScheduleTransmissionTask.Post();
}
}
void MeshForwarder::SetDiscoverParameters(const Mac::ChannelMask &aScanChannels)
{
uint32_t mask;
uint32_t supportedMask = Get<Mac::Mac>().GetSupportedChannelMask().GetMask();
mask = aScanChannels.IsEmpty() ? supportedMask : aScanChannels.GetMask();
mScanChannels.SetMask(mask & supportedMask);
}
void MeshForwarder::HandleDiscoverTimer(Timer &aTimer)
{
aTimer.GetOwner<MeshForwarder>().HandleDiscoverTimer();
}
void MeshForwarder::HandleDiscoverTimer(void)
{
if (mScanChannels.GetNextChannel(mScanChannel) != OT_ERROR_NONE)
{
mSendQueue.Dequeue(*mSendMessage);
mSendMessage->Free();
mSendMessage = NULL;
HandleDiscoverComplete();
ExitNow();
}
mSendMessage->SetDirectTransmission();
exit:
mSendBusy = false;
mScheduleTransmissionTask.Post();
}
void MeshForwarder::HandleDiscoverComplete(void)
{
assert(mScanning);
Get<Mac::Mac>().ClearTemporaryChannel();
Get<Mac::Mac>().SetPanId(mRestorePanId);
mScanning = false;
Get<Mle::MleRouter>().HandleDiscoverComplete();
mDiscoverTimer.Stop();
}
void MeshForwarder::HandleReceivedFrame(Mac::RxFrame &aFrame)
{
otThreadLinkInfo linkInfo;
Mac::Address macDest;
Mac::Address macSource;
uint8_t * payload;
uint16_t payloadLength;
otError error = OT_ERROR_NONE;
if (!mEnabled)
{
ExitNow(error = OT_ERROR_INVALID_STATE);
}
SuccessOrExit(error = aFrame.GetSrcAddr(macSource));
SuccessOrExit(error = aFrame.GetDstAddr(macDest));
aFrame.GetSrcPanId(linkInfo.mPanId);
linkInfo.mChannel = aFrame.GetChannel();
linkInfo.mRss = aFrame.GetRssi();
linkInfo.mLqi = aFrame.GetLqi();
linkInfo.mLinkSecurity = aFrame.GetSecurityEnabled();
#if OPENTHREAD_CONFIG_TIME_SYNC_ENABLE
if (aFrame.GetTimeIe() != NULL)
{
linkInfo.mNetworkTimeOffset = aFrame.ComputeNetworkTimeOffset();
linkInfo.mTimeSyncSeq = aFrame.ReadTimeSyncSeq();
}
#endif
payload = aFrame.GetPayload();
payloadLength = aFrame.GetPayloadLength();
Get<Utils::SupervisionListener>().UpdateOnReceive(macSource, linkInfo.mLinkSecurity);
switch (aFrame.GetType())
{
case Mac::Frame::kFcfFrameData:
if (Lowpan::MeshHeader::IsMeshHeader(payload, payloadLength))
{
#if OPENTHREAD_FTD
HandleMesh(payload, payloadLength, macSource, linkInfo);
#endif
}
else if (Lowpan::FragmentHeader::IsFragmentHeader(payload, payloadLength))
{
HandleFragment(payload, payloadLength, macSource, macDest, linkInfo);
}
else if (payloadLength >= 1 && Lowpan::Lowpan::IsLowpanHc(payload))
{
HandleLowpanHC(payload, payloadLength, macSource, macDest, linkInfo);
}
else
{
VerifyOrExit(payloadLength == 0, error = OT_ERROR_NOT_LOWPAN_DATA_FRAME);
LogFrame("Received empty payload frame", aFrame, OT_ERROR_NONE);
}
break;
case Mac::Frame::kFcfFrameBeacon:
break;
default:
error = OT_ERROR_DROP;
break;
}
exit:
if (error != OT_ERROR_NONE)
{
LogFrame("Dropping rx frame", aFrame, error);
}
}
void MeshForwarder::HandleFragment(uint8_t * aFrame,
uint16_t aFrameLength,
const Mac::Address & aMacSource,
const Mac::Address & aMacDest,
const otThreadLinkInfo &aLinkInfo)
{
otError error = OT_ERROR_NONE;
Lowpan::FragmentHeader fragmentHeader;
uint16_t fragmentHeaderLength;
Message * message = NULL;
// Check the fragment header
SuccessOrExit(error = fragmentHeader.ParseFrom(aFrame, aFrameLength, fragmentHeaderLength));
aFrame += fragmentHeaderLength;
aFrameLength -= fragmentHeaderLength;
if (fragmentHeader.GetDatagramOffset() == 0)
{
uint8_t priority;
int headerLength;
SuccessOrExit(error = GetFramePriority(aFrame, aFrameLength, aMacSource, aMacDest, priority));
message = Get<MessagePool>().New(Message::kTypeIp6, 0, priority);
VerifyOrExit(message != NULL, error = OT_ERROR_NO_BUFS);
message->SetLinkSecurityEnabled(aLinkInfo.mLinkSecurity);
message->SetPanId(aLinkInfo.mPanId);
message->AddRss(aLinkInfo.mRss);
#if OPENTHREAD_CONFIG_TIME_SYNC_ENABLE
message->SetTimeSyncSeq(aLinkInfo.mTimeSyncSeq);
message->SetNetworkTimeOffset(aLinkInfo.mNetworkTimeOffset);
#endif
headerLength = Get<Lowpan::Lowpan>().Decompress(*message, aMacSource, aMacDest, aFrame, aFrameLength,
fragmentHeader.GetDatagramSize());
VerifyOrExit(headerLength > 0, error = OT_ERROR_PARSE);
aFrame += headerLength;
aFrameLength -= static_cast<uint16_t>(headerLength);
VerifyOrExit(fragmentHeader.GetDatagramSize() >= message->GetOffset() + aFrameLength, error = OT_ERROR_PARSE);
SuccessOrExit(error = message->SetLength(fragmentHeader.GetDatagramSize()));
message->SetDatagramTag(fragmentHeader.GetDatagramTag());
message->SetTimeout(kReassemblyTimeout);
message->Write(message->GetOffset(), aFrameLength, aFrame);
message->MoveOffset(aFrameLength);
// Security Check
VerifyOrExit(Get<Ip6::Filter>().Accept(*message), error = OT_ERROR_DROP);
// Allow re-assembly of only one message at a time on a SED by clearing
// any remaining fragments in reassembly list upon receiving of a new
// (secure) first fragment.
if (!GetRxOnWhenIdle() && message->IsLinkSecurityEnabled())
{
ClearReassemblyList();
}
mReassemblyList.Enqueue(*message);
if (!mUpdateTimer.IsRunning())
{
mUpdateTimer.Start(kStateUpdatePeriod);
}
}
else // Received frame is a "next fragment".
{
for (message = mReassemblyList.GetHead(); message; message = message->GetNext())
{
// Security Check: only consider reassembly buffers that had the same Security Enabled setting.
if (message->GetLength() == fragmentHeader.GetDatagramSize() &&
message->GetDatagramTag() == fragmentHeader.GetDatagramTag() &&
message->GetOffset() == fragmentHeader.GetDatagramOffset() &&
message->GetOffset() + aFrameLength <= fragmentHeader.GetDatagramSize() &&
message->IsLinkSecurityEnabled() == aLinkInfo.mLinkSecurity)
{
break;
}
}
// For a sleepy-end-device, if we receive a new (secure) next fragment
// with a non-matching fragmentation offset or tag, it indicates that
// we have either missed a fragment, or the parent has moved to a new
// message with a new tag. In either case, we can safely clear any
// remaining fragments stored in the reassembly list.
if (!GetRxOnWhenIdle() && (message == NULL) && aLinkInfo.mLinkSecurity)
{
ClearReassemblyList();
}
VerifyOrExit(message != NULL, error = OT_ERROR_DROP);
message->Write(message->GetOffset(), aFrameLength, aFrame);
message->MoveOffset(aFrameLength);
message->AddRss(aLinkInfo.mRss);
message->SetTimeout(kReassemblyTimeout);
}
exit:
if (error == OT_ERROR_NONE)
{
if (message->GetOffset() >= message->GetLength())
{
mReassemblyList.Dequeue(*message);
HandleDatagram(*message, aLinkInfo, aMacSource);
}
}
else
{
LogFragmentFrameDrop(error, aFrameLength, aMacSource, aMacDest, fragmentHeader, aLinkInfo.mLinkSecurity);
if (message != NULL)
{
message->Free();
}
}
}
void MeshForwarder::ClearReassemblyList(void)
{
Message *message;
Message *next;
for (message = mReassemblyList.GetHead(); message; message = next)
{
next = message->GetNext();
mReassemblyList.Dequeue(*message);
LogMessage(kMessageReassemblyDrop, *message, NULL, OT_ERROR_NO_FRAME_RECEIVED);
if (message->GetType() == Message::kTypeIp6)
{
mIpCounters.mRxFailure++;
}
message->Free();
}
}
void MeshForwarder::HandleUpdateTimer(Timer &aTimer)
{
aTimer.GetOwner<MeshForwarder>().HandleUpdateTimer();
}
void MeshForwarder::HandleUpdateTimer(void)
{
bool shouldRun = false;
#if OPENTHREAD_FTD
shouldRun = UpdateFragmentLifetime();
#endif
if (UpdateReassemblyList() || shouldRun)
{
mUpdateTimer.Start(kStateUpdatePeriod);
}
}
bool MeshForwarder::UpdateReassemblyList(void)
{
Message *next = NULL;
for (Message *message = mReassemblyList.GetHead(); message; message = next)
{
next = message->GetNext();
if (message->GetTimeout() > 0)
{
message->DecrementTimeout();
}
else
{
mReassemblyList.Dequeue(*message);
LogMessage(kMessageReassemblyDrop, *message, NULL, OT_ERROR_REASSEMBLY_TIMEOUT);
if (message->GetType() == Message::kTypeIp6)
{
mIpCounters.mRxFailure++;
}
message->Free();
}
}
return mReassemblyList.GetHead() != NULL;
}
void MeshForwarder::HandleLowpanHC(uint8_t * aFrame,
uint16_t aFrameLength,
const Mac::Address & aMacSource,
const Mac::Address & aMacDest,
const otThreadLinkInfo &aLinkInfo)
{
otError error = OT_ERROR_NONE;
Message *message = NULL;
int headerLength;
uint8_t priority;
#if OPENTHREAD_FTD
UpdateRoutes(aFrame, aFrameLength, aMacSource, aMacDest);
#endif
SuccessOrExit(error = GetFramePriority(aFrame, aFrameLength, aMacSource, aMacDest, priority));
VerifyOrExit((message = Get<MessagePool>().New(Message::kTypeIp6, 0, priority)) != NULL, error = OT_ERROR_NO_BUFS);
message->SetLinkSecurityEnabled(aLinkInfo.mLinkSecurity);
message->SetPanId(aLinkInfo.mPanId);
message->AddRss(aLinkInfo.mRss);
#if OPENTHREAD_CONFIG_TIME_SYNC_ENABLE
message->SetTimeSyncSeq(aLinkInfo.mTimeSyncSeq);
message->SetNetworkTimeOffset(aLinkInfo.mNetworkTimeOffset);
#endif
headerLength = Get<Lowpan::Lowpan>().Decompress(*message, aMacSource, aMacDest, aFrame, aFrameLength, 0);
VerifyOrExit(headerLength > 0, error = OT_ERROR_PARSE);
aFrame += headerLength;
aFrameLength -= static_cast<uint16_t>(headerLength);
SuccessOrExit(error = message->SetLength(message->GetLength() + aFrameLength));
message->Write(message->GetOffset(), aFrameLength, aFrame);
// Security Check
VerifyOrExit(Get<Ip6::Filter>().Accept(*message), error = OT_ERROR_DROP);
exit:
if (error == OT_ERROR_NONE)
{
HandleDatagram(*message, aLinkInfo, aMacSource);
}
else
{
LogLowpanHcFrameDrop(error, aFrameLength, aMacSource, aMacDest, aLinkInfo.mLinkSecurity);
if (message != NULL)
{
message->Free();
}
}
}
otError MeshForwarder::HandleDatagram(Message & aMessage,
const otThreadLinkInfo &aLinkInfo,
const Mac::Address & aMacSource)
{
ThreadNetif &netif = Get<ThreadNetif>();
LogMessage(kMessageReceive, aMessage, &aMacSource, OT_ERROR_NONE);
if (aMessage.GetType() == Message::kTypeIp6)
{
mIpCounters.mRxSuccess++;
}
return Get<Ip6::Ip6>().HandleDatagram(aMessage, &netif, &aLinkInfo, false);
}
otError MeshForwarder::GetFramePriority(const uint8_t * aFrame,
uint16_t aFrameLength,
const Mac::Address &aMacSource,
const Mac::Address &aMacDest,
uint8_t & aPriority)
{
otError error = OT_ERROR_NONE;
Ip6::Header ip6Header;
Ip6::UdpHeader udpHeader;
uint8_t headerLength;
bool nextHeaderCompressed;
SuccessOrExit(error = DecompressIp6Header(aFrame, aFrameLength, aMacSource, aMacDest, ip6Header, headerLength,
nextHeaderCompressed));
aPriority = Ip6::Ip6::DscpToPriority(ip6Header.GetDscp());
VerifyOrExit(ip6Header.GetNextHeader() == Ip6::kProtoUdp);
aFrame += headerLength;
aFrameLength -= headerLength;
if (nextHeaderCompressed)
{
VerifyOrExit(Get<Lowpan::Lowpan>().DecompressUdpHeader(udpHeader, aFrame, aFrameLength) >= 0);
}
else
{
VerifyOrExit(aFrameLength >= sizeof(Ip6::UdpHeader), error = OT_ERROR_PARSE);
memcpy(&udpHeader, aFrame, sizeof(Ip6::UdpHeader));
}
if (udpHeader.GetDestinationPort() == Mle::kUdpPort || udpHeader.GetDestinationPort() == kCoapUdpPort)
{
aPriority = Message::kPriorityNet;
}
exit:
return error;
}
// LCOV_EXCL_START
#if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE) && (OPENTHREAD_CONFIG_LOG_MAC == 1)
otError MeshForwarder::ParseIp6UdpTcpHeader(const Message &aMessage,
Ip6::Header & aIp6Header,
uint16_t & aChecksum,
uint16_t & aSourcePort,
uint16_t & aDestPort)
{
otError error = OT_ERROR_PARSE;
union
{
Ip6::UdpHeader udp;
Ip6::TcpHeader tcp;
} header;
aChecksum = 0;
aSourcePort = 0;
aDestPort = 0;
VerifyOrExit(sizeof(Ip6::Header) == aMessage.Read(0, sizeof(Ip6::Header), &aIp6Header));
VerifyOrExit(aIp6Header.IsVersion6());
switch (aIp6Header.GetNextHeader())
{
case Ip6::kProtoUdp:
VerifyOrExit(sizeof(Ip6::UdpHeader) == aMessage.Read(sizeof(Ip6::Header), sizeof(Ip6::UdpHeader), &header.udp));
aChecksum = header.udp.GetChecksum();
aSourcePort = header.udp.GetSourcePort();
aDestPort = header.udp.GetDestinationPort();
break;
case Ip6::kProtoTcp:
VerifyOrExit(sizeof(Ip6::TcpHeader) == aMessage.Read(sizeof(Ip6::Header), sizeof(Ip6::TcpHeader), &header.tcp));
aChecksum = header.tcp.GetChecksum();
aSourcePort = header.tcp.GetSourcePort();
aDestPort = header.tcp.GetDestinationPort();
break;
default:
break;
}
error = OT_ERROR_NONE;
exit:
return error;
}
const char *MeshForwarder::MessageActionToString(MessageAction aAction, otError aError)
{
const char *actionText = "";
switch (aAction)
{
case kMessageReceive:
actionText = "Received";
break;
case kMessageTransmit:
actionText = (aError == OT_ERROR_NONE) ? "Sent" : "Failed to send";
break;
case kMessagePrepareIndirect:
actionText = "Prepping indir tx";
break;
case kMessageDrop:
actionText = "Dropping";
break;
case kMessageReassemblyDrop:
actionText = "Dropping (reassembly queue)";
break;
case kMessageEvict:
actionText = "Evicting";
break;
}
return actionText;
}
const char *MeshForwarder::MessagePriorityToString(const Message &aMessage)
{
const char *priorityText = "unknown";
switch (aMessage.GetPriority())
{
case Message::kPriorityNet:
priorityText = "net";
break;
case Message::kPriorityHigh:
priorityText = "high";
break;
case Message::kPriorityNormal:
priorityText = "normal";
break;
case Message::kPriorityLow:
priorityText = "low";
break;
}
return priorityText;
}
#if OPENTHREAD_CONFIG_LOG_SRC_DST_IP_ADDRESSES
void MeshForwarder::LogIp6SourceDestAddresses(Ip6::Header &aIp6Header,
uint16_t aSourcePort,
uint16_t aDestPort,
otLogLevel aLogLevel)
{
if (aSourcePort != 0)
{
otLogMac(aLogLevel, " src:[%s]:%d", aIp6Header.GetSource().ToString().AsCString(), aSourcePort);
}
else
{
otLogMac(aLogLevel, " src:[%s]", aIp6Header.GetSource().ToString().AsCString());
}
if (aDestPort != 0)
{
otLogMac(aLogLevel, " dst:[%s]:%d", aIp6Header.GetDestination().ToString().AsCString(), aDestPort);
}
else
{
otLogMac(aLogLevel, " dst:[%s]", aIp6Header.GetDestination().ToString().AsCString());
}
}
#else
void MeshForwarder::LogIp6SourceDestAddresses(Ip6::Header &, uint16_t, uint16_t, otLogLevel)
{
}
#endif
void MeshForwarder::LogIp6Message(MessageAction aAction,
const Message & aMessage,
const Mac::Address *aMacAddress,
otError aError,
otLogLevel aLogLevel)
{
Ip6::Header ip6Header;
uint16_t checksum;
uint16_t sourcePort;
uint16_t destPort;
bool shouldLogRss;
SuccessOrExit(ParseIp6UdpTcpHeader(aMessage, ip6Header, checksum, sourcePort, destPort));
shouldLogRss = (aAction == kMessageReceive) || (aAction == kMessageReassemblyDrop);
otLogMac(aLogLevel, "%s IPv6 %s msg, len:%d, chksum:%04x%s%s, sec:%s%s%s, prio:%s%s%s",
MessageActionToString(aAction, aError), Ip6::Ip6::IpProtoToString(ip6Header.GetNextHeader()),
aMessage.GetLength(), checksum,
(aMacAddress == NULL) ? "" : ((aAction == kMessageReceive) ? ", from:" : ", to:"),
(aMacAddress == NULL) ? "" : aMacAddress->ToString().AsCString(),
aMessage.IsLinkSecurityEnabled() ? "yes" : "no", (aError == OT_ERROR_NONE) ? "" : ", error:",
(aError == OT_ERROR_NONE) ? "" : otThreadErrorToString(aError), MessagePriorityToString(aMessage),
shouldLogRss ? ", rss:" : "", shouldLogRss ? aMessage.GetRssAverager().ToString().AsCString() : "");
if (aAction != kMessagePrepareIndirect)
{
LogIp6SourceDestAddresses(ip6Header, sourcePort, destPort, aLogLevel);
}
exit:
return;
}
void MeshForwarder::LogMessage(MessageAction aAction,
const Message & aMessage,
const Mac::Address *aMacAddress,
otError aError)
{
otLogLevel logLevel = OT_LOG_LEVEL_INFO;
switch (aAction)
{
case kMessageReceive:
case kMessageTransmit:
case kMessagePrepareIndirect:
logLevel = (aError == OT_ERROR_NONE) ? OT_LOG_LEVEL_INFO : OT_LOG_LEVEL_NOTE;
break;
case kMessageDrop:
case kMessageReassemblyDrop:
case kMessageEvict:
logLevel = OT_LOG_LEVEL_NOTE;
break;
}
VerifyOrExit(GetInstance().GetLogLevel() >= logLevel);
switch (aMessage.GetType())
{
case Message::kTypeIp6:
LogIp6Message(aAction, aMessage, aMacAddress, aError, logLevel);
break;
#if OPENTHREAD_FTD
case Message::kType6lowpan:
LogMeshMessage(aAction, aMessage, aMacAddress, aError, logLevel);
break;
#endif
default:
break;
}
exit:
return;
}
void MeshForwarder::LogFrame(const char *aActionText, const Mac::Frame &aFrame, otError aError)
{
if (aError != OT_ERROR_NONE)
{
otLogNoteMac("%s, aError:%s, %s", aActionText, otThreadErrorToString(aError),
aFrame.ToInfoString().AsCString());
}
else
{
otLogInfoMac("%s, %s", aActionText, aFrame.ToInfoString().AsCString());
}
}
void MeshForwarder::LogFragmentFrameDrop(otError aError,
uint16_t aFrameLength,
const Mac::Address & aMacSource,
const Mac::Address & aMacDest,
const Lowpan::FragmentHeader &aFragmentHeader,
bool aIsSecure)
{
otLogNoteMac("Dropping rx frag frame, error:%s, len:%d, src:%s, dst:%s, tag:%d, offset:%d, dglen:%d, sec:%s",
otThreadErrorToString(aError), aFrameLength, aMacSource.ToString().AsCString(),
aMacDest.ToString().AsCString(), aFragmentHeader.GetDatagramTag(), aFragmentHeader.GetDatagramOffset(),
aFragmentHeader.GetDatagramSize(), aIsSecure ? "yes" : "no");
}
void MeshForwarder::LogLowpanHcFrameDrop(otError aError,
uint16_t aFrameLength,
const Mac::Address &aMacSource,
const Mac::Address &aMacDest,
bool aIsSecure)
{
otLogNoteMac("Dropping rx lowpan HC frame, error:%s, len:%d, src:%s, dst:%s, sec:%s", otThreadErrorToString(aError),
aFrameLength, aMacSource.ToString().AsCString(), aMacDest.ToString().AsCString(),
aIsSecure ? "yes" : "no");
}
#else // #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE) && (OPENTHREAD_CONFIG_LOG_MAC == 1)
void MeshForwarder::LogMessage(MessageAction, const Message &, const Mac::Address *, otError)
{
}
void MeshForwarder::LogFrame(const char *, const Mac::Frame &, otError)
{
}
void MeshForwarder::LogFragmentFrameDrop(otError,
uint16_t,
const Mac::Address &,
const Mac::Address &,
const Lowpan::FragmentHeader &,
bool)
{
}
void MeshForwarder::LogLowpanHcFrameDrop(otError, uint16_t, const Mac::Address &, const Mac::Address &, bool)
{
}
#endif // #if (OPENTHREAD_CONFIG_LOG_LEVEL >= OT_LOG_LEVEL_NOTE) && (OPENTHREAD_CONFIG_LOG_MAC == 1)
// LCOV_EXCL_STOP
} // namespace ot
| 30.844848 | 120 | 0.611546 | [
"mesh"
] |
b46a36f66b73ae8f0c039e5eb83a9608ac7e88ed | 109,597 | cpp | C++ | src/OpenGL/compiler/ParseHelper.cpp | wenxiaoming/swiftshader | 13ec11db84e85fd5d53b5d8d59c55853eb854fe6 | [
"Apache-2.0"
] | 6 | 2018-10-20T10:53:55.000Z | 2021-12-25T07:58:57.000Z | src/OpenGL/compiler/ParseHelper.cpp | wenxiaoming/swiftshader | 13ec11db84e85fd5d53b5d8d59c55853eb854fe6 | [
"Apache-2.0"
] | null | null | null | src/OpenGL/compiler/ParseHelper.cpp | wenxiaoming/swiftshader | 13ec11db84e85fd5d53b5d8d59c55853eb854fe6 | [
"Apache-2.0"
] | 9 | 2018-10-31T03:07:11.000Z | 2021-08-06T08:53:21.000Z | // Copyright 2016 The SwiftShader Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "ParseHelper.h"
#include <limits>
#include <stdarg.h>
#include <stdio.h>
#include "glslang.h"
#include "preprocessor/SourceLocation.h"
#include "ValidateSwitch.h"
///////////////////////////////////////////////////////////////////////
//
// Sub- vector and matrix fields
//
////////////////////////////////////////////////////////////////////////
namespace
{
bool IsVaryingOut(TQualifier qualifier)
{
switch(qualifier)
{
case EvqVaryingOut:
case EvqSmoothOut:
case EvqFlatOut:
case EvqCentroidOut:
case EvqVertexOut:
return true;
default: break;
}
return false;
}
bool IsVaryingIn(TQualifier qualifier)
{
switch(qualifier)
{
case EvqVaryingIn:
case EvqSmoothIn:
case EvqFlatIn:
case EvqCentroidIn:
case EvqFragmentIn:
return true;
default: break;
}
return false;
}
bool IsVarying(TQualifier qualifier)
{
return IsVaryingIn(qualifier) || IsVaryingOut(qualifier);
}
bool IsAssignment(TOperator op)
{
switch(op)
{
case EOpPostIncrement:
case EOpPostDecrement:
case EOpPreIncrement:
case EOpPreDecrement:
case EOpAssign:
case EOpAddAssign:
case EOpSubAssign:
case EOpMulAssign:
case EOpVectorTimesMatrixAssign:
case EOpVectorTimesScalarAssign:
case EOpMatrixTimesScalarAssign:
case EOpMatrixTimesMatrixAssign:
case EOpDivAssign:
case EOpIModAssign:
case EOpBitShiftLeftAssign:
case EOpBitShiftRightAssign:
case EOpBitwiseAndAssign:
case EOpBitwiseXorAssign:
case EOpBitwiseOrAssign:
return true;
default:
return false;
}
}
}
//
// Look at a '.' field selector string and change it into offsets
// for a vector.
//
bool TParseContext::parseVectorFields(const TString& compString, int vecSize, TVectorFields& fields, const TSourceLoc &line)
{
fields.num = (int) compString.size();
if (fields.num > 4) {
error(line, "illegal vector field selection", compString.c_str());
return false;
}
enum {
exyzw,
ergba,
estpq
} fieldSet[4];
for (int i = 0; i < fields.num; ++i) {
switch (compString[i]) {
case 'x':
fields.offsets[i] = 0;
fieldSet[i] = exyzw;
break;
case 'r':
fields.offsets[i] = 0;
fieldSet[i] = ergba;
break;
case 's':
fields.offsets[i] = 0;
fieldSet[i] = estpq;
break;
case 'y':
fields.offsets[i] = 1;
fieldSet[i] = exyzw;
break;
case 'g':
fields.offsets[i] = 1;
fieldSet[i] = ergba;
break;
case 't':
fields.offsets[i] = 1;
fieldSet[i] = estpq;
break;
case 'z':
fields.offsets[i] = 2;
fieldSet[i] = exyzw;
break;
case 'b':
fields.offsets[i] = 2;
fieldSet[i] = ergba;
break;
case 'p':
fields.offsets[i] = 2;
fieldSet[i] = estpq;
break;
case 'w':
fields.offsets[i] = 3;
fieldSet[i] = exyzw;
break;
case 'a':
fields.offsets[i] = 3;
fieldSet[i] = ergba;
break;
case 'q':
fields.offsets[i] = 3;
fieldSet[i] = estpq;
break;
default:
error(line, "illegal vector field selection", compString.c_str());
return false;
}
}
for (int i = 0; i < fields.num; ++i) {
if (fields.offsets[i] >= vecSize) {
error(line, "vector field selection out of range", compString.c_str());
return false;
}
if (i > 0) {
if (fieldSet[i] != fieldSet[i-1]) {
error(line, "illegal - vector component fields not from the same set", compString.c_str());
return false;
}
}
}
return true;
}
///////////////////////////////////////////////////////////////////////
//
// Errors
//
////////////////////////////////////////////////////////////////////////
//
// Track whether errors have occurred.
//
void TParseContext::recover()
{
}
//
// Used by flex/bison to output all syntax and parsing errors.
//
void TParseContext::error(const TSourceLoc& loc,
const char* reason, const char* token,
const char* extraInfo)
{
pp::SourceLocation srcLoc(loc.first_file, loc.first_line);
mDiagnostics.writeInfo(pp::Diagnostics::PP_ERROR,
srcLoc, reason, token, extraInfo);
}
void TParseContext::warning(const TSourceLoc& loc,
const char* reason, const char* token,
const char* extraInfo) {
pp::SourceLocation srcLoc(loc.first_file, loc.first_line);
mDiagnostics.writeInfo(pp::Diagnostics::PP_WARNING,
srcLoc, reason, token, extraInfo);
}
void TParseContext::info(const TSourceLoc& loc,
const char* reason, const char* token,
const char* extraInfo) {
pp::SourceLocation srcLoc(loc.first_file, loc.first_line);
mDiagnostics.writeInfo(pp::Diagnostics::PP_INFO,
srcLoc, reason, token, extraInfo);
}
void TParseContext::trace(const char* str)
{
mDiagnostics.writeDebug(str);
}
//
// Same error message for all places assignments don't work.
//
void TParseContext::assignError(const TSourceLoc &line, const char* op, TString left, TString right)
{
std::stringstream extraInfoStream;
extraInfoStream << "cannot convert from '" << right << "' to '" << left << "'";
std::string extraInfo = extraInfoStream.str();
error(line, "", op, extraInfo.c_str());
}
//
// Same error message for all places unary operations don't work.
//
void TParseContext::unaryOpError(const TSourceLoc &line, const char* op, TString operand)
{
std::stringstream extraInfoStream;
extraInfoStream << "no operation '" << op << "' exists that takes an operand of type " << operand
<< " (or there is no acceptable conversion)";
std::string extraInfo = extraInfoStream.str();
error(line, " wrong operand type", op, extraInfo.c_str());
}
//
// Same error message for all binary operations don't work.
//
void TParseContext::binaryOpError(const TSourceLoc &line, const char* op, TString left, TString right)
{
std::stringstream extraInfoStream;
extraInfoStream << "no operation '" << op << "' exists that takes a left-hand operand of type '" << left
<< "' and a right operand of type '" << right << "' (or there is no acceptable conversion)";
std::string extraInfo = extraInfoStream.str();
error(line, " wrong operand types ", op, extraInfo.c_str());
}
bool TParseContext::precisionErrorCheck(const TSourceLoc &line, TPrecision precision, TBasicType type){
if (!mChecksPrecisionErrors)
return false;
switch( type ){
case EbtFloat:
if( precision == EbpUndefined ){
error( line, "No precision specified for (float)", "" );
return true;
}
break;
case EbtInt:
if( precision == EbpUndefined ){
error( line, "No precision specified (int)", "" );
return true;
}
break;
default:
return false;
}
return false;
}
//
// Both test and if necessary, spit out an error, to see if the node is really
// an l-value that can be operated on this way.
//
// Returns true if the was an error.
//
bool TParseContext::lValueErrorCheck(const TSourceLoc &line, const char* op, TIntermTyped* node)
{
TIntermSymbol* symNode = node->getAsSymbolNode();
TIntermBinary* binaryNode = node->getAsBinaryNode();
if (binaryNode) {
bool errorReturn;
switch(binaryNode->getOp()) {
case EOpIndexDirect:
case EOpIndexIndirect:
case EOpIndexDirectStruct:
return lValueErrorCheck(line, op, binaryNode->getLeft());
case EOpVectorSwizzle:
errorReturn = lValueErrorCheck(line, op, binaryNode->getLeft());
if (!errorReturn) {
int offset[4] = {0,0,0,0};
TIntermTyped* rightNode = binaryNode->getRight();
TIntermAggregate *aggrNode = rightNode->getAsAggregate();
for (TIntermSequence::iterator p = aggrNode->getSequence().begin();
p != aggrNode->getSequence().end(); p++) {
int value = (*p)->getAsTyped()->getAsConstantUnion()->getIConst(0);
offset[value]++;
if (offset[value] > 1) {
error(line, " l-value of swizzle cannot have duplicate components", op);
return true;
}
}
}
return errorReturn;
case EOpIndexDirectInterfaceBlock:
default:
break;
}
error(line, " l-value required", op);
return true;
}
const char* symbol = 0;
if (symNode != 0)
symbol = symNode->getSymbol().c_str();
const char* message = 0;
switch (node->getQualifier()) {
case EvqConstExpr: message = "can't modify a const"; break;
case EvqConstReadOnly: message = "can't modify a const"; break;
case EvqAttribute: message = "can't modify an attribute"; break;
case EvqFragmentIn: message = "can't modify an input"; break;
case EvqVertexIn: message = "can't modify an input"; break;
case EvqUniform: message = "can't modify a uniform"; break;
case EvqSmoothIn:
case EvqFlatIn:
case EvqCentroidIn:
case EvqVaryingIn: message = "can't modify a varying"; break;
case EvqInput: message = "can't modify an input"; break;
case EvqFragCoord: message = "can't modify gl_FragCoord"; break;
case EvqFrontFacing: message = "can't modify gl_FrontFacing"; break;
case EvqPointCoord: message = "can't modify gl_PointCoord"; break;
case EvqInstanceID: message = "can't modify gl_InstanceID"; break;
case EvqVertexID: message = "can't modify gl_VertexID"; break;
default:
//
// Type that can't be written to?
//
if(IsSampler(node->getBasicType()))
{
message = "can't modify a sampler";
}
else if(node->getBasicType() == EbtVoid)
{
message = "can't modify void";
}
}
if (message == 0 && binaryNode == 0 && symNode == 0) {
error(line, " l-value required", op);
return true;
}
//
// Everything else is okay, no error.
//
if (message == 0)
return false;
//
// If we get here, we have an error and a message.
//
if (symNode) {
std::stringstream extraInfoStream;
extraInfoStream << "\"" << symbol << "\" (" << message << ")";
std::string extraInfo = extraInfoStream.str();
error(line, " l-value required", op, extraInfo.c_str());
}
else {
std::stringstream extraInfoStream;
extraInfoStream << "(" << message << ")";
std::string extraInfo = extraInfoStream.str();
error(line, " l-value required", op, extraInfo.c_str());
}
return true;
}
//
// Both test, and if necessary spit out an error, to see if the node is really
// a constant.
//
// Returns true if the was an error.
//
bool TParseContext::constErrorCheck(TIntermTyped* node)
{
if (node->getQualifier() == EvqConstExpr)
return false;
error(node->getLine(), "constant expression required", "");
return true;
}
//
// Both test, and if necessary spit out an error, to see if the node is really
// an integer.
//
// Returns true if the was an error.
//
bool TParseContext::integerErrorCheck(TIntermTyped* node, const char* token)
{
if (node->isScalarInt())
return false;
error(node->getLine(), "integer expression required", token);
return true;
}
//
// Both test, and if necessary spit out an error, to see if we are currently
// globally scoped.
//
// Returns true if the was an error.
//
bool TParseContext::globalErrorCheck(const TSourceLoc &line, bool global, const char* token)
{
if (global)
return false;
error(line, "only allowed at global scope", token);
return true;
}
//
// For now, keep it simple: if it starts "gl_", it's reserved, independent
// of scope. Except, if the symbol table is at the built-in push-level,
// which is when we are parsing built-ins.
// Also checks for "webgl_" and "_webgl_" reserved identifiers if parsing a
// webgl shader.
//
// Returns true if there was an error.
//
bool TParseContext::reservedErrorCheck(const TSourceLoc &line, const TString& identifier)
{
static const char* reservedErrMsg = "reserved built-in name";
if (!symbolTable.atBuiltInLevel()) {
if (identifier.compare(0, 3, "gl_") == 0) {
error(line, reservedErrMsg, "gl_");
return true;
}
if (identifier.find("__") != TString::npos) {
error(line, "identifiers containing two consecutive underscores (__) are reserved as possible future keywords", identifier.c_str());
return true;
}
}
return false;
}
//
// Make sure there is enough data provided to the constructor to build
// something of the type of the constructor. Also returns the type of
// the constructor.
//
// Returns true if there was an error in construction.
//
bool TParseContext::constructorErrorCheck(const TSourceLoc &line, TIntermNode* node, TFunction& function, TOperator op, TType* type)
{
*type = function.getReturnType();
bool constructingMatrix = false;
switch(op) {
case EOpConstructMat2:
case EOpConstructMat2x3:
case EOpConstructMat2x4:
case EOpConstructMat3x2:
case EOpConstructMat3:
case EOpConstructMat3x4:
case EOpConstructMat4x2:
case EOpConstructMat4x3:
case EOpConstructMat4:
constructingMatrix = true;
break;
default:
break;
}
//
// Note: It's okay to have too many components available, but not okay to have unused
// arguments. 'full' will go to true when enough args have been seen. If we loop
// again, there is an extra argument, so 'overfull' will become true.
//
size_t size = 0;
bool full = false;
bool overFull = false;
bool matrixInMatrix = false;
bool arrayArg = false;
for (size_t i = 0; i < function.getParamCount(); ++i) {
const TParameter& param = function.getParam(i);
size += param.type->getObjectSize();
if (constructingMatrix && param.type->isMatrix())
matrixInMatrix = true;
if (full)
overFull = true;
if (op != EOpConstructStruct && !type->isArray() && size >= type->getObjectSize())
full = true;
if (param.type->isArray())
arrayArg = true;
}
if(type->isArray()) {
if(type->getArraySize() == 0) {
type->setArraySize(function.getParamCount());
} else if(type->getArraySize() != (int)function.getParamCount()) {
error(line, "array constructor needs one argument per array element", "constructor");
return true;
}
}
if (arrayArg && op != EOpConstructStruct) {
error(line, "constructing from a non-dereferenced array", "constructor");
return true;
}
if (matrixInMatrix && !type->isArray()) {
if (function.getParamCount() != 1) {
error(line, "constructing matrix from matrix can only take one argument", "constructor");
return true;
}
}
if (overFull) {
error(line, "too many arguments", "constructor");
return true;
}
if (op == EOpConstructStruct && !type->isArray() && type->getStruct()->fields().size() != function.getParamCount()) {
error(line, "Number of constructor parameters does not match the number of structure fields", "constructor");
return true;
}
if (!type->isMatrix() || !matrixInMatrix) {
if ((op != EOpConstructStruct && size != 1 && size < type->getObjectSize()) ||
(op == EOpConstructStruct && size < type->getObjectSize())) {
error(line, "not enough data provided for construction", "constructor");
return true;
}
}
TIntermTyped *typed = node ? node->getAsTyped() : 0;
if (typed == 0) {
error(line, "constructor argument does not have a type", "constructor");
return true;
}
if (op != EOpConstructStruct && IsSampler(typed->getBasicType())) {
error(line, "cannot convert a sampler", "constructor");
return true;
}
if (typed->getBasicType() == EbtVoid) {
error(line, "cannot convert a void", "constructor");
return true;
}
return false;
}
// This function checks to see if a void variable has been declared and raise an error message for such a case
//
// returns true in case of an error
//
bool TParseContext::voidErrorCheck(const TSourceLoc &line, const TString& identifier, const TBasicType& type)
{
if(type == EbtVoid) {
error(line, "illegal use of type 'void'", identifier.c_str());
return true;
}
return false;
}
// This function checks to see if the node (for the expression) contains a scalar boolean expression or not
//
// returns true in case of an error
//
bool TParseContext::boolErrorCheck(const TSourceLoc &line, const TIntermTyped* type)
{
if (type->getBasicType() != EbtBool || type->isArray() || type->isMatrix() || type->isVector()) {
error(line, "boolean expression expected", "");
return true;
}
return false;
}
// This function checks to see if the node (for the expression) contains a scalar boolean expression or not
//
// returns true in case of an error
//
bool TParseContext::boolErrorCheck(const TSourceLoc &line, const TPublicType& pType)
{
if (pType.type != EbtBool || pType.array || (pType.primarySize > 1) || (pType.secondarySize > 1)) {
error(line, "boolean expression expected", "");
return true;
}
return false;
}
bool TParseContext::samplerErrorCheck(const TSourceLoc &line, const TPublicType& pType, const char* reason)
{
if (pType.type == EbtStruct) {
if (containsSampler(*pType.userDef)) {
error(line, reason, getBasicString(pType.type), "(structure contains a sampler)");
return true;
}
return false;
} else if (IsSampler(pType.type)) {
error(line, reason, getBasicString(pType.type));
return true;
}
return false;
}
bool TParseContext::structQualifierErrorCheck(const TSourceLoc &line, const TPublicType& pType)
{
switch(pType.qualifier)
{
case EvqVaryingOut:
case EvqSmooth:
case EvqFlat:
case EvqCentroidOut:
case EvqVaryingIn:
case EvqSmoothIn:
case EvqFlatIn:
case EvqCentroidIn:
case EvqAttribute:
case EvqVertexIn:
case EvqFragmentOut:
if(pType.type == EbtStruct)
{
error(line, "cannot be used with a structure", getQualifierString(pType.qualifier));
return true;
}
break;
default:
break;
}
if (pType.qualifier != EvqUniform && samplerErrorCheck(line, pType, "samplers must be uniform"))
return true;
// check for layout qualifier issues
if (pType.qualifier != EvqVertexIn && pType.qualifier != EvqFragmentOut &&
layoutLocationErrorCheck(line, pType.layoutQualifier))
{
return true;
}
return false;
}
// These checks are common for all declarations starting a declarator list, and declarators that follow an empty
// declaration.
//
bool TParseContext::singleDeclarationErrorCheck(const TPublicType &publicType, const TSourceLoc &identifierLocation)
{
switch(publicType.qualifier)
{
case EvqVaryingIn:
case EvqVaryingOut:
case EvqAttribute:
case EvqVertexIn:
case EvqFragmentOut:
if(publicType.type == EbtStruct)
{
error(identifierLocation, "cannot be used with a structure",
getQualifierString(publicType.qualifier));
return true;
}
default: break;
}
if(publicType.qualifier != EvqUniform && samplerErrorCheck(identifierLocation, publicType,
"samplers must be uniform"))
{
return true;
}
// check for layout qualifier issues
const TLayoutQualifier layoutQualifier = publicType.layoutQualifier;
if(layoutQualifier.matrixPacking != EmpUnspecified)
{
error(identifierLocation, "layout qualifier", getMatrixPackingString(layoutQualifier.matrixPacking),
"only valid for interface blocks");
return true;
}
if(layoutQualifier.blockStorage != EbsUnspecified)
{
error(identifierLocation, "layout qualifier", getBlockStorageString(layoutQualifier.blockStorage),
"only valid for interface blocks");
return true;
}
if(publicType.qualifier != EvqVertexIn && publicType.qualifier != EvqFragmentOut &&
layoutLocationErrorCheck(identifierLocation, publicType.layoutQualifier))
{
return true;
}
return false;
}
bool TParseContext::layoutLocationErrorCheck(const TSourceLoc &location, const TLayoutQualifier &layoutQualifier)
{
if(layoutQualifier.location != -1)
{
error(location, "invalid layout qualifier:", "location", "only valid on program inputs and outputs");
return true;
}
return false;
}
bool TParseContext::locationDeclaratorListCheck(const TSourceLoc& line, const TPublicType &pType)
{
if(pType.layoutQualifier.location != -1)
{
error(line, "location must only be specified for a single input or output variable", "location");
return true;
}
return false;
}
bool TParseContext::parameterSamplerErrorCheck(const TSourceLoc &line, TQualifier qualifier, const TType& type)
{
if ((qualifier == EvqOut || qualifier == EvqInOut) &&
type.getBasicType() != EbtStruct && IsSampler(type.getBasicType())) {
error(line, "samplers cannot be output parameters", type.getBasicString());
return true;
}
return false;
}
bool TParseContext::containsSampler(TType& type)
{
if (IsSampler(type.getBasicType()))
return true;
if (type.getBasicType() == EbtStruct || type.isInterfaceBlock()) {
for(const auto &field : type.getStruct()->fields()) {
if (containsSampler(*(field->type())))
return true;
}
}
return false;
}
//
// Do size checking for an array type's size.
//
// Returns true if there was an error.
//
bool TParseContext::arraySizeErrorCheck(const TSourceLoc &line, TIntermTyped* expr, int& size)
{
TIntermConstantUnion* constant = expr->getAsConstantUnion();
if (expr->getQualifier() != EvqConstExpr || constant == 0 || !constant->isScalarInt())
{
error(line, "array size must be a constant integer expression", "");
size = 1;
return true;
}
if (constant->getBasicType() == EbtUInt)
{
unsigned int uintSize = constant->getUConst(0);
if (uintSize > static_cast<unsigned int>(std::numeric_limits<int>::max()))
{
error(line, "array size too large", "");
size = 1;
return true;
}
size = static_cast<int>(uintSize);
}
else
{
size = constant->getIConst(0);
if (size < 0)
{
error(line, "array size must be non-negative", "");
size = 1;
return true;
}
}
if(size == 0)
{
error(line, "array size must be greater than zero", "");
return true;
}
return false;
}
//
// See if this qualifier can be an array.
//
// Returns true if there is an error.
//
bool TParseContext::arrayQualifierErrorCheck(const TSourceLoc &line, TPublicType type)
{
if ((type.qualifier == EvqAttribute) || (type.qualifier == EvqVertexIn) || (type.qualifier == EvqConstExpr && mShaderVersion < 300)) {
error(line, "cannot declare arrays of this qualifier", TType(type).getCompleteString().c_str());
return true;
}
return false;
}
//
// See if this type can be an array.
//
// Returns true if there is an error.
//
bool TParseContext::arrayTypeErrorCheck(const TSourceLoc &line, TPublicType type)
{
//
// Can the type be an array?
//
if (type.array) {
error(line, "cannot declare arrays of arrays", TType(type).getCompleteString().c_str());
return true;
}
// In ESSL1.00 shaders, structs cannot be varying (section 4.3.5). This is checked elsewhere.
// In ESSL3.00 shaders, struct inputs/outputs are allowed but not arrays of structs (section 4.3.4).
if(mShaderVersion >= 300 && type.type == EbtStruct && IsVarying(type.qualifier))
{
error(line, "cannot declare arrays of structs of this qualifier",
TType(type).getCompleteString().c_str());
return true;
}
return false;
}
bool TParseContext::arraySetMaxSize(TIntermSymbol *node, TType* type, int size, bool updateFlag, const TSourceLoc &line)
{
bool builtIn = false;
TSymbol* symbol = symbolTable.find(node->getSymbol(), mShaderVersion, &builtIn);
if (symbol == 0) {
error(line, " undeclared identifier", node->getSymbol().c_str());
return true;
}
TVariable* variable = static_cast<TVariable*>(symbol);
type->setArrayInformationType(variable->getArrayInformationType());
variable->updateArrayInformationType(type);
// special casing to test index value of gl_FragData. If the accessed index is >= gl_MaxDrawBuffers
// its an error
if (node->getSymbol() == "gl_FragData") {
TSymbol* fragData = symbolTable.find("gl_MaxDrawBuffers", mShaderVersion, &builtIn);
ASSERT(fragData);
int fragDataValue = static_cast<TVariable*>(fragData)->getConstPointer()[0].getIConst();
if (fragDataValue <= size) {
error(line, "", "[", "gl_FragData can only have a max array size of up to gl_MaxDrawBuffers");
return true;
}
}
// we dont want to update the maxArraySize when this flag is not set, we just want to include this
// node type in the chain of node types so that its updated when a higher maxArraySize comes in.
if (!updateFlag)
return false;
size++;
variable->getType().setMaxArraySize(size);
type->setMaxArraySize(size);
TType* tt = type;
while(tt->getArrayInformationType() != 0) {
tt = tt->getArrayInformationType();
tt->setMaxArraySize(size);
}
return false;
}
//
// Enforce non-initializer type/qualifier rules.
//
// Returns true if there was an error.
//
bool TParseContext::nonInitConstErrorCheck(const TSourceLoc &line, TString& identifier, TPublicType& type, bool array)
{
if (type.qualifier == EvqConstExpr)
{
// Make the qualifier make sense.
type.qualifier = EvqTemporary;
if (array)
{
error(line, "arrays may not be declared constant since they cannot be initialized", identifier.c_str());
}
else if (type.isStructureContainingArrays())
{
error(line, "structures containing arrays may not be declared constant since they cannot be initialized", identifier.c_str());
}
else
{
error(line, "variables with qualifier 'const' must be initialized", identifier.c_str());
}
return true;
}
return false;
}
//
// Do semantic checking for a variable declaration that has no initializer,
// and update the symbol table.
//
// Returns true if there was an error.
//
bool TParseContext::nonInitErrorCheck(const TSourceLoc &line, const TString& identifier, TPublicType& type)
{
if(type.qualifier == EvqConstExpr)
{
// Make the qualifier make sense.
type.qualifier = EvqTemporary;
// Generate informative error messages for ESSL1.
// In ESSL3 arrays and structures containing arrays can be constant.
if(mShaderVersion < 300 && type.isStructureContainingArrays())
{
error(line,
"structures containing arrays may not be declared constant since they cannot be initialized",
identifier.c_str());
}
else
{
error(line, "variables with qualifier 'const' must be initialized", identifier.c_str());
}
return true;
}
if(type.isUnsizedArray())
{
error(line, "implicitly sized arrays need to be initialized", identifier.c_str());
return true;
}
return false;
}
// Do some simple checks that are shared between all variable declarations,
// and update the symbol table.
//
// Returns true if declaring the variable succeeded.
//
bool TParseContext::declareVariable(const TSourceLoc &line, const TString &identifier, const TType &type,
TVariable **variable)
{
ASSERT((*variable) == nullptr);
// gl_LastFragData may be redeclared with a new precision qualifier
if(type.isArray() && identifier.compare(0, 15, "gl_LastFragData") == 0)
{
const TVariable *maxDrawBuffers =
static_cast<const TVariable *>(symbolTable.findBuiltIn("gl_MaxDrawBuffers", mShaderVersion));
if(type.getArraySize() != maxDrawBuffers->getConstPointer()->getIConst())
{
error(line, "redeclaration of gl_LastFragData with size != gl_MaxDrawBuffers", identifier.c_str());
return false;
}
}
if(reservedErrorCheck(line, identifier))
return false;
(*variable) = new TVariable(&identifier, type);
if(!symbolTable.declare(*variable))
{
error(line, "redefinition", identifier.c_str());
delete (*variable);
(*variable) = nullptr;
return false;
}
if(voidErrorCheck(line, identifier, type.getBasicType()))
return false;
return true;
}
bool TParseContext::paramErrorCheck(const TSourceLoc &line, TQualifier qualifier, TQualifier paramQualifier, TType* type)
{
if (qualifier != EvqConstReadOnly && qualifier != EvqTemporary) {
error(line, "qualifier not allowed on function parameter", getQualifierString(qualifier));
return true;
}
if (qualifier == EvqConstReadOnly && paramQualifier != EvqIn) {
error(line, "qualifier not allowed with ", getQualifierString(qualifier), getQualifierString(paramQualifier));
return true;
}
if (qualifier == EvqConstReadOnly)
type->setQualifier(EvqConstReadOnly);
else
type->setQualifier(paramQualifier);
return false;
}
bool TParseContext::extensionErrorCheck(const TSourceLoc &line, const TString& extension)
{
const TExtensionBehavior& extBehavior = extensionBehavior();
TExtensionBehavior::const_iterator iter = extBehavior.find(extension.c_str());
if (iter == extBehavior.end()) {
error(line, "extension", extension.c_str(), "is not supported");
return true;
}
// In GLSL ES, an extension's default behavior is "disable".
if (iter->second == EBhDisable || iter->second == EBhUndefined) {
error(line, "extension", extension.c_str(), "is disabled");
return true;
}
if (iter->second == EBhWarn) {
warning(line, "extension", extension.c_str(), "is being used");
return false;
}
return false;
}
bool TParseContext::functionCallLValueErrorCheck(const TFunction *fnCandidate, TIntermAggregate *aggregate)
{
for(size_t i = 0; i < fnCandidate->getParamCount(); ++i)
{
TQualifier qual = fnCandidate->getParam(i).type->getQualifier();
if(qual == EvqOut || qual == EvqInOut)
{
TIntermTyped *node = (aggregate->getSequence())[i]->getAsTyped();
if(lValueErrorCheck(node->getLine(), "assign", node))
{
error(node->getLine(),
"Constant value cannot be passed for 'out' or 'inout' parameters.", "Error");
recover();
return true;
}
}
}
return false;
}
void TParseContext::es3InvariantErrorCheck(const TQualifier qualifier, const TSourceLoc &invariantLocation)
{
switch(qualifier)
{
case EvqVaryingOut:
case EvqSmoothOut:
case EvqFlatOut:
case EvqCentroidOut:
case EvqVertexOut:
case EvqFragmentOut:
break;
default:
error(invariantLocation, "Only out variables can be invariant.", "invariant");
recover();
break;
}
}
bool TParseContext::supportsExtension(const char* extension)
{
const TExtensionBehavior& extbehavior = extensionBehavior();
TExtensionBehavior::const_iterator iter = extbehavior.find(extension);
return (iter != extbehavior.end());
}
void TParseContext::handleExtensionDirective(const TSourceLoc &line, const char* extName, const char* behavior)
{
pp::SourceLocation loc(line.first_file, line.first_line);
mDirectiveHandler.handleExtension(loc, extName, behavior);
}
void TParseContext::handlePragmaDirective(const TSourceLoc &line, const char* name, const char* value, bool stdgl)
{
pp::SourceLocation loc(line.first_file, line.first_line);
mDirectiveHandler.handlePragma(loc, name, value, stdgl);
}
/////////////////////////////////////////////////////////////////////////////////
//
// Non-Errors.
//
/////////////////////////////////////////////////////////////////////////////////
const TVariable *TParseContext::getNamedVariable(const TSourceLoc &location,
const TString *name,
const TSymbol *symbol)
{
const TVariable *variable = nullptr;
if(!symbol)
{
error(location, "undeclared identifier", name->c_str());
recover();
}
else if(!symbol->isVariable())
{
error(location, "variable expected", name->c_str());
recover();
}
else
{
variable = static_cast<const TVariable*>(symbol);
if(symbolTable.findBuiltIn(variable->getName(), mShaderVersion))
{
recover();
}
// Reject shaders using both gl_FragData and gl_FragColor
TQualifier qualifier = variable->getType().getQualifier();
if(qualifier == EvqFragData)
{
mUsesFragData = true;
}
else if(qualifier == EvqFragColor)
{
mUsesFragColor = true;
}
// This validation is not quite correct - it's only an error to write to
// both FragData and FragColor. For simplicity, and because users shouldn't
// be rewarded for reading from undefined variables, return an error
// if they are both referenced, rather than assigned.
if(mUsesFragData && mUsesFragColor)
{
error(location, "cannot use both gl_FragData and gl_FragColor", name->c_str());
recover();
}
}
if(!variable)
{
TType type(EbtFloat, EbpUndefined);
TVariable *fakeVariable = new TVariable(name, type);
symbolTable.declare(fakeVariable);
variable = fakeVariable;
}
return variable;
}
//
// Look up a function name in the symbol table, and make sure it is a function.
//
// Return the function symbol if found, otherwise 0.
//
const TFunction* TParseContext::findFunction(const TSourceLoc &line, TFunction* call, bool *builtIn)
{
// First find by unmangled name to check whether the function name has been
// hidden by a variable name or struct typename.
const TSymbol* symbol = symbolTable.find(call->getName(), mShaderVersion, builtIn);
if (!symbol || symbol->isFunction()) {
symbol = symbolTable.find(call->getMangledName(), mShaderVersion, builtIn);
}
if (!symbol) {
error(line, "no matching overloaded function found", call->getName().c_str());
return nullptr;
}
if (!symbol->isFunction()) {
error(line, "function name expected", call->getName().c_str());
return nullptr;
}
return static_cast<const TFunction*>(symbol);
}
//
// Initializers show up in several places in the grammar. Have one set of
// code to handle them here.
//
bool TParseContext::executeInitializer(const TSourceLoc& line, const TString& identifier, const TPublicType& pType,
TIntermTyped *initializer, TIntermNode **intermNode)
{
ASSERT(intermNode != nullptr);
TType type = TType(pType);
if(type.isUnsizedArray())
{
// We have not checked yet whether the initializer actually is an array or not.
if(initializer->isArray())
{
type.setArraySize(initializer->getArraySize());
}
else
{
// Having a non-array initializer for an unsized array will result in an error later,
// so we don't generate an error message here.
type.setArraySize(1u);
}
}
TVariable *variable = nullptr;
if(!declareVariable(line, identifier, type, &variable))
{
return true;
}
if(symbolTable.atGlobalLevel() && initializer->getQualifier() != EvqConstExpr)
{
error(line, "global variable initializers must be constant expressions", "=");
return true;
}
//
// identifier must be of type constant, a global, or a temporary
//
TQualifier qualifier = type.getQualifier();
if ((qualifier != EvqTemporary) && (qualifier != EvqGlobal) && (qualifier != EvqConstExpr)) {
error(line, " cannot initialize this type of qualifier ", variable->getType().getQualifierString());
return true;
}
//
// test for and propagate constant
//
if (qualifier == EvqConstExpr) {
if (qualifier != initializer->getQualifier()) {
std::stringstream extraInfoStream;
extraInfoStream << "'" << variable->getType().getCompleteString() << "'";
std::string extraInfo = extraInfoStream.str();
error(line, " assigning non-constant to", "=", extraInfo.c_str());
variable->getType().setQualifier(EvqTemporary);
return true;
}
if (type != initializer->getType()) {
error(line, " non-matching types for const initializer ",
variable->getType().getQualifierString());
variable->getType().setQualifier(EvqTemporary);
return true;
}
if (initializer->getAsConstantUnion()) {
variable->shareConstPointer(initializer->getAsConstantUnion()->getUnionArrayPointer());
} else if (initializer->getAsSymbolNode()) {
const TSymbol* symbol = symbolTable.find(initializer->getAsSymbolNode()->getSymbol(), 0);
const TVariable* tVar = static_cast<const TVariable*>(symbol);
ConstantUnion* constArray = tVar->getConstPointer();
variable->shareConstPointer(constArray);
}
}
// Constants which aren't indexable arrays get propagated by value
// and thus don't need to initialize the symbol.
if (variable->isConstant() && !(type.isArray() && type.getArraySize() > 1))
{
*intermNode = nullptr;
}
else
{
TIntermSymbol* intermSymbol = intermediate.addSymbol(variable->getUniqueId(), variable->getName(), variable->getType(), line);
*intermNode = createAssign(EOpInitialize, intermSymbol, initializer, line);
if(*intermNode == nullptr) {
assignError(line, "=", intermSymbol->getCompleteString(), initializer->getCompleteString());
return true;
}
}
return false;
}
TPublicType TParseContext::addFullySpecifiedType(TQualifier qualifier, bool invariant, TLayoutQualifier layoutQualifier, const TPublicType &typeSpecifier)
{
TPublicType returnType = typeSpecifier;
returnType.qualifier = qualifier;
returnType.invariant = invariant;
returnType.layoutQualifier = layoutQualifier;
if(mShaderVersion < 300)
{
if(typeSpecifier.array)
{
error(typeSpecifier.line, "not supported", "first-class array");
returnType.clearArrayness();
}
if(qualifier == EvqAttribute && (typeSpecifier.type == EbtBool || typeSpecifier.type == EbtInt))
{
error(typeSpecifier.line, "cannot be bool or int", getQualifierString(qualifier));
recover();
}
if((qualifier == EvqVaryingIn || qualifier == EvqVaryingOut) &&
(typeSpecifier.type == EbtBool || typeSpecifier.type == EbtInt))
{
error(typeSpecifier.line, "cannot be bool or int", getQualifierString(qualifier));
recover();
}
}
else
{
if(!returnType.layoutQualifier.isEmpty())
{
globalErrorCheck(typeSpecifier.line, symbolTable.atGlobalLevel(), "layout");
}
if(IsVarying(returnType.qualifier) || returnType.qualifier == EvqVertexIn || returnType.qualifier == EvqFragmentOut)
{
checkInputOutputTypeIsValidES3(returnType.qualifier, typeSpecifier, typeSpecifier.line);
}
}
return returnType;
}
void TParseContext::checkInputOutputTypeIsValidES3(const TQualifier qualifier,
const TPublicType &type,
const TSourceLoc &qualifierLocation)
{
// An input/output variable can never be bool or a sampler. Samplers are checked elsewhere.
if(type.type == EbtBool)
{
error(qualifierLocation, "cannot be bool", getQualifierString(qualifier));
}
// Specific restrictions apply for vertex shader inputs and fragment shader outputs.
switch(qualifier)
{
case EvqVertexIn:
// ESSL 3.00 section 4.3.4
if(type.array)
{
error(qualifierLocation, "cannot be array", getQualifierString(qualifier));
}
// Vertex inputs with a struct type are disallowed in singleDeclarationErrorCheck
return;
case EvqFragmentOut:
// ESSL 3.00 section 4.3.6
if(type.isMatrix())
{
error(qualifierLocation, "cannot be matrix", getQualifierString(qualifier));
}
// Fragment outputs with a struct type are disallowed in singleDeclarationErrorCheck
return;
default:
break;
}
// Vertex shader outputs / fragment shader inputs have a different, slightly more lenient set of
// restrictions.
bool typeContainsIntegers = (type.type == EbtInt || type.type == EbtUInt ||
type.isStructureContainingType(EbtInt) ||
type.isStructureContainingType(EbtUInt));
if(typeContainsIntegers && qualifier != EvqFlatIn && qualifier != EvqFlatOut)
{
error(qualifierLocation, "must use 'flat' interpolation here", getQualifierString(qualifier));
}
if(type.type == EbtStruct)
{
// ESSL 3.00 sections 4.3.4 and 4.3.6.
// These restrictions are only implied by the ESSL 3.00 spec, but
// the ESSL 3.10 spec lists these restrictions explicitly.
if(type.array)
{
error(qualifierLocation, "cannot be an array of structures", getQualifierString(qualifier));
}
if(type.isStructureContainingArrays())
{
error(qualifierLocation, "cannot be a structure containing an array", getQualifierString(qualifier));
}
if(type.isStructureContainingType(EbtStruct))
{
error(qualifierLocation, "cannot be a structure containing a structure", getQualifierString(qualifier));
}
if(type.isStructureContainingType(EbtBool))
{
error(qualifierLocation, "cannot be a structure containing a bool", getQualifierString(qualifier));
}
}
}
TIntermAggregate *TParseContext::parseSingleDeclaration(TPublicType &publicType,
const TSourceLoc &identifierOrTypeLocation,
const TString &identifier)
{
TIntermSymbol *symbol = intermediate.addSymbol(0, identifier, TType(publicType), identifierOrTypeLocation);
bool emptyDeclaration = (identifier == "");
mDeferredSingleDeclarationErrorCheck = emptyDeclaration;
if(emptyDeclaration)
{
if(publicType.isUnsizedArray())
{
// ESSL3 spec section 4.1.9: Array declaration which leaves the size unspecified is an error.
// It is assumed that this applies to empty declarations as well.
error(identifierOrTypeLocation, "empty array declaration needs to specify a size", identifier.c_str());
}
}
else
{
if(singleDeclarationErrorCheck(publicType, identifierOrTypeLocation))
recover();
if(nonInitErrorCheck(identifierOrTypeLocation, identifier, publicType))
recover();
TVariable *variable = nullptr;
if(!declareVariable(identifierOrTypeLocation, identifier, TType(publicType), &variable))
recover();
if(variable && symbol)
symbol->setId(variable->getUniqueId());
}
return intermediate.makeAggregate(symbol, identifierOrTypeLocation);
}
TIntermAggregate *TParseContext::parseSingleArrayDeclaration(TPublicType &publicType,
const TSourceLoc &identifierLocation,
const TString &identifier,
const TSourceLoc &indexLocation,
TIntermTyped *indexExpression)
{
mDeferredSingleDeclarationErrorCheck = false;
if(singleDeclarationErrorCheck(publicType, identifierLocation))
recover();
if(nonInitErrorCheck(identifierLocation, identifier, publicType))
recover();
if(arrayTypeErrorCheck(indexLocation, publicType) || arrayQualifierErrorCheck(indexLocation, publicType))
{
recover();
}
TType arrayType(publicType);
int size = 0;
if(arraySizeErrorCheck(identifierLocation, indexExpression, size))
{
recover();
}
// Make the type an array even if size check failed.
// This ensures useless error messages regarding the variable's non-arrayness won't follow.
arrayType.setArraySize(size);
TVariable *variable = nullptr;
if(!declareVariable(identifierLocation, identifier, arrayType, &variable))
recover();
TIntermSymbol *symbol = intermediate.addSymbol(0, identifier, arrayType, identifierLocation);
if(variable && symbol)
symbol->setId(variable->getUniqueId());
return intermediate.makeAggregate(symbol, identifierLocation);
}
TIntermAggregate *TParseContext::parseSingleInitDeclaration(const TPublicType &publicType,
const TSourceLoc &identifierLocation,
const TString &identifier,
const TSourceLoc &initLocation,
TIntermTyped *initializer)
{
mDeferredSingleDeclarationErrorCheck = false;
if(singleDeclarationErrorCheck(publicType, identifierLocation))
recover();
TIntermNode *intermNode = nullptr;
if(!executeInitializer(identifierLocation, identifier, publicType, initializer, &intermNode))
{
//
// Build intermediate representation
//
return intermNode ? intermediate.makeAggregate(intermNode, initLocation) : nullptr;
}
else
{
recover();
return nullptr;
}
}
TIntermAggregate *TParseContext::parseSingleArrayInitDeclaration(TPublicType &publicType,
const TSourceLoc &identifierLocation,
const TString &identifier,
const TSourceLoc &indexLocation,
TIntermTyped *indexExpression,
const TSourceLoc &initLocation,
TIntermTyped *initializer)
{
mDeferredSingleDeclarationErrorCheck = false;
if(singleDeclarationErrorCheck(publicType, identifierLocation))
recover();
if(arrayTypeErrorCheck(indexLocation, publicType) || arrayQualifierErrorCheck(indexLocation, publicType))
{
recover();
}
TPublicType arrayType(publicType);
int size = 0;
// If indexExpression is nullptr, then the array will eventually get its size implicitly from the initializer.
if(indexExpression != nullptr && arraySizeErrorCheck(identifierLocation, indexExpression, size))
{
recover();
}
// Make the type an array even if size check failed.
// This ensures useless error messages regarding the variable's non-arrayness won't follow.
arrayType.setArray(true, size);
// initNode will correspond to the whole of "type b[n] = initializer".
TIntermNode *initNode = nullptr;
if(!executeInitializer(identifierLocation, identifier, arrayType, initializer, &initNode))
{
return initNode ? intermediate.makeAggregate(initNode, initLocation) : nullptr;
}
else
{
recover();
return nullptr;
}
}
TIntermAggregate *TParseContext::parseInvariantDeclaration(const TSourceLoc &invariantLoc,
const TSourceLoc &identifierLoc,
const TString *identifier,
const TSymbol *symbol)
{
// invariant declaration
if(globalErrorCheck(invariantLoc, symbolTable.atGlobalLevel(), "invariant varying"))
{
recover();
}
if(!symbol)
{
error(identifierLoc, "undeclared identifier declared as invariant", identifier->c_str());
recover();
return nullptr;
}
else
{
const TString kGlFrontFacing("gl_FrontFacing");
if(*identifier == kGlFrontFacing)
{
error(identifierLoc, "identifier should not be declared as invariant", identifier->c_str());
recover();
return nullptr;
}
symbolTable.addInvariantVarying(std::string(identifier->c_str()));
const TVariable *variable = getNamedVariable(identifierLoc, identifier, symbol);
ASSERT(variable);
const TType &type = variable->getType();
TIntermSymbol *intermSymbol = intermediate.addSymbol(variable->getUniqueId(),
*identifier, type, identifierLoc);
TIntermAggregate *aggregate = intermediate.makeAggregate(intermSymbol, identifierLoc);
aggregate->setOp(EOpInvariantDeclaration);
return aggregate;
}
}
TIntermAggregate *TParseContext::parseDeclarator(TPublicType &publicType, TIntermAggregate *aggregateDeclaration,
const TSourceLoc &identifierLocation, const TString &identifier)
{
// If the declaration starting this declarator list was empty (example: int,), some checks were not performed.
if(mDeferredSingleDeclarationErrorCheck)
{
if(singleDeclarationErrorCheck(publicType, identifierLocation))
recover();
mDeferredSingleDeclarationErrorCheck = false;
}
if(locationDeclaratorListCheck(identifierLocation, publicType))
recover();
if(nonInitErrorCheck(identifierLocation, identifier, publicType))
recover();
TVariable *variable = nullptr;
if(!declareVariable(identifierLocation, identifier, TType(publicType), &variable))
recover();
TIntermSymbol *symbol = intermediate.addSymbol(0, identifier, TType(publicType), identifierLocation);
if(variable && symbol)
symbol->setId(variable->getUniqueId());
return intermediate.growAggregate(aggregateDeclaration, symbol, identifierLocation);
}
TIntermAggregate *TParseContext::parseArrayDeclarator(TPublicType &publicType, TIntermAggregate *aggregateDeclaration,
const TSourceLoc &identifierLocation, const TString &identifier,
const TSourceLoc &arrayLocation, TIntermTyped *indexExpression)
{
// If the declaration starting this declarator list was empty (example: int,), some checks were not performed.
if(mDeferredSingleDeclarationErrorCheck)
{
if(singleDeclarationErrorCheck(publicType, identifierLocation))
recover();
mDeferredSingleDeclarationErrorCheck = false;
}
if(locationDeclaratorListCheck(identifierLocation, publicType))
recover();
if(nonInitErrorCheck(identifierLocation, identifier, publicType))
recover();
if(arrayTypeErrorCheck(arrayLocation, publicType) || arrayQualifierErrorCheck(arrayLocation, publicType))
{
recover();
}
else
{
TType arrayType = TType(publicType);
int size = 0;
if(arraySizeErrorCheck(arrayLocation, indexExpression, size))
{
recover();
}
arrayType.setArraySize(size);
TVariable *variable = nullptr;
if(!declareVariable(identifierLocation, identifier, arrayType, &variable))
recover();
TIntermSymbol *symbol = intermediate.addSymbol(0, identifier, arrayType, identifierLocation);
if(variable && symbol)
symbol->setId(variable->getUniqueId());
return intermediate.growAggregate(aggregateDeclaration, symbol, identifierLocation);
}
return nullptr;
}
TIntermAggregate *TParseContext::parseInitDeclarator(const TPublicType &publicType, TIntermAggregate *aggregateDeclaration,
const TSourceLoc &identifierLocation, const TString &identifier,
const TSourceLoc &initLocation, TIntermTyped *initializer)
{
// If the declaration starting this declarator list was empty (example: int,), some checks were not performed.
if(mDeferredSingleDeclarationErrorCheck)
{
if(singleDeclarationErrorCheck(publicType, identifierLocation))
recover();
mDeferredSingleDeclarationErrorCheck = false;
}
if(locationDeclaratorListCheck(identifierLocation, publicType))
recover();
TIntermNode *intermNode = nullptr;
if(!executeInitializer(identifierLocation, identifier, publicType, initializer, &intermNode))
{
//
// build the intermediate representation
//
if(intermNode)
{
return intermediate.growAggregate(aggregateDeclaration, intermNode, initLocation);
}
else
{
return aggregateDeclaration;
}
}
else
{
recover();
return nullptr;
}
}
TIntermAggregate *TParseContext::parseArrayInitDeclarator(const TPublicType &publicType,
TIntermAggregate *aggregateDeclaration,
const TSourceLoc &identifierLocation,
const TString &identifier,
const TSourceLoc &indexLocation,
TIntermTyped *indexExpression,
const TSourceLoc &initLocation, TIntermTyped *initializer)
{
// If the declaration starting this declarator list was empty (example: int,), some checks were not performed.
if(mDeferredSingleDeclarationErrorCheck)
{
if(singleDeclarationErrorCheck(publicType, identifierLocation))
recover();
mDeferredSingleDeclarationErrorCheck = false;
}
if(locationDeclaratorListCheck(identifierLocation, publicType))
recover();
if(arrayTypeErrorCheck(indexLocation, publicType) || arrayQualifierErrorCheck(indexLocation, publicType))
{
recover();
}
TPublicType arrayType(publicType);
int size = 0;
// If indexExpression is nullptr, then the array will eventually get its size implicitly from the initializer.
if(indexExpression != nullptr && arraySizeErrorCheck(identifierLocation, indexExpression, size))
{
recover();
}
// Make the type an array even if size check failed.
// This ensures useless error messages regarding the variable's non-arrayness won't follow.
arrayType.setArray(true, size);
// initNode will correspond to the whole of "b[n] = initializer".
TIntermNode *initNode = nullptr;
if(!executeInitializer(identifierLocation, identifier, arrayType, initializer, &initNode))
{
if(initNode)
{
return intermediate.growAggregate(aggregateDeclaration, initNode, initLocation);
}
else
{
return aggregateDeclaration;
}
}
else
{
recover();
return nullptr;
}
}
void TParseContext::parseGlobalLayoutQualifier(const TPublicType &typeQualifier)
{
if(mShaderVersion < 300)
{
error(typeQualifier.line, "layout qualifiers supported in GLSL ES 3.00 only", "layout");
recover();
return;
}
if(typeQualifier.qualifier != EvqUniform)
{
error(typeQualifier.line, "invalid qualifier:", getQualifierString(typeQualifier.qualifier), "global layout must be uniform");
recover();
return;
}
const TLayoutQualifier layoutQualifier = typeQualifier.layoutQualifier;
ASSERT(!layoutQualifier.isEmpty());
if(layoutLocationErrorCheck(typeQualifier.line, typeQualifier.layoutQualifier))
{
recover();
return;
}
if(layoutQualifier.matrixPacking != EmpUnspecified)
{
mDefaultMatrixPacking = layoutQualifier.matrixPacking;
}
if(layoutQualifier.blockStorage != EbsUnspecified)
{
mDefaultBlockStorage = layoutQualifier.blockStorage;
}
}
TIntermAggregate *TParseContext::addFunctionPrototypeDeclaration(const TFunction &function, const TSourceLoc &location)
{
// Note: symbolTableFunction could be the same as function if this is the first declaration.
// Either way the instance in the symbol table is used to track whether the function is declared
// multiple times.
TFunction *symbolTableFunction =
static_cast<TFunction *>(symbolTable.find(function.getMangledName(), getShaderVersion()));
if(symbolTableFunction->hasPrototypeDeclaration() && mShaderVersion == 100)
{
// ESSL 1.00.17 section 4.2.7.
// Doesn't apply to ESSL 3.00.4: see section 4.2.3.
error(location, "duplicate function prototype declarations are not allowed", "function");
recover();
}
symbolTableFunction->setHasPrototypeDeclaration();
TIntermAggregate *prototype = new TIntermAggregate;
prototype->setType(function.getReturnType());
prototype->setName(function.getMangledName());
for(size_t i = 0; i < function.getParamCount(); i++)
{
const TParameter ¶m = function.getParam(i);
if(param.name != 0)
{
TVariable variable(param.name, *param.type);
TIntermSymbol *paramSymbol = intermediate.addSymbol(
variable.getUniqueId(), variable.getName(), variable.getType(), location);
prototype = intermediate.growAggregate(prototype, paramSymbol, location);
}
else
{
TIntermSymbol *paramSymbol = intermediate.addSymbol(0, "", *param.type, location);
prototype = intermediate.growAggregate(prototype, paramSymbol, location);
}
}
prototype->setOp(EOpPrototype);
symbolTable.pop();
if(!symbolTable.atGlobalLevel())
{
// ESSL 3.00.4 section 4.2.4.
error(location, "local function prototype declarations are not allowed", "function");
recover();
}
return prototype;
}
TIntermAggregate *TParseContext::addFunctionDefinition(const TFunction &function, TIntermAggregate *functionPrototype, TIntermAggregate *functionBody, const TSourceLoc &location)
{
//?? Check that all paths return a value if return type != void ?
// May be best done as post process phase on intermediate code
if(mCurrentFunctionType->getBasicType() != EbtVoid && !mFunctionReturnsValue)
{
error(location, "function does not return a value:", "", function.getName().c_str());
recover();
}
TIntermAggregate *aggregate = intermediate.growAggregate(functionPrototype, functionBody, location);
intermediate.setAggregateOperator(aggregate, EOpFunction, location);
aggregate->setName(function.getMangledName().c_str());
aggregate->setType(function.getReturnType());
// store the pragma information for debug and optimize and other vendor specific
// information. This information can be queried from the parse tree
aggregate->setOptimize(pragma().optimize);
aggregate->setDebug(pragma().debug);
if(functionBody && functionBody->getAsAggregate())
aggregate->setEndLine(functionBody->getAsAggregate()->getEndLine());
symbolTable.pop();
return aggregate;
}
void TParseContext::parseFunctionPrototype(const TSourceLoc &location, TFunction *function, TIntermAggregate **aggregateOut)
{
const TSymbol *builtIn = symbolTable.findBuiltIn(function->getMangledName(), getShaderVersion());
if(builtIn)
{
error(location, "built-in functions cannot be redefined", function->getName().c_str());
recover();
}
TFunction *prevDec = static_cast<TFunction *>(symbolTable.find(function->getMangledName(), getShaderVersion()));
//
// Note: 'prevDec' could be 'function' if this is the first time we've seen function
// as it would have just been put in the symbol table. Otherwise, we're looking up
// an earlier occurance.
//
if(prevDec->isDefined())
{
// Then this function already has a body.
error(location, "function already has a body", function->getName().c_str());
recover();
}
prevDec->setDefined();
//
// Overload the unique ID of the definition to be the same unique ID as the declaration.
// Eventually we will probably want to have only a single definition and just swap the
// arguments to be the definition's arguments.
//
function->setUniqueId(prevDec->getUniqueId());
// Raise error message if main function takes any parameters or return anything other than void
if(function->getName() == "main")
{
if(function->getParamCount() > 0)
{
error(location, "function cannot take any parameter(s)", function->getName().c_str());
recover();
}
if(function->getReturnType().getBasicType() != EbtVoid)
{
error(location, "", function->getReturnType().getBasicString(), "main function cannot return a value");
recover();
}
}
//
// Remember the return type for later checking for RETURN statements.
//
mCurrentFunctionType = &(prevDec->getReturnType());
mFunctionReturnsValue = false;
//
// Insert parameters into the symbol table.
// If the parameter has no name, it's not an error, just don't insert it
// (could be used for unused args).
//
// Also, accumulate the list of parameters into the HIL, so lower level code
// knows where to find parameters.
//
TIntermAggregate *paramNodes = new TIntermAggregate;
for(size_t i = 0; i < function->getParamCount(); i++)
{
const TParameter ¶m = function->getParam(i);
if(param.name != 0)
{
TVariable *variable = new TVariable(param.name, *param.type);
//
// Insert the parameters with name in the symbol table.
//
if(!symbolTable.declare(variable))
{
error(location, "redefinition", variable->getName().c_str());
recover();
paramNodes = intermediate.growAggregate(
paramNodes, intermediate.addSymbol(0, "", *param.type, location), location);
continue;
}
//
// Add the parameter to the HIL
//
TIntermSymbol *symbol = intermediate.addSymbol(
variable->getUniqueId(), variable->getName(), variable->getType(), location);
paramNodes = intermediate.growAggregate(paramNodes, symbol, location);
}
else
{
paramNodes = intermediate.growAggregate(
paramNodes, intermediate.addSymbol(0, "", *param.type, location), location);
}
}
intermediate.setAggregateOperator(paramNodes, EOpParameters, location);
*aggregateOut = paramNodes;
setLoopNestingLevel(0);
}
TFunction *TParseContext::parseFunctionDeclarator(const TSourceLoc &location, TFunction *function)
{
//
// We don't know at this point whether this is a function definition or a prototype.
// The definition production code will check for redefinitions.
// In the case of ESSL 1.00 the prototype production code will also check for redeclarations.
//
// Return types and parameter qualifiers must match in all redeclarations, so those are checked
// here.
//
TFunction *prevDec = static_cast<TFunction *>(symbolTable.find(function->getMangledName(), getShaderVersion()));
if(getShaderVersion() >= 300 && symbolTable.hasUnmangledBuiltIn(function->getName().c_str()))
{
// With ESSL 3.00, names of built-in functions cannot be redeclared as functions.
// Therefore overloading or redefining builtin functions is an error.
error(location, "Name of a built-in function cannot be redeclared as function", function->getName().c_str());
}
else if(prevDec)
{
if(prevDec->getReturnType() != function->getReturnType())
{
error(location, "overloaded functions must have the same return type",
function->getReturnType().getBasicString());
recover();
}
for(size_t i = 0; i < prevDec->getParamCount(); ++i)
{
if(prevDec->getParam(i).type->getQualifier() != function->getParam(i).type->getQualifier())
{
error(location, "overloaded functions must have the same parameter qualifiers",
function->getParam(i).type->getQualifierString());
recover();
}
}
}
//
// Check for previously declared variables using the same name.
//
TSymbol *prevSym = symbolTable.find(function->getName(), getShaderVersion());
if(prevSym)
{
if(!prevSym->isFunction())
{
error(location, "redefinition", function->getName().c_str(), "function");
recover();
}
}
else
{
// Insert the unmangled name to detect potential future redefinition as a variable.
TFunction *unmangledFunction = new TFunction(NewPoolTString(function->getName().c_str()), function->getReturnType());
symbolTable.getOuterLevel()->insertUnmangled(unmangledFunction);
}
// We're at the inner scope level of the function's arguments and body statement.
// Add the function prototype to the surrounding scope instead.
symbolTable.getOuterLevel()->insert(function);
//
// If this is a redeclaration, it could also be a definition, in which case, we want to use the
// variable names from this one, and not the one that's
// being redeclared. So, pass back up this declaration, not the one in the symbol table.
//
return function;
}
TFunction *TParseContext::addConstructorFunc(const TPublicType &publicTypeIn)
{
TPublicType publicType = publicTypeIn;
TOperator op = EOpNull;
if(publicType.userDef)
{
op = EOpConstructStruct;
}
else
{
op = TypeToConstructorOperator(TType(publicType));
if(op == EOpNull)
{
error(publicType.line, "cannot construct this type", getBasicString(publicType.type));
recover();
publicType.type = EbtFloat;
op = EOpConstructFloat;
}
}
TString tempString;
TType type(publicType);
return new TFunction(&tempString, type, op);
}
// This function is used to test for the correctness of the parameters passed to various constructor functions
// and also convert them to the right datatype if it is allowed and required.
//
// Returns 0 for an error or the constructed node (aggregate or typed) for no error.
//
TIntermTyped* TParseContext::addConstructor(TIntermNode* arguments, const TType* type, TOperator op, TFunction* fnCall, const TSourceLoc &line)
{
TIntermAggregate *aggregateArguments = arguments->getAsAggregate();
if(!aggregateArguments)
{
aggregateArguments = new TIntermAggregate;
aggregateArguments->getSequence().push_back(arguments);
}
if(type->isArray())
{
// GLSL ES 3.00 section 5.4.4: Each argument must be the same type as the element type of
// the array.
for(TIntermNode *&argNode : aggregateArguments->getSequence())
{
const TType &argType = argNode->getAsTyped()->getType();
// It has already been checked that the argument is not an array.
ASSERT(!argType.isArray());
if(!argType.sameElementType(*type))
{
error(line, "Array constructor argument has an incorrect type", "Error");
return nullptr;
}
}
}
else if(op == EOpConstructStruct)
{
const TFieldList &fields = type->getStruct()->fields();
TIntermSequence &args = aggregateArguments->getSequence();
for(size_t i = 0; i < fields.size(); i++)
{
if(args[i]->getAsTyped()->getType() != *fields[i]->type())
{
error(line, "Structure constructor arguments do not match structure fields", "Error");
recover();
return nullptr;
}
}
}
// Turn the argument list itself into a constructor
TIntermAggregate *constructor = intermediate.setAggregateOperator(aggregateArguments, op, line);
TIntermTyped *constConstructor = foldConstConstructor(constructor, *type);
if(constConstructor)
{
return constConstructor;
}
return constructor;
}
TIntermTyped* TParseContext::foldConstConstructor(TIntermAggregate* aggrNode, const TType& type)
{
aggrNode->setType(type);
if (aggrNode->isConstantFoldable()) {
bool returnVal = false;
ConstantUnion* unionArray = new ConstantUnion[type.getObjectSize()];
if (aggrNode->getSequence().size() == 1) {
returnVal = intermediate.parseConstTree(aggrNode->getLine(), aggrNode, unionArray, aggrNode->getOp(), type, true);
}
else {
returnVal = intermediate.parseConstTree(aggrNode->getLine(), aggrNode, unionArray, aggrNode->getOp(), type);
}
if (returnVal)
return nullptr;
return intermediate.addConstantUnion(unionArray, type, aggrNode->getLine());
}
return nullptr;
}
//
// This function returns the tree representation for the vector field(s) being accessed from contant vector.
// If only one component of vector is accessed (v.x or v[0] where v is a contant vector), then a contant node is
// returned, else an aggregate node is returned (for v.xy). The input to this function could either be the symbol
// node or it could be the intermediate tree representation of accessing fields in a constant structure or column of
// a constant matrix.
//
TIntermTyped* TParseContext::addConstVectorNode(TVectorFields& fields, TIntermTyped* node, const TSourceLoc &line)
{
TIntermTyped* typedNode;
TIntermConstantUnion* tempConstantNode = node->getAsConstantUnion();
ConstantUnion *unionArray;
if (tempConstantNode) {
unionArray = tempConstantNode->getUnionArrayPointer();
if (!unionArray) {
return node;
}
} else { // The node has to be either a symbol node or an aggregate node or a tempConstant node, else, its an error
error(line, "Cannot offset into the vector", "Error");
recover();
return nullptr;
}
ConstantUnion* constArray = new ConstantUnion[fields.num];
int objSize = static_cast<int>(node->getType().getObjectSize());
for (int i = 0; i < fields.num; i++) {
if (fields.offsets[i] >= objSize) {
std::stringstream extraInfoStream;
extraInfoStream << "vector field selection out of range '" << fields.offsets[i] << "'";
std::string extraInfo = extraInfoStream.str();
error(line, "", "[", extraInfo.c_str());
recover();
fields.offsets[i] = 0;
}
constArray[i] = unionArray[fields.offsets[i]];
}
TType type(node->getType().getBasicType(), node->getType().getPrecision(), EvqConstExpr, fields.num);
typedNode = intermediate.addConstantUnion(constArray, type, line);
return typedNode;
}
//
// This function returns the column being accessed from a constant matrix. The values are retrieved from
// the symbol table and parse-tree is built for a vector (each column of a matrix is a vector). The input
// to the function could either be a symbol node (m[0] where m is a constant matrix)that represents a
// constant matrix or it could be the tree representation of the constant matrix (s.m1[0] where s is a constant structure)
//
TIntermTyped* TParseContext::addConstMatrixNode(int index, TIntermTyped* node, const TSourceLoc &line)
{
TIntermTyped* typedNode;
TIntermConstantUnion* tempConstantNode = node->getAsConstantUnion();
if (index >= node->getType().getNominalSize()) {
std::stringstream extraInfoStream;
extraInfoStream << "matrix field selection out of range '" << index << "'";
std::string extraInfo = extraInfoStream.str();
error(line, "", "[", extraInfo.c_str());
recover();
index = 0;
}
if (tempConstantNode) {
ConstantUnion* unionArray = tempConstantNode->getUnionArrayPointer();
int size = tempConstantNode->getType().getNominalSize();
typedNode = intermediate.addConstantUnion(&unionArray[size*index], tempConstantNode->getType(), line);
} else {
error(line, "Cannot offset into the matrix", "Error");
recover();
return nullptr;
}
return typedNode;
}
//
// This function returns an element of an array accessed from a constant array. The values are retrieved from
// the symbol table and parse-tree is built for the type of the element. The input
// to the function could either be a symbol node (a[0] where a is a constant array)that represents a
// constant array or it could be the tree representation of the constant array (s.a1[0] where s is a constant structure)
//
TIntermTyped* TParseContext::addConstArrayNode(int index, TIntermTyped* node, const TSourceLoc &line)
{
TIntermTyped* typedNode;
TIntermConstantUnion* tempConstantNode = node->getAsConstantUnion();
TType arrayElementType = node->getType();
arrayElementType.clearArrayness();
if (index >= node->getType().getArraySize()) {
std::stringstream extraInfoStream;
extraInfoStream << "array field selection out of range '" << index << "'";
std::string extraInfo = extraInfoStream.str();
error(line, "", "[", extraInfo.c_str());
recover();
index = 0;
}
size_t arrayElementSize = arrayElementType.getObjectSize();
if (tempConstantNode) {
ConstantUnion* unionArray = tempConstantNode->getUnionArrayPointer();
typedNode = intermediate.addConstantUnion(&unionArray[arrayElementSize * index], tempConstantNode->getType(), line);
} else {
error(line, "Cannot offset into the array", "Error");
recover();
return nullptr;
}
return typedNode;
}
//
// This function returns the value of a particular field inside a constant structure from the symbol table.
// If there is an embedded/nested struct, it appropriately calls addConstStructNested or addConstStructFromAggr
// function and returns the parse-tree with the values of the embedded/nested struct.
//
TIntermTyped* TParseContext::addConstStruct(const TString& identifier, TIntermTyped* node, const TSourceLoc &line)
{
const TFieldList &fields = node->getType().getStruct()->fields();
TIntermTyped *typedNode;
size_t instanceSize = 0;
TIntermConstantUnion *tempConstantNode = node->getAsConstantUnion();
for(const auto &field : fields) {
if (field->name() == identifier) {
break;
} else {
instanceSize += field->type()->getObjectSize();
}
}
if (tempConstantNode) {
ConstantUnion* constArray = tempConstantNode->getUnionArrayPointer();
typedNode = intermediate.addConstantUnion(constArray+instanceSize, tempConstantNode->getType(), line); // type will be changed in the calling function
} else {
error(line, "Cannot offset into the structure", "Error");
recover();
return nullptr;
}
return typedNode;
}
//
// Interface/uniform blocks
//
TIntermAggregate* TParseContext::addInterfaceBlock(const TPublicType& typeQualifier, const TSourceLoc& nameLine, const TString& blockName, TFieldList* fieldList,
const TString* instanceName, const TSourceLoc& instanceLine, TIntermTyped* arrayIndex, const TSourceLoc& arrayIndexLine)
{
if(reservedErrorCheck(nameLine, blockName))
recover();
if(typeQualifier.qualifier != EvqUniform)
{
error(typeQualifier.line, "invalid qualifier:", getQualifierString(typeQualifier.qualifier), "interface blocks must be uniform");
recover();
}
TLayoutQualifier blockLayoutQualifier = typeQualifier.layoutQualifier;
if(layoutLocationErrorCheck(typeQualifier.line, blockLayoutQualifier))
{
recover();
}
if(blockLayoutQualifier.matrixPacking == EmpUnspecified)
{
blockLayoutQualifier.matrixPacking = mDefaultMatrixPacking;
}
if(blockLayoutQualifier.blockStorage == EbsUnspecified)
{
blockLayoutQualifier.blockStorage = mDefaultBlockStorage;
}
TSymbol* blockNameSymbol = new TSymbol(&blockName);
if(!symbolTable.declare(blockNameSymbol)) {
error(nameLine, "redefinition", blockName.c_str(), "interface block name");
recover();
}
// check for sampler types and apply layout qualifiers
for(const auto &field : *fieldList) {
TType* fieldType = field->type();
if(IsSampler(fieldType->getBasicType())) {
error(field->line(), "unsupported type", fieldType->getBasicString(), "sampler types are not allowed in interface blocks");
recover();
}
const TQualifier qualifier = fieldType->getQualifier();
switch(qualifier)
{
case EvqGlobal:
case EvqUniform:
break;
default:
error(field->line(), "invalid qualifier on interface block member", getQualifierString(qualifier));
recover();
break;
}
// check layout qualifiers
TLayoutQualifier fieldLayoutQualifier = fieldType->getLayoutQualifier();
if(layoutLocationErrorCheck(field->line(), fieldLayoutQualifier))
{
recover();
}
if(fieldLayoutQualifier.blockStorage != EbsUnspecified)
{
error(field->line(), "invalid layout qualifier:", getBlockStorageString(fieldLayoutQualifier.blockStorage), "cannot be used here");
recover();
}
if(fieldLayoutQualifier.matrixPacking == EmpUnspecified)
{
fieldLayoutQualifier.matrixPacking = blockLayoutQualifier.matrixPacking;
}
else if(!fieldType->isMatrix() && (fieldType->getBasicType() != EbtStruct))
{
warning(field->line(), "extraneous layout qualifier:", getMatrixPackingString(fieldLayoutQualifier.matrixPacking), "only has an effect on matrix types");
}
fieldType->setLayoutQualifier(fieldLayoutQualifier);
// Recursively propagate the matrix packing setting down to all block/structure members
fieldType->setMatrixPackingIfUnspecified(fieldLayoutQualifier.matrixPacking);
}
// add array index
int arraySize = 0;
if(arrayIndex)
{
if(arraySizeErrorCheck(arrayIndexLine, arrayIndex, arraySize))
recover();
}
TInterfaceBlock* interfaceBlock = new TInterfaceBlock(&blockName, fieldList, instanceName, arraySize, blockLayoutQualifier);
TType interfaceBlockType(interfaceBlock, typeQualifier.qualifier, blockLayoutQualifier, arraySize);
TString symbolName = "";
int symbolId = 0;
if(!instanceName)
{
// define symbols for the members of the interface block
for(const auto &field : *fieldList)
{
TType* fieldType = field->type();
// set parent pointer of the field variable
fieldType->setInterfaceBlock(interfaceBlock);
TVariable* fieldVariable = new TVariable(&field->name(), *fieldType);
fieldVariable->setQualifier(typeQualifier.qualifier);
if(!symbolTable.declare(fieldVariable)) {
error(field->line(), "redefinition", field->name().c_str(), "interface block member name");
recover();
}
}
}
else
{
if(reservedErrorCheck(nameLine, *instanceName))
recover();
// add a symbol for this interface block
TVariable* instanceTypeDef = new TVariable(instanceName, interfaceBlockType, false);
instanceTypeDef->setQualifier(typeQualifier.qualifier);
if(!symbolTable.declare(instanceTypeDef)) {
error(instanceLine, "redefinition", instanceName->c_str(), "interface block instance name");
recover();
}
symbolId = instanceTypeDef->getUniqueId();
symbolName = instanceTypeDef->getName();
}
TIntermAggregate *aggregate = intermediate.makeAggregate(intermediate.addSymbol(symbolId, symbolName, interfaceBlockType, typeQualifier.line), nameLine);
aggregate->setOp(EOpDeclaration);
exitStructDeclaration();
return aggregate;
}
//
// Parse an array index expression
//
TIntermTyped *TParseContext::addIndexExpression(TIntermTyped *baseExpression, const TSourceLoc &location, TIntermTyped *indexExpression)
{
TIntermTyped *indexedExpression = nullptr;
if(!baseExpression->isArray() && !baseExpression->isMatrix() && !baseExpression->isVector())
{
if(baseExpression->getAsSymbolNode())
{
error(location, " left of '[' is not of type array, matrix, or vector ",
baseExpression->getAsSymbolNode()->getSymbol().c_str());
}
else
{
error(location, " left of '[' is not of type array, matrix, or vector ", "expression");
}
recover();
}
TIntermConstantUnion *indexConstantUnion = indexExpression->getAsConstantUnion();
if(indexExpression->getQualifier() == EvqConstExpr && indexConstantUnion) // TODO: Qualifier check redundant?
{
int index = indexConstantUnion->getIConst(0);
if(index < 0)
{
std::stringstream infoStream;
infoStream << index;
std::string info = infoStream.str();
error(location, "negative index", info.c_str());
recover();
index = 0;
}
if(baseExpression->getType().getQualifier() == EvqConstExpr && baseExpression->getAsConstantUnion()) // TODO: Qualifier check redundant?
{
if(baseExpression->isArray())
{
// constant folding for arrays
indexedExpression = addConstArrayNode(index, baseExpression, location);
}
else if(baseExpression->isVector())
{
// constant folding for vectors
TVectorFields fields;
fields.num = 1;
fields.offsets[0] = index; // need to do it this way because v.xy sends fields integer array
indexedExpression = addConstVectorNode(fields, baseExpression, location);
}
else if(baseExpression->isMatrix())
{
// constant folding for matrices
indexedExpression = addConstMatrixNode(index, baseExpression, location);
}
}
else
{
int safeIndex = -1;
if(baseExpression->isArray())
{
if(index >= baseExpression->getType().getArraySize())
{
std::stringstream extraInfoStream;
extraInfoStream << "array index out of range '" << index << "'";
std::string extraInfo = extraInfoStream.str();
error(location, "", "[", extraInfo.c_str());
recover();
safeIndex = baseExpression->getType().getArraySize() - 1;
}
}
else if((baseExpression->isVector() || baseExpression->isMatrix()) &&
baseExpression->getType().getNominalSize() <= index)
{
std::stringstream extraInfoStream;
extraInfoStream << "field selection out of range '" << index << "'";
std::string extraInfo = extraInfoStream.str();
error(location, "", "[", extraInfo.c_str());
recover();
safeIndex = baseExpression->getType().getNominalSize() - 1;
}
// Don't modify the data of the previous constant union, because it can point
// to builtins, like gl_MaxDrawBuffers. Instead use a new sanitized object.
if(safeIndex != -1)
{
ConstantUnion *safeConstantUnion = new ConstantUnion();
safeConstantUnion->setIConst(safeIndex);
indexConstantUnion->replaceConstantUnion(safeConstantUnion);
}
indexedExpression = intermediate.addIndex(EOpIndexDirect, baseExpression, indexExpression, location);
}
}
else
{
if(baseExpression->isInterfaceBlock())
{
error(location, "",
"[", "array indexes for interface blocks arrays must be constant integral expressions");
recover();
}
else if(baseExpression->getQualifier() == EvqFragmentOut)
{
error(location, "", "[", "array indexes for fragment outputs must be constant integral expressions");
recover();
}
indexedExpression = intermediate.addIndex(EOpIndexIndirect, baseExpression, indexExpression, location);
}
if(indexedExpression == 0)
{
ConstantUnion *unionArray = new ConstantUnion[1];
unionArray->setFConst(0.0f);
indexedExpression = intermediate.addConstantUnion(unionArray, TType(EbtFloat, EbpHigh, EvqConstExpr), location);
}
else if(baseExpression->isArray())
{
const TType &baseType = baseExpression->getType();
if(baseType.getStruct())
{
TType copyOfType(baseType.getStruct());
indexedExpression->setType(copyOfType);
}
else if(baseType.isInterfaceBlock())
{
TType copyOfType(baseType.getInterfaceBlock(), EvqTemporary, baseType.getLayoutQualifier(), 0);
indexedExpression->setType(copyOfType);
}
else
{
indexedExpression->setType(TType(baseExpression->getBasicType(), baseExpression->getPrecision(),
EvqTemporary, static_cast<unsigned char>(baseExpression->getNominalSize()),
static_cast<unsigned char>(baseExpression->getSecondarySize())));
}
if(baseExpression->getType().getQualifier() == EvqConstExpr)
{
indexedExpression->getTypePointer()->setQualifier(EvqConstExpr);
}
}
else if(baseExpression->isMatrix())
{
TQualifier qualifier = baseExpression->getType().getQualifier() == EvqConstExpr ? EvqConstExpr : EvqTemporary;
indexedExpression->setType(TType(baseExpression->getBasicType(), baseExpression->getPrecision(),
qualifier, static_cast<unsigned char>(baseExpression->getSecondarySize())));
}
else if(baseExpression->isVector())
{
TQualifier qualifier = baseExpression->getType().getQualifier() == EvqConstExpr ? EvqConstExpr : EvqTemporary;
indexedExpression->setType(TType(baseExpression->getBasicType(), baseExpression->getPrecision(), qualifier));
}
else
{
indexedExpression->setType(baseExpression->getType());
}
return indexedExpression;
}
TIntermTyped *TParseContext::addFieldSelectionExpression(TIntermTyped *baseExpression, const TSourceLoc &dotLocation,
const TString &fieldString, const TSourceLoc &fieldLocation)
{
TIntermTyped *indexedExpression = nullptr;
if(baseExpression->isArray())
{
error(fieldLocation, "cannot apply dot operator to an array", ".");
recover();
}
if(baseExpression->isVector())
{
TVectorFields fields;
if(!parseVectorFields(fieldString, baseExpression->getNominalSize(), fields, fieldLocation))
{
fields.num = 1;
fields.offsets[0] = 0;
recover();
}
if(baseExpression->getAsConstantUnion())
{
// constant folding for vector fields
indexedExpression = addConstVectorNode(fields, baseExpression, fieldLocation);
if(indexedExpression == 0)
{
recover();
indexedExpression = baseExpression;
}
}
else
{
TString vectorString = fieldString;
TIntermTyped *index = intermediate.addSwizzle(fields, fieldLocation);
indexedExpression = intermediate.addIndex(EOpVectorSwizzle, baseExpression, index, dotLocation);
indexedExpression->setType(TType(baseExpression->getBasicType(), baseExpression->getPrecision(),
baseExpression->getQualifier() == EvqConstExpr ? EvqConstExpr : EvqTemporary, (unsigned char)vectorString.size()));
}
}
else if(baseExpression->getBasicType() == EbtStruct)
{
bool fieldFound = false;
const TFieldList &fields = baseExpression->getType().getStruct()->fields();
if(fields.empty())
{
error(dotLocation, "structure has no fields", "Internal Error");
recover();
indexedExpression = baseExpression;
}
else
{
unsigned int i;
for(i = 0; i < fields.size(); ++i)
{
if(fields[i]->name() == fieldString)
{
fieldFound = true;
break;
}
}
if(fieldFound)
{
if(baseExpression->getType().getQualifier() == EvqConstExpr)
{
indexedExpression = addConstStruct(fieldString, baseExpression, dotLocation);
if(indexedExpression == 0)
{
recover();
indexedExpression = baseExpression;
}
else
{
indexedExpression->setType(*fields[i]->type());
// change the qualifier of the return type, not of the structure field
// as the structure definition is shared between various structures.
indexedExpression->getTypePointer()->setQualifier(EvqConstExpr);
}
}
else
{
TIntermTyped *index = TIntermTyped::CreateIndexNode(i);
index->setLine(fieldLocation);
indexedExpression = intermediate.addIndex(EOpIndexDirectStruct, baseExpression, index, dotLocation);
indexedExpression->setType(*fields[i]->type());
}
}
else
{
error(dotLocation, " no such field in structure", fieldString.c_str());
recover();
indexedExpression = baseExpression;
}
}
}
else if(baseExpression->isInterfaceBlock())
{
bool fieldFound = false;
const TFieldList &fields = baseExpression->getType().getInterfaceBlock()->fields();
if(fields.empty())
{
error(dotLocation, "interface block has no fields", "Internal Error");
recover();
indexedExpression = baseExpression;
}
else
{
unsigned int i;
for(i = 0; i < fields.size(); ++i)
{
if(fields[i]->name() == fieldString)
{
fieldFound = true;
break;
}
}
if(fieldFound)
{
ConstantUnion *unionArray = new ConstantUnion[1];
unionArray->setIConst(i);
TIntermTyped *index = intermediate.addConstantUnion(unionArray, *fields[i]->type(), fieldLocation);
indexedExpression = intermediate.addIndex(EOpIndexDirectInterfaceBlock, baseExpression, index,
dotLocation);
indexedExpression->setType(*fields[i]->type());
}
else
{
error(dotLocation, " no such field in interface block", fieldString.c_str());
recover();
indexedExpression = baseExpression;
}
}
}
else
{
if(mShaderVersion < 300)
{
error(dotLocation, " field selection requires structure or vector on left hand side",
fieldString.c_str());
}
else
{
error(dotLocation,
" field selection requires structure, vector, or interface block on left hand side",
fieldString.c_str());
}
recover();
indexedExpression = baseExpression;
}
return indexedExpression;
}
TLayoutQualifier TParseContext::parseLayoutQualifier(const TString &qualifierType, const TSourceLoc& qualifierTypeLine)
{
TLayoutQualifier qualifier;
qualifier.location = -1;
qualifier.matrixPacking = EmpUnspecified;
qualifier.blockStorage = EbsUnspecified;
if(qualifierType == "shared")
{
qualifier.blockStorage = EbsShared;
}
else if(qualifierType == "packed")
{
qualifier.blockStorage = EbsPacked;
}
else if(qualifierType == "std140")
{
qualifier.blockStorage = EbsStd140;
}
else if(qualifierType == "row_major")
{
qualifier.matrixPacking = EmpRowMajor;
}
else if(qualifierType == "column_major")
{
qualifier.matrixPacking = EmpColumnMajor;
}
else if(qualifierType == "location")
{
error(qualifierTypeLine, "invalid layout qualifier", qualifierType.c_str(), "location requires an argument");
recover();
}
else
{
error(qualifierTypeLine, "invalid layout qualifier", qualifierType.c_str());
recover();
}
return qualifier;
}
TLayoutQualifier TParseContext::parseLayoutQualifier(const TString &qualifierType, const TSourceLoc& qualifierTypeLine, int intValue, const TSourceLoc& intValueLine)
{
TLayoutQualifier qualifier;
qualifier.location = -1; // -1 isn't a valid location, it means the value isn't set. Negative values are checked lower in this function.
qualifier.matrixPacking = EmpUnspecified;
qualifier.blockStorage = EbsUnspecified;
if (qualifierType != "location")
{
error(qualifierTypeLine, "invalid layout qualifier", qualifierType.c_str(), "only location may have arguments");
recover();
}
else
{
// must check that location is non-negative
if (intValue < 0)
{
error(intValueLine, "out of range:", "", "location must be non-negative");
recover();
}
else
{
qualifier.location = intValue;
}
}
return qualifier;
}
TLayoutQualifier TParseContext::joinLayoutQualifiers(TLayoutQualifier leftQualifier, TLayoutQualifier rightQualifier)
{
TLayoutQualifier joinedQualifier = leftQualifier;
if (rightQualifier.location != -1)
{
joinedQualifier.location = rightQualifier.location;
}
if(rightQualifier.matrixPacking != EmpUnspecified)
{
joinedQualifier.matrixPacking = rightQualifier.matrixPacking;
}
if(rightQualifier.blockStorage != EbsUnspecified)
{
joinedQualifier.blockStorage = rightQualifier.blockStorage;
}
return joinedQualifier;
}
TPublicType TParseContext::joinInterpolationQualifiers(const TSourceLoc &interpolationLoc, TQualifier interpolationQualifier,
const TSourceLoc &storageLoc, TQualifier storageQualifier)
{
TQualifier mergedQualifier = EvqSmoothIn;
if(storageQualifier == EvqFragmentIn) {
if(interpolationQualifier == EvqSmooth)
mergedQualifier = EvqSmoothIn;
else if(interpolationQualifier == EvqFlat)
mergedQualifier = EvqFlatIn;
else UNREACHABLE(interpolationQualifier);
}
else if(storageQualifier == EvqCentroidIn) {
if(interpolationQualifier == EvqSmooth)
mergedQualifier = EvqCentroidIn;
else if(interpolationQualifier == EvqFlat)
mergedQualifier = EvqFlatIn;
else UNREACHABLE(interpolationQualifier);
}
else if(storageQualifier == EvqVertexOut) {
if(interpolationQualifier == EvqSmooth)
mergedQualifier = EvqSmoothOut;
else if(interpolationQualifier == EvqFlat)
mergedQualifier = EvqFlatOut;
else UNREACHABLE(interpolationQualifier);
}
else if(storageQualifier == EvqCentroidOut) {
if(interpolationQualifier == EvqSmooth)
mergedQualifier = EvqCentroidOut;
else if(interpolationQualifier == EvqFlat)
mergedQualifier = EvqFlatOut;
else UNREACHABLE(interpolationQualifier);
}
else {
error(interpolationLoc, "interpolation qualifier requires a fragment 'in' or vertex 'out' storage qualifier", getQualifierString(interpolationQualifier));
recover();
mergedQualifier = storageQualifier;
}
TPublicType type;
type.setBasic(EbtVoid, mergedQualifier, storageLoc);
return type;
}
TFieldList *TParseContext::addStructDeclaratorList(const TPublicType &typeSpecifier, TFieldList *fieldList)
{
if(voidErrorCheck(typeSpecifier.line, (*fieldList)[0]->name(), typeSpecifier.type))
{
recover();
}
for(const auto &field : *fieldList)
{
//
// Careful not to replace already known aspects of type, like array-ness
//
TType *type = field->type();
type->setBasicType(typeSpecifier.type);
type->setNominalSize(typeSpecifier.primarySize);
type->setSecondarySize(typeSpecifier.secondarySize);
type->setPrecision(typeSpecifier.precision);
type->setQualifier(typeSpecifier.qualifier);
type->setLayoutQualifier(typeSpecifier.layoutQualifier);
// don't allow arrays of arrays
if(type->isArray())
{
if(arrayTypeErrorCheck(typeSpecifier.line, typeSpecifier))
recover();
}
if(typeSpecifier.array)
type->setArraySize(typeSpecifier.arraySize);
if(typeSpecifier.userDef)
{
type->setStruct(typeSpecifier.userDef->getStruct());
}
if(structNestingErrorCheck(typeSpecifier.line, *field))
{
recover();
}
}
return fieldList;
}
TPublicType TParseContext::addStructure(const TSourceLoc &structLine, const TSourceLoc &nameLine,
const TString *structName, TFieldList *fieldList)
{
TStructure *structure = new TStructure(structName, fieldList);
TType *structureType = new TType(structure);
// Store a bool in the struct if we're at global scope, to allow us to
// skip the local struct scoping workaround in HLSL.
structure->setUniqueId(TSymbolTableLevel::nextUniqueId());
structure->setAtGlobalScope(symbolTable.atGlobalLevel());
if(!structName->empty())
{
if(reservedErrorCheck(nameLine, *structName))
{
recover();
}
TVariable *userTypeDef = new TVariable(structName, *structureType, true);
if(!symbolTable.declare(userTypeDef))
{
error(nameLine, "redefinition", structName->c_str(), "struct");
recover();
}
}
// ensure we do not specify any storage qualifiers on the struct members
for(const auto &field : *fieldList)
{
const TQualifier qualifier = field->type()->getQualifier();
switch(qualifier)
{
case EvqGlobal:
case EvqTemporary:
break;
default:
error(field->line(), "invalid qualifier on struct member", getQualifierString(qualifier));
recover();
break;
}
}
TPublicType publicType;
publicType.setBasic(EbtStruct, EvqTemporary, structLine);
publicType.userDef = structureType;
exitStructDeclaration();
return publicType;
}
bool TParseContext::enterStructDeclaration(const TSourceLoc &line, const TString& identifier)
{
++mStructNestingLevel;
// Embedded structure definitions are not supported per GLSL ES spec.
// They aren't allowed in GLSL either, but we need to detect this here
// so we don't rely on the GLSL compiler to catch it.
if (mStructNestingLevel > 1) {
error(line, "", "Embedded struct definitions are not allowed");
return true;
}
return false;
}
void TParseContext::exitStructDeclaration()
{
--mStructNestingLevel;
}
bool TParseContext::structNestingErrorCheck(const TSourceLoc &line, const TField &field)
{
static const int kWebGLMaxStructNesting = 4;
if(field.type()->getBasicType() != EbtStruct)
{
return false;
}
// We're already inside a structure definition at this point, so add
// one to the field's struct nesting.
if(1 + field.type()->getDeepestStructNesting() > kWebGLMaxStructNesting)
{
std::stringstream reasonStream;
reasonStream << "Reference of struct type "
<< field.type()->getStruct()->name().c_str()
<< " exceeds maximum allowed nesting level of "
<< kWebGLMaxStructNesting;
std::string reason = reasonStream.str();
error(line, reason.c_str(), field.name().c_str(), "");
return true;
}
return false;
}
TIntermTyped *TParseContext::createUnaryMath(TOperator op, TIntermTyped *child, const TSourceLoc &loc, const TType *funcReturnType)
{
if(child == nullptr)
{
return nullptr;
}
switch(op)
{
case EOpLogicalNot:
if(child->getBasicType() != EbtBool ||
child->isMatrix() ||
child->isArray() ||
child->isVector())
{
return nullptr;
}
break;
case EOpBitwiseNot:
if((child->getBasicType() != EbtInt && child->getBasicType() != EbtUInt) ||
child->isMatrix() ||
child->isArray())
{
return nullptr;
}
break;
case EOpPostIncrement:
case EOpPreIncrement:
case EOpPostDecrement:
case EOpPreDecrement:
case EOpNegative:
if(child->getBasicType() == EbtStruct ||
child->getBasicType() == EbtBool ||
child->isArray())
{
return nullptr;
}
// Operators for built-ins are already type checked against their prototype.
default:
break;
}
return intermediate.addUnaryMath(op, child, loc, funcReturnType);
}
TIntermTyped *TParseContext::addUnaryMath(TOperator op, TIntermTyped *child, const TSourceLoc &loc)
{
TIntermTyped *node = createUnaryMath(op, child, loc, nullptr);
if(node == nullptr)
{
unaryOpError(loc, getOperatorString(op), child->getCompleteString());
recover();
return child;
}
return node;
}
TIntermTyped *TParseContext::addUnaryMathLValue(TOperator op, TIntermTyped *child, const TSourceLoc &loc)
{
if(lValueErrorCheck(loc, getOperatorString(op), child))
recover();
return addUnaryMath(op, child, loc);
}
bool TParseContext::binaryOpCommonCheck(TOperator op, TIntermTyped *left, TIntermTyped *right, const TSourceLoc &loc)
{
if(left->isArray() || right->isArray())
{
if(mShaderVersion < 300)
{
error(loc, "Invalid operation for arrays", getOperatorString(op));
return false;
}
if(left->isArray() != right->isArray())
{
error(loc, "array / non-array mismatch", getOperatorString(op));
return false;
}
switch(op)
{
case EOpEqual:
case EOpNotEqual:
case EOpAssign:
case EOpInitialize:
break;
default:
error(loc, "Invalid operation for arrays", getOperatorString(op));
return false;
}
// At this point, size of implicitly sized arrays should be resolved.
if(left->getArraySize() != right->getArraySize())
{
error(loc, "array size mismatch", getOperatorString(op));
return false;
}
}
// Check ops which require integer / ivec parameters
bool isBitShift = false;
switch(op)
{
case EOpBitShiftLeft:
case EOpBitShiftRight:
case EOpBitShiftLeftAssign:
case EOpBitShiftRightAssign:
// Unsigned can be bit-shifted by signed and vice versa, but we need to
// check that the basic type is an integer type.
isBitShift = true;
if(!IsInteger(left->getBasicType()) || !IsInteger(right->getBasicType()))
{
return false;
}
break;
case EOpBitwiseAnd:
case EOpBitwiseXor:
case EOpBitwiseOr:
case EOpBitwiseAndAssign:
case EOpBitwiseXorAssign:
case EOpBitwiseOrAssign:
// It is enough to check the type of only one operand, since later it
// is checked that the operand types match.
if(!IsInteger(left->getBasicType()))
{
return false;
}
break;
default:
break;
}
// GLSL ES 1.00 and 3.00 do not support implicit type casting.
// So the basic type should usually match.
if(!isBitShift && left->getBasicType() != right->getBasicType())
{
return false;
}
// Check that type sizes match exactly on ops that require that.
// Also check restrictions for structs that contain arrays or samplers.
switch(op)
{
case EOpAssign:
case EOpInitialize:
case EOpEqual:
case EOpNotEqual:
// ESSL 1.00 sections 5.7, 5.8, 5.9
if(mShaderVersion < 300 && left->getType().isStructureContainingArrays())
{
error(loc, "undefined operation for structs containing arrays", getOperatorString(op));
return false;
}
// Samplers as l-values are disallowed also in ESSL 3.00, see section 4.1.7,
// we interpret the spec so that this extends to structs containing samplers,
// similarly to ESSL 1.00 spec.
if((mShaderVersion < 300 || op == EOpAssign || op == EOpInitialize) &&
left->getType().isStructureContainingSamplers())
{
error(loc, "undefined operation for structs containing samplers", getOperatorString(op));
return false;
}
case EOpLessThan:
case EOpGreaterThan:
case EOpLessThanEqual:
case EOpGreaterThanEqual:
if((left->getNominalSize() != right->getNominalSize()) ||
(left->getSecondarySize() != right->getSecondarySize()))
{
return false;
}
break;
case EOpAdd:
case EOpSub:
case EOpDiv:
case EOpIMod:
case EOpBitShiftLeft:
case EOpBitShiftRight:
case EOpBitwiseAnd:
case EOpBitwiseXor:
case EOpBitwiseOr:
case EOpAddAssign:
case EOpSubAssign:
case EOpDivAssign:
case EOpIModAssign:
case EOpBitShiftLeftAssign:
case EOpBitShiftRightAssign:
case EOpBitwiseAndAssign:
case EOpBitwiseXorAssign:
case EOpBitwiseOrAssign:
if((left->isMatrix() && right->isVector()) || (left->isVector() && right->isMatrix()))
{
return false;
}
// Are the sizes compatible?
if(left->getNominalSize() != right->getNominalSize() || left->getSecondarySize() != right->getSecondarySize())
{
// If the nominal sizes of operands do not match:
// One of them must be a scalar.
if(!left->isScalar() && !right->isScalar())
return false;
// In the case of compound assignment other than multiply-assign,
// the right side needs to be a scalar. Otherwise a vector/matrix
// would be assigned to a scalar. A scalar can't be shifted by a
// vector either.
if(!right->isScalar() && (IsAssignment(op) || op == EOpBitShiftLeft || op == EOpBitShiftRight))
return false;
}
break;
default:
break;
}
return true;
}
TIntermSwitch *TParseContext::addSwitch(TIntermTyped *init, TIntermAggregate *statementList, const TSourceLoc &loc)
{
TBasicType switchType = init->getBasicType();
if((switchType != EbtInt && switchType != EbtUInt) ||
init->isMatrix() ||
init->isArray() ||
init->isVector())
{
error(init->getLine(), "init-expression in a switch statement must be a scalar integer", "switch");
recover();
return nullptr;
}
if(statementList)
{
if(!ValidateSwitch::validate(switchType, this, statementList, loc))
{
recover();
return nullptr;
}
}
TIntermSwitch *node = intermediate.addSwitch(init, statementList, loc);
if(node == nullptr)
{
error(loc, "erroneous switch statement", "switch");
recover();
return nullptr;
}
return node;
}
TIntermCase *TParseContext::addCase(TIntermTyped *condition, const TSourceLoc &loc)
{
if(mSwitchNestingLevel == 0)
{
error(loc, "case labels need to be inside switch statements", "case");
recover();
return nullptr;
}
if(condition == nullptr)
{
error(loc, "case label must have a condition", "case");
recover();
return nullptr;
}
if((condition->getBasicType() != EbtInt && condition->getBasicType() != EbtUInt) ||
condition->isMatrix() ||
condition->isArray() ||
condition->isVector())
{
error(condition->getLine(), "case label must be a scalar integer", "case");
recover();
}
TIntermConstantUnion *conditionConst = condition->getAsConstantUnion();
if(conditionConst == nullptr)
{
error(condition->getLine(), "case label must be constant", "case");
recover();
}
TIntermCase *node = intermediate.addCase(condition, loc);
if(node == nullptr)
{
error(loc, "erroneous case statement", "case");
recover();
return nullptr;
}
return node;
}
TIntermCase *TParseContext::addDefault(const TSourceLoc &loc)
{
if(mSwitchNestingLevel == 0)
{
error(loc, "default labels need to be inside switch statements", "default");
recover();
return nullptr;
}
TIntermCase *node = intermediate.addCase(nullptr, loc);
if(node == nullptr)
{
error(loc, "erroneous default statement", "default");
recover();
return nullptr;
}
return node;
}
TIntermTyped *TParseContext::createAssign(TOperator op, TIntermTyped *left, TIntermTyped *right, const TSourceLoc &loc)
{
if(binaryOpCommonCheck(op, left, right, loc))
{
return intermediate.addAssign(op, left, right, loc);
}
return nullptr;
}
TIntermTyped *TParseContext::addAssign(TOperator op, TIntermTyped *left, TIntermTyped *right, const TSourceLoc &loc)
{
TIntermTyped *node = createAssign(op, left, right, loc);
if(node == nullptr)
{
assignError(loc, "assign", left->getCompleteString(), right->getCompleteString());
recover();
return left;
}
return node;
}
TIntermTyped *TParseContext::addBinaryMathInternal(TOperator op, TIntermTyped *left, TIntermTyped *right,
const TSourceLoc &loc)
{
if(!binaryOpCommonCheck(op, left, right, loc))
return nullptr;
switch(op)
{
case EOpEqual:
case EOpNotEqual:
break;
case EOpLessThan:
case EOpGreaterThan:
case EOpLessThanEqual:
case EOpGreaterThanEqual:
ASSERT(!left->isArray() && !right->isArray());
if(left->isMatrix() || left->isVector() ||
left->getBasicType() == EbtStruct)
{
return nullptr;
}
break;
case EOpLogicalOr:
case EOpLogicalXor:
case EOpLogicalAnd:
ASSERT(!left->isArray() && !right->isArray());
if(left->getBasicType() != EbtBool ||
left->isMatrix() || left->isVector())
{
return nullptr;
}
break;
case EOpAdd:
case EOpSub:
case EOpDiv:
case EOpMul:
ASSERT(!left->isArray() && !right->isArray());
if(left->getBasicType() == EbtStruct || left->getBasicType() == EbtBool)
{
return nullptr;
}
break;
case EOpIMod:
ASSERT(!left->isArray() && !right->isArray());
// Note that this is only for the % operator, not for mod()
if(left->getBasicType() == EbtStruct || left->getBasicType() == EbtBool || left->getBasicType() == EbtFloat)
{
return nullptr;
}
break;
// Note that for bitwise ops, type checking is done in promote() to
// share code between ops and compound assignment
default:
break;
}
return intermediate.addBinaryMath(op, left, right, loc);
}
TIntermTyped *TParseContext::addBinaryMath(TOperator op, TIntermTyped *left, TIntermTyped *right, const TSourceLoc &loc)
{
TIntermTyped *node = addBinaryMathInternal(op, left, right, loc);
if(node == 0)
{
binaryOpError(loc, getOperatorString(op), left->getCompleteString(), right->getCompleteString());
recover();
return left;
}
return node;
}
TIntermTyped *TParseContext::addBinaryMathBooleanResult(TOperator op, TIntermTyped *left, TIntermTyped *right, const TSourceLoc &loc)
{
TIntermTyped *node = addBinaryMathInternal(op, left, right, loc);
if(node == 0)
{
binaryOpError(loc, getOperatorString(op), left->getCompleteString(), right->getCompleteString());
recover();
ConstantUnion *unionArray = new ConstantUnion[1];
unionArray->setBConst(false);
return intermediate.addConstantUnion(unionArray, TType(EbtBool, EbpUndefined, EvqConstExpr), loc);
}
return node;
}
TIntermBranch *TParseContext::addBranch(TOperator op, const TSourceLoc &loc)
{
switch(op)
{
case EOpContinue:
if(mLoopNestingLevel <= 0)
{
error(loc, "continue statement only allowed in loops", "");
recover();
}
break;
case EOpBreak:
if(mLoopNestingLevel <= 0 && mSwitchNestingLevel <= 0)
{
error(loc, "break statement only allowed in loops and switch statements", "");
recover();
}
break;
case EOpReturn:
if(mCurrentFunctionType->getBasicType() != EbtVoid)
{
error(loc, "non-void function must return a value", "return");
recover();
}
break;
default:
// No checks for discard
break;
}
return intermediate.addBranch(op, loc);
}
TIntermBranch *TParseContext::addBranch(TOperator op, TIntermTyped *returnValue, const TSourceLoc &loc)
{
ASSERT(op == EOpReturn);
mFunctionReturnsValue = true;
if(mCurrentFunctionType->getBasicType() == EbtVoid)
{
error(loc, "void function cannot return a value", "return");
recover();
}
else if(*mCurrentFunctionType != returnValue->getType())
{
error(loc, "function return is not matching type:", "return");
recover();
}
return intermediate.addBranch(op, returnValue, loc);
}
TIntermTyped *TParseContext::addFunctionCallOrMethod(TFunction *fnCall, TIntermNode *paramNode, TIntermNode *thisNode, const TSourceLoc &loc, bool *fatalError)
{
*fatalError = false;
TOperator op = fnCall->getBuiltInOp();
TIntermTyped *callNode = nullptr;
if(thisNode != nullptr)
{
ConstantUnion *unionArray = new ConstantUnion[1];
int arraySize = 0;
TIntermTyped *typedThis = thisNode->getAsTyped();
if(fnCall->getName() != "length")
{
error(loc, "invalid method", fnCall->getName().c_str());
recover();
}
else if(paramNode != nullptr)
{
error(loc, "method takes no parameters", "length");
recover();
}
else if(typedThis == nullptr || !typedThis->isArray())
{
error(loc, "length can only be called on arrays", "length");
recover();
}
else
{
arraySize = typedThis->getArraySize();
}
unionArray->setIConst(arraySize);
callNode = intermediate.addConstantUnion(unionArray, TType(EbtInt, EbpUndefined, EvqConstExpr), loc);
}
else if(op != EOpNull)
{
//
// Then this should be a constructor.
// Don't go through the symbol table for constructors.
// Their parameters will be verified algorithmically.
//
TType type(EbtVoid, EbpUndefined); // use this to get the type back
if(!constructorErrorCheck(loc, paramNode, *fnCall, op, &type))
{
//
// It's a constructor, of type 'type'.
//
callNode = addConstructor(paramNode, &type, op, fnCall, loc);
}
if(callNode == nullptr)
{
recover();
callNode = intermediate.setAggregateOperator(nullptr, op, loc);
}
}
else
{
//
// Not a constructor. Find it in the symbol table.
//
const TFunction *fnCandidate;
bool builtIn;
fnCandidate = findFunction(loc, fnCall, &builtIn);
if(fnCandidate)
{
//
// A declared function.
//
if(builtIn && !fnCandidate->getExtension().empty() &&
extensionErrorCheck(loc, fnCandidate->getExtension()))
{
recover();
}
op = fnCandidate->getBuiltInOp();
if(builtIn && op != EOpNull)
{
//
// A function call mapped to a built-in operation.
//
if(fnCandidate->getParamCount() == 1)
{
//
// Treat it like a built-in unary operator.
//
TIntermNode *operand = paramNode->getAsAggregate()->getSequence()[0];
callNode = createUnaryMath(op, operand->getAsTyped(), loc, &fnCandidate->getReturnType());
if(callNode == nullptr)
{
std::stringstream extraInfoStream;
extraInfoStream << "built in unary operator function. Type: "
<< static_cast<TIntermTyped*>(paramNode)->getCompleteString();
std::string extraInfo = extraInfoStream.str();
error(paramNode->getLine(), " wrong operand type", "Internal Error", extraInfo.c_str());
*fatalError = true;
return nullptr;
}
}
else
{
TIntermAggregate *aggregate = intermediate.setAggregateOperator(paramNode, op, loc);
aggregate->setType(fnCandidate->getReturnType());
// Some built-in functions have out parameters too.
functionCallLValueErrorCheck(fnCandidate, aggregate);
callNode = aggregate;
if(op == EOpClamp)
{
// Special case for clamp -- try to fold it as min(max(t, minVal), maxVal)
TIntermSequence ¶meters = paramNode->getAsAggregate()->getSequence();
TIntermConstantUnion *valConstant = parameters[0]->getAsTyped()->getAsConstantUnion();
TIntermConstantUnion *minConstant = parameters[1]->getAsTyped()->getAsConstantUnion();
TIntermConstantUnion *maxConstant = parameters[2]->getAsTyped()->getAsConstantUnion();
if (valConstant && minConstant && maxConstant)
{
TIntermTyped *typedReturnNode = valConstant->fold(EOpMax, minConstant, infoSink());
if (typedReturnNode && typedReturnNode->getAsConstantUnion())
{
typedReturnNode = maxConstant->fold(EOpMin, typedReturnNode->getAsConstantUnion(), infoSink());
}
if (typedReturnNode)
{
callNode = typedReturnNode;
}
}
}
else
{
if(fnCandidate->getParamCount() == 2)
{
TIntermSequence ¶meters = paramNode->getAsAggregate()->getSequence();
TIntermTyped *left = parameters[0]->getAsTyped();
TIntermTyped *right = parameters[1]->getAsTyped();
TIntermConstantUnion *leftTempConstant = left->getAsConstantUnion();
TIntermConstantUnion *rightTempConstant = right->getAsConstantUnion();
if (leftTempConstant && rightTempConstant)
{
TIntermTyped *typedReturnNode = leftTempConstant->fold(op, rightTempConstant, infoSink());
if(typedReturnNode)
{
callNode = typedReturnNode;
}
}
}
}
}
}
else
{
// This is a real function call
TIntermAggregate *aggregate = intermediate.setAggregateOperator(paramNode, EOpFunctionCall, loc);
aggregate->setType(fnCandidate->getReturnType());
// this is how we know whether the given function is a builtIn function or a user defined function
// if builtIn == false, it's a userDefined -> could be an overloaded builtIn function also
// if builtIn == true, it's definitely a builtIn function with EOpNull
if(!builtIn)
aggregate->setUserDefined();
aggregate->setName(fnCandidate->getMangledName());
callNode = aggregate;
functionCallLValueErrorCheck(fnCandidate, aggregate);
}
}
else
{
// error message was put out by findFunction()
// Put on a dummy node for error recovery
ConstantUnion *unionArray = new ConstantUnion[1];
unionArray->setFConst(0.0f);
callNode = intermediate.addConstantUnion(unionArray, TType(EbtFloat, EbpUndefined, EvqConstExpr), loc);
recover();
}
}
delete fnCall;
return callNode;
}
TIntermTyped *TParseContext::addTernarySelection(TIntermTyped *cond, TIntermTyped *trueBlock, TIntermTyped *falseBlock, const TSourceLoc &loc)
{
if(boolErrorCheck(loc, cond))
recover();
if(trueBlock->getType() != falseBlock->getType())
{
binaryOpError(loc, ":", trueBlock->getCompleteString(), falseBlock->getCompleteString());
recover();
return falseBlock;
}
// ESSL1 sections 5.2 and 5.7:
// ESSL3 section 5.7:
// Ternary operator is not among the operators allowed for structures/arrays.
if(trueBlock->isArray() || trueBlock->getBasicType() == EbtStruct)
{
error(loc, "ternary operator is not allowed for structures or arrays", ":");
recover();
return falseBlock;
}
return intermediate.addSelection(cond, trueBlock, falseBlock, loc);
}
//
// Parse an array of strings using yyparse.
//
// Returns 0 for success.
//
int PaParseStrings(int count, const char* const string[], const int length[],
TParseContext* context) {
if ((count == 0) || !string)
return 1;
if (glslang_initialize(context))
return 1;
int error = glslang_scan(count, string, length, context);
if (!error)
error = glslang_parse(context);
glslang_finalize(context);
return (error == 0) && (context->numErrors() == 0) ? 0 : 1;
}
| 29.17918 | 178 | 0.714454 | [
"object",
"vector"
] |
b46fafed5c954f429b2ab7101f82a3e9d8312dbd | 1,323 | cc | C++ | include/glibc-stdlib/tst-quick_exit.cc | abhijeetviswam/libucresolv | f4911dcf4d9b5410a423970d698ac98ac071a413 | [
"Apache-2.0"
] | 1 | 2019-02-02T05:08:01.000Z | 2019-02-02T05:08:01.000Z | include/glibc-stdlib/tst-quick_exit.cc | DalavanCloud/libucresolv | 04a4827aa44c47556f425a4eed5e0ab4a5c0d25a | [
"Apache-2.0"
] | 3 | 2019-07-12T00:44:18.000Z | 2020-12-07T17:32:23.000Z | include/glibc-stdlib/tst-quick_exit.cc | DalavanCloud/libucresolv | 04a4827aa44c47556f425a4eed5e0ab4a5c0d25a | [
"Apache-2.0"
] | 7 | 2017-07-04T10:52:39.000Z | 2019-02-28T08:37:16.000Z | /* Bug 20198: Do not call object destructors at exit.
Copyright (C) 2016-2017 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
#include <stdlib.h>
struct A
{
~A () { abort (); }
};
thread_local A a;
void
__attribute__ ((noinline, noclone))
optimization_barrier (A &)
{
}
static int
do_test ()
{
optimization_barrier (a);
/* The C++11 standard in 18.5.12 says:
"Objects shall not be destroyed as a result of calling
quick_exit."
If quick_exit calls the destructors the test aborts. */
quick_exit (0);
return 0;
}
#define TEST_FUNCTION do_test ()
#include "../test-skeleton.c"
| 27.5625 | 71 | 0.714286 | [
"object"
] |
b4700085d1891b517ec54b273bacfc1a32c34990 | 2,816 | cc | C++ | zetasql/compliance/type_helpers.cc | dictav/zetasql | f4b7df010ae94941a984930a82175ee8836d9c0e | [
"Apache-2.0"
] | null | null | null | zetasql/compliance/type_helpers.cc | dictav/zetasql | f4b7df010ae94941a984930a82175ee8836d9c0e | [
"Apache-2.0"
] | null | null | null | zetasql/compliance/type_helpers.cc | dictav/zetasql | f4b7df010ae94941a984930a82175ee8836d9c0e | [
"Apache-2.0"
] | null | null | null | //
// Copyright 2019 ZetaSQL 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 "zetasql/compliance/type_helpers.h"
#include <memory>
#include <string>
#include <vector>
#include "zetasql/public/strings.h"
#include "zetasql/base/ret_check.h"
#include "zetasql/base/status_macros.h"
namespace zetasql {
static std::string GetColumnAlias(const std::string& alias) {
// We use the empty std::string as anonymous column name.
return IsInternalAlias(alias) ? "" : alias;
}
static zetasql_base::StatusOr<const StructType*> CreateStructTypeForTableRow(
const ResolvedColumnList& table_columns, TypeFactory* type_factory) {
std::vector<StructType::StructField> fields;
fields.reserve(table_columns.size());
for (int i = 0; i < table_columns.size(); ++i) {
fields.push_back(
{GetColumnAlias(table_columns[i].name()), table_columns[i].type()});
}
const StructType* table_struct;
ZETASQL_RETURN_IF_ERROR(type_factory->MakeStructType(fields, &table_struct));
return table_struct;
}
const char* kDMLOutputNumRowsModifiedColumnName = "num_rows_modified";
const char* kDMLOutputAllRowsColumnName = "all_rows";
zetasql_base::StatusOr<const ArrayType*> CreateTableArrayType(
const ResolvedColumnList& table_columns, bool is_value_table,
TypeFactory* type_factory) {
const Type* element_type = nullptr;
if (is_value_table) {
ZETASQL_RET_CHECK_EQ(1, table_columns.size());
element_type = table_columns[0].type();
} else {
ZETASQL_ASSIGN_OR_RETURN(const StructType* table_struct,
CreateStructTypeForTableRow(table_columns, type_factory));
element_type = table_struct;
}
const ArrayType* table_array;
ZETASQL_RETURN_IF_ERROR(type_factory->MakeArrayType(element_type, &table_array));
return table_array;
}
zetasql_base::StatusOr<const StructType*> CreateDMLOutputType(
const ArrayType* table_array_type, TypeFactory* type_factory) {
std::vector<StructType::StructField> fields;
fields.emplace_back(kDMLOutputNumRowsModifiedColumnName, types::Int64Type());
fields.emplace_back(kDMLOutputAllRowsColumnName, table_array_type);
const StructType* dml_output_type;
ZETASQL_RETURN_IF_ERROR(type_factory->MakeStructType(fields, &dml_output_type));
return dml_output_type;
}
} // namespace zetasql
| 35.64557 | 83 | 0.760653 | [
"vector"
] |
b472cdb0192b10f2d1b3e5e2126d2ad087403d0c | 5,746 | cpp | C++ | Models/src/models/MSSM30atQ.cpp | aaronvincent/gambit_aaron | a38bd6fc10d781e71f2adafd401c76e1e3476b05 | [
"Unlicense"
] | null | null | null | Models/src/models/MSSM30atQ.cpp | aaronvincent/gambit_aaron | a38bd6fc10d781e71f2adafd401c76e1e3476b05 | [
"Unlicense"
] | null | null | null | Models/src/models/MSSM30atQ.cpp | aaronvincent/gambit_aaron | a38bd6fc10d781e71f2adafd401c76e1e3476b05 | [
"Unlicense"
] | null | null | null | /// GAMBIT: Global and Modular BSM Inference Tool
/// *********************************************
///
/// MSSMD30atQ translation function definitions
///
/// Specialisation of MSSM63atQ with all
/// off-diagonal m and A terms set to zero.
///
/// *********************************************
///
/// Authors
/// =======
///
/// (add name and date if you modify)
///
/// \author Ben Farmer
/// (ben.farmer@gmail.com)
/// \date 2015 Aug
///
/// *********************************************
#include <string>
#include <vector>
#include "gambit/Models/model_macros.hpp"
#include "gambit/Models/model_helpers.hpp"
#include "gambit/Logs/logger.hpp"
#include "gambit/Utils/util_functions.hpp"
#include "gambit/Models/models/MSSM30atQ.hpp"
// Activate debug output
//#define MSSM30atQ_DBUG
using namespace Gambit::Utils;
#define MODEL MSSM30atQ
void MODEL_NAMESPACE::MSSM30atQ_to_MSSM63atQ (const ModelParameters &myP, ModelParameters &targetP)
{
logger()<<"Running interpret_as_parent calculations for MSSM30atQ --> MSSM63atQ..."<<LogTags::info<<EOM;
targetP.setValue("Qin", myP["Qin"] );
targetP.setValue("TanBeta", myP["TanBeta"] );
targetP.setValue("SignMu", myP["SignMu"] );
// soft gaugino masses
targetP.setValue("M1", myP["M1"] );
targetP.setValue("M2", myP["M2"] );
targetP.setValue("M3", myP["M3"] );
// soft Higgs masses
targetP.setValue("mHu2", myP["mHu2"] );
targetP.setValue("mHd2", myP["mHd2"] );
// RH squark soft masses
// Off-diagonal elements set to zero
// Only upper diagonal needed (symmetric)
targetP.setValue("mq2_11", myP["mq2_1"] );
targetP.setValue("mq2_12", 0. );
targetP.setValue("mq2_13", 0. );
//targetP.setValue("mq2_21", 0. );
targetP.setValue("mq2_22", myP["mq2_2"] );
targetP.setValue("mq2_23", 0. );
//targetP.setValue("mq2_31", 0. );
//targetP.setValue("mq2_32", 0. );
targetP.setValue("mq2_33", myP["mq2_2"] );
// RH slepton soft masses
// Off-diagonal elements set to zero
// Only upper diagonal needed (symmetric)
targetP.setValue("ml2_11", myP["ml2_1"] );
targetP.setValue("ml2_12", 0. );
targetP.setValue("ml2_13", 0. );
//targetP.setValue("ml2_21", 0. );
targetP.setValue("ml2_22", myP["ml2_2"] );
targetP.setValue("ml2_23", 0. );
//targetP.setValue("ml2_31", 0. );
//targetP.setValue("ml2_32", 0. );
targetP.setValue("ml2_33", myP["ml2_3"] );
// LH down-type slepton soft masses
// Off-diagonal elements set to zero
// Only upper diagonal needed (symmetric)
targetP.setValue("md2_11", myP["md2_1"] );
targetP.setValue("md2_12", 0. );
targetP.setValue("md2_13", 0. );
//targetP.setValue("md2_21", 0. );
targetP.setValue("md2_22", myP["md2_2"] );
targetP.setValue("md2_23", 0. );
//targetP.setValue("md2_31", 0. );
//targetP.setValue("md2_32", 0. );
targetP.setValue("md2_33", myP["md2_3"] );
// LH up-type slepton soft masses
// Off-diagonal elements set to zero
// Only upper diagonal needed (symmetric)
targetP.setValue("mu2_11", myP["mu2_1"] );
targetP.setValue("mu2_12", 0. );
targetP.setValue("mu2_13", 0. );
//targetP.setValue("mu2_21", 0. );
targetP.setValue("mu2_22", myP["mu2_2"] );
targetP.setValue("mu2_23", 0. );
//targetP.setValue("mu2_31", 0. );
//targetP.setValue("mu2_32", 0. );
targetP.setValue("mu2_33", myP["mu2_3"] );
// LH charged slepton soft masses
// Off-diagonal elements set to zero
// Only upper diagonal needed (symmetric)
targetP.setValue("me2_11", myP["me2_1"] );
targetP.setValue("me2_12", 0. );
targetP.setValue("me2_13", 0. );
//targetP.setValue("me2_21", 0. );
targetP.setValue("me2_22", myP["me2_2"] );
targetP.setValue("me2_23", 0. );
//targetP.setValue("me2_31", 0. );
//targetP.setValue("me2_32", 0. );
targetP.setValue("me2_33", myP["me2_3"] );
// slepton trilinear couplings
// Off-diagonal elements set to zero
targetP.setValue("Ae_11", myP["Ae_1"] );
targetP.setValue("Ae_12", 0. );
targetP.setValue("Ae_13", 0. );
targetP.setValue("Ae_21", 0. );
targetP.setValue("Ae_22", myP["Ae_2"] );
targetP.setValue("Ae_23", 0. );
targetP.setValue("Ae_31", 0. );
targetP.setValue("Ae_32", 0. );
targetP.setValue("Ae_33", myP["Ae_3"] );
// down-type trilinear couplings
// Off-diagonal elements set to zero
// First and second generation to zero
targetP.setValue("Ad_11", myP["Ad_1"] );
targetP.setValue("Ad_12", 0. );
targetP.setValue("Ad_13", 0. );
targetP.setValue("Ad_21", 0. );
targetP.setValue("Ad_22", myP["Ad_2"] );
targetP.setValue("Ad_23", 0. );
targetP.setValue("Ad_31", 0. );
targetP.setValue("Ad_32", 0. );
targetP.setValue("Ad_33", myP["Ad_3"] );
// up-type trilinear couplings
// Off-diagonal elements set to zero
// First and second generation set to zero
targetP.setValue("Au_11", myP["Au_1"] );
targetP.setValue("Au_12", 0. );
targetP.setValue("Au_13", 0. );
targetP.setValue("Au_21", 0. );
targetP.setValue("Au_22", myP["Au_2"] );
targetP.setValue("Au_23", 0. );
targetP.setValue("Au_31", 0. );
targetP.setValue("Au_32", 0. );
targetP.setValue("Au_33", myP["Au_3"] );
// Whew, done!
#ifdef MSSM30atQ_DBUG
std::cout << "MSSM30atQ parameters:" << myP << std::endl;
std::cout << "MSSM63atQ parameters:" << targetP << std::endl;
#endif
}
#undef MODEL
| 31.398907 | 109 | 0.585451 | [
"vector",
"model"
] |
b4737ed62cd0ae5c917c9ccb70be7bb6fac36187 | 28,370 | cpp | C++ | Direct3D11/BasicHLSL11/BasicHLSL11.cpp | walbourn/directx-sdk-legacy-samples | 93e8cc554b5ecb5cd574a06071ed784b6cb73fc5 | [
"MIT"
] | 27 | 2021-03-01T23:50:39.000Z | 2022-03-04T03:27:17.000Z | Direct3D11/BasicHLSL11/BasicHLSL11.cpp | walbourn/directx-sdk-legacy-samples | 93e8cc554b5ecb5cd574a06071ed784b6cb73fc5 | [
"MIT"
] | 3 | 2021-03-02T00:39:56.000Z | 2021-12-02T19:50:03.000Z | Direct3D11/BasicHLSL11/BasicHLSL11.cpp | walbourn/directx-sdk-legacy-samples | 93e8cc554b5ecb5cd574a06071ed784b6cb73fc5 | [
"MIT"
] | 3 | 2021-03-29T16:23:54.000Z | 2022-03-05T08:35:05.000Z | //--------------------------------------------------------------------------------------
// File: BasicHLSL11.cpp
//
// This sample shows a simple example of the Microsoft Direct3D's High-Level
// Shader Language (HLSL) using the Effect interface.
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License (MIT).
//--------------------------------------------------------------------------------------
#include "DXUT.h"
#include "DXUTcamera.h"
#include "DXUTgui.h"
#include "DXUTsettingsDlg.h"
#include "SDKmisc.h"
#include "SDKMesh.h"
#include "resource.h"
//--------------------------------------------------------------------------------------
// Global variables
//--------------------------------------------------------------------------------------
CDXUTDialogResourceManager g_DialogResourceManager; // manager for shared resources of dialogs
CModelViewerCamera g_Camera; // A model viewing camera
CDXUTDirectionWidget g_LightControl;
CD3DSettingsDlg g_D3DSettingsDlg; // Device settings dialog
CDXUTDialog g_HUD; // manages the 3D
CDXUTDialog g_SampleUI; // dialog for sample specific controls
D3DXMATRIXA16 g_mCenterMesh;
float g_fLightScale;
int g_nNumActiveLights;
int g_nActiveLight;
bool g_bShowHelp = false; // If true, it renders the UI control text
// Direct3D9 resources
CDXUTTextHelper* g_pTxtHelper = NULL;
CDXUTSDKMesh g_Mesh11;
ID3D11InputLayout* g_pVertexLayout11 = NULL;
ID3D11Buffer* g_pVertexBuffer = NULL;
ID3D11Buffer* g_pIndexBuffer = NULL;
ID3D11VertexShader* g_pVertexShader = NULL;
ID3D11PixelShader* g_pPixelShader = NULL;
ID3D11SamplerState* g_pSamLinear = NULL;
struct CB_VS_PER_OBJECT
{
D3DXMATRIX m_WorldViewProj;
D3DXMATRIX m_World;
};
UINT g_iCBVSPerObjectBind = 0;
struct CB_PS_PER_OBJECT
{
D3DXVECTOR4 m_vObjectColor;
};
UINT g_iCBPSPerObjectBind = 0;
struct CB_PS_PER_FRAME
{
D3DXVECTOR4 m_vLightDirAmbient;
};
UINT g_iCBPSPerFrameBind = 1;
ID3D11Buffer* g_pcbVSPerObject = NULL;
ID3D11Buffer* g_pcbPSPerObject = NULL;
ID3D11Buffer* g_pcbPSPerFrame = NULL;
//--------------------------------------------------------------------------------------
// UI control IDs
//--------------------------------------------------------------------------------------
#define IDC_TOGGLEFULLSCREEN 1
#define IDC_TOGGLEREF 3
#define IDC_CHANGEDEVICE 4
//--------------------------------------------------------------------------------------
// Forward declarations
//--------------------------------------------------------------------------------------
bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext );
void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext );
LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing,
void* pUserContext );
void CALLBACK OnKeyboard( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext );
void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext );
extern bool CALLBACK IsD3D9DeviceAcceptable( D3DCAPS9* pCaps, D3DFORMAT AdapterFormat, D3DFORMAT BackBufferFormat,
bool bWindowed, void* pUserContext );
extern HRESULT CALLBACK OnD3D9CreateDevice( IDirect3DDevice9* pd3dDevice,
const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext );
extern HRESULT CALLBACK OnD3D9ResetDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc,
void* pUserContext );
extern void CALLBACK OnD3D9FrameRender( IDirect3DDevice9* pd3dDevice, double fTime, float fElapsedTime,
void* pUserContext );
extern void CALLBACK OnD3D9LostDevice( void* pUserContext );
extern void CALLBACK OnD3D9DestroyDevice( void* pUserContext );
bool CALLBACK IsD3D11DeviceAcceptable(const CD3D11EnumAdapterInfo *AdapterInfo, UINT Output, const CD3D11EnumDeviceInfo *DeviceInfo,
DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext );
HRESULT CALLBACK OnD3D11CreateDevice( ID3D11Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc,
void* pUserContext );
HRESULT CALLBACK OnD3D11ResizedSwapChain( ID3D11Device* pd3dDevice, IDXGISwapChain* pSwapChain,
const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext );
void CALLBACK OnD3D11ReleasingSwapChain( void* pUserContext );
void CALLBACK OnD3D11DestroyDevice( void* pUserContext );
void CALLBACK OnD3D11FrameRender( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext, double fTime,
float fElapsedTime, void* pUserContext );
void InitApp();
void RenderText();
//--------------------------------------------------------------------------------------
// Entry point to the program. Initializes everything and goes into a message processing
// loop. Idle time is used to render the scene.
//--------------------------------------------------------------------------------------
int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow )
{
// Enable run-time memory check for debug builds.
#if defined(DEBUG) | defined(_DEBUG)
_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
#endif
// DXUT will create and use the best device (either D3D9 or D3D11)
// that is available on the system depending on which D3D callbacks are set below
// Set DXUT callbacks
DXUTSetCallbackDeviceChanging( ModifyDeviceSettings );
DXUTSetCallbackMsgProc( MsgProc );
DXUTSetCallbackKeyboard( OnKeyboard );
DXUTSetCallbackFrameMove( OnFrameMove );
DXUTSetCallbackD3D9DeviceAcceptable( IsD3D9DeviceAcceptable );
DXUTSetCallbackD3D9DeviceCreated( OnD3D9CreateDevice );
DXUTSetCallbackD3D9DeviceReset( OnD3D9ResetDevice );
DXUTSetCallbackD3D9FrameRender( OnD3D9FrameRender );
DXUTSetCallbackD3D9DeviceLost( OnD3D9LostDevice );
DXUTSetCallbackD3D9DeviceDestroyed( OnD3D9DestroyDevice );
DXUTSetCallbackD3D11DeviceAcceptable( IsD3D11DeviceAcceptable );
DXUTSetCallbackD3D11DeviceCreated( OnD3D11CreateDevice );
DXUTSetCallbackD3D11SwapChainResized( OnD3D11ResizedSwapChain );
DXUTSetCallbackD3D11FrameRender( OnD3D11FrameRender );
DXUTSetCallbackD3D11SwapChainReleasing( OnD3D11ReleasingSwapChain );
DXUTSetCallbackD3D11DeviceDestroyed( OnD3D11DestroyDevice );
InitApp();
DXUTInit( true, true, NULL ); // Parse the command line, show msgboxes on error, no extra command line params
DXUTSetCursorSettings( true, true ); // Show the cursor and clip it when in full screen
DXUTCreateWindow( L"BasicHLSL11" );
DXUTCreateDevice (D3D_FEATURE_LEVEL_9_2, true, 800, 600 );
//DXUTCreateDevice(true, 640, 480);
DXUTMainLoop(); // Enter into the DXUT render loop
return DXUTGetExitCode();
}
//--------------------------------------------------------------------------------------
// Initialize the app
//--------------------------------------------------------------------------------------
void InitApp()
{
D3DXVECTOR3 vLightDir( -1, 1, -1 );
D3DXVec3Normalize( &vLightDir, &vLightDir );
g_LightControl.SetLightDirection( vLightDir );
// Initialize dialogs
g_D3DSettingsDlg.Init( &g_DialogResourceManager );
g_HUD.Init( &g_DialogResourceManager );
g_SampleUI.Init( &g_DialogResourceManager );
g_HUD.SetCallback( OnGUIEvent ); int iY = 10;
g_HUD.AddButton( IDC_TOGGLEFULLSCREEN, L"Toggle full screen", 0, iY, 170, 23 );
g_HUD.AddButton( IDC_TOGGLEREF, L"Toggle REF (F3)", 0, iY += 26, 170, 23, VK_F3 );
g_HUD.AddButton( IDC_CHANGEDEVICE, L"Change device (F2)", 0, iY += 26, 170, 23, VK_F2 );
g_SampleUI.SetCallback( OnGUIEvent ); iY = 10;
}
//--------------------------------------------------------------------------------------
// Called right before creating a D3D9 or D3D11 device, allowing the app to modify the device settings as needed
//--------------------------------------------------------------------------------------
bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext )
{
// Uncomment this to get debug information from D3D11
//pDeviceSettings->d3d11.CreateFlags |= D3D11_CREATE_DEVICE_DEBUG;
// For the first device created if its a REF device, optionally display a warning dialog box
static bool s_bFirstTime = true;
if( s_bFirstTime )
{
s_bFirstTime = false;
if( ( DXUT_D3D11_DEVICE == pDeviceSettings->ver &&
pDeviceSettings->d3d11.DriverType == D3D_DRIVER_TYPE_REFERENCE ) )
{
DXUTDisplaySwitchingToREFWarning( pDeviceSettings->ver );
}
}
return true;
}
//--------------------------------------------------------------------------------------
// Handle updates to the scene. This is called regardless of which D3D API is used
//--------------------------------------------------------------------------------------
void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext )
{
// Update the camera's position based on user input
g_Camera.FrameMove( fElapsedTime );
}
//--------------------------------------------------------------------------------------
// Render the help and statistics text
//--------------------------------------------------------------------------------------
void RenderText()
{
UINT nBackBufferHeight = ( DXUTIsAppRenderingWithD3D9() ) ? DXUTGetD3D9BackBufferSurfaceDesc()->Height :
DXUTGetDXGIBackBufferSurfaceDesc()->Height;
g_pTxtHelper->Begin();
g_pTxtHelper->SetInsertionPos( 2, 0 );
g_pTxtHelper->SetForegroundColor( D3DXCOLOR( 1.0f, 1.0f, 0.0f, 1.0f ) );
g_pTxtHelper->DrawTextLine( DXUTGetFrameStats( DXUTIsVsyncEnabled() ) );
g_pTxtHelper->DrawTextLine( DXUTGetDeviceStats() );
// Draw help
if( g_bShowHelp )
{
g_pTxtHelper->SetInsertionPos( 2, nBackBufferHeight - 20 * 6 );
g_pTxtHelper->SetForegroundColor( D3DXCOLOR( 1.0f, 0.75f, 0.0f, 1.0f ) );
g_pTxtHelper->DrawTextLine( L"Controls:" );
g_pTxtHelper->SetInsertionPos( 20, nBackBufferHeight - 20 * 5 );
g_pTxtHelper->DrawTextLine( L"Rotate model: Left mouse button\n"
L"Rotate light: Right mouse button\n"
L"Rotate camera: Middle mouse button\n"
L"Zoom camera: Mouse wheel scroll\n" );
g_pTxtHelper->SetInsertionPos( 550, nBackBufferHeight - 20 * 5 );
g_pTxtHelper->DrawTextLine( L"Hide help: F1\n"
L"Quit: ESC\n" );
}
else
{
g_pTxtHelper->SetForegroundColor( D3DXCOLOR( 1.0f, 1.0f, 1.0f, 1.0f ) );
g_pTxtHelper->DrawTextLine( L"Press F1 for help" );
}
g_pTxtHelper->End();
}
//--------------------------------------------------------------------------------------
// Handle messages to the application
//--------------------------------------------------------------------------------------
LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing,
void* pUserContext )
{
// Pass messages to dialog resource manager calls so GUI state is updated correctly
*pbNoFurtherProcessing = g_DialogResourceManager.MsgProc( hWnd, uMsg, wParam, lParam );
if( *pbNoFurtherProcessing )
return 0;
// Pass messages to settings dialog if its active
if( g_D3DSettingsDlg.IsActive() )
{
g_D3DSettingsDlg.MsgProc( hWnd, uMsg, wParam, lParam );
return 0;
}
// Give the dialogs a chance to handle the message first
*pbNoFurtherProcessing = g_HUD.MsgProc( hWnd, uMsg, wParam, lParam );
if( *pbNoFurtherProcessing )
return 0;
*pbNoFurtherProcessing = g_SampleUI.MsgProc( hWnd, uMsg, wParam, lParam );
if( *pbNoFurtherProcessing )
return 0;
g_LightControl.HandleMessages( hWnd, uMsg, wParam, lParam );
// Pass all remaining windows messages to camera so it can respond to user input
g_Camera.HandleMessages( hWnd, uMsg, wParam, lParam );
return 0;
}
//--------------------------------------------------------------------------------------
// Handle key presses
//--------------------------------------------------------------------------------------
void CALLBACK OnKeyboard( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext )
{
if( bKeyDown )
{
switch( nChar )
{
case VK_F1:
g_bShowHelp = !g_bShowHelp; break;
}
}
}
//--------------------------------------------------------------------------------------
// Handles the GUI events
//--------------------------------------------------------------------------------------
void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext )
{
switch( nControlID )
{
case IDC_TOGGLEFULLSCREEN:
DXUTToggleFullScreen(); break;
case IDC_TOGGLEREF:
DXUTToggleREF(); break;
case IDC_CHANGEDEVICE:
g_D3DSettingsDlg.SetActive( !g_D3DSettingsDlg.IsActive() ); break;
}
}
//--------------------------------------------------------------------------------------
// Reject any D3D11 devices that aren't acceptable by returning false
//--------------------------------------------------------------------------------------
bool CALLBACK IsD3D11DeviceAcceptable( const CD3D11EnumAdapterInfo *AdapterInfo, UINT Output, const CD3D11EnumDeviceInfo *DeviceInfo,
DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext )
{
return true;
}
//--------------------------------------------------------------------------------------
// Find and compile the specified shader
//--------------------------------------------------------------------------------------
HRESULT CompileShaderFromFile( WCHAR* szFileName, LPCSTR szEntryPoint, LPCSTR szShaderModel, ID3DBlob** ppBlobOut )
{
HRESULT hr = S_OK;
// find the file
WCHAR str[MAX_PATH];
V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, szFileName ) );
DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS;
#if defined( DEBUG ) || defined( _DEBUG )
// Set the D3DCOMPILE_DEBUG flag to embed debug information in the shaders.
// Setting this flag improves the shader debugging experience, but still allows
// the shaders to be optimized and to run exactly the way they will run in
// the release configuration of this program.
dwShaderFlags |= D3DCOMPILE_DEBUG;
#endif
ID3DBlob* pErrorBlob;
hr = D3DX11CompileFromFile( str, NULL, NULL, szEntryPoint, szShaderModel,
dwShaderFlags, 0, NULL, ppBlobOut, &pErrorBlob, NULL );
if( FAILED(hr) )
{
if( pErrorBlob != NULL )
OutputDebugStringA( (char*)pErrorBlob->GetBufferPointer() );
SAFE_RELEASE( pErrorBlob );
return hr;
}
SAFE_RELEASE( pErrorBlob );
return S_OK;
}
//--------------------------------------------------------------------------------------
// Create any D3D11 resources that aren't dependant on the back buffer
//--------------------------------------------------------------------------------------
HRESULT CALLBACK OnD3D11CreateDevice( ID3D11Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc,
void* pUserContext )
{
HRESULT hr;
ID3D11DeviceContext* pd3dImmediateContext = DXUTGetD3D11DeviceContext();
V_RETURN( g_DialogResourceManager.OnD3D11CreateDevice( pd3dDevice, pd3dImmediateContext ) );
V_RETURN( g_D3DSettingsDlg.OnD3D11CreateDevice( pd3dDevice ) );
g_pTxtHelper = new CDXUTTextHelper( pd3dDevice, pd3dImmediateContext, &g_DialogResourceManager, 15 );
D3DXVECTOR3 vCenter( 0.25767413f, -28.503521f, 111.00689f );
FLOAT fObjectRadius = 378.15607f;
D3DXMatrixTranslation( &g_mCenterMesh, -vCenter.x, -vCenter.y, -vCenter.z );
D3DXMATRIXA16 m;
D3DXMatrixRotationY( &m, D3DX_PI );
g_mCenterMesh *= m;
D3DXMatrixRotationX( &m, D3DX_PI / 2.0f );
g_mCenterMesh *= m;
// Compile the shaders using the lowest possible profile for broadest feature level support
ID3DBlob* pVertexShaderBuffer = NULL;
V_RETURN( CompileShaderFromFile( L"BasicHLSL11_VS.hlsl", "VSMain", "vs_4_0_level_9_1", &pVertexShaderBuffer ) );
ID3DBlob* pPixelShaderBuffer = NULL;
V_RETURN( CompileShaderFromFile( L"BasicHLSL11_PS.hlsl", "PSMain", "ps_4_0_level_9_1", &pPixelShaderBuffer ) );
// Create the shaders
V_RETURN( pd3dDevice->CreateVertexShader( pVertexShaderBuffer->GetBufferPointer(),
pVertexShaderBuffer->GetBufferSize(), NULL, &g_pVertexShader ) );
DXUT_SetDebugName( g_pVertexShader, "VSMain" );
V_RETURN( pd3dDevice->CreatePixelShader( pPixelShaderBuffer->GetBufferPointer(),
pPixelShaderBuffer->GetBufferSize(), NULL, &g_pPixelShader ) );
DXUT_SetDebugName( g_pPixelShader, "PSMain" );
// Create our vertex input layout
const D3D11_INPUT_ELEMENT_DESC layout[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
V_RETURN( pd3dDevice->CreateInputLayout( layout, ARRAYSIZE( layout ), pVertexShaderBuffer->GetBufferPointer(),
pVertexShaderBuffer->GetBufferSize(), &g_pVertexLayout11 ) );
DXUT_SetDebugName( g_pVertexLayout11, "Primary" );
SAFE_RELEASE( pVertexShaderBuffer );
SAFE_RELEASE( pPixelShaderBuffer );
// Load the mesh
V_RETURN( g_Mesh11.Create( pd3dDevice, L"tiny\\tiny.sdkmesh", true ) );
// Create a sampler state
D3D11_SAMPLER_DESC SamDesc;
SamDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
SamDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
SamDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
SamDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
SamDesc.MipLODBias = 0.0f;
SamDesc.MaxAnisotropy = 1;
SamDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
SamDesc.BorderColor[0] = SamDesc.BorderColor[1] = SamDesc.BorderColor[2] = SamDesc.BorderColor[3] = 0;
SamDesc.MinLOD = 0;
SamDesc.MaxLOD = D3D11_FLOAT32_MAX;
V_RETURN( pd3dDevice->CreateSamplerState( &SamDesc, &g_pSamLinear ) );
DXUT_SetDebugName( g_pSamLinear, "Primary" );
// Setup constant buffers
D3D11_BUFFER_DESC Desc;
Desc.Usage = D3D11_USAGE_DYNAMIC;
Desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
Desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
Desc.MiscFlags = 0;
Desc.ByteWidth = sizeof( CB_VS_PER_OBJECT );
V_RETURN( pd3dDevice->CreateBuffer( &Desc, NULL, &g_pcbVSPerObject ) );
DXUT_SetDebugName( g_pcbVSPerObject, "CB_VS_PER_OBJECT" );
Desc.ByteWidth = sizeof( CB_PS_PER_OBJECT );
V_RETURN( pd3dDevice->CreateBuffer( &Desc, NULL, &g_pcbPSPerObject ) );
DXUT_SetDebugName( g_pcbPSPerObject, "CB_PS_PER_OBJECT" );
Desc.ByteWidth = sizeof( CB_PS_PER_FRAME );
V_RETURN( pd3dDevice->CreateBuffer( &Desc, NULL, &g_pcbPSPerFrame ) );
DXUT_SetDebugName( g_pcbPSPerFrame, "CB_PS_PER_FRAME" );
// Setup the camera's view parameters
D3DXVECTOR3 vecEye( 0.0f, 0.0f, -100.0f );
D3DXVECTOR3 vecAt ( 0.0f, 0.0f, -0.0f );
g_Camera.SetViewParams( &vecEye, &vecAt );
g_Camera.SetRadius( fObjectRadius * 3.0f, fObjectRadius * 0.5f, fObjectRadius * 10.0f );
return S_OK;
}
//--------------------------------------------------------------------------------------
// Create any D3D11 resources that depend on the back buffer
//--------------------------------------------------------------------------------------
HRESULT CALLBACK OnD3D11ResizedSwapChain( ID3D11Device* pd3dDevice, IDXGISwapChain* pSwapChain,
const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext )
{
HRESULT hr;
V_RETURN( g_DialogResourceManager.OnD3D11ResizedSwapChain( pd3dDevice, pBackBufferSurfaceDesc ) );
V_RETURN( g_D3DSettingsDlg.OnD3D11ResizedSwapChain( pd3dDevice, pBackBufferSurfaceDesc ) );
// Setup the camera's projection parameters
float fAspectRatio = pBackBufferSurfaceDesc->Width / ( FLOAT )pBackBufferSurfaceDesc->Height;
g_Camera.SetProjParams( D3DX_PI / 4, fAspectRatio, 2.0f, 4000.0f );
g_Camera.SetWindow( pBackBufferSurfaceDesc->Width, pBackBufferSurfaceDesc->Height );
g_Camera.SetButtonMasks( MOUSE_MIDDLE_BUTTON, MOUSE_WHEEL, MOUSE_LEFT_BUTTON );
g_HUD.SetLocation( pBackBufferSurfaceDesc->Width - 170, 0 );
g_HUD.SetSize( 170, 170 );
g_SampleUI.SetLocation( pBackBufferSurfaceDesc->Width - 170, pBackBufferSurfaceDesc->Height - 300 );
g_SampleUI.SetSize( 170, 300 );
return S_OK;
}
//--------------------------------------------------------------------------------------
// Render the scene using the D3D11 device
//--------------------------------------------------------------------------------------
void CALLBACK OnD3D11FrameRender( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext, double fTime,
float fElapsedTime, void* pUserContext )
{
HRESULT hr;
// If the settings dialog is being shown, then render it instead of rendering the app's scene
if( g_D3DSettingsDlg.IsActive() )
{
g_D3DSettingsDlg.OnRender( fElapsedTime );
return;
}
// Clear the render target and depth stencil
float ClearColor[4] = { 0.0f, 0.25f, 0.25f, 0.55f };
ID3D11RenderTargetView* pRTV = DXUTGetD3D11RenderTargetView();
pd3dImmediateContext->ClearRenderTargetView( pRTV, ClearColor );
ID3D11DepthStencilView* pDSV = DXUTGetD3D11DepthStencilView();
pd3dImmediateContext->ClearDepthStencilView( pDSV, D3D11_CLEAR_DEPTH, 1.0, 0 );
D3DXMATRIX mWorldViewProjection;
D3DXVECTOR3 vLightDir;
D3DXMATRIX mWorld;
D3DXMATRIX mView;
D3DXMATRIX mProj;
// Get the projection & view matrix from the camera class
mProj = *g_Camera.GetProjMatrix();
mView = *g_Camera.GetViewMatrix();
// Get the light direction
vLightDir = g_LightControl.GetLightDirection();
// Per frame cb update
D3D11_MAPPED_SUBRESOURCE MappedResource;
V( pd3dImmediateContext->Map( g_pcbPSPerFrame, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource ) );
CB_PS_PER_FRAME* pPerFrame = ( CB_PS_PER_FRAME* )MappedResource.pData;
float fAmbient = 0.1f;
pPerFrame->m_vLightDirAmbient = D3DXVECTOR4( vLightDir.x, vLightDir.y, vLightDir.z, fAmbient );
pd3dImmediateContext->Unmap( g_pcbPSPerFrame, 0 );
pd3dImmediateContext->PSSetConstantBuffers( g_iCBPSPerFrameBind, 1, &g_pcbPSPerFrame );
//Get the mesh
//IA setup
pd3dImmediateContext->IASetInputLayout( g_pVertexLayout11 );
UINT Strides[1];
UINT Offsets[1];
ID3D11Buffer* pVB[1];
pVB[0] = g_Mesh11.GetVB11( 0, 0 );
Strides[0] = ( UINT )g_Mesh11.GetVertexStride( 0, 0 );
Offsets[0] = 0;
pd3dImmediateContext->IASetVertexBuffers( 0, 1, pVB, Strides, Offsets );
pd3dImmediateContext->IASetIndexBuffer( g_Mesh11.GetIB11( 0 ), g_Mesh11.GetIBFormat11( 0 ), 0 );
// Set the shaders
pd3dImmediateContext->VSSetShader( g_pVertexShader, NULL, 0 );
pd3dImmediateContext->PSSetShader( g_pPixelShader, NULL, 0 );
// Set the per object constant data
mWorld = g_mCenterMesh * *g_Camera.GetWorldMatrix();
mProj = *g_Camera.GetProjMatrix();
mView = *g_Camera.GetViewMatrix();
mWorldViewProjection = mWorld * mView * mProj;
// VS Per object
V( pd3dImmediateContext->Map( g_pcbVSPerObject, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource ) );
CB_VS_PER_OBJECT* pVSPerObject = ( CB_VS_PER_OBJECT* )MappedResource.pData;
D3DXMatrixTranspose( &pVSPerObject->m_WorldViewProj, &mWorldViewProjection );
D3DXMatrixTranspose( &pVSPerObject->m_World, &mWorld );
pd3dImmediateContext->Unmap( g_pcbVSPerObject, 0 );
pd3dImmediateContext->VSSetConstantBuffers( g_iCBVSPerObjectBind, 1, &g_pcbVSPerObject );
// PS Per object
V( pd3dImmediateContext->Map( g_pcbPSPerObject, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource ) );
CB_PS_PER_OBJECT* pPSPerObject = ( CB_PS_PER_OBJECT* )MappedResource.pData;
pPSPerObject->m_vObjectColor = D3DXVECTOR4( 1, 1, 1, 1 );
pd3dImmediateContext->Unmap( g_pcbPSPerObject, 0 );
pd3dImmediateContext->PSSetConstantBuffers( g_iCBPSPerObjectBind, 1, &g_pcbPSPerObject );
//Render
SDKMESH_SUBSET* pSubset = NULL;
D3D11_PRIMITIVE_TOPOLOGY PrimType;
pd3dImmediateContext->PSSetSamplers( 0, 1, &g_pSamLinear );
for( UINT subset = 0; subset < g_Mesh11.GetNumSubsets( 0 ); ++subset )
{
// Get the subset
pSubset = g_Mesh11.GetSubset( 0, subset );
PrimType = CDXUTSDKMesh::GetPrimitiveType11( ( SDKMESH_PRIMITIVE_TYPE )pSubset->PrimitiveType );
pd3dImmediateContext->IASetPrimitiveTopology( PrimType );
// TODO: D3D11 - material loading
ID3D11ShaderResourceView* pDiffuseRV = g_Mesh11.GetMaterial( pSubset->MaterialID )->pDiffuseRV11;
pd3dImmediateContext->PSSetShaderResources( 0, 1, &pDiffuseRV );
pd3dImmediateContext->DrawIndexed( ( UINT )pSubset->IndexCount, 0, ( UINT )pSubset->VertexStart );
}
DXUT_BeginPerfEvent( DXUT_PERFEVENTCOLOR, L"HUD / Stats" );
g_HUD.OnRender( fElapsedTime );
g_SampleUI.OnRender( fElapsedTime );
RenderText();
DXUT_EndPerfEvent();
}
//--------------------------------------------------------------------------------------
// Release D3D11 resources created in OnD3D11ResizedSwapChain
//--------------------------------------------------------------------------------------
void CALLBACK OnD3D11ReleasingSwapChain( void* pUserContext )
{
g_DialogResourceManager.OnD3D11ReleasingSwapChain();
}
//--------------------------------------------------------------------------------------
// Release D3D11 resources created in OnD3D11CreateDevice
//--------------------------------------------------------------------------------------
void CALLBACK OnD3D11DestroyDevice( void* pUserContext )
{
g_DialogResourceManager.OnD3D11DestroyDevice();
g_D3DSettingsDlg.OnD3D11DestroyDevice();
//CDXUTDirectionWidget::StaticOnD3D11DestroyDevice();
DXUTGetGlobalResourceCache().OnDestroyDevice();
SAFE_DELETE( g_pTxtHelper );
g_Mesh11.Destroy();
SAFE_RELEASE( g_pVertexLayout11 );
SAFE_RELEASE( g_pVertexBuffer );
SAFE_RELEASE( g_pIndexBuffer );
SAFE_RELEASE( g_pVertexShader );
SAFE_RELEASE( g_pPixelShader );
SAFE_RELEASE( g_pSamLinear );
SAFE_RELEASE( g_pcbVSPerObject );
SAFE_RELEASE( g_pcbPSPerObject );
SAFE_RELEASE( g_pcbPSPerFrame );
}
| 43.848532 | 134 | 0.599824 | [
"mesh",
"render",
"object",
"model",
"3d"
] |
b476de4a4b21d039b32dd8cbcea074aa8b2575cd | 6,072 | cpp | C++ | example/multi_threaded_echo_c++/client.cpp | mengzhongguanyu/brpc | a43bbf7afbefd84176b3ca2b454e160d2233e898 | [
"Apache-2.0"
] | 1 | 2017-10-17T06:57:23.000Z | 2017-10-17T06:57:23.000Z | example/multi_threaded_echo_c++/client.cpp | jamestang81/brpc | f2fa4f7b6c45d153d4d2dce6624763c701c05f43 | [
"Apache-2.0"
] | null | null | null | example/multi_threaded_echo_c++/client.cpp | jamestang81/brpc | f2fa4f7b6c45d153d4d2dce6624763c701c05f43 | [
"Apache-2.0"
] | 1 | 2021-03-25T17:39:45.000Z | 2021-03-25T17:39:45.000Z | // Copyright (c) 2014 Baidu, 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.
// A client sending requests to server by multiple threads.
#include <gflags/gflags.h>
#include <bthread/bthread.h>
#include <butil/logging.h>
#include <brpc/server.h>
#include <brpc/channel.h>
#include "echo.pb.h"
#include <bvar/bvar.h>
DEFINE_int32(thread_num, 50, "Number of threads to send requests");
DEFINE_bool(use_bthread, false, "Use bthread to send requests");
DEFINE_int32(attachment_size, 0, "Carry so many byte attachment along with requests");
DEFINE_int32(request_size, 16, "Bytes of each request");
DEFINE_string(protocol, "baidu_std", "Protocol type. Defined in src/brpc/options.proto");
DEFINE_string(connection_type, "", "Connection type. Available values: single, pooled, short");
DEFINE_string(server, "0.0.0.0:8002", "IP Address of server");
DEFINE_string(load_balancer, "", "The algorithm for load balancing");
DEFINE_int32(timeout_ms, 100, "RPC timeout in milliseconds");
DEFINE_int32(max_retry, 3, "Max retries(not including the first RPC)");
DEFINE_bool(dont_fail, false, "Print fatal when some call failed");
DEFINE_int32(dummy_port, 0, "Launch dummy server at this port");
DEFINE_string(http_content_type, "application/json", "Content type of http request");
std::string g_request;
std::string g_attachment;
bvar::LatencyRecorder g_latency_recorder("client");
bvar::Adder<int> g_error_count("client_error_count");
static void* sender(void* arg) {
// Normally, you should not call a Channel directly, but instead construct
// a stub Service wrapping it. stub can be shared by all threads as well.
example::EchoService_Stub stub(static_cast<google::protobuf::RpcChannel*>(arg));
int log_id = 0;
while (!brpc::IsAskedToQuit()) {
// We will receive response synchronously, safe to put variables
// on stack.
example::EchoRequest request;
example::EchoResponse response;
brpc::Controller cntl;
request.set_message(g_request);
cntl.set_log_id(log_id++); // set by user
if (FLAGS_protocol != "http" && FLAGS_protocol != "h2c") {
// Set attachment which is wired to network directly instead of
// being serialized into protobuf messages.
cntl.request_attachment().append(g_attachment);
} else {
cntl.http_request().set_content_type(FLAGS_http_content_type);
}
// Because `done'(last parameter) is NULL, this function waits until
// the response comes back or error occurs(including timedout).
stub.Echo(&cntl, &request, &response, NULL);
if (!cntl.Failed()) {
g_latency_recorder << cntl.latency_us();
} else {
g_error_count << 1;
CHECK(brpc::IsAskedToQuit() || !FLAGS_dont_fail)
<< "error=" << cntl.ErrorText() << " latency=" << cntl.latency_us();
// We can't connect to the server, sleep a while. Notice that this
// is a specific sleeping to prevent this thread from spinning too
// fast. You should continue the business logic in a production
// server rather than sleeping.
bthread_usleep(50000);
}
}
return NULL;
}
int main(int argc, char* argv[]) {
// Parse gflags. We recommend you to use gflags as well.
GFLAGS_NS::ParseCommandLineFlags(&argc, &argv, true);
// A Channel represents a communication line to a Server. Notice that
// Channel is thread-safe and can be shared by all threads in your program.
brpc::Channel channel;
// Initialize the channel, NULL means using default options.
brpc::ChannelOptions options;
options.protocol = FLAGS_protocol;
options.connection_type = FLAGS_connection_type;
options.connect_timeout_ms = std::min(FLAGS_timeout_ms / 2, 100);
options.timeout_ms = FLAGS_timeout_ms;
options.max_retry = FLAGS_max_retry;
if (channel.Init(FLAGS_server.c_str(), FLAGS_load_balancer.c_str(), &options) != 0) {
LOG(ERROR) << "Fail to initialize channel";
return -1;
}
if (FLAGS_attachment_size > 0) {
g_attachment.resize(FLAGS_attachment_size, 'a');
}
if (FLAGS_request_size <= 0) {
LOG(ERROR) << "Bad request_size=" << FLAGS_request_size;
return -1;
}
g_request.resize(FLAGS_request_size, 'r');
if (FLAGS_dummy_port > 0) {
brpc::StartDummyServerAt(FLAGS_dummy_port);
}
std::vector<bthread_t> tids;
tids.resize(FLAGS_thread_num);
if (!FLAGS_use_bthread) {
for (int i = 0; i < FLAGS_thread_num; ++i) {
if (pthread_create(&tids[i], NULL, sender, &channel) != 0) {
LOG(ERROR) << "Fail to create pthread";
return -1;
}
}
} else {
for (int i = 0; i < FLAGS_thread_num; ++i) {
if (bthread_start_background(
&tids[i], NULL, sender, &channel) != 0) {
LOG(ERROR) << "Fail to create bthread";
return -1;
}
}
}
while (!brpc::IsAskedToQuit()) {
sleep(1);
LOG(INFO) << "Sending EchoRequest at qps=" << g_latency_recorder.qps(1)
<< " latency=" << g_latency_recorder.latency(1);
}
LOG(INFO) << "EchoClient is going to quit";
for (int i = 0; i < FLAGS_thread_num; ++i) {
if (!FLAGS_use_bthread) {
pthread_join(tids[i], NULL);
} else {
bthread_join(tids[i], NULL);
}
}
return 0;
}
| 38.923077 | 95 | 0.647727 | [
"vector"
] |
b47a4f1d1015a8ac35b7b0cd82df2c709e29f858 | 65,219 | cpp | C++ | av/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.cpp | Keneral/aframeworks | af1d0010bfb88751837fb1afc355705bd8a9ad8b | [
"Unlicense"
] | 10 | 2020-04-17T04:02:36.000Z | 2021-11-23T11:38:42.000Z | av/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.cpp | Keneral/aframeworks | af1d0010bfb88751837fb1afc355705bd8a9ad8b | [
"Unlicense"
] | 3 | 2020-02-19T16:53:25.000Z | 2021-04-29T07:28:40.000Z | av/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.cpp | Keneral/aframeworks | af1d0010bfb88751837fb1afc355705bd8a9ad8b | [
"Unlicense"
] | 5 | 2019-12-25T04:05:02.000Z | 2022-01-14T16:57:55.000Z | /*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//#define LOG_NDEBUG 0
#define LOG_TAG "NuPlayerRenderer"
#include <utils/Log.h>
#include "NuPlayerRenderer.h"
#include <algorithm>
#include <cutils/properties.h>
#include <media/stagefright/foundation/ABuffer.h>
#include <media/stagefright/foundation/ADebug.h>
#include <media/stagefright/foundation/AMessage.h>
#include <media/stagefright/foundation/AUtils.h>
#include <media/stagefright/foundation/AWakeLock.h>
#include <media/stagefright/MediaClock.h>
#include <media/stagefright/MediaErrors.h>
#include <media/stagefright/MetaData.h>
#include <media/stagefright/Utils.h>
#include <media/stagefright/VideoFrameScheduler.h>
#include <inttypes.h>
namespace android {
/*
* Example of common configuration settings in shell script form
#Turn offload audio off (use PCM for Play Music) -- AudioPolicyManager
adb shell setprop audio.offload.disable 1
#Allow offload audio with video (requires offloading to be enabled) -- AudioPolicyManager
adb shell setprop audio.offload.video 1
#Use audio callbacks for PCM data
adb shell setprop media.stagefright.audio.cbk 1
#Use deep buffer for PCM data with video (it is generally enabled for audio-only)
adb shell setprop media.stagefright.audio.deep 1
#Set size of buffers for pcm audio sink in msec (example: 1000 msec)
adb shell setprop media.stagefright.audio.sink 1000
* These configurations take effect for the next track played (not the current track).
*/
static inline bool getUseAudioCallbackSetting() {
return property_get_bool("media.stagefright.audio.cbk", false /* default_value */);
}
static inline int32_t getAudioSinkPcmMsSetting() {
return property_get_int32(
"media.stagefright.audio.sink", 500 /* default_value */);
}
// Maximum time in paused state when offloading audio decompression. When elapsed, the AudioSink
// is closed to allow the audio DSP to power down.
static const int64_t kOffloadPauseMaxUs = 10000000ll;
// Maximum allowed delay from AudioSink, 1.5 seconds.
static const int64_t kMaxAllowedAudioSinkDelayUs = 1500000ll;
static const int64_t kMinimumAudioClockUpdatePeriodUs = 20 /* msec */ * 1000;
// static
const NuPlayer::Renderer::PcmInfo NuPlayer::Renderer::AUDIO_PCMINFO_INITIALIZER = {
AUDIO_CHANNEL_NONE,
AUDIO_OUTPUT_FLAG_NONE,
AUDIO_FORMAT_INVALID,
0, // mNumChannels
0 // mSampleRate
};
// static
const int64_t NuPlayer::Renderer::kMinPositionUpdateDelayUs = 100000ll;
NuPlayer::Renderer::Renderer(
const sp<MediaPlayerBase::AudioSink> &sink,
const sp<AMessage> ¬ify,
uint32_t flags)
: mAudioSink(sink),
mUseVirtualAudioSink(false),
mNotify(notify),
mFlags(flags),
mNumFramesWritten(0),
mDrainAudioQueuePending(false),
mDrainVideoQueuePending(false),
mAudioQueueGeneration(0),
mVideoQueueGeneration(0),
mAudioDrainGeneration(0),
mVideoDrainGeneration(0),
mAudioEOSGeneration(0),
mPlaybackSettings(AUDIO_PLAYBACK_RATE_DEFAULT),
mAudioFirstAnchorTimeMediaUs(-1),
mAnchorTimeMediaUs(-1),
mAnchorNumFramesWritten(-1),
mVideoLateByUs(0ll),
mHasAudio(false),
mHasVideo(false),
mNotifyCompleteAudio(false),
mNotifyCompleteVideo(false),
mSyncQueues(false),
mPaused(false),
mPauseDrainAudioAllowedUs(0),
mVideoSampleReceived(false),
mVideoRenderingStarted(false),
mVideoRenderingStartGeneration(0),
mAudioRenderingStartGeneration(0),
mRenderingDataDelivered(false),
mNextAudioClockUpdateTimeUs(-1),
mLastAudioMediaTimeUs(-1),
mAudioOffloadPauseTimeoutGeneration(0),
mAudioTornDown(false),
mCurrentOffloadInfo(AUDIO_INFO_INITIALIZER),
mCurrentPcmInfo(AUDIO_PCMINFO_INITIALIZER),
mTotalBuffersQueued(0),
mLastAudioBufferDrained(0),
mUseAudioCallback(false),
mWakeLock(new AWakeLock()) {
mMediaClock = new MediaClock;
mPlaybackRate = mPlaybackSettings.mSpeed;
mMediaClock->setPlaybackRate(mPlaybackRate);
}
NuPlayer::Renderer::~Renderer() {
if (offloadingAudio()) {
mAudioSink->stop();
mAudioSink->flush();
mAudioSink->close();
}
}
void NuPlayer::Renderer::queueBuffer(
bool audio,
const sp<ABuffer> &buffer,
const sp<AMessage> ¬ifyConsumed) {
sp<AMessage> msg = new AMessage(kWhatQueueBuffer, this);
msg->setInt32("queueGeneration", getQueueGeneration(audio));
msg->setInt32("audio", static_cast<int32_t>(audio));
msg->setBuffer("buffer", buffer);
msg->setMessage("notifyConsumed", notifyConsumed);
msg->post();
}
void NuPlayer::Renderer::queueEOS(bool audio, status_t finalResult) {
CHECK_NE(finalResult, (status_t)OK);
sp<AMessage> msg = new AMessage(kWhatQueueEOS, this);
msg->setInt32("queueGeneration", getQueueGeneration(audio));
msg->setInt32("audio", static_cast<int32_t>(audio));
msg->setInt32("finalResult", finalResult);
msg->post();
}
status_t NuPlayer::Renderer::setPlaybackSettings(const AudioPlaybackRate &rate) {
sp<AMessage> msg = new AMessage(kWhatConfigPlayback, this);
writeToAMessage(msg, rate);
sp<AMessage> response;
status_t err = msg->postAndAwaitResponse(&response);
if (err == OK && response != NULL) {
CHECK(response->findInt32("err", &err));
}
return err;
}
status_t NuPlayer::Renderer::onConfigPlayback(const AudioPlaybackRate &rate /* sanitized */) {
if (rate.mSpeed == 0.f) {
onPause();
// don't call audiosink's setPlaybackRate if pausing, as pitch does not
// have to correspond to the any non-0 speed (e.g old speed). Keep
// settings nonetheless, using the old speed, in case audiosink changes.
AudioPlaybackRate newRate = rate;
newRate.mSpeed = mPlaybackSettings.mSpeed;
mPlaybackSettings = newRate;
return OK;
}
if (mAudioSink != NULL && mAudioSink->ready()) {
status_t err = mAudioSink->setPlaybackRate(rate);
if (err != OK) {
return err;
}
}
mPlaybackSettings = rate;
mPlaybackRate = rate.mSpeed;
mMediaClock->setPlaybackRate(mPlaybackRate);
return OK;
}
status_t NuPlayer::Renderer::getPlaybackSettings(AudioPlaybackRate *rate /* nonnull */) {
sp<AMessage> msg = new AMessage(kWhatGetPlaybackSettings, this);
sp<AMessage> response;
status_t err = msg->postAndAwaitResponse(&response);
if (err == OK && response != NULL) {
CHECK(response->findInt32("err", &err));
if (err == OK) {
readFromAMessage(response, rate);
}
}
return err;
}
status_t NuPlayer::Renderer::onGetPlaybackSettings(AudioPlaybackRate *rate /* nonnull */) {
if (mAudioSink != NULL && mAudioSink->ready()) {
status_t err = mAudioSink->getPlaybackRate(rate);
if (err == OK) {
if (!isAudioPlaybackRateEqual(*rate, mPlaybackSettings)) {
ALOGW("correcting mismatch in internal/external playback rate");
}
// get playback settings used by audiosink, as it may be
// slightly off due to audiosink not taking small changes.
mPlaybackSettings = *rate;
if (mPaused) {
rate->mSpeed = 0.f;
}
}
return err;
}
*rate = mPlaybackSettings;
return OK;
}
status_t NuPlayer::Renderer::setSyncSettings(const AVSyncSettings &sync, float videoFpsHint) {
sp<AMessage> msg = new AMessage(kWhatConfigSync, this);
writeToAMessage(msg, sync, videoFpsHint);
sp<AMessage> response;
status_t err = msg->postAndAwaitResponse(&response);
if (err == OK && response != NULL) {
CHECK(response->findInt32("err", &err));
}
return err;
}
status_t NuPlayer::Renderer::onConfigSync(const AVSyncSettings &sync, float videoFpsHint __unused) {
if (sync.mSource != AVSYNC_SOURCE_DEFAULT) {
return BAD_VALUE;
}
// TODO: support sync sources
return INVALID_OPERATION;
}
status_t NuPlayer::Renderer::getSyncSettings(AVSyncSettings *sync, float *videoFps) {
sp<AMessage> msg = new AMessage(kWhatGetSyncSettings, this);
sp<AMessage> response;
status_t err = msg->postAndAwaitResponse(&response);
if (err == OK && response != NULL) {
CHECK(response->findInt32("err", &err));
if (err == OK) {
readFromAMessage(response, sync, videoFps);
}
}
return err;
}
status_t NuPlayer::Renderer::onGetSyncSettings(
AVSyncSettings *sync /* nonnull */, float *videoFps /* nonnull */) {
*sync = mSyncSettings;
*videoFps = -1.f;
return OK;
}
void NuPlayer::Renderer::flush(bool audio, bool notifyComplete) {
{
Mutex::Autolock autoLock(mLock);
if (audio) {
mNotifyCompleteAudio |= notifyComplete;
clearAudioFirstAnchorTime_l();
++mAudioQueueGeneration;
++mAudioDrainGeneration;
} else {
mNotifyCompleteVideo |= notifyComplete;
++mVideoQueueGeneration;
++mVideoDrainGeneration;
}
clearAnchorTime_l();
mVideoLateByUs = 0;
mSyncQueues = false;
}
sp<AMessage> msg = new AMessage(kWhatFlush, this);
msg->setInt32("audio", static_cast<int32_t>(audio));
msg->post();
}
void NuPlayer::Renderer::signalTimeDiscontinuity() {
}
void NuPlayer::Renderer::signalDisableOffloadAudio() {
(new AMessage(kWhatDisableOffloadAudio, this))->post();
}
void NuPlayer::Renderer::signalEnableOffloadAudio() {
(new AMessage(kWhatEnableOffloadAudio, this))->post();
}
void NuPlayer::Renderer::pause() {
(new AMessage(kWhatPause, this))->post();
}
void NuPlayer::Renderer::resume() {
(new AMessage(kWhatResume, this))->post();
}
void NuPlayer::Renderer::setVideoFrameRate(float fps) {
sp<AMessage> msg = new AMessage(kWhatSetVideoFrameRate, this);
msg->setFloat("frame-rate", fps);
msg->post();
}
// Called on any threads without mLock acquired.
status_t NuPlayer::Renderer::getCurrentPosition(int64_t *mediaUs) {
status_t result = mMediaClock->getMediaTime(ALooper::GetNowUs(), mediaUs);
if (result == OK) {
return result;
}
// MediaClock has not started yet. Try to start it if possible.
{
Mutex::Autolock autoLock(mLock);
if (mAudioFirstAnchorTimeMediaUs == -1) {
return result;
}
AudioTimestamp ts;
status_t res = mAudioSink->getTimestamp(ts);
if (res != OK) {
return result;
}
// AudioSink has rendered some frames.
int64_t nowUs = ALooper::GetNowUs();
int64_t nowMediaUs = mAudioSink->getPlayedOutDurationUs(nowUs)
+ mAudioFirstAnchorTimeMediaUs;
mMediaClock->updateAnchor(nowMediaUs, nowUs, -1);
}
return mMediaClock->getMediaTime(ALooper::GetNowUs(), mediaUs);
}
void NuPlayer::Renderer::clearAudioFirstAnchorTime_l() {
mAudioFirstAnchorTimeMediaUs = -1;
mMediaClock->setStartingTimeMedia(-1);
}
void NuPlayer::Renderer::setAudioFirstAnchorTimeIfNeeded_l(int64_t mediaUs) {
if (mAudioFirstAnchorTimeMediaUs == -1) {
mAudioFirstAnchorTimeMediaUs = mediaUs;
mMediaClock->setStartingTimeMedia(mediaUs);
}
}
void NuPlayer::Renderer::clearAnchorTime_l() {
mMediaClock->clearAnchor();
mAnchorTimeMediaUs = -1;
mAnchorNumFramesWritten = -1;
}
void NuPlayer::Renderer::setVideoLateByUs(int64_t lateUs) {
Mutex::Autolock autoLock(mLock);
mVideoLateByUs = lateUs;
}
int64_t NuPlayer::Renderer::getVideoLateByUs() {
Mutex::Autolock autoLock(mLock);
return mVideoLateByUs;
}
status_t NuPlayer::Renderer::openAudioSink(
const sp<AMessage> &format,
bool offloadOnly,
bool hasVideo,
uint32_t flags,
bool *isOffloaded) {
sp<AMessage> msg = new AMessage(kWhatOpenAudioSink, this);
msg->setMessage("format", format);
msg->setInt32("offload-only", offloadOnly);
msg->setInt32("has-video", hasVideo);
msg->setInt32("flags", flags);
sp<AMessage> response;
msg->postAndAwaitResponse(&response);
int32_t err;
if (!response->findInt32("err", &err)) {
err = INVALID_OPERATION;
} else if (err == OK && isOffloaded != NULL) {
int32_t offload;
CHECK(response->findInt32("offload", &offload));
*isOffloaded = (offload != 0);
}
return err;
}
void NuPlayer::Renderer::closeAudioSink() {
sp<AMessage> msg = new AMessage(kWhatCloseAudioSink, this);
sp<AMessage> response;
msg->postAndAwaitResponse(&response);
}
void NuPlayer::Renderer::onMessageReceived(const sp<AMessage> &msg) {
switch (msg->what()) {
case kWhatOpenAudioSink:
{
sp<AMessage> format;
CHECK(msg->findMessage("format", &format));
int32_t offloadOnly;
CHECK(msg->findInt32("offload-only", &offloadOnly));
int32_t hasVideo;
CHECK(msg->findInt32("has-video", &hasVideo));
uint32_t flags;
CHECK(msg->findInt32("flags", (int32_t *)&flags));
status_t err = onOpenAudioSink(format, offloadOnly, hasVideo, flags);
sp<AMessage> response = new AMessage;
response->setInt32("err", err);
response->setInt32("offload", offloadingAudio());
sp<AReplyToken> replyID;
CHECK(msg->senderAwaitsResponse(&replyID));
response->postReply(replyID);
break;
}
case kWhatCloseAudioSink:
{
sp<AReplyToken> replyID;
CHECK(msg->senderAwaitsResponse(&replyID));
onCloseAudioSink();
sp<AMessage> response = new AMessage;
response->postReply(replyID);
break;
}
case kWhatStopAudioSink:
{
mAudioSink->stop();
break;
}
case kWhatDrainAudioQueue:
{
mDrainAudioQueuePending = false;
int32_t generation;
CHECK(msg->findInt32("drainGeneration", &generation));
if (generation != getDrainGeneration(true /* audio */)) {
break;
}
if (onDrainAudioQueue()) {
uint32_t numFramesPlayed;
CHECK_EQ(mAudioSink->getPosition(&numFramesPlayed),
(status_t)OK);
uint32_t numFramesPendingPlayout =
mNumFramesWritten - numFramesPlayed;
// This is how long the audio sink will have data to
// play back.
int64_t delayUs =
mAudioSink->msecsPerFrame()
* numFramesPendingPlayout * 1000ll;
if (mPlaybackRate > 1.0f) {
delayUs /= mPlaybackRate;
}
// Let's give it more data after about half that time
// has elapsed.
delayUs /= 2;
// check the buffer size to estimate maximum delay permitted.
const int64_t maxDrainDelayUs = std::max(
mAudioSink->getBufferDurationInUs(), (int64_t)500000 /* half second */);
ALOGD_IF(delayUs > maxDrainDelayUs, "postDrainAudioQueue long delay: %lld > %lld",
(long long)delayUs, (long long)maxDrainDelayUs);
Mutex::Autolock autoLock(mLock);
postDrainAudioQueue_l(delayUs);
}
break;
}
case kWhatDrainVideoQueue:
{
int32_t generation;
CHECK(msg->findInt32("drainGeneration", &generation));
if (generation != getDrainGeneration(false /* audio */)) {
break;
}
mDrainVideoQueuePending = false;
onDrainVideoQueue();
postDrainVideoQueue();
break;
}
case kWhatPostDrainVideoQueue:
{
int32_t generation;
CHECK(msg->findInt32("drainGeneration", &generation));
if (generation != getDrainGeneration(false /* audio */)) {
break;
}
mDrainVideoQueuePending = false;
postDrainVideoQueue();
break;
}
case kWhatQueueBuffer:
{
onQueueBuffer(msg);
break;
}
case kWhatQueueEOS:
{
onQueueEOS(msg);
break;
}
case kWhatEOS:
{
int32_t generation;
CHECK(msg->findInt32("audioEOSGeneration", &generation));
if (generation != mAudioEOSGeneration) {
break;
}
status_t finalResult;
CHECK(msg->findInt32("finalResult", &finalResult));
notifyEOS(true /* audio */, finalResult);
break;
}
case kWhatConfigPlayback:
{
sp<AReplyToken> replyID;
CHECK(msg->senderAwaitsResponse(&replyID));
AudioPlaybackRate rate;
readFromAMessage(msg, &rate);
status_t err = onConfigPlayback(rate);
sp<AMessage> response = new AMessage;
response->setInt32("err", err);
response->postReply(replyID);
break;
}
case kWhatGetPlaybackSettings:
{
sp<AReplyToken> replyID;
CHECK(msg->senderAwaitsResponse(&replyID));
AudioPlaybackRate rate = AUDIO_PLAYBACK_RATE_DEFAULT;
status_t err = onGetPlaybackSettings(&rate);
sp<AMessage> response = new AMessage;
if (err == OK) {
writeToAMessage(response, rate);
}
response->setInt32("err", err);
response->postReply(replyID);
break;
}
case kWhatConfigSync:
{
sp<AReplyToken> replyID;
CHECK(msg->senderAwaitsResponse(&replyID));
AVSyncSettings sync;
float videoFpsHint;
readFromAMessage(msg, &sync, &videoFpsHint);
status_t err = onConfigSync(sync, videoFpsHint);
sp<AMessage> response = new AMessage;
response->setInt32("err", err);
response->postReply(replyID);
break;
}
case kWhatGetSyncSettings:
{
sp<AReplyToken> replyID;
CHECK(msg->senderAwaitsResponse(&replyID));
ALOGV("kWhatGetSyncSettings");
AVSyncSettings sync;
float videoFps = -1.f;
status_t err = onGetSyncSettings(&sync, &videoFps);
sp<AMessage> response = new AMessage;
if (err == OK) {
writeToAMessage(response, sync, videoFps);
}
response->setInt32("err", err);
response->postReply(replyID);
break;
}
case kWhatFlush:
{
onFlush(msg);
break;
}
case kWhatDisableOffloadAudio:
{
onDisableOffloadAudio();
break;
}
case kWhatEnableOffloadAudio:
{
onEnableOffloadAudio();
break;
}
case kWhatPause:
{
onPause();
break;
}
case kWhatResume:
{
onResume();
break;
}
case kWhatSetVideoFrameRate:
{
float fps;
CHECK(msg->findFloat("frame-rate", &fps));
onSetVideoFrameRate(fps);
break;
}
case kWhatAudioTearDown:
{
int32_t reason;
CHECK(msg->findInt32("reason", &reason));
onAudioTearDown((AudioTearDownReason)reason);
break;
}
case kWhatAudioOffloadPauseTimeout:
{
int32_t generation;
CHECK(msg->findInt32("drainGeneration", &generation));
if (generation != mAudioOffloadPauseTimeoutGeneration) {
break;
}
ALOGV("Audio Offload tear down due to pause timeout.");
onAudioTearDown(kDueToTimeout);
mWakeLock->release();
break;
}
default:
TRESPASS();
break;
}
}
void NuPlayer::Renderer::postDrainAudioQueue_l(int64_t delayUs) {
if (mDrainAudioQueuePending || mSyncQueues || mUseAudioCallback) {
return;
}
if (mAudioQueue.empty()) {
return;
}
// FIXME: if paused, wait until AudioTrack stop() is complete before delivering data.
if (mPaused) {
const int64_t diffUs = mPauseDrainAudioAllowedUs - ALooper::GetNowUs();
if (diffUs > delayUs) {
delayUs = diffUs;
}
}
mDrainAudioQueuePending = true;
sp<AMessage> msg = new AMessage(kWhatDrainAudioQueue, this);
msg->setInt32("drainGeneration", mAudioDrainGeneration);
msg->post(delayUs);
}
void NuPlayer::Renderer::prepareForMediaRenderingStart_l() {
mAudioRenderingStartGeneration = mAudioDrainGeneration;
mVideoRenderingStartGeneration = mVideoDrainGeneration;
mRenderingDataDelivered = false;
}
void NuPlayer::Renderer::notifyIfMediaRenderingStarted_l() {
if (mVideoRenderingStartGeneration == mVideoDrainGeneration &&
mAudioRenderingStartGeneration == mAudioDrainGeneration) {
mRenderingDataDelivered = true;
if (mPaused) {
return;
}
mVideoRenderingStartGeneration = -1;
mAudioRenderingStartGeneration = -1;
sp<AMessage> notify = mNotify->dup();
notify->setInt32("what", kWhatMediaRenderingStart);
notify->post();
}
}
// static
size_t NuPlayer::Renderer::AudioSinkCallback(
MediaPlayerBase::AudioSink * /* audioSink */,
void *buffer,
size_t size,
void *cookie,
MediaPlayerBase::AudioSink::cb_event_t event) {
NuPlayer::Renderer *me = (NuPlayer::Renderer *)cookie;
switch (event) {
case MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER:
{
return me->fillAudioBuffer(buffer, size);
break;
}
case MediaPlayerBase::AudioSink::CB_EVENT_STREAM_END:
{
ALOGV("AudioSink::CB_EVENT_STREAM_END");
me->notifyEOS(true /* audio */, ERROR_END_OF_STREAM);
break;
}
case MediaPlayerBase::AudioSink::CB_EVENT_TEAR_DOWN:
{
ALOGV("AudioSink::CB_EVENT_TEAR_DOWN");
me->notifyAudioTearDown(kDueToError);
break;
}
}
return 0;
}
size_t NuPlayer::Renderer::fillAudioBuffer(void *buffer, size_t size) {
Mutex::Autolock autoLock(mLock);
if (!mUseAudioCallback) {
return 0;
}
bool hasEOS = false;
size_t sizeCopied = 0;
bool firstEntry = true;
QueueEntry *entry; // will be valid after while loop if hasEOS is set.
while (sizeCopied < size && !mAudioQueue.empty()) {
entry = &*mAudioQueue.begin();
if (entry->mBuffer == NULL) { // EOS
hasEOS = true;
mAudioQueue.erase(mAudioQueue.begin());
break;
}
if (firstEntry && entry->mOffset == 0) {
firstEntry = false;
int64_t mediaTimeUs;
CHECK(entry->mBuffer->meta()->findInt64("timeUs", &mediaTimeUs));
ALOGV("fillAudioBuffer: rendering audio at media time %.2f secs", mediaTimeUs / 1E6);
setAudioFirstAnchorTimeIfNeeded_l(mediaTimeUs);
}
size_t copy = entry->mBuffer->size() - entry->mOffset;
size_t sizeRemaining = size - sizeCopied;
if (copy > sizeRemaining) {
copy = sizeRemaining;
}
memcpy((char *)buffer + sizeCopied,
entry->mBuffer->data() + entry->mOffset,
copy);
entry->mOffset += copy;
if (entry->mOffset == entry->mBuffer->size()) {
entry->mNotifyConsumed->post();
mAudioQueue.erase(mAudioQueue.begin());
entry = NULL;
}
sizeCopied += copy;
notifyIfMediaRenderingStarted_l();
}
if (mAudioFirstAnchorTimeMediaUs >= 0) {
int64_t nowUs = ALooper::GetNowUs();
int64_t nowMediaUs =
mAudioFirstAnchorTimeMediaUs + mAudioSink->getPlayedOutDurationUs(nowUs);
// we don't know how much data we are queueing for offloaded tracks.
mMediaClock->updateAnchor(nowMediaUs, nowUs, INT64_MAX);
}
// for non-offloaded audio, we need to compute the frames written because
// there is no EVENT_STREAM_END notification. The frames written gives
// an estimate on the pending played out duration.
if (!offloadingAudio()) {
mNumFramesWritten += sizeCopied / mAudioSink->frameSize();
}
if (hasEOS) {
(new AMessage(kWhatStopAudioSink, this))->post();
// As there is currently no EVENT_STREAM_END callback notification for
// non-offloaded audio tracks, we need to post the EOS ourselves.
if (!offloadingAudio()) {
int64_t postEOSDelayUs = 0;
if (mAudioSink->needsTrailingPadding()) {
postEOSDelayUs = getPendingAudioPlayoutDurationUs(ALooper::GetNowUs());
}
ALOGV("fillAudioBuffer: notifyEOS "
"mNumFramesWritten:%u finalResult:%d postEOSDelay:%lld",
mNumFramesWritten, entry->mFinalResult, (long long)postEOSDelayUs);
notifyEOS(true /* audio */, entry->mFinalResult, postEOSDelayUs);
}
}
return sizeCopied;
}
void NuPlayer::Renderer::drainAudioQueueUntilLastEOS() {
List<QueueEntry>::iterator it = mAudioQueue.begin(), itEOS = it;
bool foundEOS = false;
while (it != mAudioQueue.end()) {
int32_t eos;
QueueEntry *entry = &*it++;
if (entry->mBuffer == NULL
|| (entry->mNotifyConsumed->findInt32("eos", &eos) && eos != 0)) {
itEOS = it;
foundEOS = true;
}
}
if (foundEOS) {
// post all replies before EOS and drop the samples
for (it = mAudioQueue.begin(); it != itEOS; it++) {
if (it->mBuffer == NULL) {
// delay doesn't matter as we don't even have an AudioTrack
notifyEOS(true /* audio */, it->mFinalResult);
} else {
it->mNotifyConsumed->post();
}
}
mAudioQueue.erase(mAudioQueue.begin(), itEOS);
}
}
bool NuPlayer::Renderer::onDrainAudioQueue() {
// do not drain audio during teardown as queued buffers may be invalid.
if (mAudioTornDown) {
return false;
}
// TODO: This call to getPosition checks if AudioTrack has been created
// in AudioSink before draining audio. If AudioTrack doesn't exist, then
// CHECKs on getPosition will fail.
// We still need to figure out why AudioTrack is not created when
// this function is called. One possible reason could be leftover
// audio. Another possible place is to check whether decoder
// has received INFO_FORMAT_CHANGED as the first buffer since
// AudioSink is opened there, and possible interactions with flush
// immediately after start. Investigate error message
// "vorbis_dsp_synthesis returned -135", along with RTSP.
uint32_t numFramesPlayed;
if (mAudioSink->getPosition(&numFramesPlayed) != OK) {
// When getPosition fails, renderer will not reschedule the draining
// unless new samples are queued.
// If we have pending EOS (or "eos" marker for discontinuities), we need
// to post these now as NuPlayerDecoder might be waiting for it.
drainAudioQueueUntilLastEOS();
ALOGW("onDrainAudioQueue(): audio sink is not ready");
return false;
}
#if 0
ssize_t numFramesAvailableToWrite =
mAudioSink->frameCount() - (mNumFramesWritten - numFramesPlayed);
if (numFramesAvailableToWrite == mAudioSink->frameCount()) {
ALOGI("audio sink underrun");
} else {
ALOGV("audio queue has %d frames left to play",
mAudioSink->frameCount() - numFramesAvailableToWrite);
}
#endif
uint32_t prevFramesWritten = mNumFramesWritten;
while (!mAudioQueue.empty()) {
QueueEntry *entry = &*mAudioQueue.begin();
mLastAudioBufferDrained = entry->mBufferOrdinal;
if (entry->mBuffer == NULL) {
// EOS
int64_t postEOSDelayUs = 0;
if (mAudioSink->needsTrailingPadding()) {
postEOSDelayUs = getPendingAudioPlayoutDurationUs(ALooper::GetNowUs());
}
notifyEOS(true /* audio */, entry->mFinalResult, postEOSDelayUs);
mLastAudioMediaTimeUs = getDurationUsIfPlayedAtSampleRate(mNumFramesWritten);
mAudioQueue.erase(mAudioQueue.begin());
entry = NULL;
if (mAudioSink->needsTrailingPadding()) {
// If we're not in gapless playback (i.e. through setNextPlayer), we
// need to stop the track here, because that will play out the last
// little bit at the end of the file. Otherwise short files won't play.
mAudioSink->stop();
mNumFramesWritten = 0;
}
return false;
}
// ignore 0-sized buffer which could be EOS marker with no data
if (entry->mOffset == 0 && entry->mBuffer->size() > 0) {
int64_t mediaTimeUs;
CHECK(entry->mBuffer->meta()->findInt64("timeUs", &mediaTimeUs));
ALOGV("onDrainAudioQueue: rendering audio at media time %.2f secs",
mediaTimeUs / 1E6);
onNewAudioMediaTime(mediaTimeUs);
}
size_t copy = entry->mBuffer->size() - entry->mOffset;
ssize_t written = mAudioSink->write(entry->mBuffer->data() + entry->mOffset,
copy, false /* blocking */);
if (written < 0) {
// An error in AudioSink write. Perhaps the AudioSink was not properly opened.
if (written == WOULD_BLOCK) {
ALOGV("AudioSink write would block when writing %zu bytes", copy);
} else {
ALOGE("AudioSink write error(%zd) when writing %zu bytes", written, copy);
// This can only happen when AudioSink was opened with doNotReconnect flag set to
// true, in which case the NuPlayer will handle the reconnect.
notifyAudioTearDown(kDueToError);
}
break;
}
entry->mOffset += written;
size_t remainder = entry->mBuffer->size() - entry->mOffset;
if ((ssize_t)remainder < mAudioSink->frameSize()) {
if (remainder > 0) {
ALOGW("Corrupted audio buffer has fractional frames, discarding %zu bytes.",
remainder);
entry->mOffset += remainder;
copy -= remainder;
}
entry->mNotifyConsumed->post();
mAudioQueue.erase(mAudioQueue.begin());
entry = NULL;
}
size_t copiedFrames = written / mAudioSink->frameSize();
mNumFramesWritten += copiedFrames;
{
Mutex::Autolock autoLock(mLock);
int64_t maxTimeMedia;
maxTimeMedia =
mAnchorTimeMediaUs +
(int64_t)(max((long long)mNumFramesWritten - mAnchorNumFramesWritten, 0LL)
* 1000LL * mAudioSink->msecsPerFrame());
mMediaClock->updateMaxTimeMedia(maxTimeMedia);
notifyIfMediaRenderingStarted_l();
}
if (written != (ssize_t)copy) {
// A short count was received from AudioSink::write()
//
// AudioSink write is called in non-blocking mode.
// It may return with a short count when:
//
// 1) Size to be copied is not a multiple of the frame size. Fractional frames are
// discarded.
// 2) The data to be copied exceeds the available buffer in AudioSink.
// 3) An error occurs and data has been partially copied to the buffer in AudioSink.
// 4) AudioSink is an AudioCache for data retrieval, and the AudioCache is exceeded.
// (Case 1)
// Must be a multiple of the frame size. If it is not a multiple of a frame size, it
// needs to fail, as we should not carry over fractional frames between calls.
CHECK_EQ(copy % mAudioSink->frameSize(), 0);
// (Case 2, 3, 4)
// Return early to the caller.
// Beware of calling immediately again as this may busy-loop if you are not careful.
ALOGV("AudioSink write short frame count %zd < %zu", written, copy);
break;
}
}
// calculate whether we need to reschedule another write.
bool reschedule = !mAudioQueue.empty()
&& (!mPaused
|| prevFramesWritten != mNumFramesWritten); // permit pause to fill buffers
//ALOGD("reschedule:%d empty:%d mPaused:%d prevFramesWritten:%u mNumFramesWritten:%u",
// reschedule, mAudioQueue.empty(), mPaused, prevFramesWritten, mNumFramesWritten);
return reschedule;
}
int64_t NuPlayer::Renderer::getDurationUsIfPlayedAtSampleRate(uint32_t numFrames) {
int32_t sampleRate = offloadingAudio() ?
mCurrentOffloadInfo.sample_rate : mCurrentPcmInfo.mSampleRate;
if (sampleRate == 0) {
ALOGE("sampleRate is 0 in %s mode", offloadingAudio() ? "offload" : "non-offload");
return 0;
}
// TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours.
return (int64_t)((int32_t)numFrames * 1000000LL / sampleRate);
}
// Calculate duration of pending samples if played at normal rate (i.e., 1.0).
int64_t NuPlayer::Renderer::getPendingAudioPlayoutDurationUs(int64_t nowUs) {
int64_t writtenAudioDurationUs = getDurationUsIfPlayedAtSampleRate(mNumFramesWritten);
if (mUseVirtualAudioSink) {
int64_t nowUs = ALooper::GetNowUs();
int64_t mediaUs;
if (mMediaClock->getMediaTime(nowUs, &mediaUs) != OK) {
return 0ll;
} else {
return writtenAudioDurationUs - (mediaUs - mAudioFirstAnchorTimeMediaUs);
}
}
return writtenAudioDurationUs - mAudioSink->getPlayedOutDurationUs(nowUs);
}
int64_t NuPlayer::Renderer::getRealTimeUs(int64_t mediaTimeUs, int64_t nowUs) {
int64_t realUs;
if (mMediaClock->getRealTimeFor(mediaTimeUs, &realUs) != OK) {
// If failed to get current position, e.g. due to audio clock is
// not ready, then just play out video immediately without delay.
return nowUs;
}
return realUs;
}
void NuPlayer::Renderer::onNewAudioMediaTime(int64_t mediaTimeUs) {
Mutex::Autolock autoLock(mLock);
// TRICKY: vorbis decoder generates multiple frames with the same
// timestamp, so only update on the first frame with a given timestamp
if (mediaTimeUs == mAnchorTimeMediaUs) {
return;
}
setAudioFirstAnchorTimeIfNeeded_l(mediaTimeUs);
// mNextAudioClockUpdateTimeUs is -1 if we're waiting for audio sink to start
if (mNextAudioClockUpdateTimeUs == -1) {
AudioTimestamp ts;
if (mAudioSink->getTimestamp(ts) == OK && ts.mPosition > 0) {
mNextAudioClockUpdateTimeUs = 0; // start our clock updates
}
}
int64_t nowUs = ALooper::GetNowUs();
if (mNextAudioClockUpdateTimeUs >= 0) {
if (nowUs >= mNextAudioClockUpdateTimeUs) {
int64_t nowMediaUs = mediaTimeUs - getPendingAudioPlayoutDurationUs(nowUs);
mMediaClock->updateAnchor(nowMediaUs, nowUs, mediaTimeUs);
mUseVirtualAudioSink = false;
mNextAudioClockUpdateTimeUs = nowUs + kMinimumAudioClockUpdatePeriodUs;
}
} else {
int64_t unused;
if ((mMediaClock->getMediaTime(nowUs, &unused) != OK)
&& (getDurationUsIfPlayedAtSampleRate(mNumFramesWritten)
> kMaxAllowedAudioSinkDelayUs)) {
// Enough data has been sent to AudioSink, but AudioSink has not rendered
// any data yet. Something is wrong with AudioSink, e.g., the device is not
// connected to audio out.
// Switch to system clock. This essentially creates a virtual AudioSink with
// initial latenty of getDurationUsIfPlayedAtSampleRate(mNumFramesWritten).
// This virtual AudioSink renders audio data starting from the very first sample
// and it's paced by system clock.
ALOGW("AudioSink stuck. ARE YOU CONNECTED TO AUDIO OUT? Switching to system clock.");
mMediaClock->updateAnchor(mAudioFirstAnchorTimeMediaUs, nowUs, mediaTimeUs);
mUseVirtualAudioSink = true;
}
}
mAnchorNumFramesWritten = mNumFramesWritten;
mAnchorTimeMediaUs = mediaTimeUs;
}
// Called without mLock acquired.
void NuPlayer::Renderer::postDrainVideoQueue() {
if (mDrainVideoQueuePending
|| getSyncQueues()
|| (mPaused && mVideoSampleReceived)) {
return;
}
if (mVideoQueue.empty()) {
return;
}
QueueEntry &entry = *mVideoQueue.begin();
sp<AMessage> msg = new AMessage(kWhatDrainVideoQueue, this);
msg->setInt32("drainGeneration", getDrainGeneration(false /* audio */));
if (entry.mBuffer == NULL) {
// EOS doesn't carry a timestamp.
msg->post();
mDrainVideoQueuePending = true;
return;
}
bool needRepostDrainVideoQueue = false;
int64_t delayUs;
int64_t nowUs = ALooper::GetNowUs();
int64_t realTimeUs;
if (mFlags & FLAG_REAL_TIME) {
int64_t mediaTimeUs;
CHECK(entry.mBuffer->meta()->findInt64("timeUs", &mediaTimeUs));
realTimeUs = mediaTimeUs;
} else {
int64_t mediaTimeUs;
CHECK(entry.mBuffer->meta()->findInt64("timeUs", &mediaTimeUs));
{
Mutex::Autolock autoLock(mLock);
if (mAnchorTimeMediaUs < 0) {
mMediaClock->updateAnchor(mediaTimeUs, nowUs, mediaTimeUs);
mAnchorTimeMediaUs = mediaTimeUs;
realTimeUs = nowUs;
} else if (!mVideoSampleReceived) {
// Always render the first video frame.
realTimeUs = nowUs;
} else if (mAudioFirstAnchorTimeMediaUs < 0
|| mMediaClock->getRealTimeFor(mediaTimeUs, &realTimeUs) == OK) {
realTimeUs = getRealTimeUs(mediaTimeUs, nowUs);
} else if (mediaTimeUs - mAudioFirstAnchorTimeMediaUs >= 0) {
needRepostDrainVideoQueue = true;
realTimeUs = nowUs;
} else {
realTimeUs = nowUs;
}
}
if (!mHasAudio) {
// smooth out videos >= 10fps
mMediaClock->updateMaxTimeMedia(mediaTimeUs + 100000);
}
// Heuristics to handle situation when media time changed without a
// discontinuity. If we have not drained an audio buffer that was
// received after this buffer, repost in 10 msec. Otherwise repost
// in 500 msec.
delayUs = realTimeUs - nowUs;
int64_t postDelayUs = -1;
if (delayUs > 500000) {
postDelayUs = 500000;
if (mHasAudio && (mLastAudioBufferDrained - entry.mBufferOrdinal) <= 0) {
postDelayUs = 10000;
}
} else if (needRepostDrainVideoQueue) {
// CHECK(mPlaybackRate > 0);
// CHECK(mAudioFirstAnchorTimeMediaUs >= 0);
// CHECK(mediaTimeUs - mAudioFirstAnchorTimeMediaUs >= 0);
postDelayUs = mediaTimeUs - mAudioFirstAnchorTimeMediaUs;
postDelayUs /= mPlaybackRate;
}
if (postDelayUs >= 0) {
msg->setWhat(kWhatPostDrainVideoQueue);
msg->post(postDelayUs);
mVideoScheduler->restart();
ALOGI("possible video time jump of %dms or uninitialized media clock, retrying in %dms",
(int)(delayUs / 1000), (int)(postDelayUs / 1000));
mDrainVideoQueuePending = true;
return;
}
}
realTimeUs = mVideoScheduler->schedule(realTimeUs * 1000) / 1000;
int64_t twoVsyncsUs = 2 * (mVideoScheduler->getVsyncPeriod() / 1000);
delayUs = realTimeUs - nowUs;
ALOGW_IF(delayUs > 500000, "unusually high delayUs: %" PRId64, delayUs);
// post 2 display refreshes before rendering is due
msg->post(delayUs > twoVsyncsUs ? delayUs - twoVsyncsUs : 0);
mDrainVideoQueuePending = true;
}
void NuPlayer::Renderer::onDrainVideoQueue() {
if (mVideoQueue.empty()) {
return;
}
QueueEntry *entry = &*mVideoQueue.begin();
if (entry->mBuffer == NULL) {
// EOS
notifyEOS(false /* audio */, entry->mFinalResult);
mVideoQueue.erase(mVideoQueue.begin());
entry = NULL;
setVideoLateByUs(0);
return;
}
int64_t nowUs = ALooper::GetNowUs();
int64_t realTimeUs;
int64_t mediaTimeUs = -1;
if (mFlags & FLAG_REAL_TIME) {
CHECK(entry->mBuffer->meta()->findInt64("timeUs", &realTimeUs));
} else {
CHECK(entry->mBuffer->meta()->findInt64("timeUs", &mediaTimeUs));
realTimeUs = getRealTimeUs(mediaTimeUs, nowUs);
}
bool tooLate = false;
if (!mPaused) {
setVideoLateByUs(nowUs - realTimeUs);
tooLate = (mVideoLateByUs > 40000);
if (tooLate) {
ALOGV("video late by %lld us (%.2f secs)",
(long long)mVideoLateByUs, mVideoLateByUs / 1E6);
} else {
int64_t mediaUs = 0;
mMediaClock->getMediaTime(realTimeUs, &mediaUs);
ALOGV("rendering video at media time %.2f secs",
(mFlags & FLAG_REAL_TIME ? realTimeUs :
mediaUs) / 1E6);
if (!(mFlags & FLAG_REAL_TIME)
&& mLastAudioMediaTimeUs != -1
&& mediaTimeUs > mLastAudioMediaTimeUs) {
// If audio ends before video, video continues to drive media clock.
// Also smooth out videos >= 10fps.
mMediaClock->updateMaxTimeMedia(mediaTimeUs + 100000);
}
}
} else {
setVideoLateByUs(0);
if (!mVideoSampleReceived && !mHasAudio) {
// This will ensure that the first frame after a flush won't be used as anchor
// when renderer is in paused state, because resume can happen any time after seek.
Mutex::Autolock autoLock(mLock);
clearAnchorTime_l();
}
}
// Always render the first video frame while keeping stats on A/V sync.
if (!mVideoSampleReceived) {
realTimeUs = nowUs;
tooLate = false;
}
entry->mNotifyConsumed->setInt64("timestampNs", realTimeUs * 1000ll);
entry->mNotifyConsumed->setInt32("render", !tooLate);
entry->mNotifyConsumed->post();
mVideoQueue.erase(mVideoQueue.begin());
entry = NULL;
mVideoSampleReceived = true;
if (!mPaused) {
if (!mVideoRenderingStarted) {
mVideoRenderingStarted = true;
notifyVideoRenderingStart();
}
Mutex::Autolock autoLock(mLock);
notifyIfMediaRenderingStarted_l();
}
}
void NuPlayer::Renderer::notifyVideoRenderingStart() {
sp<AMessage> notify = mNotify->dup();
notify->setInt32("what", kWhatVideoRenderingStart);
notify->post();
}
void NuPlayer::Renderer::notifyEOS(bool audio, status_t finalResult, int64_t delayUs) {
if (audio && delayUs > 0) {
sp<AMessage> msg = new AMessage(kWhatEOS, this);
msg->setInt32("audioEOSGeneration", mAudioEOSGeneration);
msg->setInt32("finalResult", finalResult);
msg->post(delayUs);
return;
}
sp<AMessage> notify = mNotify->dup();
notify->setInt32("what", kWhatEOS);
notify->setInt32("audio", static_cast<int32_t>(audio));
notify->setInt32("finalResult", finalResult);
notify->post(delayUs);
}
void NuPlayer::Renderer::notifyAudioTearDown(AudioTearDownReason reason) {
sp<AMessage> msg = new AMessage(kWhatAudioTearDown, this);
msg->setInt32("reason", reason);
msg->post();
}
void NuPlayer::Renderer::onQueueBuffer(const sp<AMessage> &msg) {
int32_t audio;
CHECK(msg->findInt32("audio", &audio));
if (dropBufferIfStale(audio, msg)) {
return;
}
if (audio) {
mHasAudio = true;
} else {
mHasVideo = true;
}
if (mHasVideo) {
if (mVideoScheduler == NULL) {
mVideoScheduler = new VideoFrameScheduler();
mVideoScheduler->init();
}
}
sp<ABuffer> buffer;
CHECK(msg->findBuffer("buffer", &buffer));
sp<AMessage> notifyConsumed;
CHECK(msg->findMessage("notifyConsumed", ¬ifyConsumed));
QueueEntry entry;
entry.mBuffer = buffer;
entry.mNotifyConsumed = notifyConsumed;
entry.mOffset = 0;
entry.mFinalResult = OK;
entry.mBufferOrdinal = ++mTotalBuffersQueued;
if (audio) {
Mutex::Autolock autoLock(mLock);
mAudioQueue.push_back(entry);
postDrainAudioQueue_l();
} else {
mVideoQueue.push_back(entry);
postDrainVideoQueue();
}
Mutex::Autolock autoLock(mLock);
if (!mSyncQueues || mAudioQueue.empty() || mVideoQueue.empty()) {
return;
}
sp<ABuffer> firstAudioBuffer = (*mAudioQueue.begin()).mBuffer;
sp<ABuffer> firstVideoBuffer = (*mVideoQueue.begin()).mBuffer;
if (firstAudioBuffer == NULL || firstVideoBuffer == NULL) {
// EOS signalled on either queue.
syncQueuesDone_l();
return;
}
int64_t firstAudioTimeUs;
int64_t firstVideoTimeUs;
CHECK(firstAudioBuffer->meta()
->findInt64("timeUs", &firstAudioTimeUs));
CHECK(firstVideoBuffer->meta()
->findInt64("timeUs", &firstVideoTimeUs));
int64_t diff = firstVideoTimeUs - firstAudioTimeUs;
ALOGV("queueDiff = %.2f secs", diff / 1E6);
if (diff > 100000ll) {
// Audio data starts More than 0.1 secs before video.
// Drop some audio.
(*mAudioQueue.begin()).mNotifyConsumed->post();
mAudioQueue.erase(mAudioQueue.begin());
return;
}
syncQueuesDone_l();
}
void NuPlayer::Renderer::syncQueuesDone_l() {
if (!mSyncQueues) {
return;
}
mSyncQueues = false;
if (!mAudioQueue.empty()) {
postDrainAudioQueue_l();
}
if (!mVideoQueue.empty()) {
mLock.unlock();
postDrainVideoQueue();
mLock.lock();
}
}
void NuPlayer::Renderer::onQueueEOS(const sp<AMessage> &msg) {
int32_t audio;
CHECK(msg->findInt32("audio", &audio));
if (dropBufferIfStale(audio, msg)) {
return;
}
int32_t finalResult;
CHECK(msg->findInt32("finalResult", &finalResult));
QueueEntry entry;
entry.mOffset = 0;
entry.mFinalResult = finalResult;
if (audio) {
Mutex::Autolock autoLock(mLock);
if (mAudioQueue.empty() && mSyncQueues) {
syncQueuesDone_l();
}
mAudioQueue.push_back(entry);
postDrainAudioQueue_l();
} else {
if (mVideoQueue.empty() && getSyncQueues()) {
Mutex::Autolock autoLock(mLock);
syncQueuesDone_l();
}
mVideoQueue.push_back(entry);
postDrainVideoQueue();
}
}
void NuPlayer::Renderer::onFlush(const sp<AMessage> &msg) {
int32_t audio, notifyComplete;
CHECK(msg->findInt32("audio", &audio));
{
Mutex::Autolock autoLock(mLock);
if (audio) {
notifyComplete = mNotifyCompleteAudio;
mNotifyCompleteAudio = false;
mLastAudioMediaTimeUs = -1;
} else {
notifyComplete = mNotifyCompleteVideo;
mNotifyCompleteVideo = false;
}
// If we're currently syncing the queues, i.e. dropping audio while
// aligning the first audio/video buffer times and only one of the
// two queues has data, we may starve that queue by not requesting
// more buffers from the decoder. If the other source then encounters
// a discontinuity that leads to flushing, we'll never find the
// corresponding discontinuity on the other queue.
// Therefore we'll stop syncing the queues if at least one of them
// is flushed.
syncQueuesDone_l();
clearAnchorTime_l();
}
ALOGV("flushing %s", audio ? "audio" : "video");
if (audio) {
{
Mutex::Autolock autoLock(mLock);
flushQueue(&mAudioQueue);
++mAudioDrainGeneration;
++mAudioEOSGeneration;
prepareForMediaRenderingStart_l();
// the frame count will be reset after flush.
clearAudioFirstAnchorTime_l();
}
mDrainAudioQueuePending = false;
if (offloadingAudio()) {
mAudioSink->pause();
mAudioSink->flush();
if (!mPaused) {
mAudioSink->start();
}
} else {
mAudioSink->pause();
mAudioSink->flush();
// Call stop() to signal to the AudioSink to completely fill the
// internal buffer before resuming playback.
// FIXME: this is ignored after flush().
mAudioSink->stop();
if (mPaused) {
// Race condition: if renderer is paused and audio sink is stopped,
// we need to make sure that the audio track buffer fully drains
// before delivering data.
// FIXME: remove this if we can detect if stop() is complete.
const int delayUs = 2 * 50 * 1000; // (2 full mixer thread cycles at 50ms)
mPauseDrainAudioAllowedUs = ALooper::GetNowUs() + delayUs;
} else {
mAudioSink->start();
}
mNumFramesWritten = 0;
}
mNextAudioClockUpdateTimeUs = -1;
} else {
flushQueue(&mVideoQueue);
mDrainVideoQueuePending = false;
if (mVideoScheduler != NULL) {
mVideoScheduler->restart();
}
Mutex::Autolock autoLock(mLock);
++mVideoDrainGeneration;
prepareForMediaRenderingStart_l();
}
mVideoSampleReceived = false;
if (notifyComplete) {
notifyFlushComplete(audio);
}
}
void NuPlayer::Renderer::flushQueue(List<QueueEntry> *queue) {
while (!queue->empty()) {
QueueEntry *entry = &*queue->begin();
if (entry->mBuffer != NULL) {
entry->mNotifyConsumed->post();
}
queue->erase(queue->begin());
entry = NULL;
}
}
void NuPlayer::Renderer::notifyFlushComplete(bool audio) {
sp<AMessage> notify = mNotify->dup();
notify->setInt32("what", kWhatFlushComplete);
notify->setInt32("audio", static_cast<int32_t>(audio));
notify->post();
}
bool NuPlayer::Renderer::dropBufferIfStale(
bool audio, const sp<AMessage> &msg) {
int32_t queueGeneration;
CHECK(msg->findInt32("queueGeneration", &queueGeneration));
if (queueGeneration == getQueueGeneration(audio)) {
return false;
}
sp<AMessage> notifyConsumed;
if (msg->findMessage("notifyConsumed", ¬ifyConsumed)) {
notifyConsumed->post();
}
return true;
}
void NuPlayer::Renderer::onAudioSinkChanged() {
if (offloadingAudio()) {
return;
}
CHECK(!mDrainAudioQueuePending);
mNumFramesWritten = 0;
{
Mutex::Autolock autoLock(mLock);
mAnchorNumFramesWritten = -1;
}
uint32_t written;
if (mAudioSink->getFramesWritten(&written) == OK) {
mNumFramesWritten = written;
}
}
void NuPlayer::Renderer::onDisableOffloadAudio() {
Mutex::Autolock autoLock(mLock);
mFlags &= ~FLAG_OFFLOAD_AUDIO;
++mAudioDrainGeneration;
if (mAudioRenderingStartGeneration != -1) {
prepareForMediaRenderingStart_l();
}
}
void NuPlayer::Renderer::onEnableOffloadAudio() {
Mutex::Autolock autoLock(mLock);
mFlags |= FLAG_OFFLOAD_AUDIO;
++mAudioDrainGeneration;
if (mAudioRenderingStartGeneration != -1) {
prepareForMediaRenderingStart_l();
}
}
void NuPlayer::Renderer::onPause() {
if (mPaused) {
return;
}
{
Mutex::Autolock autoLock(mLock);
// we do not increment audio drain generation so that we fill audio buffer during pause.
++mVideoDrainGeneration;
prepareForMediaRenderingStart_l();
mPaused = true;
mMediaClock->setPlaybackRate(0.0);
}
mDrainAudioQueuePending = false;
mDrainVideoQueuePending = false;
// Note: audio data may not have been decoded, and the AudioSink may not be opened.
mAudioSink->pause();
startAudioOffloadPauseTimeout();
ALOGV("now paused audio queue has %zu entries, video has %zu entries",
mAudioQueue.size(), mVideoQueue.size());
}
void NuPlayer::Renderer::onResume() {
if (!mPaused) {
return;
}
// Note: audio data may not have been decoded, and the AudioSink may not be opened.
cancelAudioOffloadPauseTimeout();
if (mAudioSink->ready()) {
status_t err = mAudioSink->start();
if (err != OK) {
ALOGE("cannot start AudioSink err %d", err);
notifyAudioTearDown(kDueToError);
}
}
{
Mutex::Autolock autoLock(mLock);
mPaused = false;
// rendering started message may have been delayed if we were paused.
if (mRenderingDataDelivered) {
notifyIfMediaRenderingStarted_l();
}
// configure audiosink as we did not do it when pausing
if (mAudioSink != NULL && mAudioSink->ready()) {
mAudioSink->setPlaybackRate(mPlaybackSettings);
}
mMediaClock->setPlaybackRate(mPlaybackRate);
if (!mAudioQueue.empty()) {
postDrainAudioQueue_l();
}
}
if (!mVideoQueue.empty()) {
postDrainVideoQueue();
}
}
void NuPlayer::Renderer::onSetVideoFrameRate(float fps) {
if (mVideoScheduler == NULL) {
mVideoScheduler = new VideoFrameScheduler();
}
mVideoScheduler->init(fps);
}
int32_t NuPlayer::Renderer::getQueueGeneration(bool audio) {
Mutex::Autolock autoLock(mLock);
return (audio ? mAudioQueueGeneration : mVideoQueueGeneration);
}
int32_t NuPlayer::Renderer::getDrainGeneration(bool audio) {
Mutex::Autolock autoLock(mLock);
return (audio ? mAudioDrainGeneration : mVideoDrainGeneration);
}
bool NuPlayer::Renderer::getSyncQueues() {
Mutex::Autolock autoLock(mLock);
return mSyncQueues;
}
void NuPlayer::Renderer::onAudioTearDown(AudioTearDownReason reason) {
if (mAudioTornDown) {
return;
}
mAudioTornDown = true;
int64_t currentPositionUs;
sp<AMessage> notify = mNotify->dup();
if (getCurrentPosition(¤tPositionUs) == OK) {
notify->setInt64("positionUs", currentPositionUs);
}
mAudioSink->stop();
mAudioSink->flush();
notify->setInt32("what", kWhatAudioTearDown);
notify->setInt32("reason", reason);
notify->post();
}
void NuPlayer::Renderer::startAudioOffloadPauseTimeout() {
if (offloadingAudio()) {
mWakeLock->acquire();
sp<AMessage> msg = new AMessage(kWhatAudioOffloadPauseTimeout, this);
msg->setInt32("drainGeneration", mAudioOffloadPauseTimeoutGeneration);
msg->post(kOffloadPauseMaxUs);
}
}
void NuPlayer::Renderer::cancelAudioOffloadPauseTimeout() {
// We may have called startAudioOffloadPauseTimeout() without
// the AudioSink open and with offloadingAudio enabled.
//
// When we cancel, it may be that offloadingAudio is subsequently disabled, so regardless
// we always release the wakelock and increment the pause timeout generation.
//
// Note: The acquired wakelock prevents the device from suspending
// immediately after offload pause (in case a resume happens shortly thereafter).
mWakeLock->release(true);
++mAudioOffloadPauseTimeoutGeneration;
}
status_t NuPlayer::Renderer::onOpenAudioSink(
const sp<AMessage> &format,
bool offloadOnly,
bool hasVideo,
uint32_t flags) {
ALOGV("openAudioSink: offloadOnly(%d) offloadingAudio(%d)",
offloadOnly, offloadingAudio());
bool audioSinkChanged = false;
int32_t numChannels;
CHECK(format->findInt32("channel-count", &numChannels));
int32_t channelMask;
if (!format->findInt32("channel-mask", &channelMask)) {
// signal to the AudioSink to derive the mask from count.
channelMask = CHANNEL_MASK_USE_CHANNEL_ORDER;
}
int32_t sampleRate;
CHECK(format->findInt32("sample-rate", &sampleRate));
if (offloadingAudio()) {
audio_format_t audioFormat = AUDIO_FORMAT_PCM_16_BIT;
AString mime;
CHECK(format->findString("mime", &mime));
status_t err = mapMimeToAudioFormat(audioFormat, mime.c_str());
if (err != OK) {
ALOGE("Couldn't map mime \"%s\" to a valid "
"audio_format", mime.c_str());
onDisableOffloadAudio();
} else {
ALOGV("Mime \"%s\" mapped to audio_format 0x%x",
mime.c_str(), audioFormat);
int avgBitRate = -1;
format->findInt32("bitrate", &avgBitRate);
int32_t aacProfile = -1;
if (audioFormat == AUDIO_FORMAT_AAC
&& format->findInt32("aac-profile", &aacProfile)) {
// Redefine AAC format as per aac profile
mapAACProfileToAudioFormat(
audioFormat,
aacProfile);
}
audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
offloadInfo.duration_us = -1;
format->findInt64(
"durationUs", &offloadInfo.duration_us);
offloadInfo.sample_rate = sampleRate;
offloadInfo.channel_mask = channelMask;
offloadInfo.format = audioFormat;
offloadInfo.stream_type = AUDIO_STREAM_MUSIC;
offloadInfo.bit_rate = avgBitRate;
offloadInfo.has_video = hasVideo;
offloadInfo.is_streaming = true;
if (memcmp(&mCurrentOffloadInfo, &offloadInfo, sizeof(offloadInfo)) == 0) {
ALOGV("openAudioSink: no change in offload mode");
// no change from previous configuration, everything ok.
return OK;
}
mCurrentPcmInfo = AUDIO_PCMINFO_INITIALIZER;
ALOGV("openAudioSink: try to open AudioSink in offload mode");
uint32_t offloadFlags = flags;
offloadFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
offloadFlags &= ~AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
audioSinkChanged = true;
mAudioSink->close();
err = mAudioSink->open(
sampleRate,
numChannels,
(audio_channel_mask_t)channelMask,
audioFormat,
0 /* bufferCount - unused */,
&NuPlayer::Renderer::AudioSinkCallback,
this,
(audio_output_flags_t)offloadFlags,
&offloadInfo);
if (err == OK) {
err = mAudioSink->setPlaybackRate(mPlaybackSettings);
}
if (err == OK) {
// If the playback is offloaded to h/w, we pass
// the HAL some metadata information.
// We don't want to do this for PCM because it
// will be going through the AudioFlinger mixer
// before reaching the hardware.
// TODO
mCurrentOffloadInfo = offloadInfo;
if (!mPaused) { // for preview mode, don't start if paused
err = mAudioSink->start();
}
ALOGV_IF(err == OK, "openAudioSink: offload succeeded");
}
if (err != OK) {
// Clean up, fall back to non offload mode.
mAudioSink->close();
onDisableOffloadAudio();
mCurrentOffloadInfo = AUDIO_INFO_INITIALIZER;
ALOGV("openAudioSink: offload failed");
if (offloadOnly) {
notifyAudioTearDown(kForceNonOffload);
}
} else {
mUseAudioCallback = true; // offload mode transfers data through callback
++mAudioDrainGeneration; // discard pending kWhatDrainAudioQueue message.
}
}
}
if (!offloadOnly && !offloadingAudio()) {
ALOGV("openAudioSink: open AudioSink in NON-offload mode");
uint32_t pcmFlags = flags;
pcmFlags &= ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
const PcmInfo info = {
(audio_channel_mask_t)channelMask,
(audio_output_flags_t)pcmFlags,
AUDIO_FORMAT_PCM_16_BIT, // TODO: change to audioFormat
numChannels,
sampleRate
};
if (memcmp(&mCurrentPcmInfo, &info, sizeof(info)) == 0) {
ALOGV("openAudioSink: no change in pcm mode");
// no change from previous configuration, everything ok.
return OK;
}
audioSinkChanged = true;
mAudioSink->close();
mCurrentOffloadInfo = AUDIO_INFO_INITIALIZER;
// Note: It is possible to set up the callback, but not use it to send audio data.
// This requires a fix in AudioSink to explicitly specify the transfer mode.
mUseAudioCallback = getUseAudioCallbackSetting();
if (mUseAudioCallback) {
++mAudioDrainGeneration; // discard pending kWhatDrainAudioQueue message.
}
// Compute the desired buffer size.
// For callback mode, the amount of time before wakeup is about half the buffer size.
const uint32_t frameCount =
(unsigned long long)sampleRate * getAudioSinkPcmMsSetting() / 1000;
// The doNotReconnect means AudioSink will signal back and let NuPlayer to re-construct
// AudioSink. We don't want this when there's video because it will cause a video seek to
// the previous I frame. But we do want this when there's only audio because it will give
// NuPlayer a chance to switch from non-offload mode to offload mode.
// So we only set doNotReconnect when there's no video.
const bool doNotReconnect = !hasVideo;
// We should always be able to set our playback settings if the sink is closed.
LOG_ALWAYS_FATAL_IF(mAudioSink->setPlaybackRate(mPlaybackSettings) != OK,
"onOpenAudioSink: can't set playback rate on closed sink");
status_t err = mAudioSink->open(
sampleRate,
numChannels,
(audio_channel_mask_t)channelMask,
AUDIO_FORMAT_PCM_16_BIT,
0 /* bufferCount - unused */,
mUseAudioCallback ? &NuPlayer::Renderer::AudioSinkCallback : NULL,
mUseAudioCallback ? this : NULL,
(audio_output_flags_t)pcmFlags,
NULL,
doNotReconnect,
frameCount);
if (err != OK) {
ALOGW("openAudioSink: non offloaded open failed status: %d", err);
mAudioSink->close();
mCurrentPcmInfo = AUDIO_PCMINFO_INITIALIZER;
return err;
}
mCurrentPcmInfo = info;
if (!mPaused) { // for preview mode, don't start if paused
mAudioSink->start();
}
}
if (audioSinkChanged) {
onAudioSinkChanged();
}
mAudioTornDown = false;
return OK;
}
void NuPlayer::Renderer::onCloseAudioSink() {
mAudioSink->close();
mCurrentOffloadInfo = AUDIO_INFO_INITIALIZER;
mCurrentPcmInfo = AUDIO_PCMINFO_INITIALIZER;
}
} // namespace android
| 33.566135 | 100 | 0.608688 | [
"render"
] |
b47efbe440a0a2dd3eac6af3af881f17a6fafbf2 | 5,322 | hpp | C++ | Simple-Demo/glm/detail/func_matrix.hpp | ganyc717/Simple-Demo | 3e550af547393c5d53efec545a2c2c86172faaea | [
"MIT"
] | null | null | null | Simple-Demo/glm/detail/func_matrix.hpp | ganyc717/Simple-Demo | 3e550af547393c5d53efec545a2c2c86172faaea | [
"MIT"
] | null | null | null | Simple-Demo/glm/detail/func_matrix.hpp | ganyc717/Simple-Demo | 3e550af547393c5d53efec545a2c2c86172faaea | [
"MIT"
] | null | null | null | /// @ref core
/// @file glm/detail/func_matrix.hpp
///
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.6 Matrix Functions</a>
///
/// @defgroup core_func_matrix Matrix functions
/// @ingroup core
///
/// For each of the following built-in matrix functions, there is both a
/// single-precision floating point version, where all arguments and return values
/// are single precision, and a double-precision floating version, where all
/// arguments and return values are double precision. Only the single-precision
/// floating point version is shown.
#pragma once
// Dependencies
#include "../detail/precision.hpp"
#include "../detail/setup.hpp"
#include "../detail/type_mat.hpp"
#include "../vec2.hpp"
#include "../vec3.hpp"
#include "../vec4.hpp"
#include "../mat2x2.hpp"
#include "../mat2x3.hpp"
#include "../mat2x4.hpp"
#include "../mat3x2.hpp"
#include "../mat3x3.hpp"
#include "../mat3x4.hpp"
#include "../mat4x2.hpp"
#include "../mat4x3.hpp"
#include "../mat4x4.hpp"
namespace glm{
namespace detail
{
template<typename T, precision P>
struct outerProduct_trait<2, 2, T, P, vec, vec>
{
typedef mat<2, 2, T, P> type;
};
template<typename T, precision P>
struct outerProduct_trait<2, 3, T, P, vec, vec>
{
typedef mat<3, 2, T, P> type;
};
template<typename T, precision P>
struct outerProduct_trait<2, 4, T, P, vec, vec>
{
typedef mat<4, 2, T, P> type;
};
template<typename T, precision P>
struct outerProduct_trait<3, 2, T, P, vec, vec>
{
typedef mat<2, 3, T, P> type;
};
template<typename T, precision P>
struct outerProduct_trait<3, 3, T, P, vec, vec>
{
typedef mat<3, 3, T, P> type;
};
template<typename T, precision P>
struct outerProduct_trait<3, 4, T, P, vec, vec>
{
typedef mat<4, 3, T, P> type;
};
template<typename T, precision P>
struct outerProduct_trait<4, 2, T, P, vec, vec>
{
typedef mat<2, 4, T, P> type;
};
template<typename T, precision P>
struct outerProduct_trait<4, 3, T, P, vec, vec>
{
typedef mat<3, 4, T, P> type;
};
template<typename T, precision P>
struct outerProduct_trait<4, 4, T, P, vec, vec>
{
typedef mat<4, 4, T, P> type;
};
}//namespace detail
/// @addtogroup core_func_matrix
/// @{
/// Multiply matrix x by matrix y component-wise, i.e.,
/// result[i][j] is the scalar product of x[i][j] and y[i][j].
///
/// @tparam matType Floating-point matrix types.
///
/// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/matrixCompMult.xml">GLSL matrixCompMult man page</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.6 Matrix Functions</a>
template<typename T, precision P, template<typename, precision> class matType>
GLM_FUNC_DECL matType<T, P> matrixCompMult(matType<T, P> const & x, matType<T, P> const & y);
/// Treats the first parameter c as a column vector
/// and the second parameter r as a row vector
/// and does a linear algebraic matrix multiply c * r.
///
/// @tparam matType Floating-point matrix types.
///
/// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/outerProduct.xml">GLSL outerProduct man page</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.6 Matrix Functions</a>
template<int DA, int DB, typename T, precision P, template<length_t, typename, precision> class vecTypeA, template<length_t, typename, precision> class vecTypeB>
GLM_FUNC_DECL typename detail::outerProduct_trait<DA, DB, T, P, vecTypeA, vecTypeB>::type outerProduct(vecTypeA<DA, T, P> const & c, vecTypeB<DB, T, P> const & r);
/// Returns the transposed matrix of x
///
/// @tparam matType Floating-point matrix types.
///
/// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/transpose.xml">GLSL transpose man page</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.6 Matrix Functions</a>
# if((GLM_COMPILER & GLM_COMPILER_VC) && (GLM_COMPILER >= GLM_COMPILER_VC11))
template<typename T, precision P, template<typename, precision> class matType>
GLM_FUNC_DECL typename matType<T, P>::transpose_type transpose(matType<T, P> const & x);
# endif
/// Return the determinant of a squared matrix.
///
/// @tparam valType Floating-point scalar types.
///
/// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/determinant.xml">GLSL determinant man page</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.6 Matrix Functions</a>
template<typename T, precision P, template<typename, precision> class matType>
GLM_FUNC_DECL T determinant(matType<T, P> const & m);
/// Return the inverse of a squared matrix.
///
/// @tparam valType Floating-point scalar types.
///
/// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/inverse.xml">GLSL inverse man page</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.6 Matrix Functions</a>
template<typename T, precision P, template<typename, precision> class matType>
GLM_FUNC_DECL matType<T, P> inverse(matType<T, P> const & m);
/// @}
}//namespace glm
#include "func_matrix.inl"
| 35.48 | 164 | 0.693724 | [
"vector"
] |
b47fcb4878da059c4ef530dcf04e47a8942506d2 | 657 | hpp | C++ | src/math/geometry/cartesian2polar.hpp | dmilos/math | 977cb171d8d582411cfab73a23ce85a8ccf3b132 | [
"Apache-2.0"
] | 3 | 2020-07-02T12:44:32.000Z | 2021-04-07T20:31:41.000Z | src/math/geometry/cartesian2polar.hpp | dmilos/math | 977cb171d8d582411cfab73a23ce85a8ccf3b132 | [
"Apache-2.0"
] | null | null | null | src/math/geometry/cartesian2polar.hpp | dmilos/math | 977cb171d8d582411cfab73a23ce85a8ccf3b132 | [
"Apache-2.0"
] | 1 | 2020-09-04T11:01:28.000Z | 2020-09-04T11:01:28.000Z | #ifndef math_geometry_cartesian2polar
#define math_geometry_cartesian2polar
// ::math::geometry::cartesian2polar( )
#include "../linear/vector/structure.hpp"
namespace math
{
namespace geometry
{
template< typename scalar_name >
::math::linear::vector::point<scalar_name,2>
cartesian2polar( ::math::linear::vector::point<scalar_name,2> const& point )
{ // ( x, y) -> ( r, phi )
::math::linear::vector::point<scalar_name,2> result;
result[0] = sqrt( point[0]*point[0] + point[1]*point[1] );
result[1] = atan2( point[1], point[0]);
return result;
}
}
}
#endif
| 24.333333 | 82 | 0.604262 | [
"geometry",
"vector"
] |
b48263c07eef77bd48d9762b85ed032c84c0cc2c | 3,294 | cpp | C++ | Causality/CharacterBehavier.cpp | ArcEarth/PPARM | 8e22e3f20a90a22940218c243b7fe5e24e754e5b | [
"MIT"
] | 3 | 2016-07-13T18:30:33.000Z | 2020-03-31T22:20:34.000Z | Causality/CharacterBehavier.cpp | ArcEarth/PPARM | 8e22e3f20a90a22940218c243b7fe5e24e754e5b | [
"MIT"
] | null | null | null | Causality/CharacterBehavier.cpp | ArcEarth/PPARM | 8e22e3f20a90a22940218c243b7fe5e24e754e5b | [
"MIT"
] | 5 | 2016-01-16T14:25:28.000Z | 2017-06-12T16:15:18.000Z | #include "pch_bcl.h"
#include "CharacterBehavier.h"
using namespace Causality;
using namespace DirectX;
using namespace std;
BehavierSpace::animation_type & BehavierSpace::operator[](const std::string & name)
{
for (auto& clip : m_AnimClips)
{
if (clip.Name == name) return clip;
}
throw std::out_of_range("No animation with specified name exist in this aniamtion space.");
}
const BehavierSpace::animation_type & BehavierSpace::operator[](const std::string & name) const
{
for (const auto& clip : m_AnimClips)
{
if (clip.Name == name) return clip;
}
throw std::out_of_range("No animation with specified name exist in this aniamtion space.");
}
void Causality::BehavierSpace::AddAnimationClip(animation_type && animation)
{
#ifdef _DEBUG
for (auto& clip : m_AnimClips)
if (clip.Name == animation.Name)
throw std::out_of_range("Name of animation is already existed.");
#endif
m_AnimClips.emplace_back(std::move(animation));
}
BehavierSpace::animation_type & BehavierSpace::AddAnimationClip(const std::string & name)
{
#ifdef _DEBUG
for (auto& clip : m_AnimClips)
if (clip.Name == name)
throw std::out_of_range("Name of animation is already existed.");
#endif
m_AnimClips.emplace_back(name);
auto& anim = m_AnimClips.back();
anim.SetArmature(*m_pArmature);
return anim;
}
bool Causality::BehavierSpace::Contains(const std::string & name) const
{
for (auto& clip : m_AnimClips)
{
if (clip.Name == name) return true;
}
return false;
}
//void Causality::BehavierSpace::UpdateArmatureParts()
//{
// //auto& armature = *m_pArmature;
//}
const IArmature & BehavierSpace::Armature() const { return *m_pArmature; }
IArmature & BehavierSpace::Armature() { return *m_pArmature; }
void BehavierSpace::SetArmature(IArmature & armature) {
assert(this->Clips().empty());
m_pArmature = &armature;
//UpdateArmatureParts();
}
BehavierSpace::frame_const_view BehavierSpace::RestFrame() const { return Armature().bind_frame(); }
void BehavierSpace::UniformQuaternionsBetweenClips()
{
auto& armature = *m_pArmature;
auto& clips = m_AnimClips;
// Try to unify rotation pivot direction
typedef vector<Vector4, DirectX::AlignedAllocator<Vector4, alignof(DirectX::XMVECTOR)>> aligned_vector_of_vector4;
aligned_vector_of_vector4 gbl_pivots(armature.size());
bool gbl_def = true;
for (auto& anim : clips)
{
using namespace DirectX;
aligned_vector_of_vector4 pivots(armature.size());
for (auto& frame : anim.GetFrameBuffer())
{
for (size_t i = 0; i < armature.size(); i++)
{
pivots[i] += XMLoadA(frame[i].LclRotation);
}
}
if (gbl_def)
{
for (size_t i = 0; i < armature.size(); i++)
{
gbl_pivots[i] = DirectX::XMVector3Normalize(XMLoadA(pivots[i]));
}
gbl_def = false;
}
else
{
//for (size_t i = 0; i < armature.size(); i++)
//{
// XMVECTOR pivot = DirectX::XMVector3Normalize(pivots[i].LoadA());
// XMVECTOR gbl_pivot = gbl_pivots[i].Load();
// if (XMVector4Less(XMVector3Dot(gbl_pivot, pivot), XMVectorZero()))
// {
// for (auto& frame : anim.GetFrameBuffer())
// {
// frame[i].LclRotation.StoreA(-frame[i].LclRotation.LoadA());
// }
// }
//}
}
}
}
| 27.22314 | 116 | 0.672738 | [
"vector"
] |
b487ecde323aa0aba3259ca632b1f2f92d0930cc | 69,055 | cpp | C++ | Athos/Networks/SqueezeNetImgNet/AccuracyAnalysisHelper/squeezenet64_acc_test.cpp | mayank0403/EzPC | 25eea0d7d9990d23f10d5aadaa5f82901f3b3b0a | [
"MIT"
] | 2 | 2020-07-13T12:43:30.000Z | 2021-06-29T12:12:49.000Z | Athos/Networks/SqueezeNetImgNet/AccuracyAnalysisHelper/squeezenet64_acc_test.cpp | mayank0403/EzPC | 25eea0d7d9990d23f10d5aadaa5f82901f3b3b0a | [
"MIT"
] | null | null | null | Athos/Networks/SqueezeNetImgNet/AccuracyAnalysisHelper/squeezenet64_acc_test.cpp | mayank0403/EzPC | 25eea0d7d9990d23f10d5aadaa5f82901f3b3b0a | [
"MIT"
] | 1 | 2020-10-21T02:46:28.000Z | 2020-10-21T02:46:28.000Z | /*
Authors: Nishant Kumar.
Copyright:
Copyright (c) 2018 Microsoft Research
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.
Code auto-generated by Athos and then hand-modified by author.
*/
#include<vector>
#include<math.h>
#include<cstdlib>
#include<iostream>
#include<fstream>
#include<Eigen/Dense>
#include<cstdlib>
#include<string>
using namespace std;
using namespace Eigen;
uint32_t public_lrshift(uint32_t x, uint32_t y){
return (x >> y);
}
int32_t public_lrshift(int32_t x, uint32_t y){
return ((int32_t)(((uint32_t)x) >> y));
}
uint64_t public_lrshift(uint64_t x, uint64_t y){
return (x >> y);
}
int64_t public_lrshift(int64_t x, uint64_t y){
return ((int64_t)(((uint64_t)x) >> y));
}
template<typename T>
vector<T> make_vector(size_t size) {
return std::vector<T>(size);
}
template <typename T, typename... Args>
auto make_vector(size_t first, Args... sizes)
{
auto inner = make_vector<T>(sizes...);
return vector<decltype(inner)>(first, inner);
}
template<typename T>
ostream& operator<< (ostream &os, const vector<T> &v)
{
for(auto it = v.begin (); it != v.end (); ++it) {
os << *it << endl;
}
return os;
}
uint32_t signedgtbl(int64_t x, int64_t y){
uint64_t ux = x;
uint64_t uy = y;
uint64_t signBitX = (x & ( (int64_t)1 << (int64_t)63));
uint64_t signBitY = (y & ( (int64_t)1 << (int64_t)63));
return ((signBitX ^ signBitY) > (uint64_t)0) ? (signBitX > (uint64_t)0) ? 0 : 1 : (ux > uy);
}
int64_t signedarshiftbl(int64_t x, uint64_t y){
uint64_t ux = x;
uint64_t signBitX = (x & ( (int64_t)1 << (int64_t)63));
return (signBitX > (uint64_t)0) ? ( (uint64_t)0 - (( (uint64_t)0 - ux) >> y)) : (ux >> y);
}
uint32_t unsignedltbl(uint64_t x, uint64_t y){
return (y > x);
}
uint32_t signedltbl(int64_t x, int64_t y){
return (y > x);
}
uint32_t unsignedleqbl(uint64_t x, uint64_t y){
return ! (x > y);
}
uint32_t signedleqbl(int64_t x, int64_t y){
return ! (x > y);
}
uint32_t unsignedgeqbl(uint64_t x, uint64_t y){
return ! (y > x);
}
uint32_t signedgeqbl(int64_t x, int64_t y){
return ! (y > x);
}
uint32_t unsignedequalsbl(uint64_t x, uint64_t y){
return (! (x < y) && ! (y < x));
}
uint32_t signedequalsbl(int64_t x, int64_t y){
return (! (x < y) && ! (y < x));
}
uint64_t longDivision(uint64_t x, uint64_t y, uint32_t getQuotient){
uint64_t q = (uint64_t)0;
uint64_t divisor = (uint64_t)0;
uint32_t cond = 0;
for (uint32_t iter = (int32_t)0; iter < (int32_t)64; iter++){
uint64_t i = ( (int64_t)63 - iter);
divisor = (divisor << (uint64_t)1);
divisor = (divisor + (public_lrshift((x & ( (uint64_t)1 << i)), i)));
cond = (divisor >= y);
divisor = cond ? (divisor - y) : divisor;
q = (q << (uint64_t)1);
q = cond ? (q + (uint64_t)1) : q;
}
return getQuotient ? q : divisor;
}
uint64_t unsigneddivbl(uint64_t x, uint64_t y){
return longDivision(x, y, 1);
}
uint64_t unsigneddival(uint64_t x, uint64_t y){
uint64_t bx = x;
uint64_t by = y;
return (bx / by);
}
int64_t signeddivbl(int64_t x, int64_t y){
uint32_t isXNeg = (x < (int64_t)0);
uint32_t isYNeg = (y < (int64_t)0);
uint64_t ux = isXNeg ? ( (int64_t)0 - x) : x;
uint64_t uy = isYNeg ? ( (int64_t)0 - y) : y;
uint64_t ures = (ux / uy);
uint32_t isResNeg = (isXNeg ^ isYNeg);
return isResNeg ? ( (uint64_t)0 - ures) : ures;
}
int64_t signeddival(int64_t x, int64_t y){
int64_t bx = x;
int64_t by = y;
return (bx / by);
}
uint64_t unsignedmodbl(uint64_t x, uint64_t y){
return longDivision(x, y, 0);
}
uint64_t unsignedmodal(uint64_t x, uint64_t y){
uint64_t bx = x;
uint64_t by = y;
return (bx % by);
}
int64_t signedmodbl(int64_t x, int64_t y){
uint32_t isXNeg = (x < (int64_t)0);
uint32_t isYNeg = (y < (int64_t)0);
uint64_t ux = isXNeg ? ( (int64_t)0 - x) : x;
uint64_t uy = isYNeg ? ( (int64_t)0 - y) : y;
uint64_t urem = (ux % uy);
return isXNeg ? ( (uint64_t)0 - urem) : urem;
}
int64_t signedmodal(int64_t x, int64_t y){
int64_t bx = x;
int64_t by = y;
return (bx % by);
}
void MatMulCSF2DEigen(int32_t i, int32_t j, int32_t k, auto& A, auto& B, auto& C, int64_t consSF){
Matrix<int64_t, Dynamic, Dynamic> eigen_a(i, j);
Matrix<int64_t, Dynamic, Dynamic> eigen_b(j, k);
Matrix<int64_t, Dynamic, Dynamic> eigen_c(i, k);
for (int i0 = 0; i0 < i; ++i0){
for (int i1 = 0; i1 < j; ++i1){
eigen_a(i0, i1) = A[i0][i1];
}
}
for (int i0 = 0; i0 < j; ++i0){
for (int i1 = 0; i1 < k; ++i1){
eigen_b(i0, i1) = B[i0][i1];
}
}
eigen_c = eigen_a * eigen_b;
for (int i0 = 0; i0 < i; ++i0){
for (int i1 = 0; i1 < k; ++i1){
C[i0][i1] = (eigen_c(i0, i1) >> consSF);
}
}
}
void MatMulCSF2D(int32_t i, int32_t j, int32_t k, auto& A, auto& B, auto& C, int64_t consSF){
// for (uint32_t i1 = (int32_t)0; i1 < i; i1++){
// for (uint32_t i2 = (int32_t)0; i2 < k; i2++){
// C[i1][i2] = (int64_t)0;
// for (uint32_t i3 = (int32_t)0; i3 < j; i3++){
// C[i1][i2] = (C[i1][i2] + (A[i1][i3] * B[i3][i2]));
// }
// C[i1][i2] = (C[i1][i2] >> consSF);
// }
// }
MatMulCSF2DEigen(i,j,k,A,B,C,consSF);
}
void ArgMax1(int32_t outArrS1, int32_t inArrS1, int32_t inArrS2, auto& inArr, int32_t dim, auto& outArr){
for (uint32_t od = (int32_t)0; od < inArrS1; od++){
int64_t maxi = inArr[od][ (int32_t)0];
int64_t maxiIdx = (int64_t)0;
for (uint32_t i = (int32_t)0; i < inArrS2; i++){
int64_t iL = i;
maxiIdx = (inArr[od][i] > maxi) ? iL : maxiIdx;
maxi = (inArr[od][i] > maxi) ? inArr[od][i] : maxi;
}
outArr[od] = maxiIdx;
}
}
void Relu2(int32_t s1, int32_t s2, auto& inArr, auto& outArr){
for (uint32_t i1 = (int32_t)0; i1 < s1; i1++){
for (uint32_t i2 = (int32_t)0; i2 < s2; i2++){
outArr[i1][i2] = (inArr[i1][i2] > (int64_t)0) ? inArr[i1][i2] : (int64_t)0;
}
}
}
void Relu4(int32_t s1, int32_t s2, int32_t s3, int32_t s4, auto& inArr, auto& outArr){
for (uint32_t i1 = (int32_t)0; i1 < s1; i1++){
for (uint32_t i2 = (int32_t)0; i2 < s2; i2++){
for (uint32_t i3 = (int32_t)0; i3 < s3; i3++){
for (uint32_t i4 = (int32_t)0; i4 < s4; i4++){
outArr[i1][i2][i3][i4] = (inArr[i1][i2][i3][i4] > (int64_t)0) ? inArr[i1][i2][i3][i4] : (int64_t)0;
}
}
}
}
}
void ElemWiseMul2(int32_t s1, int32_t s2, auto& arr1, auto& arr2, auto& outArr, int64_t shrout){
for (uint32_t i1 = (int32_t)0; i1 < s1; i1++){
for (uint32_t i2 = (int32_t)0; i2 < s2; i2++){
outArr[i1][i2] = ((arr1[i1][i2] * arr2[i1][i2]) >> shrout);
}
}
}
void ElemWiseMul4(int32_t s1, int32_t s2, int32_t s3, int32_t s4, auto& arr1, auto& arr2, auto& outArr, int64_t shrout){
for (uint32_t i1 = (int32_t)0; i1 < s1; i1++){
for (uint32_t i2 = (int32_t)0; i2 < s2; i2++){
for (uint32_t i3 = (int32_t)0; i3 < s3; i3++){
for (uint32_t i4 = (int32_t)0; i4 < s4; i4++){
outArr[i1][i2][i3][i4] = ((arr1[i1][i2][i3][i4] * arr2[i1][i2][i3][i4]) >> shrout);
}
}
}
}
}
void ElemWiseDiv2(int32_t s1, int32_t s2, auto& arr1, auto& arr2, auto& outArr, int64_t shrout){
for (uint32_t i1 = (int32_t)0; i1 < s1; i1++){
for (uint32_t i2 = (int32_t)0; i2 < s2; i2++){
outArr[i1][i2] = ((arr1[i1][i2] / arr2[i1][i2]) << shrout);
}
}
}
void Floor2(int32_t s1, int32_t s2, auto& inArr, auto& outArr, int64_t curSF){
for (uint32_t i1 = (int32_t)0; i1 < s1; i1++){
for (uint32_t i2 = (int32_t)0; i2 < s2; i2++){
int64_t mask = ~ (( (int64_t)1 << curSF) - (int64_t)1);
outArr[i1][i2] = (inArr[i1][i2] & mask);
}
}
}
void MaxPool(int32_t N, int32_t H, int32_t W, int32_t C, int32_t ksizeH, int32_t ksizeW, int32_t zPadHLeft, int32_t zPadHRight, int32_t zPadWLeft, int32_t zPadWRight, int32_t strideH, int32_t strideW, int32_t N1, int32_t imgH, int32_t imgW, int32_t C1, auto& inArr, auto& outArr){
for (uint32_t n = (int32_t)0; n < N; n++){
for (uint32_t c = (int32_t)0; c < C; c++){
int32_t leftTopCornerH = ( (int32_t)0 - zPadHLeft);
int32_t extremeRightBottomCornerH = ((imgH - (int32_t)1) + zPadHRight);
int32_t ctH = (int32_t)0;
while ((((leftTopCornerH + ksizeH) - (int32_t)1) <= extremeRightBottomCornerH)) {
int32_t leftTopCornerW = ( (int32_t)0 - zPadWLeft);
int32_t extremeRightBottomCornerW = ((imgW - (int32_t)1) + zPadWRight);
int32_t ctW = (int32_t)0;
while ((((leftTopCornerW + ksizeW) - (int32_t)1) <= extremeRightBottomCornerW)) {
int64_t maxi = (int64_t)0;
if ((((leftTopCornerH < (int32_t)0) || (leftTopCornerH >= imgH)) || ((leftTopCornerW < (int32_t)0) || (leftTopCornerW >= imgW)))) {
maxi = (int64_t)0;
} else {
maxi = inArr[n][leftTopCornerH][leftTopCornerW][c];
}
for (uint32_t fh = (int32_t)0; fh < ksizeH; fh++){
for (uint32_t fw = (int32_t)0; fw < ksizeW; fw++){
int32_t curPosH = (leftTopCornerH + fh);
int32_t curPosW = (leftTopCornerW + fw);
int64_t temp = (int64_t)0;
if ((((curPosH < (int32_t)0) || (curPosH >= imgH)) || ((curPosW < (int32_t)0) || (curPosW >= imgW)))) {
temp = (int64_t)0;
} else {
temp = inArr[n][curPosH][curPosW][c];
}
maxi = (maxi < temp) ? temp : maxi;
}
}
outArr[n][ctH][ctW][c] = maxi;
leftTopCornerW = (leftTopCornerW + strideW);
ctW = (ctW + (int32_t)1);
}
leftTopCornerH = (leftTopCornerH + strideH);
ctH = (ctH + (int32_t)1);
}
}
}
}
void AvgPool(int32_t N, int32_t H, int32_t W, int32_t C, int32_t ksizeH, int32_t ksizeW, int32_t zPadHLeft, int32_t zPadHRight, int32_t zPadWLeft, int32_t zPadWRight, int32_t strideH, int32_t strideW, int32_t N1, int32_t imgH, int32_t imgW, int32_t C1, auto& inArr, auto& outArr){
int32_t rows = (((N * C) * H) * W);
auto filterAvg = make_vector<int64_t>(rows);
int32_t rowIdx = (int32_t)0;
for (uint32_t n = (int32_t)0; n < N; n++){
for (uint32_t c = (int32_t)0; c < C; c++){
int32_t leftTopCornerH = ( (int32_t)0 - zPadHLeft);
int32_t extremeRightBottomCornerH = ((imgH - (int32_t)1) + zPadHRight);
int32_t ctH = (int32_t)0;
while ((((leftTopCornerH + ksizeH) - (int32_t)1) <= extremeRightBottomCornerH)) {
int32_t leftTopCornerW = ( (int32_t)0 - zPadWLeft);
int32_t extremeRightBottomCornerW = ((imgW - (int32_t)1) + zPadWRight);
int32_t ctW = (int32_t)0;
while ((((leftTopCornerW + ksizeW) - (int32_t)1) <= extremeRightBottomCornerW)) {
int64_t curFilterSum = (int64_t)0;
for (uint32_t fh = (int32_t)0; fh < ksizeH; fh++){
for (uint32_t fw = (int32_t)0; fw < ksizeW; fw++){
int32_t curPosH = (leftTopCornerH + fh);
int32_t curPosW = (leftTopCornerW + fw);
int64_t temp = (int64_t)0;
if ((((curPosH < (int32_t)0) || (curPosH >= imgH)) || ((curPosW < (int32_t)0) || (curPosW >= imgW)))) {
temp = (int64_t)0;
} else {
temp = inArr[n][curPosH][curPosW][c];
}
curFilterSum = (curFilterSum + temp);
}
}
int64_t ksizeH64 = ksizeH;
int64_t ksizeW64 = ksizeW;
int64_t filterSz64 = (ksizeH64 * ksizeW64);
int64_t curFilterAvg = (curFilterSum / filterSz64);
filterAvg[rowIdx] = curFilterAvg;
rowIdx = (rowIdx + (int32_t)1);
leftTopCornerW = (leftTopCornerW + strideW);
ctW = (ctW + (int32_t)1);
}
leftTopCornerH = (leftTopCornerH + strideH);
ctH = (ctH + (int32_t)1);
}
}
}
for (uint32_t n = (int32_t)0; n < N; n++){
for (uint32_t c = (int32_t)0; c < C; c++){
for (uint32_t h = (int32_t)0; h < H; h++){
for (uint32_t w = (int32_t)0; w < W; w++){
outArr[n][h][w][c] = filterAvg[((((((n * C) * H) * W) + ((c * H) * W)) + (h * W)) + w)];
}
}
}
}
}
void TempFusedBatchNorm4411(int32_t s1, int32_t s2, int32_t s3, int32_t s4, auto& inArr, int32_t vecS1, auto& multArr, auto& biasArr, auto& outputArr, int64_t consSF){
for (uint32_t i1 = (int32_t)0; i1 < s1; i1++){
for (uint32_t i2 = (int32_t)0; i2 < s2; i2++){
for (uint32_t i3 = (int32_t)0; i3 < s3; i3++){
for (uint32_t i4 = (int32_t)0; i4 < s4; i4++){
int64_t t1 = (inArr[i1][i2][i3][i4] * multArr[i4]);
int64_t t2 = (t1 >> consSF);
outputArr[i1][i2][i3][i4] = (t2 + biasArr[i4]);
}
}
}
}
}
void ScalarMul4(int32_t s1, int32_t s2, int32_t s3, int32_t s4, int64_t scalar, auto& inputArr, auto& outputArr, int64_t consSF){
for (uint32_t i1 = (int32_t)0; i1 < s1; i1++){
for (uint32_t i2 = (int32_t)0; i2 < s2; i2++){
for (uint32_t i3 = (int32_t)0; i3 < s3; i3++){
for (uint32_t i4 = (int32_t)0; i4 < s4; i4++){
outputArr[i1][i2][i3][i4] = (inputArr[i1][i2][i3][i4] * scalar);
}
}
}
}
}
void ReduceMean24(int32_t outS1, int32_t outS2, int32_t inS1, int32_t inS2, int32_t inS3, int32_t inS4, auto& inputArr, auto& axes, auto& outputArr){
for (uint32_t i1 = (int32_t)0; i1 < outS1; i1++){
for (uint32_t i2 = (int32_t)0; i2 < outS2; i2++){
int64_t summ = (int64_t)0;
for (uint32_t i = (int32_t)0; i < inS2; i++){
for (uint32_t j = (int32_t)0; j < inS3; j++){
summ = (summ + inputArr[i1][i][j][i2]);
}
}
int64_t numElem = (inS2 * inS3);
summ = (summ / numElem);
outputArr[i1][i2] = summ;
}
}
}
void MatAddBroadCast2(int32_t s1, int32_t s2, auto& A, auto& B, auto& outArr){
for (uint32_t i1 = (int32_t)0; i1 < s1; i1++){
for (uint32_t i2 = (int32_t)0; i2 < s2; i2++){
outArr[i1][i2] = (A[i1][i2] + B[i2]);
}
}
}
void MatAdd2(int32_t s1, int32_t s2, auto& A, auto& B, auto& outArr){
for (uint32_t i1 = (int32_t)0; i1 < s1; i1++){
for (uint32_t i2 = (int32_t)0; i2 < s2; i2++){
outArr[i1][i2] = (A[i1][i2] + B[i1][i2]);
}
}
}
void MatAddBroadCast4(int32_t s1, int32_t s2, int32_t s3, int32_t s4, auto& A, auto& B, auto& outArr){
for (uint32_t i1 = (int32_t)0; i1 < s1; i1++){
for (uint32_t i2 = (int32_t)0; i2 < s2; i2++){
for (uint32_t i3 = (int32_t)0; i3 < s3; i3++){
for (uint32_t i4 = (int32_t)0; i4 < s4; i4++){
outArr[i1][i2][i3][i4] = (A[i1][i2][i3][i4] + B[i4]);
}
}
}
}
}
void MatAdd4(int32_t s1, int32_t s2, int32_t s3, int32_t s4, auto& A, auto& B, auto& outArr){
for (uint32_t i1 = (int32_t)0; i1 < s1; i1++){
for (uint32_t i2 = (int32_t)0; i2 < s2; i2++){
for (uint32_t i3 = (int32_t)0; i3 < s3; i3++){
for (uint32_t i4 = (int32_t)0; i4 < s4; i4++){
outArr[i1][i2][i3][i4] = (A[i1][i2][i3][i4] + B[i1][i2][i3][i4]);
}
}
}
}
}
void CreateTensor1(int32_t s1, int64_t val, auto& arr){
for (uint32_t i1 = (int32_t)0; i1 < s1; i1++){
arr[i1] = val;
}
}
void CreateTensor2(int32_t s1, int32_t s2, int64_t val, auto& arr){
for (uint32_t i1 = (int32_t)0; i1 < s1; i1++){
for (uint32_t i2 = (int32_t)0; i2 < s2; i2++){
arr[i1][i2] = val;
}
}
}
void CreateTensor4(int32_t s1, int32_t s2, int32_t s3, int32_t s4, int64_t val, auto& arr){
for (uint32_t i1 = (int32_t)0; i1 < s1; i1++){
for (uint32_t i2 = (int32_t)0; i2 < s2; i2++){
for (uint32_t i3 = (int32_t)0; i3 < s3; i3++){
for (uint32_t i4 = (int32_t)0; i4 < s4; i4++){
arr[i1][i2][i3][i4] = val;
}
}
}
}
}
void CopyTensor1(int32_t s1, auto& targetArr, auto& fromArr, auto& ignore){
for (uint32_t i1 = (int32_t)0; i1 < s1; i1++){
targetArr[i1] = fromArr[i1];
}
}
void CopyTensor2(int32_t s1, int32_t s2, auto& targetArr, auto& fromArr, auto& ignore){
for (uint32_t i1 = (int32_t)0; i1 < s1; i1++){
for (uint32_t i2 = (int32_t)0; i2 < s2; i2++){
targetArr[i1][i2] = fromArr[i1][i2];
}
}
}
void CopyTensor4(int32_t s1, int32_t s2, int32_t s3, int32_t s4, auto& targetArr, auto& fromArr, auto& ignore){
for (uint32_t i1 = (int32_t)0; i1 < s1; i1++){
for (uint32_t i2 = (int32_t)0; i2 < s2; i2++){
for (uint32_t i3 = (int32_t)0; i3 < s3; i3++){
for (uint32_t i4 = (int32_t)0; i4 < s4; i4++){
targetArr[i1][i2][i3][i4] = fromArr[i1][i2][i3][i4];
}
}
}
}
}
void CreateIdentity11(int32_t s1, auto& fromArr, auto& newArr){
for (uint32_t i1 = (int32_t)0; i1 < s1; i1++){
newArr[i1] = fromArr[i1];
}
}
void CreateIdentity22(int32_t s1, int32_t s2, auto& fromArr, auto& newArr){
for (uint32_t i1 = (int32_t)0; i1 < s1; i1++){
for (uint32_t i2 = (int32_t)0; i2 < s2; i2++){
newArr[i1][i2] = fromArr[i1][i2];
}
}
}
void CreateIdentity44(int32_t s1, int32_t s2, int32_t s3, int32_t s4, auto& fromArr, auto& newArr){
for (uint32_t i1 = (int32_t)0; i1 < s1; i1++){
for (uint32_t i2 = (int32_t)0; i2 < s2; i2++){
for (uint32_t i3 = (int32_t)0; i3 < s3; i3++){
for (uint32_t i4 = (int32_t)0; i4 < s4; i4++){
newArr[i1][i2][i3][i4] = fromArr[i1][i2][i3][i4];
}
}
}
}
}
void Concat2T444(int32_t s1, int32_t s2, int32_t s3, int32_t s4, int32_t inp1s1, int32_t inp1s2, int32_t inp1s3, int32_t inp1s4, auto& inp1, int32_t inp2s1, int32_t inp2s2, int32_t inp2s3, int32_t inp2s4, auto& inp2, int32_t axis, auto& outp){
for (uint32_t i1 = (int32_t)0; i1 < s1; i1++){
for (uint32_t i2 = (int32_t)0; i2 < s2; i2++){
for (uint32_t i3 = (int32_t)0; i3 < s3; i3++){
for (uint32_t i4 = (int32_t)0; i4 < s4; i4++){
if ((axis == (int32_t)0)) {
if ((i1 < inp1s1)) {
outp[i1][i2][i3][i4] = inp1[i1][i2][i3][i4];
} else {
outp[i1][i2][i3][i4] = inp2[(i1 - inp1s1)][i2][i3][i4];
}
} else {
if ((axis == (int32_t)1)) {
if ((i2 < inp1s2)) {
outp[i1][i2][i3][i4] = inp1[i1][i2][i3][i4];
} else {
outp[i1][i2][i3][i4] = inp2[i1][(i2 - inp1s2)][i3][i4];
}
} else {
if ((axis == (int32_t)2)) {
if ((i3 < inp1s3)) {
outp[i1][i2][i3][i4] = inp1[i1][i2][i3][i4];
} else {
outp[i1][i2][i3][i4] = inp2[i1][i2][(i3 - inp1s3)][i4];
}
} else {
if ((i4 < inp1s4)) {
outp[i1][i2][i3][i4] = inp1[i1][i2][i3][i4];
} else {
outp[i1][i2][i3][i4] = inp2[i1][i2][i3][(i4 - inp1s4)];
}
}
}
}
}
}
}
}
}
void RandomUniform2(int32_t s1, int32_t s2, int64_t dataType, auto& outArr){
for (uint32_t i1 = (int32_t)0; i1 < s1; i1++){
for (uint32_t i2 = (int32_t)0; i2 < s2; i2++){
outArr[i1][i2] = (int64_t)100;
}
}
}
void Conv2DReshapeFilter(int32_t FH, int32_t FW, int32_t CI, int32_t CO, auto& inputArr, auto& outputArr){
for (uint32_t co = (int32_t)0; co < CO; co++){
for (uint32_t fh = (int32_t)0; fh < FH; fh++){
for (uint32_t fw = (int32_t)0; fw < FW; fw++){
for (uint32_t ci = (int32_t)0; ci < CI; ci++){
int32_t linIdx = ((((fh * FW) * CI) + (fw * CI)) + ci);
outputArr[co][linIdx] = inputArr[fh][fw][ci][co];
}
}
}
}
}
void Conv2DReshapeMatMulOP(int32_t N, int32_t finalH, int32_t finalW, int32_t CO, auto& inputArr, auto& outputArr){
for (uint32_t co = (int32_t)0; co < CO; co++){
for (uint32_t n = (int32_t)0; n < N; n++){
for (uint32_t h = (int32_t)0; h < finalH; h++){
for (uint32_t w = (int32_t)0; w < finalW; w++){
outputArr[n][h][w][co] = inputArr[co][((((n * finalH) * finalW) + (h * finalW)) + w)];
}
}
}
}
}
void Conv2DReshapeInput(int32_t N, int32_t H, int32_t W, int32_t CI, int32_t FH, int32_t FW, int32_t zPadHLeft, int32_t zPadHRight, int32_t zPadWLeft, int32_t zPadWRight, int32_t strideH, int32_t strideW, int32_t RRows, int32_t RCols, auto& inputArr, auto& outputArr){
int32_t linIdxFilterMult = (int32_t)0;
for (uint32_t n = (int32_t)0; n < N; n++){
int32_t leftTopCornerH = ( (int32_t)0 - zPadHLeft);
int32_t extremeRightBottomCornerH = ((H - (int32_t)1) + zPadHRight);
while ((((leftTopCornerH + FH) - (int32_t)1) <= extremeRightBottomCornerH)) {
int32_t leftTopCornerW = ( (int32_t)0 - zPadWLeft);
int32_t extremeRightBottomCornerW = ((W - (int32_t)1) + zPadWRight);
while ((((leftTopCornerW + FW) - (int32_t)1) <= extremeRightBottomCornerW)) {
for (uint32_t fh = (int32_t)0; fh < FH; fh++){
for (uint32_t fw = (int32_t)0; fw < FW; fw++){
int32_t curPosH = (leftTopCornerH + fh);
int32_t curPosW = (leftTopCornerW + fw);
int64_t val = (int64_t)0;
for (uint32_t ci = (int32_t)0; ci < CI; ci++){
if ((((curPosH < (int32_t)0) || (curPosH >= H)) || ((curPosW < (int32_t)0) || (curPosW >= W)))) {
val = (int64_t)0;
} else {
val = inputArr[n][curPosH][curPosW][ci];
}
outputArr[((((fh * FW) * CI) + (fw * CI)) + ci)][linIdxFilterMult] = val;
}
}
}
linIdxFilterMult = (linIdxFilterMult + (int32_t)1);
leftTopCornerW = (leftTopCornerW + strideW);
}
leftTopCornerH = (leftTopCornerH + strideH);
}
}
}
void Conv2DCSF(int32_t N, int32_t H, int32_t W, int32_t CI, int32_t FH, int32_t FW, int32_t CO, int32_t zPadHLeft, int32_t zPadHRight, int32_t zPadWLeft, int32_t zPadWRight, int32_t strideH, int32_t strideW, auto& inputArr, auto& filterArr, auto& outArr, int64_t consSF){
int32_t reshapedFilterRows = CO;
int32_t reshapedFilterCols = ((FH * FW) * CI);
int32_t reshapedIPRows = ((FH * FW) * CI);
int32_t newH = ((((H + (zPadHLeft + zPadHRight)) - FH) / strideH) + (int32_t)1);
int32_t newW = ((((W + (zPadWLeft + zPadWRight)) - FW) / strideW) + (int32_t)1);
int32_t reshapedIPCols = ((N * newH) * newW);
auto filterReshaped = make_vector<int64_t>(reshapedFilterRows, reshapedFilterCols);
auto inputReshaped = make_vector<int64_t>(reshapedIPRows, reshapedIPCols);
auto matmulOP = make_vector<int64_t>(reshapedFilterRows, reshapedIPCols);
Conv2DReshapeFilter(FH, FW, CI, CO, filterArr, filterReshaped);
Conv2DReshapeInput(N, H, W, CI, FH, FW, zPadHLeft, zPadHRight, zPadWLeft, zPadWRight, strideH, strideW, reshapedIPRows, reshapedIPCols, inputArr, inputReshaped);
MatMulCSF2D(reshapedFilterRows, reshapedFilterCols, reshapedIPCols, filterReshaped, inputReshaped, matmulOP, consSF);
Conv2DReshapeMatMulOP(N, newH, newW, CO, matmulOP, outArr);
}
void Transpose2(int32_t s1, int32_t s2, auto& inArr, auto& outArr){
for (uint32_t i = (int32_t)0; i < s1; i++){
for (uint32_t j = (int32_t)0; j < s2; j++){
outArr[i][j] = inArr[j][i];
}
}
}
void Pad442(int32_t s1, int32_t s2, int32_t s3, int32_t s4, int32_t inps1, int32_t inps2, int32_t inps3, int32_t inps4, auto& inpArr, int32_t pads1, int32_t pads2, auto& paddings, auto& outArr){
int32_t lbounds1 = paddings[ (int32_t)0][ (int32_t)0];
int32_t rbounds1excl = (s1 - paddings[ (int32_t)0][ (int32_t)1]);
int32_t lbounds2 = paddings[ (int32_t)1][ (int32_t)0];
int32_t rbounds2excl = (s2 - paddings[ (int32_t)1][ (int32_t)1]);
int32_t lbounds3 = paddings[ (int32_t)2][ (int32_t)0];
int32_t rbounds3excl = (s3 - paddings[ (int32_t)2][ (int32_t)1]);
int32_t lbounds4 = paddings[ (int32_t)3][ (int32_t)0];
int32_t rbounds4excl = (s4 - paddings[ (int32_t)3][ (int32_t)1]);
for (uint32_t i = (int32_t)0; i < s1; i++){
for (uint32_t j = (int32_t)0; j < s2; j++){
for (uint32_t k = (int32_t)0; k < s3; k++){
for (uint32_t l = (int32_t)0; l < s4; l++){
if (((((((((i >= lbounds1) && (i < rbounds1excl)) && (j >= lbounds2)) && (j < rbounds2excl)) && (k >= lbounds3)) && (k < rbounds3excl)) && (l >= lbounds4)) && (l < rbounds4excl))) {
outArr[i][j][k][l] = inpArr[(i - paddings[ (int32_t)0][ (int32_t)0])][(j - paddings[ (int32_t)1][ (int32_t)0])][(k - paddings[ (int32_t)2][ (int32_t)0])][(l - paddings[ (int32_t)3][ (int32_t)0])];
} else {
outArr[i][j][k][l] = (int64_t)0;
}
}
}
}
}
}
void Squeeze24(int32_t s1, int32_t s2, int32_t dim1, int32_t dim2, int32_t ins1, int32_t ins2, int32_t ins3, int32_t ins4, auto& inArr, auto& outArr){
for (uint32_t i = (int32_t)0; i < ins1; i++){
for (uint32_t j = (int32_t)0; j < ins2; j++){
for (uint32_t k = (int32_t)0; k < ins3; k++){
for (uint32_t l = (int32_t)0; l < ins4; l++){
int32_t linIdx = ((((((i * ins2) * ins3) * ins4) + ((j * ins3) * ins4)) + (k * ins4)) + l);
int32_t outIdx1 = (linIdx / s2);
int32_t outIdx2 = (linIdx % s2);
outArr[outIdx1][outIdx2] = inArr[i][j][k][l];
}
}
}
}
}
void readIdxFromRandomSubsetFile(string idxFile, int M, int acutalImgIdx[]){
ifstream filep(idxFile);
string str;
int ct = 0;
while(getline(filep,str)){
acutalImgIdx[ct++] = atoi(str.c_str());
if (ct >= M){
break;
}
}
if (ct!=M){
assert(false);
}
}
int main (int argc, char** argv) {
ios_base::sync_with_stdio(false);
if ((argc != 5) && (argc != 7)){
cerr<<"Incorrect args provided."<<endl;
exit(1);
}
int consSF = atoi(argv[1]);
int startImgNum = atoi(argv[2]);
int endImgNum = atoi(argv[3]);
string preProcessedImgDir = string(argv[4]);
int randomSubsetNumImages = 1;
string randomSubsetIdxTestFileName = "";
if (argc == 7){
randomSubsetNumImages = atoi(argv[5]);
randomSubsetIdxTestFileName = string(argv[6]);
}
if ((preProcessedImgDir[preProcessedImgDir.length()-1] == '/')
|| (randomSubsetIdxTestFileName[randomSubsetIdxTestFileName.length()-1] == '/')){
cerr<<"Paths provided shouldn't have / at their end."<<endl;
exit(1);
}
if (startImgNum==0){
cerr<<"Start img number should be 1-indexed."<<endl;
exit(1);
}
auto tmp53 = make_vector<int64_t>( (int32_t)1, (int32_t)113, (int32_t)113, (int32_t)64);
auto tmp54 = make_vector<int64_t>( (int32_t)1, (int32_t)113, (int32_t)113, (int32_t)64);
auto tmp55 = make_vector<int64_t>( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)64);
auto tmp56 = make_vector<int64_t>( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)64);
auto tmp57 = make_vector<int64_t>( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)16);
auto tmp58 = make_vector<int64_t>( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)16);
auto tmp59 = make_vector<int64_t>( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)16);
auto tmp60 = make_vector<int64_t>( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)64);
auto tmp61 = make_vector<int64_t>( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)64);
auto tmp62 = make_vector<int64_t>( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)64);
auto tmp63 = make_vector<int64_t>( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)64);
auto tmp64 = make_vector<int64_t>( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)64);
auto tmp65 = make_vector<int64_t>( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)64);
auto tmp66 = make_vector<int64_t>( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)128);
auto tmp67 = make_vector<int64_t>( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)16);
auto tmp68 = make_vector<int64_t>( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)16);
auto tmp69 = make_vector<int64_t>( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)16);
auto tmp70 = make_vector<int64_t>( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)64);
auto tmp71 = make_vector<int64_t>( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)64);
auto tmp72 = make_vector<int64_t>( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)64);
auto tmp73 = make_vector<int64_t>( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)64);
auto tmp74 = make_vector<int64_t>( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)64);
auto tmp75 = make_vector<int64_t>( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)64);
auto tmp76 = make_vector<int64_t>( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)128);
auto tmp77 = make_vector<int64_t>( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)128);
auto tmp78 = make_vector<int64_t>( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)32);
auto tmp79 = make_vector<int64_t>( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)32);
auto tmp80 = make_vector<int64_t>( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)32);
auto tmp81 = make_vector<int64_t>( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)128);
auto tmp82 = make_vector<int64_t>( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)128);
auto tmp83 = make_vector<int64_t>( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)128);
auto tmp84 = make_vector<int64_t>( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)128);
auto tmp85 = make_vector<int64_t>( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)128);
auto tmp86 = make_vector<int64_t>( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)128);
auto tmp87 = make_vector<int64_t>( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)256);
auto tmp88 = make_vector<int64_t>( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)32);
auto tmp89 = make_vector<int64_t>( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)32);
auto tmp90 = make_vector<int64_t>( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)32);
auto tmp91 = make_vector<int64_t>( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)128);
auto tmp92 = make_vector<int64_t>( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)128);
auto tmp93 = make_vector<int64_t>( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)128);
auto tmp94 = make_vector<int64_t>( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)128);
auto tmp95 = make_vector<int64_t>( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)128);
auto tmp96 = make_vector<int64_t>( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)128);
auto tmp97 = make_vector<int64_t>( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)256);
auto tmp98 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)256);
auto tmp99 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)48);
auto tmp100 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)48);
auto tmp101 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)48);
auto tmp102 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)192);
auto tmp103 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)192);
auto tmp104 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)192);
auto tmp105 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)192);
auto tmp106 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)192);
auto tmp107 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)192);
auto tmp108 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)384);
auto tmp109 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)48);
auto tmp110 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)48);
auto tmp111 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)48);
auto tmp112 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)192);
auto tmp113 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)192);
auto tmp114 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)192);
auto tmp115 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)192);
auto tmp116 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)192);
auto tmp117 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)192);
auto tmp118 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)384);
auto tmp119 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)64);
auto tmp120 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)64);
auto tmp121 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)64);
auto tmp122 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)256);
auto tmp123 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)256);
auto tmp124 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)256);
auto tmp125 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)256);
auto tmp126 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)256);
auto tmp127 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)256);
auto tmp128 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)512);
auto tmp129 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)64);
auto tmp130 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)64);
auto tmp131 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)64);
auto tmp132 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)256);
auto tmp133 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)256);
auto tmp134 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)256);
auto tmp135 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)256);
auto tmp136 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)256);
auto tmp137 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)256);
auto tmp138 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)512);
auto tmp139 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)1000);
auto tmp140 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)1000);
auto tmp141 = make_vector<int64_t>( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)1000);
auto tmp142 = make_vector<int64_t>( (int32_t)1, (int32_t)1, (int32_t)1, (int32_t)1000);
auto tmp1 = make_vector<int64_t>( (int32_t)3, (int32_t)3, (int32_t)3, (int32_t)64);
/* Variable to read the clear value corresponding to the input variable tmp1 at (768,1-768,44) */
long double __tmp_in_tmp1;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)3; i0++){
for (uint32_t i1 = (uint32_t)0; i1 < (int32_t)3; i1++){
for (uint32_t i2 = (uint32_t)0; i2 < (int32_t)3; i2++){
for (uint32_t i3 = (uint32_t)0; i3 < (int32_t)64; i3++){
cin >> __tmp_in_tmp1;
tmp1[i0][i1][i2][i3] = ldexp(__tmp_in_tmp1, consSF);
}
}
}
}
auto tmp2 = make_vector<int64_t>( (int32_t)64);
/* Variable to read the clear value corresponding to the input variable tmp2 at (770,1-770,35) */
long double __tmp_in_tmp2;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)64; i0++){
cin >> __tmp_in_tmp2;
tmp2[i0] = ldexp(__tmp_in_tmp2, consSF);
}
auto tmp3 = make_vector<int64_t>( (int32_t)1, (int32_t)1, (int32_t)64, (int32_t)16);
/* Variable to read the clear value corresponding to the input variable tmp3 at (772,1-772,45) */
long double __tmp_in_tmp3;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)1; i0++){
for (uint32_t i1 = (uint32_t)0; i1 < (int32_t)1; i1++){
for (uint32_t i2 = (uint32_t)0; i2 < (int32_t)64; i2++){
for (uint32_t i3 = (uint32_t)0; i3 < (int32_t)16; i3++){
cin >> __tmp_in_tmp3;
tmp3[i0][i1][i2][i3] = ldexp(__tmp_in_tmp3, consSF);
}
}
}
}
auto tmp4 = make_vector<int64_t>( (int32_t)16);
/* Variable to read the clear value corresponding to the input variable tmp4 at (774,1-774,35) */
long double __tmp_in_tmp4;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)16; i0++){
cin >> __tmp_in_tmp4;
tmp4[i0] = ldexp(__tmp_in_tmp4, consSF);
}
auto tmp5 = make_vector<int64_t>( (int32_t)1, (int32_t)1, (int32_t)16, (int32_t)64);
/* Variable to read the clear value corresponding to the input variable tmp5 at (776,1-776,45) */
long double __tmp_in_tmp5;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)1; i0++){
for (uint32_t i1 = (uint32_t)0; i1 < (int32_t)1; i1++){
for (uint32_t i2 = (uint32_t)0; i2 < (int32_t)16; i2++){
for (uint32_t i3 = (uint32_t)0; i3 < (int32_t)64; i3++){
cin >> __tmp_in_tmp5;
tmp5[i0][i1][i2][i3] = ldexp(__tmp_in_tmp5, consSF);
}
}
}
}
auto tmp6 = make_vector<int64_t>( (int32_t)64);
/* Variable to read the clear value corresponding to the input variable tmp6 at (778,1-778,35) */
long double __tmp_in_tmp6;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)64; i0++){
cin >> __tmp_in_tmp6;
tmp6[i0] = ldexp(__tmp_in_tmp6, consSF);
}
auto tmp7 = make_vector<int64_t>( (int32_t)3, (int32_t)3, (int32_t)16, (int32_t)64);
/* Variable to read the clear value corresponding to the input variable tmp7 at (780,1-780,45) */
long double __tmp_in_tmp7;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)3; i0++){
for (uint32_t i1 = (uint32_t)0; i1 < (int32_t)3; i1++){
for (uint32_t i2 = (uint32_t)0; i2 < (int32_t)16; i2++){
for (uint32_t i3 = (uint32_t)0; i3 < (int32_t)64; i3++){
cin >> __tmp_in_tmp7;
tmp7[i0][i1][i2][i3] = ldexp(__tmp_in_tmp7, consSF);
}
}
}
}
auto tmp8 = make_vector<int64_t>( (int32_t)64);
/* Variable to read the clear value corresponding to the input variable tmp8 at (782,1-782,35) */
long double __tmp_in_tmp8;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)64; i0++){
cin >> __tmp_in_tmp8;
tmp8[i0] = ldexp(__tmp_in_tmp8, consSF);
}
auto tmp9 = make_vector<int64_t>( (int32_t)1, (int32_t)1, (int32_t)128, (int32_t)16);
/* Variable to read the clear value corresponding to the input variable tmp9 at (784,1-784,46) */
long double __tmp_in_tmp9;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)1; i0++){
for (uint32_t i1 = (uint32_t)0; i1 < (int32_t)1; i1++){
for (uint32_t i2 = (uint32_t)0; i2 < (int32_t)128; i2++){
for (uint32_t i3 = (uint32_t)0; i3 < (int32_t)16; i3++){
cin >> __tmp_in_tmp9;
tmp9[i0][i1][i2][i3] = ldexp(__tmp_in_tmp9, consSF);
}
}
}
}
auto tmp10 = make_vector<int64_t>( (int32_t)16);
/* Variable to read the clear value corresponding to the input variable tmp10 at (786,1-786,36) */
long double __tmp_in_tmp10;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)16; i0++){
cin >> __tmp_in_tmp10;
tmp10[i0] = ldexp(__tmp_in_tmp10, consSF);
}
auto tmp11 = make_vector<int64_t>( (int32_t)1, (int32_t)1, (int32_t)16, (int32_t)64);
/* Variable to read the clear value corresponding to the input variable tmp11 at (788,1-788,46) */
long double __tmp_in_tmp11;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)1; i0++){
for (uint32_t i1 = (uint32_t)0; i1 < (int32_t)1; i1++){
for (uint32_t i2 = (uint32_t)0; i2 < (int32_t)16; i2++){
for (uint32_t i3 = (uint32_t)0; i3 < (int32_t)64; i3++){
cin >> __tmp_in_tmp11;
tmp11[i0][i1][i2][i3] = ldexp(__tmp_in_tmp11, consSF);
}
}
}
}
auto tmp12 = make_vector<int64_t>( (int32_t)64);
/* Variable to read the clear value corresponding to the input variable tmp12 at (790,1-790,36) */
long double __tmp_in_tmp12;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)64; i0++){
cin >> __tmp_in_tmp12;
tmp12[i0] = ldexp(__tmp_in_tmp12, consSF);
}
auto tmp13 = make_vector<int64_t>( (int32_t)3, (int32_t)3, (int32_t)16, (int32_t)64);
/* Variable to read the clear value corresponding to the input variable tmp13 at (792,1-792,46) */
long double __tmp_in_tmp13;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)3; i0++){
for (uint32_t i1 = (uint32_t)0; i1 < (int32_t)3; i1++){
for (uint32_t i2 = (uint32_t)0; i2 < (int32_t)16; i2++){
for (uint32_t i3 = (uint32_t)0; i3 < (int32_t)64; i3++){
cin >> __tmp_in_tmp13;
tmp13[i0][i1][i2][i3] = ldexp(__tmp_in_tmp13, consSF);
}
}
}
}
auto tmp14 = make_vector<int64_t>( (int32_t)64);
/* Variable to read the clear value corresponding to the input variable tmp14 at (794,1-794,36) */
long double __tmp_in_tmp14;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)64; i0++){
cin >> __tmp_in_tmp14;
tmp14[i0] = ldexp(__tmp_in_tmp14, consSF);
}
auto tmp15 = make_vector<int64_t>( (int32_t)1, (int32_t)1, (int32_t)128, (int32_t)32);
/* Variable to read the clear value corresponding to the input variable tmp15 at (796,1-796,47) */
long double __tmp_in_tmp15;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)1; i0++){
for (uint32_t i1 = (uint32_t)0; i1 < (int32_t)1; i1++){
for (uint32_t i2 = (uint32_t)0; i2 < (int32_t)128; i2++){
for (uint32_t i3 = (uint32_t)0; i3 < (int32_t)32; i3++){
cin >> __tmp_in_tmp15;
tmp15[i0][i1][i2][i3] = ldexp(__tmp_in_tmp15, consSF);
}
}
}
}
auto tmp16 = make_vector<int64_t>( (int32_t)32);
/* Variable to read the clear value corresponding to the input variable tmp16 at (798,1-798,36) */
long double __tmp_in_tmp16;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)32; i0++){
cin >> __tmp_in_tmp16;
tmp16[i0] = ldexp(__tmp_in_tmp16, consSF);
}
auto tmp17 = make_vector<int64_t>( (int32_t)1, (int32_t)1, (int32_t)32, (int32_t)128);
/* Variable to read the clear value corresponding to the input variable tmp17 at (800,1-800,47) */
long double __tmp_in_tmp17;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)1; i0++){
for (uint32_t i1 = (uint32_t)0; i1 < (int32_t)1; i1++){
for (uint32_t i2 = (uint32_t)0; i2 < (int32_t)32; i2++){
for (uint32_t i3 = (uint32_t)0; i3 < (int32_t)128; i3++){
cin >> __tmp_in_tmp17;
tmp17[i0][i1][i2][i3] = ldexp(__tmp_in_tmp17, consSF);
}
}
}
}
auto tmp18 = make_vector<int64_t>( (int32_t)128);
/* Variable to read the clear value corresponding to the input variable tmp18 at (802,1-802,37) */
long double __tmp_in_tmp18;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)128; i0++){
cin >> __tmp_in_tmp18;
tmp18[i0] = ldexp(__tmp_in_tmp18, consSF);
}
auto tmp19 = make_vector<int64_t>( (int32_t)3, (int32_t)3, (int32_t)32, (int32_t)128);
/* Variable to read the clear value corresponding to the input variable tmp19 at (804,1-804,47) */
long double __tmp_in_tmp19;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)3; i0++){
for (uint32_t i1 = (uint32_t)0; i1 < (int32_t)3; i1++){
for (uint32_t i2 = (uint32_t)0; i2 < (int32_t)32; i2++){
for (uint32_t i3 = (uint32_t)0; i3 < (int32_t)128; i3++){
cin >> __tmp_in_tmp19;
tmp19[i0][i1][i2][i3] = ldexp(__tmp_in_tmp19, consSF);
}
}
}
}
auto tmp20 = make_vector<int64_t>( (int32_t)128);
/* Variable to read the clear value corresponding to the input variable tmp20 at (806,1-806,37) */
long double __tmp_in_tmp20;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)128; i0++){
cin >> __tmp_in_tmp20;
tmp20[i0] = ldexp(__tmp_in_tmp20, consSF);
}
auto tmp21 = make_vector<int64_t>( (int32_t)1, (int32_t)1, (int32_t)256, (int32_t)32);
/* Variable to read the clear value corresponding to the input variable tmp21 at (808,1-808,47) */
long double __tmp_in_tmp21;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)1; i0++){
for (uint32_t i1 = (uint32_t)0; i1 < (int32_t)1; i1++){
for (uint32_t i2 = (uint32_t)0; i2 < (int32_t)256; i2++){
for (uint32_t i3 = (uint32_t)0; i3 < (int32_t)32; i3++){
cin >> __tmp_in_tmp21;
tmp21[i0][i1][i2][i3] = ldexp(__tmp_in_tmp21, consSF);
}
}
}
}
auto tmp22 = make_vector<int64_t>( (int32_t)32);
/* Variable to read the clear value corresponding to the input variable tmp22 at (810,1-810,36) */
long double __tmp_in_tmp22;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)32; i0++){
cin >> __tmp_in_tmp22;
tmp22[i0] = ldexp(__tmp_in_tmp22, consSF);
}
auto tmp23 = make_vector<int64_t>( (int32_t)1, (int32_t)1, (int32_t)32, (int32_t)128);
/* Variable to read the clear value corresponding to the input variable tmp23 at (812,1-812,47) */
long double __tmp_in_tmp23;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)1; i0++){
for (uint32_t i1 = (uint32_t)0; i1 < (int32_t)1; i1++){
for (uint32_t i2 = (uint32_t)0; i2 < (int32_t)32; i2++){
for (uint32_t i3 = (uint32_t)0; i3 < (int32_t)128; i3++){
cin >> __tmp_in_tmp23;
tmp23[i0][i1][i2][i3] = ldexp(__tmp_in_tmp23, consSF);
}
}
}
}
auto tmp24 = make_vector<int64_t>( (int32_t)128);
/* Variable to read the clear value corresponding to the input variable tmp24 at (814,1-814,37) */
long double __tmp_in_tmp24;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)128; i0++){
cin >> __tmp_in_tmp24;
tmp24[i0] = ldexp(__tmp_in_tmp24, consSF);
}
auto tmp25 = make_vector<int64_t>( (int32_t)3, (int32_t)3, (int32_t)32, (int32_t)128);
/* Variable to read the clear value corresponding to the input variable tmp25 at (816,1-816,47) */
long double __tmp_in_tmp25;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)3; i0++){
for (uint32_t i1 = (uint32_t)0; i1 < (int32_t)3; i1++){
for (uint32_t i2 = (uint32_t)0; i2 < (int32_t)32; i2++){
for (uint32_t i3 = (uint32_t)0; i3 < (int32_t)128; i3++){
cin >> __tmp_in_tmp25;
tmp25[i0][i1][i2][i3] = ldexp(__tmp_in_tmp25, consSF);
}
}
}
}
auto tmp26 = make_vector<int64_t>( (int32_t)128);
/* Variable to read the clear value corresponding to the input variable tmp26 at (818,1-818,37) */
long double __tmp_in_tmp26;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)128; i0++){
cin >> __tmp_in_tmp26;
tmp26[i0] = ldexp(__tmp_in_tmp26, consSF);
}
auto tmp27 = make_vector<int64_t>( (int32_t)1, (int32_t)1, (int32_t)256, (int32_t)48);
/* Variable to read the clear value corresponding to the input variable tmp27 at (820,1-820,47) */
long double __tmp_in_tmp27;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)1; i0++){
for (uint32_t i1 = (uint32_t)0; i1 < (int32_t)1; i1++){
for (uint32_t i2 = (uint32_t)0; i2 < (int32_t)256; i2++){
for (uint32_t i3 = (uint32_t)0; i3 < (int32_t)48; i3++){
cin >> __tmp_in_tmp27;
tmp27[i0][i1][i2][i3] = ldexp(__tmp_in_tmp27, consSF);
}
}
}
}
auto tmp28 = make_vector<int64_t>( (int32_t)48);
/* Variable to read the clear value corresponding to the input variable tmp28 at (822,1-822,36) */
long double __tmp_in_tmp28;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)48; i0++){
cin >> __tmp_in_tmp28;
tmp28[i0] = ldexp(__tmp_in_tmp28, consSF);
}
auto tmp29 = make_vector<int64_t>( (int32_t)1, (int32_t)1, (int32_t)48, (int32_t)192);
/* Variable to read the clear value corresponding to the input variable tmp29 at (824,1-824,47) */
long double __tmp_in_tmp29;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)1; i0++){
for (uint32_t i1 = (uint32_t)0; i1 < (int32_t)1; i1++){
for (uint32_t i2 = (uint32_t)0; i2 < (int32_t)48; i2++){
for (uint32_t i3 = (uint32_t)0; i3 < (int32_t)192; i3++){
cin >> __tmp_in_tmp29;
tmp29[i0][i1][i2][i3] = ldexp(__tmp_in_tmp29, consSF);
}
}
}
}
auto tmp30 = make_vector<int64_t>( (int32_t)192);
/* Variable to read the clear value corresponding to the input variable tmp30 at (826,1-826,37) */
long double __tmp_in_tmp30;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)192; i0++){
cin >> __tmp_in_tmp30;
tmp30[i0] = ldexp(__tmp_in_tmp30, consSF);
}
auto tmp31 = make_vector<int64_t>( (int32_t)3, (int32_t)3, (int32_t)48, (int32_t)192);
/* Variable to read the clear value corresponding to the input variable tmp31 at (828,1-828,47) */
long double __tmp_in_tmp31;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)3; i0++){
for (uint32_t i1 = (uint32_t)0; i1 < (int32_t)3; i1++){
for (uint32_t i2 = (uint32_t)0; i2 < (int32_t)48; i2++){
for (uint32_t i3 = (uint32_t)0; i3 < (int32_t)192; i3++){
cin >> __tmp_in_tmp31;
tmp31[i0][i1][i2][i3] = ldexp(__tmp_in_tmp31, consSF);
}
}
}
}
auto tmp32 = make_vector<int64_t>( (int32_t)192);
/* Variable to read the clear value corresponding to the input variable tmp32 at (830,1-830,37) */
long double __tmp_in_tmp32;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)192; i0++){
cin >> __tmp_in_tmp32;
tmp32[i0] = ldexp(__tmp_in_tmp32, consSF);
}
auto tmp33 = make_vector<int64_t>( (int32_t)1, (int32_t)1, (int32_t)384, (int32_t)48);
/* Variable to read the clear value corresponding to the input variable tmp33 at (832,1-832,47) */
long double __tmp_in_tmp33;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)1; i0++){
for (uint32_t i1 = (uint32_t)0; i1 < (int32_t)1; i1++){
for (uint32_t i2 = (uint32_t)0; i2 < (int32_t)384; i2++){
for (uint32_t i3 = (uint32_t)0; i3 < (int32_t)48; i3++){
cin >> __tmp_in_tmp33;
tmp33[i0][i1][i2][i3] = ldexp(__tmp_in_tmp33, consSF);
}
}
}
}
auto tmp34 = make_vector<int64_t>( (int32_t)48);
/* Variable to read the clear value corresponding to the input variable tmp34 at (834,1-834,36) */
long double __tmp_in_tmp34;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)48; i0++){
cin >> __tmp_in_tmp34;
tmp34[i0] = ldexp(__tmp_in_tmp34, consSF);
}
auto tmp35 = make_vector<int64_t>( (int32_t)1, (int32_t)1, (int32_t)48, (int32_t)192);
/* Variable to read the clear value corresponding to the input variable tmp35 at (836,1-836,47) */
long double __tmp_in_tmp35;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)1; i0++){
for (uint32_t i1 = (uint32_t)0; i1 < (int32_t)1; i1++){
for (uint32_t i2 = (uint32_t)0; i2 < (int32_t)48; i2++){
for (uint32_t i3 = (uint32_t)0; i3 < (int32_t)192; i3++){
cin >> __tmp_in_tmp35;
tmp35[i0][i1][i2][i3] = ldexp(__tmp_in_tmp35, consSF);
}
}
}
}
auto tmp36 = make_vector<int64_t>( (int32_t)192);
/* Variable to read the clear value corresponding to the input variable tmp36 at (838,1-838,37) */
long double __tmp_in_tmp36;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)192; i0++){
cin >> __tmp_in_tmp36;
tmp36[i0] = ldexp(__tmp_in_tmp36, consSF);
}
auto tmp37 = make_vector<int64_t>( (int32_t)3, (int32_t)3, (int32_t)48, (int32_t)192);
/* Variable to read the clear value corresponding to the input variable tmp37 at (840,1-840,47) */
long double __tmp_in_tmp37;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)3; i0++){
for (uint32_t i1 = (uint32_t)0; i1 < (int32_t)3; i1++){
for (uint32_t i2 = (uint32_t)0; i2 < (int32_t)48; i2++){
for (uint32_t i3 = (uint32_t)0; i3 < (int32_t)192; i3++){
cin >> __tmp_in_tmp37;
tmp37[i0][i1][i2][i3] = ldexp(__tmp_in_tmp37, consSF);
}
}
}
}
auto tmp38 = make_vector<int64_t>( (int32_t)192);
/* Variable to read the clear value corresponding to the input variable tmp38 at (842,1-842,37) */
long double __tmp_in_tmp38;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)192; i0++){
cin >> __tmp_in_tmp38;
tmp38[i0] = ldexp(__tmp_in_tmp38, consSF);
}
auto tmp39 = make_vector<int64_t>( (int32_t)1, (int32_t)1, (int32_t)384, (int32_t)64);
/* Variable to read the clear value corresponding to the input variable tmp39 at (844,1-844,47) */
long double __tmp_in_tmp39;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)1; i0++){
for (uint32_t i1 = (uint32_t)0; i1 < (int32_t)1; i1++){
for (uint32_t i2 = (uint32_t)0; i2 < (int32_t)384; i2++){
for (uint32_t i3 = (uint32_t)0; i3 < (int32_t)64; i3++){
cin >> __tmp_in_tmp39;
tmp39[i0][i1][i2][i3] = ldexp(__tmp_in_tmp39, consSF);
}
}
}
}
auto tmp40 = make_vector<int64_t>( (int32_t)64);
/* Variable to read the clear value corresponding to the input variable tmp40 at (846,1-846,36) */
long double __tmp_in_tmp40;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)64; i0++){
cin >> __tmp_in_tmp40;
tmp40[i0] = ldexp(__tmp_in_tmp40, consSF);
}
auto tmp41 = make_vector<int64_t>( (int32_t)1, (int32_t)1, (int32_t)64, (int32_t)256);
/* Variable to read the clear value corresponding to the input variable tmp41 at (848,1-848,47) */
long double __tmp_in_tmp41;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)1; i0++){
for (uint32_t i1 = (uint32_t)0; i1 < (int32_t)1; i1++){
for (uint32_t i2 = (uint32_t)0; i2 < (int32_t)64; i2++){
for (uint32_t i3 = (uint32_t)0; i3 < (int32_t)256; i3++){
cin >> __tmp_in_tmp41;
tmp41[i0][i1][i2][i3] = ldexp(__tmp_in_tmp41, consSF);
}
}
}
}
auto tmp42 = make_vector<int64_t>( (int32_t)256);
/* Variable to read the clear value corresponding to the input variable tmp42 at (850,1-850,37) */
long double __tmp_in_tmp42;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)256; i0++){
cin >> __tmp_in_tmp42;
tmp42[i0] = ldexp(__tmp_in_tmp42, consSF);
}
auto tmp43 = make_vector<int64_t>( (int32_t)3, (int32_t)3, (int32_t)64, (int32_t)256);
/* Variable to read the clear value corresponding to the input variable tmp43 at (852,1-852,47) */
long double __tmp_in_tmp43;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)3; i0++){
for (uint32_t i1 = (uint32_t)0; i1 < (int32_t)3; i1++){
for (uint32_t i2 = (uint32_t)0; i2 < (int32_t)64; i2++){
for (uint32_t i3 = (uint32_t)0; i3 < (int32_t)256; i3++){
cin >> __tmp_in_tmp43;
tmp43[i0][i1][i2][i3] = ldexp(__tmp_in_tmp43, consSF);
}
}
}
}
auto tmp44 = make_vector<int64_t>( (int32_t)256);
/* Variable to read the clear value corresponding to the input variable tmp44 at (854,1-854,37) */
long double __tmp_in_tmp44;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)256; i0++){
cin >> __tmp_in_tmp44;
tmp44[i0] = ldexp(__tmp_in_tmp44, consSF);
}
auto tmp45 = make_vector<int64_t>( (int32_t)1, (int32_t)1, (int32_t)512, (int32_t)64);
/* Variable to read the clear value corresponding to the input variable tmp45 at (856,1-856,47) */
long double __tmp_in_tmp45;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)1; i0++){
for (uint32_t i1 = (uint32_t)0; i1 < (int32_t)1; i1++){
for (uint32_t i2 = (uint32_t)0; i2 < (int32_t)512; i2++){
for (uint32_t i3 = (uint32_t)0; i3 < (int32_t)64; i3++){
cin >> __tmp_in_tmp45;
tmp45[i0][i1][i2][i3] = ldexp(__tmp_in_tmp45, consSF);
}
}
}
}
auto tmp46 = make_vector<int64_t>( (int32_t)64);
/* Variable to read the clear value corresponding to the input variable tmp46 at (858,1-858,36) */
long double __tmp_in_tmp46;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)64; i0++){
cin >> __tmp_in_tmp46;
tmp46[i0] = ldexp(__tmp_in_tmp46, consSF);
}
auto tmp47 = make_vector<int64_t>( (int32_t)1, (int32_t)1, (int32_t)64, (int32_t)256);
/* Variable to read the clear value corresponding to the input variable tmp47 at (860,1-860,47) */
long double __tmp_in_tmp47;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)1; i0++){
for (uint32_t i1 = (uint32_t)0; i1 < (int32_t)1; i1++){
for (uint32_t i2 = (uint32_t)0; i2 < (int32_t)64; i2++){
for (uint32_t i3 = (uint32_t)0; i3 < (int32_t)256; i3++){
cin >> __tmp_in_tmp47;
tmp47[i0][i1][i2][i3] = ldexp(__tmp_in_tmp47, consSF);
}
}
}
}
auto tmp48 = make_vector<int64_t>( (int32_t)256);
/* Variable to read the clear value corresponding to the input variable tmp48 at (862,1-862,37) */
long double __tmp_in_tmp48;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)256; i0++){
cin >> __tmp_in_tmp48;
tmp48[i0] = ldexp(__tmp_in_tmp48, consSF);
}
auto tmp49 = make_vector<int64_t>( (int32_t)3, (int32_t)3, (int32_t)64, (int32_t)256);
/* Variable to read the clear value corresponding to the input variable tmp49 at (864,1-864,47) */
long double __tmp_in_tmp49;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)3; i0++){
for (uint32_t i1 = (uint32_t)0; i1 < (int32_t)3; i1++){
for (uint32_t i2 = (uint32_t)0; i2 < (int32_t)64; i2++){
for (uint32_t i3 = (uint32_t)0; i3 < (int32_t)256; i3++){
cin >> __tmp_in_tmp49;
tmp49[i0][i1][i2][i3] = ldexp(__tmp_in_tmp49, consSF);
}
}
}
}
auto tmp50 = make_vector<int64_t>( (int32_t)256);
/* Variable to read the clear value corresponding to the input variable tmp50 at (866,1-866,37) */
long double __tmp_in_tmp50;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)256; i0++){
cin >> __tmp_in_tmp50;
tmp50[i0] = ldexp(__tmp_in_tmp50, consSF);
}
auto tmp51 = make_vector<int64_t>( (int32_t)1, (int32_t)1, (int32_t)512, (int32_t)1000);
/* Variable to read the clear value corresponding to the input variable tmp51 at (868,1-868,49) */
long double __tmp_in_tmp51;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)1; i0++){
for (uint32_t i1 = (uint32_t)0; i1 < (int32_t)1; i1++){
for (uint32_t i2 = (uint32_t)0; i2 < (int32_t)512; i2++){
for (uint32_t i3 = (uint32_t)0; i3 < (int32_t)1000; i3++){
cin >> __tmp_in_tmp51;
tmp51[i0][i1][i2][i3] = ldexp(__tmp_in_tmp51, consSF);
}
}
}
}
auto tmp52 = make_vector<int64_t>( (int32_t)1000);
/* Variable to read the clear value corresponding to the input variable tmp52 at (870,1-870,38) */
long double __tmp_in_tmp52;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)1000; i0++){
cin >> __tmp_in_tmp52;
tmp52[i0] = ldexp(__tmp_in_tmp52, consSF);
}
auto tmp0 = make_vector<int64_t>( (int32_t)1, (int32_t)227, (int32_t)227, (int32_t)3);
int randomSubsetAcutalImgIdxArr[randomSubsetNumImages];
bool choosingImgFromRandomSubset = (randomSubsetIdxTestFileName!="");
if (choosingImgFromRandomSubset){
readIdxFromRandomSubsetFile(randomSubsetIdxTestFileName, randomSubsetNumImages, randomSubsetAcutalImgIdxArr);
}
for(int __imgCounter = startImgNum; __imgCounter < endImgNum; __imgCounter++){
cout<<"Answer for image number = "<<__imgCounter<<":"<<endl;
int actualIdx = __imgCounter;
if (choosingImgFromRandomSubset){
actualIdx = randomSubsetAcutalImgIdxArr[__imgCounter-1];
}
/* Variable to read the clear value corresponding to the input variable tmp0 at (863,1-863,47) */
long double __tmp_in_tmp0;
string line;
string inputImgFileName = preProcessedImgDir + "/ImageNum_" + to_string(actualIdx) + ".inp";
ifstream myfile(inputImgFileName);
getline(myfile, line);
stringstream lineStream(line);
string num;
for (uint32_t i0 = (uint32_t)0; i0 < (int32_t)1; i0++){
for (uint32_t i1 = (uint32_t)0; i1 < (int32_t)227; i1++){
for (uint32_t i2 = (uint32_t)0; i2 < (int32_t)227; i2++){
for (uint32_t i3 = (uint32_t)0; i3 < (int32_t)3; i3++){
lineStream >> num;
__tmp_in_tmp0 = stold(num);
tmp0[i0][i1][i2][i3] = ldexp(__tmp_in_tmp0, consSF);
}
}
}
}
Conv2DCSF( (int32_t)1, (int32_t)227, (int32_t)227, (int32_t)3, (int32_t)3, (int32_t)3, (int32_t)64, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)2, (int32_t)2, tmp0, tmp1, tmp53, consSF);
MatAddBroadCast4( (int32_t)1, (int32_t)113, (int32_t)113, (int32_t)64, tmp53, tmp2, tmp54);
MaxPool( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)64, (int32_t)3, (int32_t)3, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)2, (int32_t)2, (int32_t)1, (int32_t)113, (int32_t)113, (int32_t)64, tmp54, tmp55);
Relu4( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)64, tmp55, tmp56);
Conv2DCSF( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)64, (int32_t)1, (int32_t)1, (int32_t)16, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)1, (int32_t)1, tmp56, tmp3, tmp57, consSF);
MatAddBroadCast4( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)16, tmp57, tmp4, tmp58);
Relu4( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)16, tmp58, tmp59);
Conv2DCSF( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)16, (int32_t)1, (int32_t)1, (int32_t)64, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)1, (int32_t)1, tmp59, tmp5, tmp60, consSF);
MatAddBroadCast4( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)64, tmp60, tmp6, tmp61);
Relu4( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)64, tmp61, tmp62);
Conv2DCSF( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)16, (int32_t)3, (int32_t)3, (int32_t)64, (int32_t)1, (int32_t)1, (int32_t)1, (int32_t)1, (int32_t)1, (int32_t)1, tmp59, tmp7, tmp63, consSF);
MatAddBroadCast4( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)64, tmp63, tmp8, tmp64);
Relu4( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)64, tmp64, tmp65);
Concat2T444( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)128, (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)64, tmp62, (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)64, tmp65, (int32_t)3, tmp66);
Conv2DCSF( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)128, (int32_t)1, (int32_t)1, (int32_t)16, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)1, (int32_t)1, tmp66, tmp9, tmp67, consSF);
MatAddBroadCast4( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)16, tmp67, tmp10, tmp68);
Relu4( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)16, tmp68, tmp69);
Conv2DCSF( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)16, (int32_t)1, (int32_t)1, (int32_t)64, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)1, (int32_t)1, tmp69, tmp11, tmp70, consSF);
MatAddBroadCast4( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)64, tmp70, tmp12, tmp71);
Relu4( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)64, tmp71, tmp72);
Conv2DCSF( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)16, (int32_t)3, (int32_t)3, (int32_t)64, (int32_t)1, (int32_t)1, (int32_t)1, (int32_t)1, (int32_t)1, (int32_t)1, tmp69, tmp13, tmp73, consSF);
MatAddBroadCast4( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)64, tmp73, tmp14, tmp74);
Relu4( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)64, tmp74, tmp75);
Concat2T444( (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)128, (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)64, tmp72, (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)64, tmp75, (int32_t)3, tmp76);
MaxPool( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)128, (int32_t)3, (int32_t)3, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)2, (int32_t)2, (int32_t)1, (int32_t)56, (int32_t)56, (int32_t)128, tmp76, tmp77);
Conv2DCSF( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)128, (int32_t)1, (int32_t)1, (int32_t)32, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)1, (int32_t)1, tmp77, tmp15, tmp78, consSF);
MatAddBroadCast4( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)32, tmp78, tmp16, tmp79);
Relu4( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)32, tmp79, tmp80);
Conv2DCSF( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)32, (int32_t)1, (int32_t)1, (int32_t)128, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)1, (int32_t)1, tmp80, tmp17, tmp81, consSF);
MatAddBroadCast4( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)128, tmp81, tmp18, tmp82);
Relu4( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)128, tmp82, tmp83);
Conv2DCSF( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)32, (int32_t)3, (int32_t)3, (int32_t)128, (int32_t)1, (int32_t)1, (int32_t)1, (int32_t)1, (int32_t)1, (int32_t)1, tmp80, tmp19, tmp84, consSF);
MatAddBroadCast4( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)128, tmp84, tmp20, tmp85);
Relu4( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)128, tmp85, tmp86);
Concat2T444( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)256, (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)128, tmp83, (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)128, tmp86, (int32_t)3, tmp87);
Conv2DCSF( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)256, (int32_t)1, (int32_t)1, (int32_t)32, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)1, (int32_t)1, tmp87, tmp21, tmp88, consSF);
MatAddBroadCast4( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)32, tmp88, tmp22, tmp89);
Relu4( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)32, tmp89, tmp90);
Conv2DCSF( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)32, (int32_t)1, (int32_t)1, (int32_t)128, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)1, (int32_t)1, tmp90, tmp23, tmp91, consSF);
MatAddBroadCast4( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)128, tmp91, tmp24, tmp92);
Relu4( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)128, tmp92, tmp93);
Conv2DCSF( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)32, (int32_t)3, (int32_t)3, (int32_t)128, (int32_t)1, (int32_t)1, (int32_t)1, (int32_t)1, (int32_t)1, (int32_t)1, tmp90, tmp25, tmp94, consSF);
MatAddBroadCast4( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)128, tmp94, tmp26, tmp95);
Relu4( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)128, tmp95, tmp96);
Concat2T444( (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)256, (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)128, tmp93, (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)128, tmp96, (int32_t)3, tmp97);
MaxPool( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)256, (int32_t)3, (int32_t)3, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)2, (int32_t)2, (int32_t)1, (int32_t)27, (int32_t)27, (int32_t)256, tmp97, tmp98);
Conv2DCSF( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)256, (int32_t)1, (int32_t)1, (int32_t)48, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)1, (int32_t)1, tmp98, tmp27, tmp99, consSF);
MatAddBroadCast4( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)48, tmp99, tmp28, tmp100);
Relu4( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)48, tmp100, tmp101);
Conv2DCSF( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)48, (int32_t)1, (int32_t)1, (int32_t)192, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)1, (int32_t)1, tmp101, tmp29, tmp102, consSF);
MatAddBroadCast4( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)192, tmp102, tmp30, tmp103);
Relu4( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)192, tmp103, tmp104);
Conv2DCSF( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)48, (int32_t)3, (int32_t)3, (int32_t)192, (int32_t)1, (int32_t)1, (int32_t)1, (int32_t)1, (int32_t)1, (int32_t)1, tmp101, tmp31, tmp105, consSF);
MatAddBroadCast4( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)192, tmp105, tmp32, tmp106);
Relu4( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)192, tmp106, tmp107);
Concat2T444( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)384, (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)192, tmp104, (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)192, tmp107, (int32_t)3, tmp108);
Conv2DCSF( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)384, (int32_t)1, (int32_t)1, (int32_t)48, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)1, (int32_t)1, tmp108, tmp33, tmp109, consSF);
MatAddBroadCast4( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)48, tmp109, tmp34, tmp110);
Relu4( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)48, tmp110, tmp111);
Conv2DCSF( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)48, (int32_t)1, (int32_t)1, (int32_t)192, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)1, (int32_t)1, tmp111, tmp35, tmp112, consSF);
MatAddBroadCast4( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)192, tmp112, tmp36, tmp113);
Relu4( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)192, tmp113, tmp114);
Conv2DCSF( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)48, (int32_t)3, (int32_t)3, (int32_t)192, (int32_t)1, (int32_t)1, (int32_t)1, (int32_t)1, (int32_t)1, (int32_t)1, tmp111, tmp37, tmp115, consSF);
MatAddBroadCast4( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)192, tmp115, tmp38, tmp116);
Relu4( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)192, tmp116, tmp117);
Concat2T444( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)384, (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)192, tmp114, (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)192, tmp117, (int32_t)3, tmp118);
Conv2DCSF( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)384, (int32_t)1, (int32_t)1, (int32_t)64, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)1, (int32_t)1, tmp118, tmp39, tmp119, consSF);
MatAddBroadCast4( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)64, tmp119, tmp40, tmp120);
Relu4( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)64, tmp120, tmp121);
Conv2DCSF( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)64, (int32_t)1, (int32_t)1, (int32_t)256, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)1, (int32_t)1, tmp121, tmp41, tmp122, consSF);
MatAddBroadCast4( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)256, tmp122, tmp42, tmp123);
Relu4( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)256, tmp123, tmp124);
Conv2DCSF( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)64, (int32_t)3, (int32_t)3, (int32_t)256, (int32_t)1, (int32_t)1, (int32_t)1, (int32_t)1, (int32_t)1, (int32_t)1, tmp121, tmp43, tmp125, consSF);
MatAddBroadCast4( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)256, tmp125, tmp44, tmp126);
Relu4( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)256, tmp126, tmp127);
Concat2T444( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)512, (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)256, tmp124, (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)256, tmp127, (int32_t)3, tmp128);
Conv2DCSF( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)512, (int32_t)1, (int32_t)1, (int32_t)64, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)1, (int32_t)1, tmp128, tmp45, tmp129, consSF);
MatAddBroadCast4( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)64, tmp129, tmp46, tmp130);
Relu4( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)64, tmp130, tmp131);
Conv2DCSF( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)64, (int32_t)1, (int32_t)1, (int32_t)256, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)1, (int32_t)1, tmp131, tmp47, tmp132, consSF);
MatAddBroadCast4( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)256, tmp132, tmp48, tmp133);
Relu4( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)256, tmp133, tmp134);
Conv2DCSF( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)64, (int32_t)3, (int32_t)3, (int32_t)256, (int32_t)1, (int32_t)1, (int32_t)1, (int32_t)1, (int32_t)1, (int32_t)1, tmp131, tmp49, tmp135, consSF);
MatAddBroadCast4( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)256, tmp135, tmp50, tmp136);
Relu4( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)256, tmp136, tmp137);
Concat2T444( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)512, (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)256, tmp134, (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)256, tmp137, (int32_t)3, tmp138);
Conv2DCSF( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)512, (int32_t)1, (int32_t)1, (int32_t)1000, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)1, (int32_t)1, tmp138, tmp51, tmp139, consSF);
MatAddBroadCast4( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)1000, tmp139, tmp52, tmp140);
Relu4( (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)1000, tmp140, tmp141);
AvgPool( (int32_t)1, (int32_t)1, (int32_t)1, (int32_t)1000, (int32_t)13, (int32_t)13, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)0, (int32_t)1, (int32_t)1, (int32_t)1, (int32_t)13, (int32_t)13, (int32_t)1000, tmp141, tmp142);
for(int i=0;i<1000;i++){
cout<<tmp142[0][0][0][i]<<" ";
}
cout<<endl;
}
return 0;
}
| 39.46 | 280 | 0.662877 | [
"vector"
] |
b487f64947ba8b5105cd269b4ffd630b6889a01e | 3,536 | cc | C++ | content/child/test_request_peer.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-05-24T13:52:28.000Z | 2021-05-24T13:53:10.000Z | content/child/test_request_peer.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/child/test_request_peer.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 3 | 2018-03-12T07:58:10.000Z | 2019-08-31T04:53:58.000Z | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/child/test_request_peer.h"
#include "content/child/resource_dispatcher.h"
#include "net/url_request/redirect_info.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace content {
TestRequestPeer::TestRequestPeer(ResourceDispatcher* dispatcher,
Context* context)
: dispatcher_(dispatcher), context_(context) {}
TestRequestPeer::~TestRequestPeer() = default;
void TestRequestPeer::OnUploadProgress(uint64_t position, uint64_t size) {
EXPECT_FALSE(context_->complete);
}
bool TestRequestPeer::OnReceivedRedirect(const net::RedirectInfo& redirect_info,
const ResourceResponseInfo& info) {
EXPECT_FALSE(context_->cancelled);
EXPECT_FALSE(context_->complete);
++context_->seen_redirects;
if (context_->defer_on_redirect)
dispatcher_->SetDefersLoading(context_->request_id, true);
return context_->follow_redirects;
}
void TestRequestPeer::OnReceivedResponse(const ResourceResponseInfo& info) {
EXPECT_FALSE(context_->cancelled);
EXPECT_FALSE(context_->received_response);
EXPECT_FALSE(context_->complete);
context_->received_response = true;
if (context_->cancel_on_receive_response) {
dispatcher_->Cancel(context_->request_id);
context_->cancelled = true;
}
}
void TestRequestPeer::OnDownloadedData(int len, int encoded_data_length) {
EXPECT_TRUE(context_->received_response);
EXPECT_FALSE(context_->cancelled);
EXPECT_FALSE(context_->complete);
context_->total_downloaded_data_length += len;
context_->total_encoded_data_length += encoded_data_length;
}
void TestRequestPeer::OnReceivedData(std::unique_ptr<ReceivedData> data) {
if (context_->cancelled)
return;
EXPECT_TRUE(context_->received_response);
EXPECT_FALSE(context_->complete);
context_->data.append(data->payload(), data->length());
if (context_->cancel_on_receive_data) {
dispatcher_->Cancel(context_->request_id);
context_->cancelled = true;
}
}
void TestRequestPeer::OnTransferSizeUpdated(int transfer_size_diff) {
EXPECT_TRUE(context_->received_response);
EXPECT_FALSE(context_->complete);
if (context_->cancelled)
return;
context_->total_encoded_data_length += transfer_size_diff;
if (context_->defer_on_transfer_size_updated)
dispatcher_->SetDefersLoading(context_->request_id, true);
}
void TestRequestPeer::OnReceivedCachedMetadata(const char* data, int len) {
EXPECT_TRUE(context_->received_response);
EXPECT_FALSE(context_->complete);
if (context_->cancelled)
return;
context_->cached_metadata = std::vector<char>(data, data + len);
}
void TestRequestPeer::OnCompletedRequest(int error_code,
bool was_ignored_by_handler,
bool stale_copy_in_cache,
const base::TimeTicks& completion_time,
int64_t total_transfer_size,
int64_t encoded_body_size,
int64_t decoded_body_size) {
if (context_->cancelled)
return;
EXPECT_TRUE(context_->received_response);
EXPECT_FALSE(context_->complete);
context_->complete = true;
}
TestRequestPeer::Context::Context() = default;
TestRequestPeer::Context::~Context() = default;
} // namespace content
| 35.009901 | 80 | 0.70871 | [
"vector"
] |
b48975f1d18cf1d1522d3129d8415b2b16267e89 | 1,242 | hpp | C++ | src/tensorOps.hpp | GEOSX/LvArray | 3ad0795f10023bd9a2fd8a41f0de0caa376845c0 | [
"BSD-3-Clause"
] | 16 | 2020-07-10T00:04:08.000Z | 2022-03-28T03:59:51.000Z | src/tensorOps.hpp | GEOSX/LvArray | 3ad0795f10023bd9a2fd8a41f0de0caa376845c0 | [
"BSD-3-Clause"
] | 55 | 2020-06-30T06:26:49.000Z | 2022-03-29T18:21:47.000Z | src/tensorOps.hpp | GEOSX/LvArray | 3ad0795f10023bd9a2fd8a41f0de0caa376845c0 | [
"BSD-3-Clause"
] | 5 | 2021-02-03T02:00:20.000Z | 2022-03-21T20:37:51.000Z | /*
* Copyright (c) 2021, Lawrence Livermore National Security, LLC and LvArray contributors.
* All rights reserved.
* See the LICENSE file for details.
* SPDX-License-Identifier: (BSD-3-Clause)
*/
/**
* @file tensorOps.hpp
*/
#pragma once
// Source includes
#include "genericTensorOps.hpp"
#include "fixedSizeSquareMatrixOps.hpp"
namespace LvArray
{
/**
* @brief Contains operations for operating on compile time sized vectors and matrices.
* @details LvArray::tensorOps functions accept four differnet types of arguments
* -# Scalars
* -# Vectors: These can either be a one dimensional c-array such as double[ 3 ] or a one dimensional
* LvArray::Array, LvArray::ArrayView, or LvArray::ArraySlice.
* -# Matrices: These can either be a two dimensional c-array such as int[ 5 ][ 2 ] or a two dimensional
* LvArray::Array, LvArray::ArrayView, or LvArray::ArraySlice.
* -# Symmetric matrices: These are represented in Voigt notation as a vector.
*
* Each function takes in the size of the objects as template parameters. As an example to take
* the dot product of two vectors of length 3 you'd call
* @code LvArray::tensorOps::AiBi< 3 >( x, y ) @endcode
*/
namespace tensorOps
{}
}
| 31.846154 | 108 | 0.706924 | [
"vector"
] |
b493fe40e3dee182120d24560e1263c4a3d93ddf | 3,370 | cpp | C++ | Code/Framework/AzQtComponents/AzQtComponents/Components/SearchLineEdit.cpp | jpakkane/o3de | bb680810e6ca31088ed8bcb084331c03a1a1facf | [
"Apache-2.0",
"MIT"
] | 1 | 2021-07-19T23:54:05.000Z | 2021-07-19T23:54:05.000Z | Code/Framework/AzQtComponents/AzQtComponents/Components/SearchLineEdit.cpp | jpakkane/o3de | bb680810e6ca31088ed8bcb084331c03a1a1facf | [
"Apache-2.0",
"MIT"
] | null | null | null | Code/Framework/AzQtComponents/AzQtComponents/Components/SearchLineEdit.cpp | jpakkane/o3de | bb680810e6ca31088ed8bcb084331c03a1a1facf | [
"Apache-2.0",
"MIT"
] | null | null | null | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include "SearchLineEdit.h"
#include <AzQtComponents/Components/SearchLineEdit.h>
#include <AzQtComponents/Components/Widgets/LineEdit.h>
#include <QAction>
#include <QCompleter>
#include <QIcon>
#include <QMenu>
#include <QStyle>
using namespace AzQtComponents;
SearchLineEdit::SearchLineEdit(QWidget* parent)
: QLineEdit(parent)
, m_errorState(false)
{
setProperty("class", "SearchLineEdit");
m_searchAction = new QAction(QIcon(":/stylesheet/img/16x16/Search.png"), QString(), this);
m_searchAction->setEnabled(false);
addAction(m_searchAction, QLineEdit::LeadingPosition);
}
bool SearchLineEdit::errorState() const
{
return m_errorState;
}
void SearchLineEdit::setMenu(QMenu* menu)
{
if (!menu)
{
return;
}
m_menu = menu;
removeAction(m_searchAction);
m_searchAction = new QAction(QIcon(":/stylesheet/img/16x16/Search_more.png"), QString(), this);
m_searchAction->setEnabled(true);
addAction(m_searchAction, QLineEdit::LeadingPosition);
connect(m_searchAction, &QAction::triggered, this, &SearchLineEdit::displayMenu);
}
void SearchLineEdit::setIconToolTip(const QString& tooltip)
{
m_searchAction->setToolTip(tooltip);
}
QString SearchLineEdit::userInputText() const
{
QString lineEditText = text();
// The QCompleter doesn't seem to update the completion prefix when you delete anything, only when things are added.
// To get it to update correctly when the user deletes something, I'm using the combination of things:
//
// 1) If we have a completion, that text will be auto filled into the quick filter because of the completion model.
// So, we will compare those two values, and if they match, we know we want to search using the completion prefix.
//
// 2) If they don't match, it means that user deleted something, and the Completer didn't update it's internal state, so we'll just
// use whatever is in the text box.
//
// 3) When the text field is set to empty, the current completion gets invalidated, but the prefix doesn't, so that gets special cased
// out.
//
// Extra fun: If you type in something, "Like" then delete a middle character, "Lie", and then put the k back in. It will auto complete
// the E visually but the completion prefix will be the entire word.
if (completer() && completer()->currentCompletion().compare(lineEditText, Qt::CaseInsensitive) == 0 && !lineEditText.isEmpty())
{
lineEditText = completer()->completionPrefix();
}
return lineEditText;
}
void SearchLineEdit::setErrorState(bool errorState)
{
if (m_errorState == errorState)
{
return;
}
m_errorState = errorState;
AzQtComponents::LineEdit::setExternalError(this, errorState);
emit errorStateChanged(m_errorState);
}
void SearchLineEdit::displayMenu()
{
if (m_menu)
{
const auto rect = QRect(0, 0, width(), height());
const auto actionSelected = m_menu->exec(mapToGlobal(rect.bottomLeft()));
emit menuEntryClicked(actionSelected);
}
}
#ifndef MESON_BUILD
#include "Components/moc_SearchLineEdit.cpp"
#endif
| 30.636364 | 139 | 0.709199 | [
"model",
"3d"
] |
a33260fd063d552f3685d6289661ada08904b677 | 5,219 | cpp | C++ | propcov/tests/tests-cpp/TestSliceTree.cpp | EarthObservationSimulator/orbits | b476762532f8644b9fe0723760b5202ab77a4547 | [
"Apache-2.0"
] | 4 | 2021-12-23T16:49:06.000Z | 2022-02-09T21:36:31.000Z | propcov/tests/tests-cpp/TestSliceTree.cpp | EarthObservationSimulator/orbits | b476762532f8644b9fe0723760b5202ab77a4547 | [
"Apache-2.0"
] | 15 | 2022-01-14T17:28:14.000Z | 2022-02-11T02:39:25.000Z | propcov/tests/tests-cpp/TestSliceTree.cpp | EarthObservationSimulator/orbits | b476762532f8644b9fe0723760b5202ab77a4547 | [
"Apache-2.0"
] | 1 | 2022-02-03T15:44:16.000Z | 2022-02-03T15:44:16.000Z | #include "SlicedPolygon.hpp"
#include "SliceTree.hpp"
#include <gtest/gtest.h>
class DISABLED_Poly_01 : public ::testing::Test {
protected:
void SetUp() override
{
int numElements = 13;
std::vector<AnglePair> polygon(numElements);
AnglePair contained = {0,0};
for (int i = 0;i < numElements;i++)
polygon[i][0] = M_PI/4.0;
polygon[0][1] = 0.0;
polygon[1][1] = 0.5235987756;
polygon[2][1] = 1.047197551;
polygon[3][1] = 1.570796327;
polygon[4][1] = 2.094395102;
polygon[5][1] = 2.617993878;
polygon[6][1] = 3.141592654;
polygon[7][1] = 3.665191429;
polygon[8][1] = 4.188790205;
polygon[9][1] = 4.71238898;
polygon[10][1] = 5.235987756;
polygon[11][1] = 5.759586532;
polygon[12][1] = 0.0;
grapefruit = new SlicedPolygon(polygon,contained);
sliceTree = new SliceTree(grapefruit->getEdgeArray(),1,16);
sliceTree->preprocess();
grapefruit->addPreprocessor(sliceTree);
}
void TearDown() override
{
delete(grapefruit);
}
Real tol = .00000001;
SlicedPolygon* grapefruit;
Preprocessor* sliceTree;
};
TEST_F(DISABLED_Poly_01,getEdges)
{
Real crit1 = 1;
Real crit2 = 16;
SliceTree* test = new SliceTree(grapefruit->getEdgeArray(),crit1,crit2);
ASSERT_TRUE(true);
}
TEST_F(DISABLED_Poly_01,Query_03_numCrossings)
{
// Test 1: Lies inside polygon
int expectedCrossings = 0;
AnglePair query = {0,0};
int crossings = grapefruit->numCrossings(query);
ASSERT_EQ(expectedCrossings,crossings);
}
TEST_F(DISABLED_Poly_01,Query_02_boundsPoint)
{
// Test 2: Lies outside polygon, at same clock angle as starting point
int expectedCrossings = 1;
AnglePair query = {1.047197551,0};
Rmatrix33 QI = grapefruit->getQI();
query = util::transformSpherical(query,QI);
Real lon = query[1];
std::vector<Edge> edgeArray = grapefruit->getEdgeArray();
int expectedNumBounds = 1;
int numBounds = 0;
int i = 0;
for (Edge edge : edgeArray)
{
if (edge.boundsPoint(lon))
std::cerr << i;
numBounds += edge.boundsPoint(lon);
i++;
}
// Point should only be bounded by one edge
EXPECT_EQ(expectedNumBounds,numBounds);
// Point should be bounded by first edge
EXPECT_EQ(1,edgeArray[0].boundsPoint(lon));
}
TEST_F(DISABLED_Poly_01,Query_02_numCrossings)
{
// Test 2: Lies outside polygon, at same clock angle as starting point
int expectedCrossings = 1;
AnglePair query = {1.047197551,0};
int crossings = grapefruit->numCrossings(query);
ASSERT_EQ(expectedCrossings,crossings);
}
TEST_F(DISABLED_Poly_01,Query_01_numCrossings)
{
int expectedCrossings = 0;
AnglePair query = {0.6283185307,0};
int crossings = grapefruit->numCrossings(query);
ASSERT_EQ(expectedCrossings,crossings);
}
TEST_F(DISABLED_Poly_01,Query_05_numCrossings)
{
// Test 5: lies inside the polygon, at clock angle in the middle of a segment
int expectedCrossings = 0;
AnglePair query = {0.5235987756,0.4487989505};
int crossings = grapefruit->numCrossings(query);
ASSERT_EQ(expectedCrossings,crossings);
// new
AnglePair query_Q = grapefruit->toQueryFrame(query);
std::vector<int> subset = grapefruit->getSubset(query_Q);
ASSERT_EQ(1,subset.size());
}
TEST_F(DISABLED_Poly_01,Query_06_numCrossings)
{
// Test 6: lies inside the polygon, at clock angle in the middle of a segment
int expectedCrossings = 0;
AnglePair query = {0.5235987756,0.897597901};
int crossings = grapefruit->numCrossings(query);
ASSERT_EQ(expectedCrossings,crossings);
// new
AnglePair query_Q = grapefruit->toQueryFrame(query);
std::vector<int> subset = grapefruit->getSubset(query_Q);
ASSERT_EQ(1,subset.size());
}
TEST_F(DISABLED_Poly_01,Query_07_numCrossings)
{
// Test 7: lies outside the polygon, at clock angle in the middle of a segment
int expectedCrossings = 1;
AnglePair query = {1.047197551,0.4487989505};
int crossings = grapefruit->numCrossings(query);
ASSERT_EQ(expectedCrossings,crossings);
// new
AnglePair query_Q = grapefruit->toQueryFrame(query);
std::vector<int> subset = grapefruit->getSubset(query_Q);
ASSERT_EQ(1,subset.size());
}
TEST_F(DISABLED_Poly_01,Query_08_numCrossings)
{
// Test 7: lies outside the polygon, at clock angle in the middle of a segment
int expectedCrossings = 1;
AnglePair query = {1.047197551,0.897597901};
int crossings = grapefruit->numCrossings(query);
ASSERT_EQ(expectedCrossings,crossings);
// new
AnglePair query_Q = grapefruit->toQueryFrame(query);
std::vector<int> subset = grapefruit->getSubset(query_Q);
ASSERT_EQ(1,subset.size());
}
TEST_F(DISABLED_Poly_01,Query_08_boundsPoint)
{
// Test 2: Lies outside polygon, at same clock angle as starting point
int expectedCrossings = 1;
AnglePair query = {1.047197551,0.897597901};
Rmatrix33 QI = grapefruit->getQI();
query = util::transformSpherical(query,QI);
Real lon = query[1];
std::vector<Edge> edgeArray = grapefruit->getEdgeArray();
int expectedNumBounds = 1;
int numBounds = 0;
int i = 0;
for (Edge edge : edgeArray)
{
if (edge.boundsPoint(lon))
std::cerr << i;
numBounds += edge.boundsPoint(lon);
i++;
}
// Point should only be bounded by one edge
EXPECT_EQ(expectedNumBounds,numBounds);
}
int main(int argc, char **argv)
{
testing::InitGoogleTest(&argc,argv);
return RUN_ALL_TESTS();
} | 24.971292 | 79 | 0.72351 | [
"vector"
] |
a3327bd314d567eef9f4659d546854564222a961 | 7,538 | cpp | C++ | liboctopipespp/src/message.cpp | ChristianVisintin/liboctopipes | a9833c10046d8d8fd312101c5273b6bec5da8c53 | [
"MIT"
] | null | null | null | liboctopipespp/src/message.cpp | ChristianVisintin/liboctopipes | a9833c10046d8d8fd312101c5273b6bec5da8c53 | [
"MIT"
] | null | null | null | liboctopipespp/src/message.cpp | ChristianVisintin/liboctopipes | a9833c10046d8d8fd312101c5273b6bec5da8c53 | [
"MIT"
] | null | null | null | /**
* Octopipes
* Developed by Christian Visintin
*
* MIT License
* Copyright (c) 2019-2020 Christian Visintin
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
**/
#include <octopipespp/message.hpp>
#include <octopipes/octopipes.h>
#include <octopipes/serializer.h>
#include <cstring>
namespace octopipes {
Error translate_octopipes_error(OctopipesError error);
/**
* @brief Message default class constructor
*/
Message::Message() {
this->payload = nullptr;
this->payload_size = 0;
this->checksum = 0;
this->ttl = 0;
this->options = Options::NONE;
}
/**
* @brief Message class constructor
* @param ProtocolVersion version
* @param string origin
* @param string remote
* @param uint8_t* payload
* @param size_t payload size
* @param Options options
* @param int ttl
* @throw std::bad_alloc
* NOTE: data is copied to message, so the user must free the payload himself
*/
Message::Message(const ProtocolVersion version, const std::string& origin, const std::string& remote, const uint8_t* payload, const size_t payload_size, const Options options, const int ttl) {
this->version = version;
this->origin = origin;
this->remote = remote;
this->payload_size = payload_size;
if (this->payload_size > 0) {
this->payload = new uint8_t[payload_size];
memcpy(this->payload, payload, payload_size);
}
this->ttl = ttl;
this->options = options;
}
/**
* @brief Construct a Message object using an OctopipesMessage pointer
* @param void* message pointer (OctopipesMessage*)
*/
Message::Message(const void* message_ptr) {
const OctopipesMessage* message = reinterpret_cast<const OctopipesMessage*>(message_ptr);
//Convert OctopipesMessage to Message
version = static_cast<ProtocolVersion>(message->version);
if (message->origin != NULL) {
origin = std::string(message->origin);
}
if (message->remote != NULL) {
remote = std::string(message->remote);
}
options = static_cast<Options>(message->options);
ttl = message->ttl;
payload = nullptr;
payload_size = message->data_size;
if (payload_size > 0) {
payload = new uint8_t[payload_size];
memcpy(payload, message->data, payload_size);
}
}
/**
* @brief Message class destructor
*/
Message::~Message() {
if (this->payload != nullptr) {
delete[] this->payload;
}
}
/**
* @brief decode data into Message class attributes
* @param uint8_t* data
* @param size_t data size
* @return octopipes::Error
* @throw std::bad_alloc
*/
Error Message::decodeData(const uint8_t* data, size_t data_size) {
OctopipesMessage* msg;
OctopipesError rc;
if ((rc = octopipes_decode(data, data_size, &msg)) != OCTOPIPES_ERROR_SUCCESS) {
return translate_octopipes_error(rc);
}
this->version = static_cast<ProtocolVersion>(msg->version);
this->origin = msg->origin;
this->remote = msg->remote;
this->checksum = msg->checksum;
this->options = static_cast<Options>(msg->options);
this->ttl = msg->ttl;
this->payload_size = msg->data_size;
if (this->payload_size > 0) {
this->payload = new uint8_t[payload_size];
memcpy(this->payload, msg->data, this->payload_size);
}
octopipes_cleanup_message(msg);
return Error::SUCCESS;
}
/**
* @brief encode Message instance to message buffer
* @param uint8_t*& data
* @param size_t& data_size
* @return octopipes::Error
* @throw std::bad_alloc
*/
Error Message::encodeData(uint8_t*& data, size_t& data_size) {
//Fill message attributes; don't use new, since we're going to use cleanup message then. Don't ever mix C with C++!
OctopipesMessage* msg = (OctopipesMessage*) malloc(sizeof(OctopipesMessage));
if (msg == NULL) {
return Error::BAD_ALLOC;
}
msg->origin = NULL;
msg->remote = NULL;
msg->data = NULL;
//Version
msg->version = static_cast<OctopipesVersion>(version);
//Origin
msg->origin_size = origin.length();
msg->origin = (char*) malloc(sizeof(char) * (msg->origin_size + 1));
if (msg->origin == NULL) {
octopipes_cleanup_message(msg);
return Error::BAD_ALLOC;
}
memcpy(msg->origin, origin.c_str(), msg->origin_size);
msg->origin[msg->origin_size] = 0x00;
//Remote
msg->remote_size = remote.length();
msg->remote = (char*) malloc(sizeof(char) * (msg->remote_size + 1));
if (msg->remote == NULL) {
octopipes_cleanup_message(msg);
return Error::BAD_ALLOC;
}
memcpy(msg->remote, remote.c_str(), msg->remote_size);
msg->remote[msg->remote_size] = 0x00;
//Options
msg->options = static_cast<OctopipesOptions>(options);
//TTL
msg->ttl = ttl;
//Assign data
msg->data_size = this->payload_size;
msg->data = (uint8_t*) malloc(sizeof(uint8_t) * msg->data_size);
if (msg->data == NULL) {
octopipes_cleanup_message(msg);
return Error::BAD_ALLOC;
}
memcpy(msg->data, this->payload, msg->data_size);
//If checksum has to be calculated, calc checksum
if (!getOption(Options::IGNORE_CHECKSUM)) {
msg->checksum = calculate_checksum(msg);
this->checksum = msg->checksum;
}
//Encode message
uint8_t* out_data;
size_t out_data_size;
OctopipesError rc;
if ((rc = octopipes_encode(msg, &out_data, &out_data_size)) != OCTOPIPES_ERROR_SUCCESS) {
octopipes_cleanup_message(msg);
return translate_octopipes_error(rc);
}
//Assign data
data = out_data;
data_size = out_data_size;
octopipes_cleanup_message(msg);
return Error::SUCCESS;
}
/**
* @brief return the Message protocol version
* @return ProtocolVersion
*/
ProtocolVersion Message::getVersion() const {
return version;
}
/**
* @brief return the Message origin
* @return string
*/
const std::string Message::getOrigin() const {
return origin;
}
/**
* @brief return the Message remote
* @return string
*/
const std::string Message::getRemote() const {
return remote;
}
/**
* @brief return the Message payload and its size
* @param size_t& data_size
* @return uint8_t*
*/
const uint8_t* Message::getPayload(size_t& data_size) const {
data_size = this->payload_size;
return payload;
}
/**
* @brief return the Message TTL
* @return int
*/
const int Message::getTTL() const {
return ttl;
}
/**
* @brief return the Message checksum
* @return int
*/
const int Message::getChecksum() const {
return checksum;
}
/**
* @brief return the desidered Option value from Message options
* @param Options desired option get get
* @return bool
*/
bool Message::getOption(const Options option) const {
return (static_cast<uint8_t>(this->options) & static_cast<uint8_t>(option)) != 0;
}
}
| 27.713235 | 192 | 0.703768 | [
"object"
] |
a33320a7cf1bac8c256c97159f40a8dd8124555c | 12,261 | cpp | C++ | Prototypes/ARKit Mapbox/Classes/Native/Bulk_UnityEngine.ImageConversionModule_0.cpp | noelkonagai/TEE-Fellowship | b38d896ba1702412feb94dada52d31ec5f2a3fd2 | [
"Apache-2.0"
] | null | null | null | Prototypes/ARKit Mapbox/Classes/Native/Bulk_UnityEngine.ImageConversionModule_0.cpp | noelkonagai/TEE-Fellowship | b38d896ba1702412feb94dada52d31ec5f2a3fd2 | [
"Apache-2.0"
] | null | null | null | Prototypes/ARKit Mapbox/Classes/Native/Bulk_UnityEngine.ImageConversionModule_0.cpp | noelkonagai/TEE-Fellowship | b38d896ba1702412feb94dada52d31ec5f2a3fd2 | [
"Apache-2.0"
] | null | null | null | #include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <cstring>
#include <string.h>
#include <stdio.h>
#include <cmath>
#include <limits>
#include <assert.h>
#include <stdint.h>
#include "il2cpp-class-internals.h"
#include "codegen/il2cpp-codegen.h"
#include "il2cpp-object-internals.h"
// UnityEngine.Texture2D
struct Texture2D_t3542995729;
// System.Byte[]
struct ByteU5BU5D_t3397334013;
// System.String
struct String_t;
// System.Void
struct Void_t1841601450;
struct ByteU5BU5D_t3397334013;
#ifndef U3CMODULEU3E_T3783534221_H
#define U3CMODULEU3E_T3783534221_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// <Module>
struct U3CModuleU3E_t3783534221
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // U3CMODULEU3E_T3783534221_H
#ifndef RUNTIMEOBJECT_H
#define RUNTIMEOBJECT_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Object
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // RUNTIMEOBJECT_H
struct Il2CppArrayBounds;
#ifndef RUNTIMEARRAY_H
#define RUNTIMEARRAY_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Array
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // RUNTIMEARRAY_H
#ifndef IMAGECONVERSION_T2189217709_H
#define IMAGECONVERSION_T2189217709_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.ImageConversion
struct ImageConversion_t2189217709 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // IMAGECONVERSION_T2189217709_H
#ifndef VALUETYPE_T3507792607_H
#define VALUETYPE_T3507792607_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ValueType
struct ValueType_t3507792607 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of System.ValueType
struct ValueType_t3507792607_marshaled_pinvoke
{
};
// Native definition for COM marshalling of System.ValueType
struct ValueType_t3507792607_marshaled_com
{
};
#endif // VALUETYPE_T3507792607_H
#ifndef BYTE_T3683104436_H
#define BYTE_T3683104436_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Byte
struct Byte_t3683104436
{
public:
// System.Byte System.Byte::m_value
uint8_t ___m_value_2;
public:
inline static int32_t get_offset_of_m_value_2() { return static_cast<int32_t>(offsetof(Byte_t3683104436, ___m_value_2)); }
inline uint8_t get_m_value_2() const { return ___m_value_2; }
inline uint8_t* get_address_of_m_value_2() { return &___m_value_2; }
inline void set_m_value_2(uint8_t value)
{
___m_value_2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // BYTE_T3683104436_H
#ifndef BOOLEAN_T3825574718_H
#define BOOLEAN_T3825574718_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Boolean
struct Boolean_t3825574718
{
public:
// System.Boolean System.Boolean::m_value
bool ___m_value_2;
public:
inline static int32_t get_offset_of_m_value_2() { return static_cast<int32_t>(offsetof(Boolean_t3825574718, ___m_value_2)); }
inline bool get_m_value_2() const { return ___m_value_2; }
inline bool* get_address_of_m_value_2() { return &___m_value_2; }
inline void set_m_value_2(bool value)
{
___m_value_2 = value;
}
};
struct Boolean_t3825574718_StaticFields
{
public:
// System.String System.Boolean::FalseString
String_t* ___FalseString_0;
// System.String System.Boolean::TrueString
String_t* ___TrueString_1;
public:
inline static int32_t get_offset_of_FalseString_0() { return static_cast<int32_t>(offsetof(Boolean_t3825574718_StaticFields, ___FalseString_0)); }
inline String_t* get_FalseString_0() const { return ___FalseString_0; }
inline String_t** get_address_of_FalseString_0() { return &___FalseString_0; }
inline void set_FalseString_0(String_t* value)
{
___FalseString_0 = value;
Il2CppCodeGenWriteBarrier((&___FalseString_0), value);
}
inline static int32_t get_offset_of_TrueString_1() { return static_cast<int32_t>(offsetof(Boolean_t3825574718_StaticFields, ___TrueString_1)); }
inline String_t* get_TrueString_1() const { return ___TrueString_1; }
inline String_t** get_address_of_TrueString_1() { return &___TrueString_1; }
inline void set_TrueString_1(String_t* value)
{
___TrueString_1 = value;
Il2CppCodeGenWriteBarrier((&___TrueString_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // BOOLEAN_T3825574718_H
#ifndef INTPTR_T_H
#define INTPTR_T_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.IntPtr
struct IntPtr_t
{
public:
// System.Void* System.IntPtr::m_value
void* ___m_value_0;
public:
inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(IntPtr_t, ___m_value_0)); }
inline void* get_m_value_0() const { return ___m_value_0; }
inline void** get_address_of_m_value_0() { return &___m_value_0; }
inline void set_m_value_0(void* value)
{
___m_value_0 = value;
}
};
struct IntPtr_t_StaticFields
{
public:
// System.IntPtr System.IntPtr::Zero
intptr_t ___Zero_1;
public:
inline static int32_t get_offset_of_Zero_1() { return static_cast<int32_t>(offsetof(IntPtr_t_StaticFields, ___Zero_1)); }
inline intptr_t get_Zero_1() const { return ___Zero_1; }
inline intptr_t* get_address_of_Zero_1() { return &___Zero_1; }
inline void set_Zero_1(intptr_t value)
{
___Zero_1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // INTPTR_T_H
#ifndef OBJECT_T1021602117_H
#define OBJECT_T1021602117_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.Object
struct Object_t1021602117 : public RuntimeObject
{
public:
// System.IntPtr UnityEngine.Object::m_CachedPtr
intptr_t ___m_CachedPtr_0;
public:
inline static int32_t get_offset_of_m_CachedPtr_0() { return static_cast<int32_t>(offsetof(Object_t1021602117, ___m_CachedPtr_0)); }
inline intptr_t get_m_CachedPtr_0() const { return ___m_CachedPtr_0; }
inline intptr_t* get_address_of_m_CachedPtr_0() { return &___m_CachedPtr_0; }
inline void set_m_CachedPtr_0(intptr_t value)
{
___m_CachedPtr_0 = value;
}
};
struct Object_t1021602117_StaticFields
{
public:
// System.Int32 UnityEngine.Object::OffsetOfInstanceIDInCPlusPlusObject
int32_t ___OffsetOfInstanceIDInCPlusPlusObject_1;
public:
inline static int32_t get_offset_of_OffsetOfInstanceIDInCPlusPlusObject_1() { return static_cast<int32_t>(offsetof(Object_t1021602117_StaticFields, ___OffsetOfInstanceIDInCPlusPlusObject_1)); }
inline int32_t get_OffsetOfInstanceIDInCPlusPlusObject_1() const { return ___OffsetOfInstanceIDInCPlusPlusObject_1; }
inline int32_t* get_address_of_OffsetOfInstanceIDInCPlusPlusObject_1() { return &___OffsetOfInstanceIDInCPlusPlusObject_1; }
inline void set_OffsetOfInstanceIDInCPlusPlusObject_1(int32_t value)
{
___OffsetOfInstanceIDInCPlusPlusObject_1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of UnityEngine.Object
struct Object_t1021602117_marshaled_pinvoke
{
intptr_t ___m_CachedPtr_0;
};
// Native definition for COM marshalling of UnityEngine.Object
struct Object_t1021602117_marshaled_com
{
intptr_t ___m_CachedPtr_0;
};
#endif // OBJECT_T1021602117_H
#ifndef TEXTURE_T2243626319_H
#define TEXTURE_T2243626319_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.Texture
struct Texture_t2243626319 : public Object_t1021602117
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // TEXTURE_T2243626319_H
#ifndef TEXTURE2D_T3542995729_H
#define TEXTURE2D_T3542995729_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.Texture2D
struct Texture2D_t3542995729 : public Texture_t2243626319
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // TEXTURE2D_T3542995729_H
// System.Byte[]
struct ByteU5BU5D_t3397334013 : public RuntimeArray
{
public:
ALIGN_FIELD (8) uint8_t m_Items[1];
public:
inline uint8_t GetAt(il2cpp_array_size_t index) const
{
IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length);
return m_Items[index];
}
inline uint8_t* GetAddressAt(il2cpp_array_size_t index)
{
IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length);
return m_Items + index;
}
inline void SetAt(il2cpp_array_size_t index, uint8_t value)
{
IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length);
m_Items[index] = value;
}
inline uint8_t GetAtUnchecked(il2cpp_array_size_t index) const
{
return m_Items[index];
}
inline uint8_t* GetAddressAtUnchecked(il2cpp_array_size_t index)
{
return m_Items + index;
}
inline void SetAtUnchecked(il2cpp_array_size_t index, uint8_t value)
{
m_Items[index] = value;
}
};
// System.Boolean UnityEngine.ImageConversion::LoadImage(UnityEngine.Texture2D,System.Byte[],System.Boolean)
extern "C" bool ImageConversion_LoadImage_m3547015270 (RuntimeObject * __this /* static, unused */, Texture2D_t3542995729 * ___tex0, ByteU5BU5D_t3397334013* ___data1, bool ___markNonReadable2, const RuntimeMethod* method) IL2CPP_METHOD_ATTR;
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Boolean UnityEngine.ImageConversion::LoadImage(UnityEngine.Texture2D,System.Byte[],System.Boolean)
extern "C" bool ImageConversion_LoadImage_m3547015270 (RuntimeObject * __this /* static, unused */, Texture2D_t3542995729 * ___tex0, ByteU5BU5D_t3397334013* ___data1, bool ___markNonReadable2, const RuntimeMethod* method)
{
typedef bool (*ImageConversion_LoadImage_m3547015270_ftn) (Texture2D_t3542995729 *, ByteU5BU5D_t3397334013*, bool);
static ImageConversion_LoadImage_m3547015270_ftn _il2cpp_icall_func;
if (!_il2cpp_icall_func)
_il2cpp_icall_func = (ImageConversion_LoadImage_m3547015270_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ImageConversion::LoadImage(UnityEngine.Texture2D,System.Byte[],System.Boolean)");
bool retVal = _il2cpp_icall_func(___tex0, ___data1, ___markNonReadable2);
return retVal;
}
// System.Boolean UnityEngine.ImageConversion::LoadImage(UnityEngine.Texture2D,System.Byte[])
extern "C" bool ImageConversion_LoadImage_m3156064641 (RuntimeObject * __this /* static, unused */, Texture2D_t3542995729 * ___tex0, ByteU5BU5D_t3397334013* ___data1, const RuntimeMethod* method)
{
bool V_0 = false;
bool V_1 = false;
{
V_0 = (bool)0;
Texture2D_t3542995729 * L_0 = ___tex0;
ByteU5BU5D_t3397334013* L_1 = ___data1;
bool L_2 = V_0;
bool L_3 = ImageConversion_LoadImage_m3547015270(NULL /*static, unused*/, L_0, L_1, L_2, /*hidden argument*/NULL);
V_1 = L_3;
goto IL_0011;
}
IL_0011:
{
bool L_4 = V_1;
return L_4;
}
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| 27.552809 | 242 | 0.801321 | [
"object"
] |
a335629516cae7c4a29b7088967f1047250f31d2 | 3,424 | cpp | C++ | test/algorithms-range/alg.modifying.operations/alg.transform/unary_transform.pass.cpp | marcinz/libcxx-ranges | ee4ebf99147da4bbb5356b6ab0e7a79a1bfa0704 | [
"MIT"
] | 2 | 2021-11-25T02:37:22.000Z | 2021-12-11T07:33:27.000Z | test/algorithms-range/alg.modifying.operations/alg.transform/unary_transform.pass.cpp | marcinz/libcxx-ranges | ee4ebf99147da4bbb5356b6ab0e7a79a1bfa0704 | [
"MIT"
] | null | null | null | test/algorithms-range/alg.modifying.operations/alg.transform/unary_transform.pass.cpp | marcinz/libcxx-ranges | ee4ebf99147da4bbb5356b6ab0e7a79a1bfa0704 | [
"MIT"
] | null | null | null | //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <algorithm>
// template<InputIterator InIter, class OutIter,
// Callable<auto, const InIter::value_type&> Op>
// requires OutputIterator<OutIter, Op::result_type> && CopyConstructible<Op>
// OutIter
// transform(InIter first, InIter last, OutIter result, Op op);
#include <algorithm-range>
#include <functional>
#include <cassert>
#include "test_ranges.h"
template <class InRange, class OutRange>
void
test()
{
int ia[] = {0, 1, 2, 3, 4};
const unsigned sa = sizeof(ia)/sizeof(ia[0]);
int ib[sa] = {0};
OutRange r = std::transform(InRange(std::make_iter_range(ia, ia+sa)), OutRange(std::make_single_iter_range(ib)),
std::bind2nd(std::plus<int>(), 1));
assert(base(r).base() == ib + sa);
assert(ib[0] == 1);
assert(ib[1] == 2);
assert(ib[2] == 3);
assert(ib[3] == 4);
assert(ib[4] == 5);
}
int main()
{
test<input_range<std::iter_range<const int*> >, output_range<std::single_iter_range<int*> > >();
test<input_range<std::iter_range<const int*> >, input_range<std::single_iter_range<int*> > >();
test<input_range<std::iter_range<const int*> >, forward_range<std::single_iter_range<int*> > >();
test<input_range<std::iter_range<const int*> >, bidirectional_range<std::single_iter_range<int*> > >();
test<input_range<std::iter_range<const int*> >, random_access_range<std::single_iter_range<int*> > >();
test<forward_range<std::iter_range<const int*> >, output_range<std::single_iter_range<int*> > >();
test<forward_range<std::iter_range<const int*> >, input_range<std::single_iter_range<int*> > >();
test<forward_range<std::iter_range<const int*> >, forward_range<std::single_iter_range<int*> > >();
test<forward_range<std::iter_range<const int*> >, bidirectional_range<std::single_iter_range<int*> > >();
test<forward_range<std::iter_range<const int*> >, random_access_range<std::single_iter_range<int*> > >();
test<bidirectional_range<std::iter_range<const int*> >, output_range<std::single_iter_range<int*> > >();
test<bidirectional_range<std::iter_range<const int*> >, input_range<std::single_iter_range<int*> > >();
test<bidirectional_range<std::iter_range<const int*> >, forward_range<std::single_iter_range<int*> > >();
test<bidirectional_range<std::iter_range<const int*> >, bidirectional_range<std::single_iter_range<int*> > >();
test<bidirectional_range<std::iter_range<const int*> >, random_access_range<std::single_iter_range<int*> > >();
test<random_access_range<std::iter_range<const int*> >, output_range<std::single_iter_range<int*> > >();
test<random_access_range<std::iter_range<const int*> >, input_range<std::single_iter_range<int*> > >();
test<random_access_range<std::iter_range<const int*> >, forward_range<std::single_iter_range<int*> > >();
test<random_access_range<std::iter_range<const int*> >, bidirectional_range<std::single_iter_range<int*> > >();
test<random_access_range<std::iter_range<const int*> >, random_access_range<std::single_iter_range<int*> > >();
}
| 51.104478 | 116 | 0.653914 | [
"transform"
] |
a337d81c3d331d7a52d3297ccdd129c529db24aa | 34,628 | cc | C++ | extensions/browser/api/declarative_net_request/indexed_rule_unittest.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | extensions/browser/api/declarative_net_request/indexed_rule_unittest.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | extensions/browser/api/declarative_net_request/indexed_rule_unittest.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-03-07T14:20:02.000Z | 2021-03-07T14:20:02.000Z | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "extensions/browser/api/declarative_net_request/indexed_rule.h"
#include <memory>
#include <utility>
#include "base/format_macros.h"
#include "base/json/json_reader.h"
#include "base/macros.h"
#include "base/numerics/safe_conversions.h"
#include "base/stl_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "extensions/browser/api/declarative_net_request/constants.h"
#include "extensions/browser/api/declarative_net_request/test_utils.h"
#include "extensions/common/api/declarative_net_request.h"
#include "extensions/common/api/declarative_net_request/constants.h"
#include "extensions/common/extension.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace extensions {
namespace declarative_net_request {
namespace {
namespace flat_rule = url_pattern_index::flat;
namespace dnr_api = extensions::api::declarative_net_request;
constexpr const char* kTestExtensionId = "extensionid";
GURL GetBaseURL() {
return Extension::GetBaseURLFromExtensionId(kTestExtensionId);
}
std::unique_ptr<dnr_api::Redirect> MakeRedirectUrl(const char* redirect_url) {
auto redirect = std::make_unique<dnr_api::Redirect>();
redirect->url = std::make_unique<std::string>(redirect_url);
return redirect;
}
dnr_api::Rule CreateGenericParsedRule() {
dnr_api::Rule rule;
rule.priority = std::make_unique<int>(kMinValidPriority);
rule.id = kMinValidID;
rule.condition.url_filter = std::make_unique<std::string>("filter");
rule.action.type = dnr_api::RULE_ACTION_TYPE_BLOCK;
return rule;
}
using IndexedRuleTest = ::testing::Test;
TEST_F(IndexedRuleTest, IDParsing) {
struct {
const int id;
const ParseResult expected_result;
} cases[] = {
{kMinValidID - 1, ParseResult::ERROR_INVALID_RULE_ID},
{kMinValidID, ParseResult::SUCCESS},
{kMinValidID + 1, ParseResult::SUCCESS},
};
for (size_t i = 0; i < base::size(cases); ++i) {
SCOPED_TRACE(base::StringPrintf("Testing case[%" PRIuS "]", i));
dnr_api::Rule rule = CreateGenericParsedRule();
rule.id = cases[i].id;
IndexedRule indexed_rule;
ParseResult result = IndexedRule::CreateIndexedRule(
std::move(rule), GetBaseURL(), &indexed_rule);
EXPECT_EQ(cases[i].expected_result, result);
if (result == ParseResult::SUCCESS)
EXPECT_EQ(base::checked_cast<uint32_t>(cases[i].id), indexed_rule.id);
}
}
TEST_F(IndexedRuleTest, PriorityParsing) {
struct {
dnr_api::RuleActionType action_type;
std::unique_ptr<int> priority;
const ParseResult expected_result;
// Only valid if |expected_result| is SUCCESS.
const uint32_t expected_priority;
} cases[] = {
{dnr_api::RULE_ACTION_TYPE_REDIRECT,
std::make_unique<int>(kMinValidPriority - 1),
ParseResult::ERROR_INVALID_RULE_PRIORITY, kDefaultPriority},
{dnr_api::RULE_ACTION_TYPE_REDIRECT,
std::make_unique<int>(kMinValidPriority), ParseResult::SUCCESS,
kMinValidPriority},
{dnr_api::RULE_ACTION_TYPE_REDIRECT, nullptr, ParseResult::SUCCESS,
kDefaultPriority},
{dnr_api::RULE_ACTION_TYPE_REDIRECT,
std::make_unique<int>(kMinValidPriority + 1), ParseResult::SUCCESS,
kMinValidPriority + 1},
{dnr_api::RULE_ACTION_TYPE_UPGRADESCHEME,
std::make_unique<int>(kMinValidPriority - 1),
ParseResult::ERROR_INVALID_RULE_PRIORITY, kDefaultPriority},
{dnr_api::RULE_ACTION_TYPE_UPGRADESCHEME,
std::make_unique<int>(kMinValidPriority), ParseResult::SUCCESS,
kMinValidPriority},
{dnr_api::RULE_ACTION_TYPE_BLOCK,
std::make_unique<int>(kMinValidPriority - 1),
ParseResult::ERROR_INVALID_RULE_PRIORITY, kDefaultPriority},
{dnr_api::RULE_ACTION_TYPE_BLOCK,
std::make_unique<int>(kMinValidPriority), ParseResult::SUCCESS,
kMinValidPriority},
};
for (size_t i = 0; i < base::size(cases); ++i) {
SCOPED_TRACE(base::StringPrintf("Testing case[%" PRIuS "]", i));
dnr_api::Rule rule = CreateGenericParsedRule();
rule.priority = std::move(cases[i].priority);
rule.action.type = cases[i].action_type;
if (cases[i].action_type == dnr_api::RULE_ACTION_TYPE_REDIRECT) {
rule.action.redirect = MakeRedirectUrl("http://google.com");
}
IndexedRule indexed_rule;
ParseResult result = IndexedRule::CreateIndexedRule(
std::move(rule), GetBaseURL(), &indexed_rule);
EXPECT_EQ(cases[i].expected_result, result);
if (result == ParseResult::SUCCESS)
EXPECT_EQ(ComputeIndexedRulePriority(cases[i].expected_priority,
cases[i].action_type),
indexed_rule.priority);
}
}
TEST_F(IndexedRuleTest, OptionsParsing) {
struct {
const dnr_api::DomainType domain_type;
const dnr_api::RuleActionType action_type;
std::unique_ptr<bool> is_url_filter_case_sensitive;
const uint8_t expected_options;
} cases[] = {
{dnr_api::DOMAIN_TYPE_NONE, dnr_api::RULE_ACTION_TYPE_BLOCK, nullptr,
flat_rule::OptionFlag_APPLIES_TO_THIRD_PARTY |
flat_rule::OptionFlag_APPLIES_TO_FIRST_PARTY},
{dnr_api::DOMAIN_TYPE_FIRSTPARTY, dnr_api::RULE_ACTION_TYPE_ALLOW,
std::make_unique<bool>(true),
flat_rule::OptionFlag_IS_ALLOWLIST |
flat_rule::OptionFlag_APPLIES_TO_FIRST_PARTY},
{dnr_api::DOMAIN_TYPE_FIRSTPARTY, dnr_api::RULE_ACTION_TYPE_ALLOW,
std::make_unique<bool>(false),
flat_rule::OptionFlag_IS_ALLOWLIST |
flat_rule::OptionFlag_APPLIES_TO_FIRST_PARTY |
flat_rule::OptionFlag_IS_CASE_INSENSITIVE},
};
for (size_t i = 0; i < base::size(cases); ++i) {
SCOPED_TRACE(base::StringPrintf("Testing case[%" PRIuS "]", i));
dnr_api::Rule rule = CreateGenericParsedRule();
rule.condition.domain_type = cases[i].domain_type;
rule.action.type = cases[i].action_type;
rule.condition.is_url_filter_case_sensitive =
std::move(cases[i].is_url_filter_case_sensitive);
IndexedRule indexed_rule;
ParseResult result = IndexedRule::CreateIndexedRule(
std::move(rule), GetBaseURL(), &indexed_rule);
EXPECT_EQ(ParseResult::SUCCESS, result);
EXPECT_EQ(cases[i].expected_options, indexed_rule.options);
}
}
TEST_F(IndexedRuleTest, ResourceTypesParsing) {
using ResourceTypeVec = std::vector<dnr_api::ResourceType>;
struct {
std::unique_ptr<ResourceTypeVec> resource_types;
std::unique_ptr<ResourceTypeVec> excluded_resource_types;
const ParseResult expected_result;
// Only valid if |expected_result| is SUCCESS.
const uint16_t expected_element_types;
} cases[] = {
{nullptr, nullptr, ParseResult::SUCCESS,
flat_rule::ElementType_ANY & ~flat_rule::ElementType_MAIN_FRAME},
{nullptr,
std::make_unique<ResourceTypeVec>(
ResourceTypeVec({dnr_api::RESOURCE_TYPE_SCRIPT})),
ParseResult::SUCCESS,
flat_rule::ElementType_ANY & ~flat_rule::ElementType_SCRIPT},
{std::make_unique<ResourceTypeVec>(ResourceTypeVec(
{dnr_api::RESOURCE_TYPE_SCRIPT, dnr_api::RESOURCE_TYPE_IMAGE})),
nullptr, ParseResult::SUCCESS,
flat_rule::ElementType_SCRIPT | flat_rule::ElementType_IMAGE},
{std::make_unique<ResourceTypeVec>(ResourceTypeVec(
{dnr_api::RESOURCE_TYPE_SCRIPT, dnr_api::RESOURCE_TYPE_IMAGE})),
std::make_unique<ResourceTypeVec>(
ResourceTypeVec({dnr_api::RESOURCE_TYPE_SCRIPT})),
ParseResult::ERROR_RESOURCE_TYPE_DUPLICATED,
flat_rule::ElementType_NONE},
{nullptr,
std::make_unique<ResourceTypeVec>(ResourceTypeVec(
{dnr_api::RESOURCE_TYPE_MAIN_FRAME, dnr_api::RESOURCE_TYPE_SUB_FRAME,
dnr_api::RESOURCE_TYPE_STYLESHEET, dnr_api::RESOURCE_TYPE_SCRIPT,
dnr_api::RESOURCE_TYPE_IMAGE, dnr_api::RESOURCE_TYPE_FONT,
dnr_api::RESOURCE_TYPE_OBJECT,
dnr_api::RESOURCE_TYPE_XMLHTTPREQUEST, dnr_api::RESOURCE_TYPE_PING,
dnr_api::RESOURCE_TYPE_CSP_REPORT, dnr_api::RESOURCE_TYPE_MEDIA,
dnr_api::RESOURCE_TYPE_WEBSOCKET, dnr_api::RESOURCE_TYPE_OTHER})),
ParseResult::ERROR_NO_APPLICABLE_RESOURCE_TYPES,
flat_rule::ElementType_NONE},
{std::make_unique<ResourceTypeVec>(), std::make_unique<ResourceTypeVec>(),
ParseResult::ERROR_EMPTY_RESOURCE_TYPES_LIST,
flat_rule::ElementType_NONE},
{std::make_unique<ResourceTypeVec>(
ResourceTypeVec({dnr_api::RESOURCE_TYPE_SCRIPT})),
std::make_unique<ResourceTypeVec>(ResourceTypeVec()),
ParseResult::SUCCESS, flat_rule::ElementType_SCRIPT},
};
for (size_t i = 0; i < base::size(cases); ++i) {
SCOPED_TRACE(base::StringPrintf("Testing case[%" PRIuS "]", i));
dnr_api::Rule rule = CreateGenericParsedRule();
rule.condition.resource_types = std::move(cases[i].resource_types);
rule.condition.excluded_resource_types =
std::move(cases[i].excluded_resource_types);
IndexedRule indexed_rule;
ParseResult result = IndexedRule::CreateIndexedRule(
std::move(rule), GetBaseURL(), &indexed_rule);
EXPECT_EQ(cases[i].expected_result, result);
if (result == ParseResult::SUCCESS)
EXPECT_EQ(cases[i].expected_element_types, indexed_rule.element_types);
}
}
TEST_F(IndexedRuleTest, UrlFilterParsing) {
struct {
std::unique_ptr<std::string> input_url_filter;
// Only valid if |expected_result| is SUCCESS.
const flat_rule::UrlPatternType expected_url_pattern_type;
const flat_rule::AnchorType expected_anchor_left;
const flat_rule::AnchorType expected_anchor_right;
const std::string expected_url_pattern;
const ParseResult expected_result;
} cases[] = {
{nullptr, flat_rule::UrlPatternType_SUBSTRING, flat_rule::AnchorType_NONE,
flat_rule::AnchorType_NONE, "", ParseResult::SUCCESS},
{std::make_unique<std::string>(""), flat_rule::UrlPatternType_SUBSTRING,
flat_rule::AnchorType_NONE, flat_rule::AnchorType_NONE, "",
ParseResult::ERROR_EMPTY_URL_FILTER},
{std::make_unique<std::string>("|"), flat_rule::UrlPatternType_SUBSTRING,
flat_rule::AnchorType_BOUNDARY, flat_rule::AnchorType_NONE, "",
ParseResult::SUCCESS},
{std::make_unique<std::string>("||"), flat_rule::UrlPatternType_SUBSTRING,
flat_rule::AnchorType_SUBDOMAIN, flat_rule::AnchorType_NONE, "",
ParseResult::SUCCESS},
{std::make_unique<std::string>("|||"),
flat_rule::UrlPatternType_SUBSTRING, flat_rule::AnchorType_SUBDOMAIN,
flat_rule::AnchorType_BOUNDARY, "", ParseResult::SUCCESS},
{std::make_unique<std::string>("|*|||"),
flat_rule::UrlPatternType_WILDCARDED, flat_rule::AnchorType_BOUNDARY,
flat_rule::AnchorType_BOUNDARY, "*||", ParseResult::SUCCESS},
{std::make_unique<std::string>("|xyz|"),
flat_rule::UrlPatternType_SUBSTRING, flat_rule::AnchorType_BOUNDARY,
flat_rule::AnchorType_BOUNDARY, "xyz", ParseResult::SUCCESS},
{std::make_unique<std::string>("||x^yz"),
flat_rule::UrlPatternType_WILDCARDED, flat_rule::AnchorType_SUBDOMAIN,
flat_rule::AnchorType_NONE, "x^yz", ParseResult::SUCCESS},
{std::make_unique<std::string>("||xyz|"),
flat_rule::UrlPatternType_SUBSTRING, flat_rule::AnchorType_SUBDOMAIN,
flat_rule::AnchorType_BOUNDARY, "xyz", ParseResult::SUCCESS},
{std::make_unique<std::string>("x*y|z"),
flat_rule::UrlPatternType_WILDCARDED, flat_rule::AnchorType_NONE,
flat_rule::AnchorType_NONE, "x*y|z", ParseResult::SUCCESS},
{std::make_unique<std::string>("**^"),
flat_rule::UrlPatternType_WILDCARDED, flat_rule::AnchorType_NONE,
flat_rule::AnchorType_NONE, "**^", ParseResult::SUCCESS},
{std::make_unique<std::string>("||google.com"),
flat_rule::UrlPatternType_SUBSTRING, flat_rule::AnchorType_SUBDOMAIN,
flat_rule::AnchorType_NONE, "google.com", ParseResult::SUCCESS},
// Url pattern with non-ascii characters -ⱴase.com.
{std::make_unique<std::string>(base::WideToUTF8(L"\x2c74"
L"ase.com")),
flat_rule::UrlPatternType_SUBSTRING, flat_rule::AnchorType_NONE,
flat_rule::AnchorType_NONE, "", ParseResult::ERROR_NON_ASCII_URL_FILTER},
// Url pattern starting with the domain anchor followed by a wildcard.
{std::make_unique<std::string>("||*xyz"),
flat_rule::UrlPatternType_WILDCARDED, flat_rule::AnchorType_SUBDOMAIN,
flat_rule::AnchorType_NONE, "", ParseResult::ERROR_INVALID_URL_FILTER}};
for (size_t i = 0; i < base::size(cases); ++i) {
SCOPED_TRACE(base::StringPrintf("Testing case[%" PRIuS "]", i));
dnr_api::Rule rule = CreateGenericParsedRule();
rule.condition.url_filter = std::move(cases[i].input_url_filter);
IndexedRule indexed_rule;
ParseResult result = IndexedRule::CreateIndexedRule(
std::move(rule), GetBaseURL(), &indexed_rule);
if (result != ParseResult::SUCCESS)
continue;
EXPECT_EQ(cases[i].expected_result, result);
EXPECT_EQ(cases[i].expected_url_pattern_type,
indexed_rule.url_pattern_type);
EXPECT_EQ(cases[i].expected_anchor_left, indexed_rule.anchor_left);
EXPECT_EQ(cases[i].expected_anchor_right, indexed_rule.anchor_right);
EXPECT_EQ(cases[i].expected_url_pattern, indexed_rule.url_pattern);
}
}
// Ensure case-insensitive patterns are lower-cased as required by
// url_pattern_index.
TEST_F(IndexedRuleTest, CaseInsensitiveLowerCased) {
const std::string kPattern = "/QUERY";
struct {
std::unique_ptr<bool> is_url_filter_case_sensitive;
std::string expected_pattern;
} test_cases[] = {
{std::make_unique<bool>(false), "/query"},
{std::make_unique<bool>(true), "/QUERY"},
{nullptr, "/QUERY"} // By default patterns are case sensitive.
};
for (auto& test_case : test_cases) {
dnr_api::Rule rule = CreateGenericParsedRule();
rule.condition.url_filter = std::make_unique<std::string>(kPattern);
rule.condition.is_url_filter_case_sensitive =
std::move(test_case.is_url_filter_case_sensitive);
IndexedRule indexed_rule;
ASSERT_EQ(ParseResult::SUCCESS,
IndexedRule::CreateIndexedRule(std::move(rule), GetBaseURL(),
&indexed_rule));
EXPECT_EQ(test_case.expected_pattern, indexed_rule.url_pattern);
}
}
TEST_F(IndexedRuleTest, DomainsParsing) {
using DomainVec = std::vector<std::string>;
struct {
std::unique_ptr<DomainVec> domains;
std::unique_ptr<DomainVec> excluded_domains;
const ParseResult expected_result;
// Only valid if |expected_result| is SUCCESS.
const DomainVec expected_domains;
const DomainVec expected_excluded_domains;
} cases[] = {
{nullptr, nullptr, ParseResult::SUCCESS, {}, {}},
{std::make_unique<DomainVec>(),
nullptr,
ParseResult::ERROR_EMPTY_DOMAINS_LIST,
{},
{}},
{nullptr, std::make_unique<DomainVec>(), ParseResult::SUCCESS, {}, {}},
{std::make_unique<DomainVec>(DomainVec({"a.com", "b.com", "a.com"})),
std::make_unique<DomainVec>(
DomainVec({"g.com", "XY.COM", "zzz.com", "a.com", "google.com"})),
ParseResult::SUCCESS,
{"a.com", "a.com", "b.com"},
{"google.com", "zzz.com", "xy.com", "a.com", "g.com"}},
// Domain with non-ascii characters.
{std::make_unique<DomainVec>(
DomainVec({base::WideToUTF8(L"abc\x2010" /*hyphen*/ L"def.com")})),
nullptr,
ParseResult::ERROR_NON_ASCII_DOMAIN,
{},
{}},
// Excluded domain with non-ascii characters.
{nullptr,
std::make_unique<DomainVec>(
DomainVec({base::WideToUTF8(L"36\x00b0"
L"c.com" /*36°c.com*/)})),
ParseResult::ERROR_NON_ASCII_EXCLUDED_DOMAIN,
{},
{}},
// Internationalized domain in punycode.
{std::make_unique<DomainVec>(
DomainVec({"xn--36c-tfa.com" /* punycode for 36°c.com*/})),
nullptr,
ParseResult::SUCCESS,
{"xn--36c-tfa.com"},
{}},
};
for (size_t i = 0; i < base::size(cases); ++i) {
SCOPED_TRACE(base::StringPrintf("Testing case[%" PRIuS "]", i));
dnr_api::Rule rule = CreateGenericParsedRule();
rule.condition.domains = std::move(cases[i].domains);
rule.condition.excluded_domains = std::move(cases[i].excluded_domains);
IndexedRule indexed_rule;
ParseResult result = IndexedRule::CreateIndexedRule(
std::move(rule), GetBaseURL(), &indexed_rule);
EXPECT_EQ(cases[i].expected_result, result);
if (result == ParseResult::SUCCESS) {
EXPECT_EQ(cases[i].expected_domains, indexed_rule.domains);
EXPECT_EQ(cases[i].expected_excluded_domains,
indexed_rule.excluded_domains);
}
}
}
TEST_F(IndexedRuleTest, RedirectUrlParsing) {
struct {
const char* redirect_url;
const ParseResult expected_result;
// Only valid if |expected_result| is SUCCESS.
const std::string expected_redirect_url;
} cases[] = {
{"", ParseResult::ERROR_INVALID_REDIRECT_URL, ""},
{"http://google.com", ParseResult::SUCCESS, "http://google.com"},
{"/relative/url?q=1", ParseResult::ERROR_INVALID_REDIRECT_URL, ""},
{"abc", ParseResult::ERROR_INVALID_REDIRECT_URL, ""}};
for (size_t i = 0; i < base::size(cases); ++i) {
SCOPED_TRACE(base::StringPrintf("Testing case[%" PRIuS "]", i));
dnr_api::Rule rule = CreateGenericParsedRule();
rule.action.redirect = MakeRedirectUrl(cases[i].redirect_url);
rule.action.type = dnr_api::RULE_ACTION_TYPE_REDIRECT;
IndexedRule indexed_rule;
ParseResult result = IndexedRule::CreateIndexedRule(
std::move(rule), GetBaseURL(), &indexed_rule);
EXPECT_EQ(cases[i].expected_result, result) << static_cast<int>(result);
if (result == ParseResult::SUCCESS)
EXPECT_EQ(cases[i].expected_redirect_url, indexed_rule.redirect_url);
}
}
TEST_F(IndexedRuleTest, RedirectParsing) {
struct {
std::string redirect_dictionary_json;
ParseResult expected_result;
base::Optional<std::string> expected_redirect_url;
} cases[] = {
// clang-format off
{
"{}",
ParseResult::ERROR_INVALID_REDIRECT,
base::nullopt
},
{
R"({"url": "xyz"})",
ParseResult::ERROR_INVALID_REDIRECT_URL,
base::nullopt
},
{
R"({"url": "javascript:window.alert(\"hello,world\");"})",
ParseResult::ERROR_JAVASCRIPT_REDIRECT,
base::nullopt
},
{
R"({"url": "http://google.com"})",
ParseResult::SUCCESS,
std::string("http://google.com")
},
{
R"({"extensionPath": "foo/xyz/"})",
ParseResult::ERROR_INVALID_EXTENSION_PATH,
base::nullopt
},
{
R"({"extensionPath": "/foo/xyz?q=1"})",
ParseResult::SUCCESS,
GetBaseURL().Resolve("/foo/xyz?q=1").spec()
},
{
R"(
{
"transform": {
"scheme": "",
"host": "foo.com"
}
})", ParseResult::ERROR_INVALID_TRANSFORM_SCHEME, base::nullopt
},
{
R"(
{
"transform": {
"scheme": "javascript",
"host": "foo.com"
}
})", ParseResult::ERROR_INVALID_TRANSFORM_SCHEME, base::nullopt
},
{
R"(
{
"transform": {
"scheme": "http",
"port": "-1"
}
})", ParseResult::ERROR_INVALID_TRANSFORM_PORT, base::nullopt
},
{
R"(
{
"transform": {
"scheme": "http",
"query": "abc"
}
})", ParseResult::ERROR_INVALID_TRANSFORM_QUERY, base::nullopt
},
{
R"({"transform": {"path": "abc"}})",
ParseResult::SUCCESS,
base::nullopt
},
{
R"({"transform": {"fragment": "abc"}})",
ParseResult::ERROR_INVALID_TRANSFORM_FRAGMENT,
base::nullopt
},
{
R"({"transform": {"path": ""}})",
ParseResult::SUCCESS,
base::nullopt
},
{
R"(
{
"transform": {
"scheme": "http",
"query": "?abc",
"queryTransform": {
"removeParams": ["abc"]
}
}
})", ParseResult::ERROR_QUERY_AND_TRANSFORM_BOTH_SPECIFIED, base::nullopt
},
{
R"(
{
"transform": {
"scheme": "https",
"host": "foo.com",
"port": "80",
"path": "/foo",
"queryTransform": {
"removeParams": ["x1", "x2"],
"addOrReplaceParams": [
{"key": "y1", "value": "foo"}
]
},
"fragment": "",
"username": "user"
}
})", ParseResult::SUCCESS, base::nullopt
}
};
// clang-format on
for (size_t i = 0; i < base::size(cases); ++i) {
SCOPED_TRACE(base::StringPrintf("Testing case[%" PRIuS "]", i));
dnr_api::Rule rule = CreateGenericParsedRule();
rule.action.type = dnr_api::RULE_ACTION_TYPE_REDIRECT;
base::Optional<base::Value> redirect_val =
base::JSONReader::Read(cases[i].redirect_dictionary_json);
ASSERT_TRUE(redirect_val);
base::string16 error;
rule.action.redirect = dnr_api::Redirect::FromValue(*redirect_val, &error);
ASSERT_TRUE(rule.action.redirect);
ASSERT_TRUE(error.empty());
IndexedRule indexed_rule;
ParseResult result = IndexedRule::CreateIndexedRule(
std::move(rule), GetBaseURL(), &indexed_rule);
EXPECT_EQ(cases[i].expected_result, result) << static_cast<int>(result);
if (result != ParseResult::SUCCESS)
continue;
EXPECT_TRUE(indexed_rule.url_transform || indexed_rule.redirect_url);
EXPECT_FALSE(indexed_rule.url_transform && indexed_rule.redirect_url);
EXPECT_EQ(cases[i].expected_redirect_url, indexed_rule.redirect_url);
}
}
TEST_F(IndexedRuleTest, RegexFilterParsing) {
struct {
std::string regex_filter;
ParseResult result;
} cases[] = {{"", ParseResult::ERROR_EMPTY_REGEX_FILTER},
// Filter with non-ascii characters.
{"αcd", ParseResult::ERROR_NON_ASCII_REGEX_FILTER},
// Invalid regex: Unterminated character class.
{"x[ab", ParseResult::ERROR_INVALID_REGEX_FILTER},
// Invalid regex: Incomplete capturing group.
{"x(", ParseResult::ERROR_INVALID_REGEX_FILTER},
// Invalid regex: Invalid escape sequence \x.
{R"(ij\x1)", ParseResult::ERROR_INVALID_REGEX_FILTER},
{R"(ij\\x1)", ParseResult::SUCCESS},
{R"(^http://www\.(abc|def)\.xyz\.com/)", ParseResult::SUCCESS}};
for (const auto& test_case : cases) {
SCOPED_TRACE(test_case.regex_filter);
dnr_api::Rule rule = CreateGenericParsedRule();
rule.condition.url_filter.reset();
rule.condition.regex_filter =
std::make_unique<std::string>(test_case.regex_filter);
IndexedRule indexed_rule;
ParseResult result = IndexedRule::CreateIndexedRule(
std::move(rule), GetBaseURL(), &indexed_rule);
EXPECT_EQ(result, test_case.result);
if (result == ParseResult::SUCCESS) {
EXPECT_EQ(indexed_rule.url_pattern, test_case.regex_filter);
EXPECT_EQ(flat_rule::UrlPatternType_REGEXP,
indexed_rule.url_pattern_type);
}
}
}
TEST_F(IndexedRuleTest, MultipleFiltersSpecified) {
dnr_api::Rule rule = CreateGenericParsedRule();
rule.condition.url_filter = std::make_unique<std::string>("google");
rule.condition.regex_filter = std::make_unique<std::string>("example");
IndexedRule indexed_rule;
ParseResult result = IndexedRule::CreateIndexedRule(
std::move(rule), GetBaseURL(), &indexed_rule);
EXPECT_EQ(ParseResult::ERROR_MULTIPLE_FILTERS_SPECIFIED, result);
}
TEST_F(IndexedRuleTest, RegexSubstitutionParsing) {
struct {
// |regex_filter| may be null.
const char* regex_filter;
std::string regex_substitution;
ParseResult result;
} cases[] = {
{nullptr, "http://google.com",
ParseResult::ERROR_REGEX_SUBSTITUTION_WITHOUT_FILTER},
// \0 in |regex_substitution| refers to the entire matching text.
{R"(^http://(.*)\.com/)", R"(https://redirect.com?referrer=\0)",
ParseResult::SUCCESS},
{R"(^http://google\.com?q1=(.*)&q2=(.*))",
R"(https://redirect.com?&q1=\0&q2=\2)", ParseResult::SUCCESS},
// Referencing invalid capture group.
{R"(^http://google\.com?q1=(.*)&q2=(.*))",
R"(https://redirect.com?&q1=\1&q2=\3)",
ParseResult::ERROR_INVALID_REGEX_SUBSTITUTION},
// Empty substitution.
{R"(^http://(.*)\.com/)", "",
ParseResult::ERROR_INVALID_REGEX_SUBSTITUTION},
// '\' must always be followed by a '\' or a digit.
{R"(^http://(.*)\.com/)", R"(https://example.com?q=\a)",
ParseResult::ERROR_INVALID_REGEX_SUBSTITUTION},
};
for (const auto& test_case : cases) {
SCOPED_TRACE(test_case.regex_substitution);
dnr_api::Rule rule = CreateGenericParsedRule();
rule.condition.url_filter.reset();
if (test_case.regex_filter) {
rule.condition.regex_filter =
std::make_unique<std::string>(test_case.regex_filter);
}
rule.priority = std::make_unique<int>(kMinValidPriority);
rule.action.type = dnr_api::RULE_ACTION_TYPE_REDIRECT;
rule.action.redirect = std::make_unique<dnr_api::Redirect>();
rule.action.redirect->regex_substitution =
std::make_unique<std::string>(test_case.regex_substitution);
IndexedRule indexed_rule;
ParseResult result = IndexedRule::CreateIndexedRule(
std::move(rule), GetBaseURL(), &indexed_rule);
EXPECT_EQ(test_case.result, result);
if (result == ParseResult::SUCCESS) {
EXPECT_EQ(flat_rule::UrlPatternType_REGEXP,
indexed_rule.url_pattern_type);
ASSERT_TRUE(indexed_rule.regex_substitution);
EXPECT_EQ(test_case.regex_substitution, *indexed_rule.regex_substitution);
}
}
}
// Tests the parsing behavior when multiple keys in "Redirect" dictionary are
// specified.
TEST_F(IndexedRuleTest, MultipleRedirectKeys) {
dnr_api::Rule rule = CreateGenericParsedRule();
rule.priority = std::make_unique<int>(kMinValidPriority);
rule.condition.url_filter.reset();
rule.condition.regex_filter = std::make_unique<std::string>("\\.*");
rule.action.type = dnr_api::RULE_ACTION_TYPE_REDIRECT;
rule.action.redirect = std::make_unique<dnr_api::Redirect>();
dnr_api::Redirect& redirect = *rule.action.redirect;
redirect.url = std::make_unique<std::string>("http://google.com");
redirect.regex_substitution =
std::make_unique<std::string>("http://example.com");
redirect.transform = std::make_unique<dnr_api::URLTransform>();
redirect.transform->scheme = std::make_unique<std::string>("https");
IndexedRule indexed_rule;
ParseResult result = IndexedRule::CreateIndexedRule(
std::move(rule), GetBaseURL(), &indexed_rule);
EXPECT_EQ(ParseResult::SUCCESS, result);
// The redirect "url" is given preference in this case.
EXPECT_FALSE(indexed_rule.url_transform);
EXPECT_FALSE(indexed_rule.regex_substitution);
EXPECT_EQ("http://google.com", indexed_rule.redirect_url);
}
TEST_F(IndexedRuleTest, InvalidAllowAllRequestsResourceType) {
using ResourceTypeVec = std::vector<dnr_api::ResourceType>;
struct {
ResourceTypeVec resource_types;
ResourceTypeVec excluded_resource_types;
const ParseResult expected_result;
// Only valid if |expected_result| is SUCCESS.
const uint16_t expected_element_types;
} cases[] = {
{{}, {}, ParseResult::ERROR_INVALID_ALLOW_ALL_REQUESTS_RESOURCE_TYPE, 0},
{{dnr_api::RESOURCE_TYPE_SUB_FRAME},
{dnr_api::RESOURCE_TYPE_SCRIPT},
ParseResult::SUCCESS,
flat_rule::ElementType_SUBDOCUMENT},
{{dnr_api::RESOURCE_TYPE_SCRIPT, dnr_api::RESOURCE_TYPE_MAIN_FRAME},
{},
ParseResult::ERROR_INVALID_ALLOW_ALL_REQUESTS_RESOURCE_TYPE,
0},
{{dnr_api::RESOURCE_TYPE_MAIN_FRAME, dnr_api::RESOURCE_TYPE_SUB_FRAME},
{},
ParseResult::SUCCESS,
flat_rule::ElementType_MAIN_FRAME | flat_rule::ElementType_SUBDOCUMENT},
{{dnr_api::RESOURCE_TYPE_MAIN_FRAME},
{},
ParseResult::SUCCESS,
flat_rule::ElementType_MAIN_FRAME},
};
for (size_t i = 0; i < base::size(cases); ++i) {
SCOPED_TRACE(base::StringPrintf("Testing case[%" PRIuS "]", i));
dnr_api::Rule rule = CreateGenericParsedRule();
if (cases[i].resource_types.empty())
rule.condition.resource_types = nullptr;
else
rule.condition.resource_types =
std::make_unique<ResourceTypeVec>(cases[i].resource_types);
rule.condition.excluded_resource_types =
std::make_unique<ResourceTypeVec>(cases[i].excluded_resource_types);
rule.action.type = dnr_api::RULE_ACTION_TYPE_ALLOWALLREQUESTS;
IndexedRule indexed_rule;
ParseResult result = IndexedRule::CreateIndexedRule(
std::move(rule), GetBaseURL(), &indexed_rule);
EXPECT_EQ(cases[i].expected_result, result);
if (result == ParseResult::SUCCESS)
EXPECT_EQ(cases[i].expected_element_types, indexed_rule.element_types);
}
}
TEST_F(IndexedRuleTest, ModifyHeadersParsing) {
struct RawHeaderInfo {
dnr_api::HeaderOperation operation;
std::string header;
base::Optional<std::string> value;
};
using RawHeaderInfoList = std::vector<RawHeaderInfo>;
using ModifyHeaderInfoList = std::vector<dnr_api::ModifyHeaderInfo>;
// A copy-able version of dnr_api::ModifyHeaderInfo is used for ease of
// specifying test cases because elements are copied when initializing a
// vector from an array.
struct {
base::Optional<RawHeaderInfoList> request_headers;
base::Optional<RawHeaderInfoList> response_headers;
ParseResult expected_result;
} cases[] = {
// Raise an error if no headers are specified.
{base::nullopt, base::nullopt, ParseResult::ERROR_NO_HEADERS_SPECIFIED},
// Raise an error if the request or response headers list is specified,
// but empty.
{RawHeaderInfoList(),
RawHeaderInfoList(
{{dnr_api::HEADER_OPERATION_REMOVE, "set-cookie", base::nullopt}}),
ParseResult::ERROR_EMPTY_REQUEST_HEADERS_LIST},
{base::nullopt, RawHeaderInfoList(),
ParseResult::ERROR_EMPTY_RESPONSE_HEADERS_LIST},
// Raise an error if a header list contains an empty or invalid header
// name.
{base::nullopt,
RawHeaderInfoList(
{{dnr_api::HEADER_OPERATION_REMOVE, "", base::nullopt}}),
ParseResult::ERROR_INVALID_HEADER_NAME},
{base::nullopt,
RawHeaderInfoList(
{{dnr_api::HEADER_OPERATION_REMOVE, "<<invalid>>", base::nullopt}}),
ParseResult::ERROR_INVALID_HEADER_NAME},
// Raise an error if a header list contains an invalid header value.
{base::nullopt,
RawHeaderInfoList({{dnr_api::HEADER_OPERATION_APPEND, "set-cookie",
"invalid\nvalue"}}),
ParseResult::ERROR_INVALID_HEADER_VALUE},
// Raise an error if a header value is specified for a remove rule.
{RawHeaderInfoList(
{{dnr_api::HEADER_OPERATION_REMOVE, "cookie", "remove"}}),
base::nullopt, ParseResult::ERROR_HEADER_VALUE_PRESENT},
// Raise an error if no header value is specified for an append or set
// rule.
{RawHeaderInfoList(
{{dnr_api::HEADER_OPERATION_SET, "cookie", base::nullopt}}),
base::nullopt, ParseResult::ERROR_HEADER_VALUE_NOT_SPECIFIED},
{base::nullopt,
RawHeaderInfoList(
{{dnr_api::HEADER_OPERATION_APPEND, "set-cookie", base::nullopt}}),
ParseResult::ERROR_HEADER_VALUE_NOT_SPECIFIED},
// Raise an error if a rule specifies a request header to be appended.
{RawHeaderInfoList(
{{dnr_api::HEADER_OPERATION_APPEND, "cookie", "cookie-value"}}),
base::nullopt, ParseResult::ERROR_APPEND_REQUEST_HEADER_UNSUPPORTED},
{RawHeaderInfoList(
{{dnr_api::HEADER_OPERATION_REMOVE, "cookie", base::nullopt},
{dnr_api::HEADER_OPERATION_SET, "referer", ""}}),
base::nullopt, ParseResult::SUCCESS},
{RawHeaderInfoList(
{{dnr_api::HEADER_OPERATION_REMOVE, "referer", base::nullopt}}),
RawHeaderInfoList(
{{dnr_api::HEADER_OPERATION_APPEND, "set-cookie", "abcd"}}),
ParseResult::SUCCESS},
};
for (size_t i = 0; i < base::size(cases); ++i) {
SCOPED_TRACE(base::StringPrintf("Testing case[%" PRIuS "]", i));
dnr_api::Rule rule = CreateGenericParsedRule();
rule.action.type = dnr_api::RULE_ACTION_TYPE_MODIFYHEADERS;
ModifyHeaderInfoList expected_request_headers;
if (cases[i].request_headers) {
rule.action.request_headers = std::make_unique<ModifyHeaderInfoList>();
for (auto header : *cases[i].request_headers) {
rule.action.request_headers->push_back(CreateModifyHeaderInfo(
header.operation, header.header, header.value));
expected_request_headers.push_back(CreateModifyHeaderInfo(
header.operation, header.header, header.value));
}
}
ModifyHeaderInfoList expected_response_headers;
if (cases[i].response_headers) {
rule.action.response_headers = std::make_unique<ModifyHeaderInfoList>();
for (auto header : *cases[i].response_headers) {
rule.action.response_headers->push_back(CreateModifyHeaderInfo(
header.operation, header.header, header.value));
expected_response_headers.push_back(CreateModifyHeaderInfo(
header.operation, header.header, header.value));
}
}
IndexedRule indexed_rule;
ParseResult result = IndexedRule::CreateIndexedRule(
std::move(rule), GetBaseURL(), &indexed_rule);
EXPECT_EQ(cases[i].expected_result, result);
if (result != ParseResult::SUCCESS)
continue;
EXPECT_EQ(dnr_api::RULE_ACTION_TYPE_MODIFYHEADERS,
indexed_rule.action_type);
EXPECT_TRUE(std::equal(
expected_request_headers.begin(), expected_request_headers.end(),
indexed_rule.request_headers.begin(), EqualsForTesting));
EXPECT_TRUE(std::equal(
expected_response_headers.begin(), expected_response_headers.end(),
indexed_rule.response_headers.begin(), EqualsForTesting));
}
}
} // namespace
} // namespace declarative_net_request
} // namespace extensions
| 38.561247 | 80 | 0.675292 | [
"vector",
"transform"
] |
a33fc21d9bcd63ac7ecef0a8b8c07f9f15eaa61c | 4,531 | cpp | C++ | luogu/1002.cpp | windcry1/My-ACM-ICPC | b85b1c83b72c6b51731dae946a0df57c31d3e7a1 | [
"MIT"
] | null | null | null | luogu/1002.cpp | windcry1/My-ACM-ICPC | b85b1c83b72c6b51731dae946a0df57c31d3e7a1 | [
"MIT"
] | null | null | null | luogu/1002.cpp | windcry1/My-ACM-ICPC | b85b1c83b72c6b51731dae946a0df57c31d3e7a1 | [
"MIT"
] | null | null | null | /*************************************************************************
>>> Author: WindCry1
>>> Mail: lanceyu120@gmail.com
>>> Website: https://windcry1.com
>>> Date: 12/30/2019 11:03:37 PM
*************************************************************************/
#include <cstring>
#include <cmath>
#include <cstdio>
#include <cctype>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <iostream>
#include <string>
#include <queue>
#include <set>
#include <map>
#include <algorithm>
#include <complex>
#include <stack>
#include <bitset>
#include <iomanip>
#include <list>
#include <sstream>
#include <fstream>
#if __cplusplus >= 201103L
#include <unordered_map>
#include <unordered_set>
#endif
#define endl '\n'
#define ll long long
#define ull unsigned long long
#define DEBUG(x) cout<<#x<<" : "<<x<<endl;
#define lowbit(x) x&(-x)
#define ls u<<1
#define rs u<<1|1
using namespace std;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
const double eps = 1e-8;
const int INF = 0x3f3f3f3f;
const int mod = 1e9+7;
const int dir[4][2]={-1,0,1,0,0,-1,0,1};
namespace IN {
const int MAX_INPUT = 1000000;
#define getc() (p1 == p2 && (p2 = (p1 = buf) + inbuf -> sgetn(buf, MAX_INPUT), p1 == p2) ? EOF : *p1++)
char buf[MAX_INPUT], *p1, *p2;
template <typename T> inline bool redi(T &x) {
static std::streambuf *inbuf = cin.rdbuf();
x = 0;
register int f = 0, flag = false;
register char ch = getc();
while (!std::isdigit(ch)) {
if (ch == '-') f = 1;
ch = getc();
}
if (std::isdigit(ch)) x = x * 10 + ch - '0', ch = getc(),flag = true;
while (std::isdigit(ch)) {
x = x * 10 + ch - 48;
ch = getc();
}
x = f ? -x : x ;
return flag;
}
template <typename T,typename ...Args> inline bool redi(T& a,Args& ...args) {
return redi(a) && redi(args...);
}
#undef getc
}
namespace OUT {
template <typename T> inline void put(T x) {
static std::streambuf *outbuf = cout.rdbuf();
static char stack[21];
static int top = 0;
if (x < 0) {
outbuf -> sputc('-');
x=-x;
}
if (!x) {
outbuf -> sputc('0');
return;
}
while (x) {
stack[++top] = x % 10 + '0';
x /= 10;
}
while (top) {
outbuf -> sputc(stack[top]);
-- top;
}
}
inline void putc (const char ch) {
static std::streambuf *outbuf = cout.rdbuf();
outbuf -> sputc(ch);
}
template <typename T> inline void put(const char ch,T x)
{
static std::streambuf *outbuf = cout.rdbuf();
static char stack[21];
static int top = 0;
if (x < 0) {
outbuf -> sputc('-');
x=-x;
}
if (!x) {
outbuf -> sputc('0');
outbuf -> sputc(ch);
return;
}
while (x) {
stack[++top] = x % 10 + '0';
x /= 10;
}
while (top) {
outbuf -> sputc(stack[top]);
--top;
}
outbuf -> sputc(ch);
}
template<typename T,typename ...Args> inline void put(T a,Args ...args) {
put(a);put(args...);
}
template<typename T,typename ...Args> inline void put(const char ch,T a,Args ...args) {
put(ch,a);put(ch,args...);
}
}
//using namespace IN;
//using namespace OUT;
ll dp[30][30];
int main(){
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#ifdef WindCry1
freopen("C:\\Users\\LENOVO\\Desktop\\in.txt","r",stdin);
#endif
int x1,y1,x2,y2;
cin>>x1>>y1>>x2>>y2;
set<pii> s;
s.insert(make_pair(x2,y2));
s.insert(make_pair(x2+1,y2+2)); s.insert(make_pair(x2+2,y2+1));
s.insert(make_pair(x2+1,y2-2)); s.insert(make_pair(x2+2,y2-1));
s.insert(make_pair(x2-1,y2+2)); s.insert(make_pair(x2-2,y2+1));
s.insert(make_pair(x2-1,y2-2)); s.insert(make_pair(x2-2,y2-1));
#ifdef WindCry1
for(auto i:s) cout<<i.first<<" "<<i.second<<endl;
#endif
for(int i=0;i<=x1;i++) {
if(!s.count(make_pair(i,0))) dp[i][0]=1;
else break;
}
for(int i=0;i<=y1;i++) {
if(!s.count(make_pair(0,i))) dp[0][i]=1;
else break;
}
for(int i=1;i<=x1;i++){
for(int j=1;j<=y1;j++){
if(!s.count(make_pair(i,j)))
dp[i][j]=dp[i-1][j]+dp[i][j-1];
}
}
#ifdef WindCry1
for(int i=0;i<=x1;i++){
for(int j=0;j<=y1;j++){
cout<<dp[i][j]<<" ";
}
cout<<endl;
}
#endif
cout<<dp[x1][y1]<<endl;
return 0;
}
| 26.04023 | 107 | 0.510704 | [
"vector"
] |
a33fdd1bb99209d99f103d879701725724e6c397 | 12,343 | cpp | C++ | hphp/runtime/ext/json/ext_json.cpp | atdt/hhvm | 63fe59e67d0129090ccb4c096e66dcfc92031f94 | [
"PHP-3.01",
"Zend-2.0"
] | 1 | 2015-02-12T07:24:28.000Z | 2015-02-12T07:24:28.000Z | hphp/runtime/ext/json/ext_json.cpp | atdt/hhvm | 63fe59e67d0129090ccb4c096e66dcfc92031f94 | [
"PHP-3.01",
"Zend-2.0"
] | null | null | null | hphp/runtime/ext/json/ext_json.cpp | atdt/hhvm | 63fe59e67d0129090ccb4c096e66dcfc92031f94 | [
"PHP-3.01",
"Zend-2.0"
] | 1 | 2015-06-16T05:47:12.000Z | 2015-06-16T05:47:12.000Z | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2014 Facebook, Inc. (http://www.facebook.com) |
| Copyright (c) 1997-2010 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/ext/json/ext_json.h"
#include "hphp/runtime/ext/json/JSON_parser.h"
#include "hphp/runtime/ext/string/ext_string.h"
#include "hphp/runtime/base/array-data-defs.h"
#include "hphp/runtime/base/utf8-decode.h"
#include "hphp/runtime/base/variable-serializer.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
// json_encode() options
const int64_t k_JSON_HEX_TAG = 1<<0;
const int64_t k_JSON_HEX_AMP = 1<<1;
const int64_t k_JSON_HEX_APOS = 1<<2;
const int64_t k_JSON_HEX_QUOT = 1<<3;
const int64_t k_JSON_FORCE_OBJECT = 1<<4;
const int64_t k_JSON_NUMERIC_CHECK = 1<<5;
const int64_t k_JSON_UNESCAPED_SLASHES = 1<<6;
const int64_t k_JSON_PRETTY_PRINT = 1<<7;
const int64_t k_JSON_UNESCAPED_UNICODE = 1<<8;
const int64_t k_JSON_PARTIAL_OUTPUT_ON_ERROR = 1<<9;
// json_decode() options
const int64_t k_JSON_BIGINT_AS_STRING = 1<<1;
// FB json_decode() options
// intentionally higher so when PHP adds more options we're fine
const int64_t k_JSON_FB_LOOSE = 1<<20;
const int64_t k_JSON_FB_UNLIMITED = 1<<21;
const int64_t k_JSON_FB_EXTRA_ESCAPES = 1<<22;
const int64_t k_JSON_FB_COLLECTIONS = 1<<23;
const int64_t k_JSON_FB_STABLE_MAPS = 1<<24;
const int64_t k_JSON_ERROR_NONE
= json_error_codes::JSON_ERROR_NONE;
const int64_t k_JSON_ERROR_DEPTH
= json_error_codes::JSON_ERROR_DEPTH;
const int64_t k_JSON_ERROR_STATE_MISMATCH
= json_error_codes::JSON_ERROR_STATE_MISMATCH;
const int64_t k_JSON_ERROR_CTRL_CHAR
= json_error_codes::JSON_ERROR_CTRL_CHAR;
const int64_t k_JSON_ERROR_SYNTAX
= json_error_codes::JSON_ERROR_SYNTAX;
const int64_t k_JSON_ERROR_UTF8
= json_error_codes::JSON_ERROR_UTF8;
const int64_t k_JSON_ERROR_RECURSION
= json_error_codes::JSON_ERROR_RECURSION;
const int64_t k_JSON_ERROR_INF_OR_NAN
= json_error_codes::JSON_ERROR_INF_OR_NAN;
const int64_t k_JSON_ERROR_UNSUPPORTED_TYPE
= json_error_codes::JSON_ERROR_UNSUPPORTED_TYPE;
///////////////////////////////////////////////////////////////////////////////
int64_t HHVM_FUNCTION(json_last_error) {
return (int) json_get_last_error_code();
}
String HHVM_FUNCTION(json_last_error_msg) {
return json_get_last_error_msg();
}
// Handles output of `json_encode` with fallback value for
// partial output on errors, and `false` otherwise.
Variant json_guard_error_result(const String& partial_error_output,
int64_t options /* = 0*/) {
int is_partial_output = options & k_JSON_PARTIAL_OUTPUT_ON_ERROR;
// Issue a warning on unsupported type in case of HH syntax.
if (json_get_last_error_code() ==
json_error_codes::JSON_ERROR_UNSUPPORTED_TYPE &&
RuntimeOption::EnableHipHopSyntax) {
// Unhandled case is always returned as `false`; for partial output
// we render "null" value.
raise_warning("json_encode(): type is unsupported, encoded as %s",
is_partial_output ? "null" : "false");
}
if (is_partial_output) {
return partial_error_output;
}
return false;
}
Variant HHVM_FUNCTION(json_encode, const Variant& value,
int64_t options /* = 0 */,
int64_t depth /* = 512 */) {
// Special case for resource since VariableSerializer does not take care of it
if (value.isResource()) {
json_set_last_error_code(json_error_codes::JSON_ERROR_UNSUPPORTED_TYPE);
return json_guard_error_result("null", options);
}
json_set_last_error_code(json_error_codes::JSON_ERROR_NONE);
VariableSerializer vs(VariableSerializer::Type::JSON, options);
vs.setDepthLimit(depth);
String json = vs.serializeValue(value, !(options & k_JSON_FB_UNLIMITED));
if (json_get_last_error_code() != json_error_codes::JSON_ERROR_NONE) {
return json_guard_error_result(json, options);
}
return json;
}
Variant HHVM_FUNCTION(json_decode, const String& json, bool assoc /* = false */,
int64_t depth /* = 512 */, int64_t options /* = 0 */) {
json_set_last_error_code(json_error_codes::JSON_ERROR_NONE);
if (json.empty()) {
return init_null();
}
const int64_t supported_options =
k_JSON_FB_LOOSE |
k_JSON_FB_COLLECTIONS |
k_JSON_FB_STABLE_MAPS |
k_JSON_BIGINT_AS_STRING;
int64_t parser_options = options & supported_options;
Variant z;
if (JSON_parser(z, json.data(), json.size(), assoc, depth, parser_options)) {
return z;
}
String trimmed = HHVM_FN(trim)(json, "\t\n\r ");
if (trimmed.size() == 4) {
if (!strcasecmp(trimmed.data(), "null")) {
json_set_last_error_code(json_error_codes::JSON_ERROR_NONE);
return init_null();
}
if (!strcasecmp(trimmed.data(), "true")) {
json_set_last_error_code(json_error_codes::JSON_ERROR_NONE);
return true;
}
} else if (trimmed.size() == 5 && !strcasecmp(trimmed.data(), "false")) {
json_set_last_error_code(json_error_codes::JSON_ERROR_NONE);
return false;
}
int64_t p;
double d;
DataType type = json.get()->isNumericWithVal(p, d, 0);
if (type == KindOfInt64) {
json_set_last_error_code(json_error_codes::JSON_ERROR_NONE);
return p;
} else if (type == KindOfDouble) {
json_set_last_error_code(json_error_codes::JSON_ERROR_NONE);
if ((options & k_JSON_BIGINT_AS_STRING) &&
(json.toInt64() == LLONG_MAX || json.toInt64() == LLONG_MIN)
&& errno == ERANGE) { // Overflow
bool is_float = false;
for (int i = (trimmed[0] == '-' ? 1 : 0); i < trimmed.size(); ++i) {
if (trimmed[i] < '0' || trimmed[i] > '9') {
is_float = true;
break;
}
}
if (!is_float) {
return trimmed;
}
}
return d;
}
char ch0 = json.charAt(0);
if (json.size() > 1 && ch0 == '"' && json.charAt(json.size() - 1) == '"') {
json_set_last_error_code(json_error_codes::JSON_ERROR_NONE);
// Wrap the string in an array to allow the JSON_parser to handle
// things like unicode escape sequences, then unwrap to get result
String wrapped("[");
wrapped += json + "]";
// Stick to a normal hhvm array for the wrapper
const int64_t mask = ~(k_JSON_FB_COLLECTIONS | k_JSON_FB_STABLE_MAPS);
if (JSON_parser(z, wrapped.data(), wrapped.size(), false, depth,
parser_options & mask) && z.isArray()) {
Array arr = z.toArray();
if ((arr.size() == 1) && arr.exists(0)) {
return arr[0];
}
// The input string could be something like: "foo","bar"
// Which will parse inside the [] wrapper, but be invalid
json_set_last_error_code(json_error_codes::JSON_ERROR_SYNTAX);
}
}
if ((options & k_JSON_FB_LOOSE) && json.size() > 1 &&
ch0 == '\'' && json.charAt(json.size() - 1) == '\'') {
json_set_last_error_code(json_error_codes::JSON_ERROR_NONE);
return json.substr(1, json.size() - 2);
}
assert(json_get_last_error_code() != json_error_codes::JSON_ERROR_NONE);
return init_null();
}
///////////////////////////////////////////////////////////////////////////////
const StaticString
s_JSON_HEX_TAG("JSON_HEX_TAG"),
s_JSON_HEX_AMP("JSON_HEX_AMP"),
s_JSON_HEX_APOS("JSON_HEX_APOS"),
s_JSON_HEX_QUOT("JSON_HEX_QUOT"),
s_JSON_FORCE_OBJECT("JSON_FORCE_OBJECT"),
s_JSON_NUMERIC_CHECK("JSON_NUMERIC_CHECK"),
s_JSON_UNESCAPED_SLASHES("JSON_UNESCAPED_SLASHES"),
s_JSON_PRETTY_PRINT("JSON_PRETTY_PRINT"),
s_JSON_UNESCAPED_UNICODE("JSON_UNESCAPED_UNICODE"),
s_JSON_PARTIAL_OUTPUT_ON_ERROR("JSON_PARTIAL_OUTPUT_ON_ERROR"),
s_JSON_BIGINT_AS_STRING("JSON_BIGINT_AS_STRING"),
s_JSON_FB_LOOSE("JSON_FB_LOOSE"),
s_JSON_FB_UNLIMITED("JSON_FB_UNLIMITED"),
s_JSON_FB_EXTRA_ESCAPES("JSON_FB_EXTRA_ESCAPES"),
s_JSON_FB_COLLECTIONS("JSON_FB_COLLECTIONS"),
s_JSON_FB_STABLE_MAPS("JSON_FB_STABLE_MAPS"),
s_JSON_ERROR_NONE("JSON_ERROR_NONE"),
s_JSON_ERROR_DEPTH("JSON_ERROR_DEPTH"),
s_JSON_ERROR_STATE_MISMATCH("JSON_ERROR_STATE_MISMATCH"),
s_JSON_ERROR_CTRL_CHAR("JSON_ERROR_CTRL_CHAR"),
s_JSON_ERROR_SYNTAX("JSON_ERROR_SYNTAX"),
s_JSON_ERROR_UTF8("JSON_ERROR_UTF8"),
s_JSON_ERROR_RECURSION("JSON_ERROR_RECURSION"),
s_JSON_ERROR_INF_OR_NAN("JSON_ERROR_INF_OR_NAN"),
s_JSON_ERROR_UNSUPPORTED_TYPE("JSON_ERROR_UNSUPPORTED_TYPE");
class JsonExtension final : public Extension {
public:
JsonExtension() : Extension("json", "1.2.1") {}
void moduleInit() override {
Native::registerConstant<KindOfInt64>(
s_JSON_HEX_TAG.get(), k_JSON_HEX_TAG
);
Native::registerConstant<KindOfInt64>(
s_JSON_HEX_AMP.get(), k_JSON_HEX_AMP
);
Native::registerConstant<KindOfInt64>(
s_JSON_HEX_APOS.get(), k_JSON_HEX_APOS
);
Native::registerConstant<KindOfInt64>(
s_JSON_HEX_QUOT.get(), k_JSON_HEX_QUOT
);
Native::registerConstant<KindOfInt64>(
s_JSON_FORCE_OBJECT.get(), k_JSON_FORCE_OBJECT
);
Native::registerConstant<KindOfInt64>(
s_JSON_NUMERIC_CHECK.get(), k_JSON_NUMERIC_CHECK
);
Native::registerConstant<KindOfInt64>(
s_JSON_UNESCAPED_SLASHES.get(), k_JSON_UNESCAPED_SLASHES
);
Native::registerConstant<KindOfInt64>(
s_JSON_PRETTY_PRINT.get(), k_JSON_PRETTY_PRINT
);
Native::registerConstant<KindOfInt64>(
s_JSON_UNESCAPED_UNICODE.get(), k_JSON_UNESCAPED_UNICODE
);
Native::registerConstant<KindOfInt64>(
s_JSON_PARTIAL_OUTPUT_ON_ERROR.get(), k_JSON_PARTIAL_OUTPUT_ON_ERROR
);
Native::registerConstant<KindOfInt64>(
s_JSON_BIGINT_AS_STRING.get(), k_JSON_BIGINT_AS_STRING
);
Native::registerConstant<KindOfInt64>(
s_JSON_FB_LOOSE.get(), k_JSON_FB_LOOSE
);
Native::registerConstant<KindOfInt64>(
s_JSON_FB_UNLIMITED.get(), k_JSON_FB_UNLIMITED
);
Native::registerConstant<KindOfInt64>(
s_JSON_FB_EXTRA_ESCAPES.get(), k_JSON_FB_EXTRA_ESCAPES
);
Native::registerConstant<KindOfInt64>(
s_JSON_FB_COLLECTIONS.get(), k_JSON_FB_COLLECTIONS
);
Native::registerConstant<KindOfInt64>(
s_JSON_FB_STABLE_MAPS.get(), k_JSON_FB_STABLE_MAPS
);
Native::registerConstant<KindOfInt64>(
s_JSON_ERROR_NONE.get(), k_JSON_ERROR_NONE
);
Native::registerConstant<KindOfInt64>(
s_JSON_ERROR_DEPTH.get(), k_JSON_ERROR_DEPTH
);
Native::registerConstant<KindOfInt64>(
s_JSON_ERROR_STATE_MISMATCH.get(), k_JSON_ERROR_STATE_MISMATCH
);
Native::registerConstant<KindOfInt64>(
s_JSON_ERROR_CTRL_CHAR.get(), k_JSON_ERROR_CTRL_CHAR
);
Native::registerConstant<KindOfInt64>(
s_JSON_ERROR_SYNTAX.get(), k_JSON_ERROR_SYNTAX
);
Native::registerConstant<KindOfInt64>(
s_JSON_ERROR_UTF8.get(), k_JSON_ERROR_UTF8
);
Native::registerConstant<KindOfInt64>(
s_JSON_ERROR_RECURSION.get(), k_JSON_ERROR_RECURSION
);
Native::registerConstant<KindOfInt64>(
s_JSON_ERROR_INF_OR_NAN.get(), k_JSON_ERROR_INF_OR_NAN
);
Native::registerConstant<KindOfInt64>(
s_JSON_ERROR_UNSUPPORTED_TYPE.get(), k_JSON_ERROR_UNSUPPORTED_TYPE
);
HHVM_FE(json_last_error);
HHVM_FE(json_last_error_msg);
HHVM_FE(json_encode);
HHVM_FE(json_decode);
loadSystemlib();
}
} s_json_extension;
}
| 36.735119 | 80 | 0.666937 | [
"render"
] |
a33ffb61df0425f7151ed7f1d5e0178e49d98cf5 | 9,538 | cpp | C++ | src/crypto/openssl/key_pair.cpp | securelogicgroup/CCF | 2bad8ca6caa146e6b7cd4167fea551d61fecabfa | [
"Apache-2.0"
] | null | null | null | src/crypto/openssl/key_pair.cpp | securelogicgroup/CCF | 2bad8ca6caa146e6b7cd4167fea551d61fecabfa | [
"Apache-2.0"
] | 2 | 2022-02-03T06:32:47.000Z | 2022-02-09T23:00:07.000Z | src/crypto/openssl/key_pair.cpp | securelogicgroup/CCF | 2bad8ca6caa146e6b7cd4167fea551d61fecabfa | [
"Apache-2.0"
] | null | null | null | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the Apache 2.0 License.
#include "key_pair.h"
#include "crypto/curve.h"
#include "crypto/openssl/public_key.h"
#include "hash.h"
#include "openssl_wrappers.h"
#define FMT_HEADER_ONLY
#include <fmt/format.h>
#include <openssl/asn1.h>
#include <openssl/ec.h>
#include <openssl/engine.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/x509v3.h>
#include <stdexcept>
#include <string>
namespace crypto
{
using namespace OpenSSL;
static inline int get_openssl_group_id(CurveID gid)
{
switch (gid)
{
case CurveID::NONE:
return NID_undef;
case CurveID::SECP384R1:
return NID_secp384r1;
case CurveID::SECP256R1:
return NID_X9_62_prime256v1;
default:
throw std::logic_error(
fmt::format("unsupported OpenSSL CurveID {}", gid));
}
return MBEDTLS_ECP_DP_NONE;
}
static std::map<std::string, std::string> parse_name(const std::string& name)
{
std::map<std::string, std::string> result;
const auto ns = nonstd::split(name, ",");
for (const auto& n : ns)
{
const auto& [key, value] = nonstd::split_1(n, "=");
result.emplace(
std::string(key.data(), key.size()),
std::string(value.data(), value.size()));
}
return result;
}
KeyPair_OpenSSL::KeyPair_OpenSSL(CurveID curve_id)
{
int curve_nid = get_openssl_group_id(curve_id);
key = EVP_PKEY_new();
Unique_EVP_PKEY_CTX pkctx;
if (
EVP_PKEY_paramgen_init(pkctx) < 0 ||
EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pkctx, curve_nid) < 0 ||
EVP_PKEY_CTX_set_ec_param_enc(pkctx, OPENSSL_EC_NAMED_CURVE) < 0)
throw std::runtime_error("could not initialize PK context");
if (EVP_PKEY_keygen_init(pkctx) < 0 || EVP_PKEY_keygen(pkctx, &key) < 0)
throw std::runtime_error("could not generate new EC key");
}
KeyPair_OpenSSL::KeyPair_OpenSSL(const Pem& pem, CBuffer pw)
{
Unique_BIO mem(pem);
key = PEM_read_bio_PrivateKey(mem, NULL, NULL, (void*)pw.p);
if (!key)
throw std::runtime_error("could not parse PEM");
}
Pem KeyPair_OpenSSL::private_key_pem() const
{
Unique_BIO buf;
OpenSSL::CHECK1(
PEM_write_bio_PrivateKey(buf, key, NULL, NULL, 0, NULL, NULL));
BUF_MEM* bptr;
BIO_get_mem_ptr(buf, &bptr);
return Pem((uint8_t*)bptr->data, bptr->length);
}
Pem KeyPair_OpenSSL::public_key_pem() const
{
return PublicKey_OpenSSL::public_key_pem();
}
std::vector<uint8_t> KeyPair_OpenSSL::public_key_der() const
{
return PublicKey_OpenSSL::public_key_der();
}
bool KeyPair_OpenSSL::verify(
const std::vector<uint8_t>& contents, const std::vector<uint8_t>& signature)
{
return PublicKey_OpenSSL::verify(contents, signature);
}
bool KeyPair_OpenSSL::verify(
const uint8_t* contents,
size_t contents_size,
const uint8_t* signature,
size_t signature_size)
{
return PublicKey_OpenSSL::verify(
contents, contents_size, signature, signature_size);
}
std::vector<uint8_t> KeyPair_OpenSSL::sign(CBuffer d, MDType md_type) const
{
if (md_type == MDType::NONE)
{
md_type = get_md_for_ec(get_curve_id());
}
OpenSSLHashProvider hp;
HashBytes hash = hp.Hash(d.p, d.rawSize(), md_type);
return sign_hash(hash.data(), hash.size());
}
int KeyPair_OpenSSL::sign(
CBuffer d, size_t* sig_size, uint8_t* sig, MDType md_type) const
{
if (md_type == MDType::NONE)
{
md_type = get_md_for_ec(get_curve_id());
}
OpenSSLHashProvider hp;
HashBytes hash = hp.Hash(d.p, d.rawSize(), md_type);
return sign_hash(hash.data(), hash.size(), sig_size, sig);
}
std::vector<uint8_t> KeyPair_OpenSSL::sign_hash(
const uint8_t* hash, size_t hash_size) const
{
std::vector<uint8_t> sig(EVP_PKEY_size(key));
size_t written = sig.size();
if (sign_hash(hash, hash_size, &written, sig.data()) != 0)
{
return {};
}
sig.resize(written);
return sig;
}
int KeyPair_OpenSSL::sign_hash(
const uint8_t* hash, size_t hash_size, size_t* sig_size, uint8_t* sig) const
{
Unique_EVP_PKEY_CTX pctx(key);
OpenSSL::CHECK1(EVP_PKEY_sign_init(pctx));
OpenSSL::CHECK1(EVP_PKEY_sign(pctx, sig, sig_size, hash, hash_size));
return 0;
}
Pem KeyPair_OpenSSL::create_csr(
const std::string& name, const std::vector<SubjectAltName>& sans) const
{
Unique_X509_REQ req;
OpenSSL::CHECK1(X509_REQ_set_pubkey(req, key));
X509_NAME* subj_name = NULL;
OpenSSL::CHECKNULL(subj_name = X509_NAME_new());
for (const auto& [k, v] : parse_name(name))
{
OpenSSL::CHECK1(X509_NAME_add_entry_by_txt(
subj_name,
k.data(),
MBSTRING_ASC,
(const unsigned char*)v.data(),
-1,
-1,
0));
}
OpenSSL::CHECK1(X509_REQ_set_subject_name(req, subj_name));
X509_NAME_free(subj_name);
if (!sans.empty())
{
Unique_STACK_OF_X509_EXTENSIONS exts;
X509_EXTENSION* ext = NULL;
OpenSSL::CHECKNULL(
ext = X509V3_EXT_conf_nid(
NULL,
NULL,
NID_subject_alt_name,
fmt::format("{}", fmt::join(sans, ", ")).c_str()));
sk_X509_EXTENSION_push(exts, ext);
X509_REQ_add_extensions(req, exts);
}
if (key)
OpenSSL::CHECK1(X509_REQ_sign(req, key, EVP_sha512()));
Unique_BIO mem;
OpenSSL::CHECK1(PEM_write_bio_X509_REQ(mem, req));
BUF_MEM* bptr;
BIO_get_mem_ptr(mem, &bptr);
Pem result((uint8_t*)bptr->data, bptr->length);
return result;
}
Pem KeyPair_OpenSSL::sign_csr(
const Pem& issuer_cert, const Pem& signing_request, bool ca) const
{
X509* icrt = NULL;
Unique_BIO mem(signing_request);
Unique_X509_REQ csr(mem);
Unique_X509 crt;
// First, verify self-signed CSR
EVP_PKEY* req_pubkey = X509_REQ_get0_pubkey(csr);
OpenSSL::CHECK1(X509_REQ_verify(csr, req_pubkey));
// Add version
OpenSSL::CHECK1(X509_set_version(crt, 2));
// Add serial number
unsigned char rndbytes[16];
OpenSSL::CHECK1(RAND_bytes(rndbytes, sizeof(rndbytes)));
BIGNUM* bn = NULL;
OpenSSL::CHECKNULL(bn = BN_new());
BN_bin2bn(rndbytes, sizeof(rndbytes), bn);
ASN1_INTEGER* serial = ASN1_INTEGER_new();
BN_to_ASN1_INTEGER(bn, serial);
OpenSSL::CHECK1(X509_set_serialNumber(crt, serial));
ASN1_INTEGER_free(serial);
BN_free(bn);
// Add issuer name
if (!issuer_cert.empty())
{
Unique_BIO imem(issuer_cert);
OpenSSL::CHECKNULL(icrt = PEM_read_bio_X509(imem, NULL, NULL, NULL));
OpenSSL::CHECK1(X509_set_issuer_name(crt, X509_get_subject_name(icrt)));
}
else
{
OpenSSL::CHECK1(
X509_set_issuer_name(crt, X509_REQ_get_subject_name(csr)));
}
// Note: 825-day validity range
// https://support.apple.com/en-us/HT210176
ASN1_TIME *before = NULL, *after = NULL;
OpenSSL::CHECKNULL(before = ASN1_TIME_new());
OpenSSL::CHECKNULL(after = ASN1_TIME_new());
OpenSSL::CHECK1(ASN1_TIME_set_string(before, "20210311000000Z"));
OpenSSL::CHECK1(ASN1_TIME_set_string(after, "20230611235959Z"));
OpenSSL::CHECK1(ASN1_TIME_normalize(before));
OpenSSL::CHECK1(ASN1_TIME_normalize(after));
OpenSSL::CHECK1(X509_set1_notBefore(crt, before));
OpenSSL::CHECK1(X509_set1_notAfter(crt, after));
ASN1_TIME_free(before);
ASN1_TIME_free(after);
X509_set_subject_name(crt, X509_REQ_get_subject_name(csr));
X509_set_pubkey(crt, req_pubkey);
// Extensions
X509V3_CTX v3ctx;
X509V3_set_ctx_nodb(&v3ctx);
X509V3_set_ctx(&v3ctx, icrt ? icrt : crt, NULL, csr, NULL, 0);
// Add basic constraints
X509_EXTENSION* ext = NULL;
OpenSSL::CHECKNULL(
ext = X509V3_EXT_conf_nid(
NULL, &v3ctx, NID_basic_constraints, ca ? "CA:TRUE" : "CA:FALSE"));
OpenSSL::CHECK1(X509_add_ext(crt, ext, -1));
X509_EXTENSION_free(ext);
// Add subject key identifier
OpenSSL::CHECKNULL(
ext =
X509V3_EXT_conf_nid(NULL, &v3ctx, NID_subject_key_identifier, "hash"));
OpenSSL::CHECK1(X509_add_ext(crt, ext, -1));
X509_EXTENSION_free(ext);
// Add authority key identifier
OpenSSL::CHECKNULL(
ext = X509V3_EXT_conf_nid(
NULL, &v3ctx, NID_authority_key_identifier, "keyid:always"));
OpenSSL::CHECK1(X509_add_ext(crt, ext, -1));
X509_EXTENSION_free(ext);
// Add subject alternative names (read from csr)
Unique_STACK_OF_X509_EXTENSIONS exts = X509_REQ_get_extensions(csr);
int extension_count = sk_X509_EXTENSION_num(exts);
if (extension_count > 0)
{
for (size_t i = 0; i < extension_count; i++)
{
X509_EXTENSION* ext = sk_X509_EXTENSION_value(exts, i);
ASN1_OBJECT* obj = X509_EXTENSION_get_object(ext);
auto nid = OBJ_obj2nid(obj);
if (nid == NID_subject_alt_name)
{
OpenSSL::CHECK1(X509_add_ext(crt, ext, -1));
}
}
}
// Sign
auto md = get_md_type(get_md_for_ec(get_curve_id()));
int size = X509_sign(crt, key, md);
if (size <= 0)
throw std::runtime_error("could not sign CRT");
Unique_BIO omem;
OpenSSL::CHECK1(PEM_write_bio_X509(omem, crt));
// Export
BUF_MEM* bptr;
BIO_get_mem_ptr(omem, &bptr);
Pem result((uint8_t*)bptr->data, bptr->length);
if (icrt)
X509_free(icrt);
return result;
}
}
| 28.135693 | 80 | 0.66083 | [
"vector"
] |
a3412d2cac1bb9d311473df3fde88e04863a6834 | 3,807 | cc | C++ | adi_lib/matrix-io-canary/src/main/cpp/detector/repeat_read_detector.cc | zkwlx/ADI | 41952d15e3cb32fa855adf558613c9a7b9926607 | [
"Apache-2.0"
] | 226 | 2019-10-09T03:17:14.000Z | 2022-03-21T07:11:43.000Z | adi_lib/matrix-io-canary/src/main/cpp/detector/repeat_read_detector.cc | JayChou/ADI | 41952d15e3cb32fa855adf558613c9a7b9926607 | [
"Apache-2.0"
] | 4 | 2019-12-29T10:40:05.000Z | 2022-01-22T02:55:23.000Z | adi_lib/matrix-io-canary/src/main/cpp/detector/repeat_read_detector.cc | JayChou/ADI | 41952d15e3cb32fa855adf558613c9a7b9926607 | [
"Apache-2.0"
] | 22 | 2019-10-15T06:08:23.000Z | 2022-03-22T03:10:38.000Z | /*
* Tencent is pleased to support the open source community by making wechat-matrix available.
* Copyright (C) 2018 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the BSD 3-Clause License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* 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.
*/
//
// Created by liyongjie on 2017/12/7.
//
#include "repeat_read_detector.h"
namespace iocanary {
RepeatReadInfo::RepeatReadInfo(const std::string &path, const std::string &java_stack,
long java_thread_id, long op_size,
int file_size) : path_(path), java_stack_(java_stack), java_thread_id_(java_thread_id) ,
op_size_(op_size), file_size_(file_size), op_timems(GetTickCount()) {
repeat_cnt_ = 1;
}
bool RepeatReadInfo::operator==(const RepeatReadInfo &target) const {
return target.path_ == path_
&& target.java_thread_id_ == java_thread_id_
&& target.java_stack_ == java_stack_
&& target.file_size_ == file_size_
&& target.op_size_ == op_size_;
}
void RepeatReadInfo::IncRepeatReadCount() {
repeat_cnt_ ++;
}
int RepeatReadInfo::GetRepeatReadCount() {
return repeat_cnt_;
}
std::string RepeatReadInfo::GetStack() {
return java_stack_;
}
void FileIORepeatReadDetector::Detect(const IOCanaryEnv &env,
const IOInfo &file_io_info,
std::vector<Issue>& issues) {
const std::string& path = file_io_info.path_;
if (observing_map_.find(path) == observing_map_.end()) {
if (file_io_info.max_continual_rw_cost_time_μs_ < env.kPossibleNegativeThreshold) {
return;
}
observing_map_.insert(std::make_pair(path, std::vector<RepeatReadInfo>()));
}
std::vector<RepeatReadInfo>& repeat_infos = observing_map_[path];
if (file_io_info.op_type_ == FileOpType::kWrite) {
repeat_infos.clear();
return;
}
RepeatReadInfo repeat_read_info(file_io_info.path_, file_io_info.java_context_.stack_, file_io_info.java_context_.thread_id_,
file_io_info.op_size_, file_io_info.file_size_);
if (repeat_infos.size() == 0) {
repeat_infos.push_back(repeat_read_info);
return;
}
if((GetTickCount() - repeat_infos[repeat_infos.size() - 1].op_timems) > 17) { //17ms todo astrozhou add to params
repeat_infos.clear();
}
bool found = false;
int repeatCnt;
for (auto& info : repeat_infos) {
if (info == repeat_read_info) {
found = true;
info.IncRepeatReadCount();
repeatCnt = info.GetRepeatReadCount();
break;
}
}
if (!found) {
repeat_infos.push_back(repeat_read_info);
return;
}
if (repeatCnt >= env.GetRepeatReadThreshold()) {
Issue issue(kType, file_io_info);
issue.repeat_read_cnt_ = repeatCnt;
issue.stack = repeat_read_info.GetStack();
PublishIssue(issue, issues);
}
}
}
| 34.926606 | 136 | 0.597058 | [
"vector"
] |
a3426810a759490e3cffd3eaa983aab783e247ab | 15,453 | cpp | C++ | vm/llvm/jit_builder.cpp | bruce/rubinius | 44d3bdd0d988a17de1fe446bd29d2e9dede65f45 | [
"BSD-3-Clause"
] | 1 | 2017-09-09T21:28:06.000Z | 2017-09-09T21:28:06.000Z | vm/llvm/jit_builder.cpp | bruce/rubinius | 44d3bdd0d988a17de1fe446bd29d2e9dede65f45 | [
"BSD-3-Clause"
] | null | null | null | vm/llvm/jit_builder.cpp | bruce/rubinius | 44d3bdd0d988a17de1fe446bd29d2e9dede65f45 | [
"BSD-3-Clause"
] | null | null | null | #ifdef ENABLE_LLVM
#include "llvm/jit_builder.hpp"
#include "call_frame.hpp"
#include "vmmethod.hpp"
#include "llvm/jit_visit.hpp"
#include "llvm/control_flow.hpp"
#include "llvm/cfg.hpp"
#include <llvm/Analysis/CaptureTracking.h>
namespace rubinius {
namespace jit {
Builder::Builder(LLVMState* ls, JITMethodInfo& i)
: ls_(ls)
, vmm_(i.vmm)
, builder_(ls->ctx())
, use_full_scope_(false)
, import_args_(0)
, method_body_(0)
, info_(i)
{
llvm::Module* mod = ls->module();
cf_type = mod->getTypeByName("struct.rubinius::CallFrame");
vars_type = mod->getTypeByName("struct.rubinius::VariableScope");
stack_vars_type = mod->getTypeByName("struct.rubinius::StackVariables");
obj_type = ls->ptr_type("Object");
obj_ary_type = PointerType::getUnqual(obj_type);
}
Value* Builder::get_field(Value* val, int which) {
return b().CreateConstGEP2_32(val, 0, which);
}
void Builder::nil_stack(int size, Value* nil) {
if(size == 0) return;
// Stack size 5 or less, do 5 stores in a row rather than
// the loop.
if(size <= 5) {
for(int i = 0; i < size; i++) {
b().CreateStore(nil, b().CreateConstGEP1_32(stk, i, "stack_pos"));
}
return;
}
Value* max = ConstantInt::get(ls_->Int32Ty, size);
Value* one = ConstantInt::get(ls_->Int32Ty, 1);
BasicBlock* top = BasicBlock::Create(ls_->ctx(), "stack_nil", func);
BasicBlock* cont = BasicBlock::Create(ls_->ctx(), "bottom", func);
b().CreateStore(ConstantInt::get(ls_->Int32Ty, 0), info_.counter());
b().CreateBr(top);
b().SetInsertPoint(top);
Value* cur = b().CreateLoad(info_.counter(), "counter");
b().CreateStore(nil, b().CreateGEP(stk, cur, "stack_pos"));
Value* added = b().CreateAdd(cur, one, "added");
b().CreateStore(added, info_.counter());
Value* cmp = b().CreateICmpEQ(added, max, "loop_check");
b().CreateCondBr(cmp, cont, top);
b().SetInsertPoint(cont);
}
void Builder::nil_locals() {
Value* nil = constant(Qnil, obj_type);
int size = vmm_->number_of_locals;
if(size == 0) return;
// Stack size 5 or less, do 5 stores in a row rather than
// the loop.
if(size <= 5) {
for(int i = 0; i < size; i++) {
Value* idx[] = {
ConstantInt::get(ls_->Int32Ty, 0),
ConstantInt::get(ls_->Int32Ty, offset::vars_tuple),
ConstantInt::get(ls_->Int32Ty, i)
};
Value* gep = b().CreateGEP(vars, idx, idx+3, "local_pos");
b().CreateStore(nil, gep);
}
return;
}
Value* max = ConstantInt::get(ls_->Int32Ty, size);
Value* one = ConstantInt::get(ls_->Int32Ty, 1);
BasicBlock* top = BasicBlock::Create(ls_->ctx(), "locals_nil", func);
BasicBlock* cont = BasicBlock::Create(ls_->ctx(), "bottom", func);
b().CreateStore(ConstantInt::get(ls_->Int32Ty, 0), info_.counter());
b().CreateBr(top);
b().SetInsertPoint(top);
Value* cur = b().CreateLoad(info_.counter(), "counter");
Value* idx[] = {
ConstantInt::get(ls_->Int32Ty, 0),
ConstantInt::get(ls_->Int32Ty, offset::vars_tuple),
cur
};
Value* gep = b().CreateGEP(vars, idx, idx+3, "local_pos");
b().CreateStore(nil, gep);
Value* added = b().CreateAdd(cur, one, "added");
b().CreateStore(added, info_.counter());
Value* cmp = b().CreateICmpEQ(added, max, "loop_check");
b().CreateCondBr(cmp, cont, top);
b().SetInsertPoint(cont);
}
void Builder::check_self_type() {
int klass_id = 0;
{
if(Class* cls = try_as<Class>(info_.method()->scope()->module())) {
klass_id = cls->class_id();
} else {
return;
}
}
// Now, validate class_id
Value* self = b().CreateLoad(
b().CreateConstGEP2_32(args, 0, offset::args_recv), "self");
BasicBlock* restart_interp = BasicBlock::Create(ls_->ctx(), "restart_interp", func);
BasicBlock* check_class = BasicBlock::Create(ls_->ctx(), "check_class", func);
BasicBlock* cont = BasicBlock::Create(ls_->ctx(), "prologue_continue", func);
Value* mask = ConstantInt::get(ls_->Int32Ty, TAG_REF_MASK);
Value* zero = ConstantInt::get(ls_->Int32Ty, TAG_REF);
Value* lint = b().CreateAnd(
b().CreatePtrToInt(self, ls_->Int32Ty),
mask, "masked");
Value* is_ref = b().CreateICmpEQ(lint, zero, "is_reference");
b().CreateCondBr(is_ref, check_class, restart_interp);
b().SetInsertPoint(check_class);
Value* class_idx[] = {
ConstantInt::get(ls_->Int32Ty, 0),
ConstantInt::get(ls_->Int32Ty, 0),
ConstantInt::get(ls_->Int32Ty, 1)
};
Value* self_class = b().CreateLoad(
b().CreateGEP(self, class_idx, class_idx+3),
"class");
Value* runtime_id = b().CreateLoad(
b().CreateConstGEP2_32(self_class, 0, 3),
"class_id");
Value* equal = b().CreateICmpEQ(runtime_id,
ConstantInt::get(ls_->Int32Ty, klass_id));
b().CreateCondBr(equal, cont, restart_interp);
b().SetInsertPoint(restart_interp);
Value* call_args[] = { vm, prev, msg, args };
Signature sig(ls_, "Object");
sig << "VM";
sig << "CallFrame";
sig << "Dispatch";
sig << "Arguments";
b().CreateRet(sig.call("rbx_restart_interp", call_args, 4, "ir", b()));
b().SetInsertPoint(cont);
}
class PassOne : public VisitInstructions<PassOne> {
LLVMState* ls_;
BlockMap& map_;
Function* function_;
opcode current_ip_;
int force_break_;
bool creates_blocks_;
int number_of_sends_;
bool loops_;
int sp_;
JITBasicBlock* current_block_;
bool calls_evalish_;
Symbol* s_eval_;
Symbol* s_binding_;
Symbol* s_class_eval_;
Symbol* s_module_eval_;
std::list<JITBasicBlock*> exception_handlers_;
CFGCalculator& cfg_;
public:
PassOne(LLVMState* ls, BlockMap& map, Function* func, BasicBlock* start,
CFGCalculator& cfg)
: ls_(ls)
, map_(map)
, function_(func)
, current_ip_(0)
, force_break_(false)
, creates_blocks_(false)
, number_of_sends_(0)
, loops_(false)
, sp_(-1)
, calls_evalish_(false)
, cfg_(cfg)
{
JITBasicBlock& jbb = map_[0];
jbb.reachable = true;
jbb.block = start;
current_block_ = &jbb;
s_eval_ = ls->symbol("eval");
s_binding_ = ls->symbol("binding");
s_class_eval_ = ls->symbol("class_eval");
s_module_eval_ = ls->symbol("module_eval");
// By default, there is no handler.
exception_handlers_.push_back(0);
}
bool calls_evalish() {
return calls_evalish_;
}
bool creates_blocks() {
return creates_blocks_;
}
int number_of_sends() {
return number_of_sends_;
}
bool loops_p() {
return loops_;
}
void at_ip(int ip) {
current_ip_ = ip;
// If this is a new block, reset sp here
/*
BlockMap::iterator i = map_.find(ip);
if(i != map_.end()) {
sp_ = i->second.sp;
}
*/
}
const static int cUnknown = -10;
const static bool cDebugStack = false;
#include "gen/instruction_effects.hpp"
bool before(opcode op, opcode arg1=0, opcode arg2=0) {
// Handle pop_unwind specially, so we always see it.
if(op == InstructionSequence::insn_pop_unwind) {
exception_handlers_.pop_back();
}
BlockMap::iterator i = map_.find(current_ip_);
if(i != map_.end()) {
if(i->second.sp == cUnknown) {
if(cDebugStack) {
std::cout << current_ip_ << ": " << sp_ << " (inherit)\n";
}
i->second.sp = sp_;
} else {
sp_ = i->second.sp;
if(cDebugStack) {
std::cout << current_ip_ << ": " << sp_ << " (reset)\n";
}
}
current_block_ = &i->second;
} else {
if(force_break_) {
if(cDebugStack) {
std::cout << current_ip_ << ": dead\n";
}
return false;
}
if(cDebugStack) {
std::cout << current_ip_ << ": " << sp_ << "\n";
}
}
// Update current_block everytime. When current_block changes,
// previous current blocks will thereby contain their real end_ip
current_block_->end_ip = current_ip_;
force_break_ = false;
if(sp_ != cUnknown) {
sp_ += stack_difference(op, arg1, arg2);
assert(sp_ >= -1);
}
return true;
}
JITBasicBlock* break_at(opcode ip) {
BlockMap::iterator i = map_.find(ip);
if(i == map_.end()) {
std::ostringstream ss;
ss << "ip" << ip;
JITBasicBlock& jbb = map_[ip];
jbb.block = BasicBlock::Create(ls_->ctx(), ss.str().c_str(), function_);
jbb.start_ip = ip;
jbb.sp = sp_;
CFGBlock* cfg_block = cfg_.find_block(ip);
assert(cfg_block);
if(CFGBlock* handler = cfg_block->exception_handler()) {
BlockMap::iterator hi = map_.find(handler->start_ip());
assert(hi != map_.end());
jbb.exception_handler = &hi->second;
}
// Assign the new block the current handler. This works
// because code creates now blocks always within the
// scope of the current handler and it's illegal for code
// to generate a goto across a handler boundary
// if(exception_handlers_.size() > 0) {
// jbb.exception_handler = exception_handlers_.back();
// }
if(ip < current_ip_) {
jbb.end_ip = current_ip_;
}
if(cDebugStack) {
std::cout << "patch " << ip << ": " << jbb.sp << "\n";
}
return &jbb;
} else {
assert(i->second.sp == sp_);
return &(i->second);
}
}
void next_ip_too() {
force_break_ = true;
}
void visit_goto(opcode which) {
if(current_ip_ < which) loops_ = true;
break_at(which);
next_ip_too();
}
void visit_goto_if_true(opcode which) {
if(current_ip_ < which) loops_ = true;
break_at(which);
break_at(current_ip_ + 2);
}
void visit_goto_if_false(opcode which) {
if(current_ip_ < which) loops_ = true;
break_at(which);
break_at(current_ip_ + 2);
}
void visit_goto_if_defined(opcode which) {
if(current_ip_ < which) loops_ = true;
break_at(which);
break_at(current_ip_ + 2);
}
void visit_setup_unwind(opcode which, opcode type) {
// setup_unwind must always refer to an instruction further
// on in the stream
assert(current_ip_ < which);
JITBasicBlock* jbb = break_at(which);
// Install the handler...
exception_handlers_.push_back(jbb);
// Break at the next IP. When we advance to it, the logic
// above will install the handler we just installed on it.
break_at(current_ip_ + 3);
}
void visit_ret() {
next_ip_too();
}
void visit_raise_return() {
next_ip_too();
}
void visit_raise_break() {
next_ip_too();
}
void visit_ensure_return() {
next_ip_too();
}
void visit_reraise() {
next_ip_too();
}
void visit_raise_exc() {
next_ip_too();
}
void visit_create_block(opcode which) {
creates_blocks_ = true;
}
void check_for_eval(opcode which) {
InlineCache* ic = reinterpret_cast<InlineCache*>(which);
if(ic->name == s_eval_ ||
ic->name == s_binding_ ||
ic->name == s_class_eval_ ||
ic->name == s_module_eval_) {
calls_evalish_ = true;
}
}
void visit_send_stack(opcode which, opcode args) {
check_for_eval(which);
number_of_sends_++;
}
void visit_send_method(opcode which) {
number_of_sends_++;
}
void visit_send_stack_with_block(opcode which, opcode args) {
number_of_sends_++;
}
void visit_send_stack_with_splat(opcode which, opcode args) {
check_for_eval(which);
number_of_sends_++;
}
void visit_send_super_stack_with_block(opcode which, opcode args) {
number_of_sends_++;
}
void visit_send_super_stack_with_splat(opcode which, opcode args) {
number_of_sends_++;
}
void visit_zsuper(opcode which) {
// HACK. zsuper accesses scope.
calls_evalish_ = true;
number_of_sends_++;
}
};
void Builder::pass_one(BasicBlock* body) {
CFGCalculator cfg(vmm_);
cfg.build();
// Pass 1, detect BasicBlock boundaries
PassOne finder(ls_, block_map_, func, body, cfg);
finder.drive(vmm_);
if(finder.creates_blocks() || finder.calls_evalish()) {
info_.set_use_full_scope();
use_full_scope_ = true;
}
number_of_sends_ = finder.number_of_sends();
loops_ = finder.loops_p();
}
class Walker {
JITVisit& v_;
BlockMap& map_;
public:
Walker(JITVisit& v, BlockMap& map)
: v_(v)
, map_(map)
{}
void call(OpcodeIterator& iter) {
v_.dispatch(iter.stream(), iter.ip());
if(v_.b().GetInsertBlock()->getTerminator() == NULL) {
BlockMap::iterator i = map_.find(iter.next_ip());
if(i != map_.end()) {
v_.b().CreateBr(i->second.block);
}
}
}
};
bool Builder::generate_body() {
JITVisit visitor(ls_, info_, block_map_, b().GetInsertBlock());
if(info_.inline_policy) {
visitor.set_policy(info_.inline_policy);
} else {
visitor.init_policy();
}
visitor.set_called_args(info_.called_args);
visitor.set_valid_flag(valid_flag);
if(use_full_scope_) visitor.use_full_scope();
visitor.initialize();
// Pass 2, compile!
// Drive by following the control flow.
jit::ControlFlowWalker walker(info_.vmm);
Walker cb(visitor, block_map_);
try {
walker.run<Walker>(cb);
} catch(JITVisit::Unsupported &e) {
return false;
}
// See if we should check interrupts now
if(method_body_ && (visitor.sends_done() > 2 || loops_)) {
BasicBlock* cur = b().GetInsertBlock();
// Remove the branch to method_body
import_args_->back().eraseFromParent();
b().SetInsertPoint(import_args_);
Signature sig(ls_, obj_type);
sig << "VM";
sig << "CallFrame";
Function* func_ci = sig.function("rbx_check_interrupts");
func_ci->setDoesNotCapture(1, true);
func_ci->setDoesNotCapture(2, true);
Value* call_args[] = { vm, call_frame };
BasicBlock* ret_null = BasicBlock::Create(ls_->ctx(), "ret_null", func);
Value* ret = sig.call("rbx_prologue_check", call_args, 2, "ci", b());
b().CreateCondBr(
b().CreateICmpEQ(ret, Constant::getNullValue(obj_type)),
ret_null, method_body_);
b().SetInsertPoint(ret_null);
b().CreateRet(Constant::getNullValue(obj_type));
b().SetInsertPoint(cur);
}
// debugging/optimization test code
/*
if(llvm::PointerMayBeCaptured(stk, true)) {
std::cout << "Stack is captured!\n";
} else {
std::cout << "Stack is NOT captured!\n";
}
*/
info_.return_pad()->moveAfter(visitor.current_block());
info_.fin_block = visitor.current_block();
return true;
}
void Builder::generate_hard_return() {
b().SetInsertPoint(info_.return_pad());
b().CreateRet(info_.return_phi());
}
}
}
#endif
| 25.626866 | 88 | 0.59516 | [
"object"
] |
a34474a67ac1ac4b6fc5c602da92b1c87209b3b0 | 2,748 | cpp | C++ | codechef_DSA/yet_aother_partition_problem.cpp | archit-1997/codechef | 713051daa25b436fa63a0a7ac7fd769ac8a091ef | [
"MIT"
] | 1 | 2021-01-27T16:37:34.000Z | 2021-01-27T16:37:34.000Z | codechef_DSA/yet_aother_partition_problem.cpp | archit-1997/codechef | 713051daa25b436fa63a0a7ac7fd769ac8a091ef | [
"MIT"
] | null | null | null | codechef_DSA/yet_aother_partition_problem.cpp | archit-1997/codechef | 713051daa25b436fa63a0a7ac7fd769ac8a091ef | [
"MIT"
] | null | null | null | // Archit Singh
// architsingh456@gmail.com
// GitHub : archit-1997
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define ld long double
#define line cout << "-------------" << endl;
#define F first
#define S second
#define P pair<ll, ll>
#define PP pair<pair<ll, ll>, ll>
#define V vector<ll>
#define VP vector<pair<ll, ll>>
#define VS vector<string>
#define VV vector<vector<ll>>
#define VVP vector<vector<pair<ll, ll>>>
#define pb push_back
#define pf push_front
#define PQ priority_queue<ll>
#define PQ_G priority_queue<ll, vector<ll>, greater<ll>>
#define line cout << "-------------" << endl;
#define mod 1000000007
#define inf 1e18
#define setbits(x) __builtin_popcount(x)
#define zerobits(x) __builtin_ctzll(x)
#define ps(x, y) fixed << setprecision(y) << x
#define w(x) \
ll x; \
cin >> x; \
while (x--)
#define FOR(i, a, b) for (ll i = a; i < b; i++)
#define ma(arr, n, type) type *arr = new type[n]
void init() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
}
void remove(set<ll> &st, ll num) {
auto it = st.find(num);
if (it != st.end())
st.erase(it);
}
int main() {
init();
ll n, q;
cin >> n >> q;
V v(n + 1, 0), s(n + 1, 0);
FOR(i, 1, n + 1)
cin >> v[i];
s[1] = 1;
FOR(i, 1, n) {
if (v[i + 1] % v[i] == 0)
s[i + 1] = s[i];
else
s[i + 1] = s[i] + 1;
}
// now insert the indexes at which the elements are changing
set<ll> st;
st.insert(1);
ll val = s[1];
FOR(i, 2, n + 1) {
if (s[i] != val) {
st.insert(i);
val = s[i];
}
}
// This prints the elements of the set
// for (auto it = st.begin(); it != st.end(); it++)
// cout << *it << " ";
while (q--) {
ll type, index, val, f_i, f_i1;
cin >> type;
switch (type) {
case 1:
cin >> index >> val;
v[index] = val;
st.insert(index);
st.insert(index + 1);
// check for the condition of i and i-1
f_i = 0, f_i1 = 0;
if (index != 1 && v[index] % v[index - 1] == 0)
f_i = 1;
if (v[index + 1] % v[index] == 0)
f_i1 = 1;
if (f_i)
remove(st, index);
if (f_i1)
remove(st, index + 1);
break;
case 2:
cin >> index;
auto it = st.upper_bound(index);
it--;
cout << *it << endl;
}
}
return 0;
} | 23.092437 | 81 | 0.470524 | [
"vector"
] |
a3449d2ec6ea1f8d19fdcc29ac85116cb27f6769 | 4,444 | cxx | C++ | Libs/MRML/DisplayableManager/Testing/Cxx/vtkMRMLTestCustomDisplayableManager.cxx | forfullstack/slicersources-src | 91bcecf037a27f3fad4c0ab57e8286fc258bb0f5 | [
"Apache-2.0"
] | null | null | null | Libs/MRML/DisplayableManager/Testing/Cxx/vtkMRMLTestCustomDisplayableManager.cxx | forfullstack/slicersources-src | 91bcecf037a27f3fad4c0ab57e8286fc258bb0f5 | [
"Apache-2.0"
] | null | null | null | Libs/MRML/DisplayableManager/Testing/Cxx/vtkMRMLTestCustomDisplayableManager.cxx | forfullstack/slicersources-src | 91bcecf037a27f3fad4c0ab57e8286fc258bb0f5 | [
"Apache-2.0"
] | null | null | null | /*==============================================================================
Program: 3D Slicer
Copyright (c) Kitware Inc.
See COPYRIGHT.txt
or http://www.slicer.org/copyright/copyright.txt for details.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
This file was originally developed by Jean-Christophe Fillion-Robin, Kitware Inc.
and was partially funded by NIH grant 3P41RR013218-12S1
==============================================================================*/
// MRMLDisplayableManager includes
#include "vtkMRMLTestCustomDisplayableManager.h"
// MRML includes
#include <vtkMRMLCameraNode.h>
#include <vtkMRMLViewNode.h>
#include <vtkMRMLSliceNode.h>
// VTK includes
#include <vtkObjectFactory.h>
// STD includes
#include <cassert>
//---------------------------------------------------------------------------
vtkStandardNewMacro(vtkMRMLTestCustomDisplayableManager );
//---------------------------------------------------------------------------
int vtkMRMLTestCustomDisplayableManager::NodeAddedCountThreeDView = 0;
int vtkMRMLTestCustomDisplayableManager::NodeAddedCountSliceView = 0;
//---------------------------------------------------------------------------
class vtkMRMLTestCustomDisplayableManager::vtkInternal
{
public:
vtkInternal(vtkMRMLTestCustomDisplayableManager * external);
~vtkInternal();
vtkMRMLTestCustomDisplayableManager* External;
};
//---------------------------------------------------------------------------
// vtkInternal methods
//---------------------------------------------------------------------------
vtkMRMLTestCustomDisplayableManager::vtkInternal::vtkInternal(vtkMRMLTestCustomDisplayableManager * external)
{
this->External = external;
}
//---------------------------------------------------------------------------
vtkMRMLTestCustomDisplayableManager::vtkInternal::~vtkInternal() = default;
//---------------------------------------------------------------------------
// vtkMRMLTestCustomDisplayableManager methods
//---------------------------------------------------------------------------
vtkMRMLTestCustomDisplayableManager::vtkMRMLTestCustomDisplayableManager()
{
this->Internal = new vtkInternal(this);
}
//---------------------------------------------------------------------------
vtkMRMLTestCustomDisplayableManager::~vtkMRMLTestCustomDisplayableManager()
{
delete this->Internal;
}
//---------------------------------------------------------------------------
void vtkMRMLTestCustomDisplayableManager::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
//---------------------------------------------------------------------------
void vtkMRMLTestCustomDisplayableManager::AdditionnalInitializeStep()
{
this->AddInteractorStyleObservableEvent(vtkCommand::KeyPressEvent);
}
//---------------------------------------------------------------------------
void vtkMRMLTestCustomDisplayableManager::OnInteractorStyleEvent(int eventid)
{
std::cout << "OnInteractorStyleEvent: event id = " << eventid << std::endl;
}
//---------------------------------------------------------------------------
void vtkMRMLTestCustomDisplayableManager::Create()
{
assert(this->GetRenderer());
assert(this->GetMRMLDisplayableNode());
}
//---------------------------------------------------------------------------
void vtkMRMLTestCustomDisplayableManager::OnMRMLSceneNodeAdded(vtkMRMLNode* node)
{
vtkMRMLCameraNode * cameraNode = vtkMRMLCameraNode::SafeDownCast(node);
if (!cameraNode)
{
return;
}
if (vtkMRMLViewNode::SafeDownCast(this->GetMRMLDisplayableNode()))
{
vtkMRMLTestCustomDisplayableManager::NodeAddedCountThreeDView++;
//std::cout << "vtkMRMLTestCustomDisplayableManager[vtkMRMLViewNode] - NodeAdded - "
// << (node ? node->GetName() : "None")<< std::endl;
}
if (vtkMRMLSliceNode::SafeDownCast(this->GetMRMLDisplayableNode()))
{
vtkMRMLTestCustomDisplayableManager::NodeAddedCountSliceView++;
//std::cout << "vtkMRMLTestCustomDisplayableManager[vtkMRMLSliceNode] - NodeAdded - "
// << (node ? node->GetName() : "None")<< std::endl;
}
}
| 35.552 | 109 | 0.555806 | [
"3d"
] |
a346b24fbb4d0d1d99834d632cd5d6352ed7f803 | 4,194 | cxx | C++ | src/Cxx/Texture/AnimateVectors.cxx | cvandijck/VTKExamples | b6bb89414522afc1467be8a1f0089a37d0c16883 | [
"Apache-2.0"
] | 309 | 2017-05-21T09:07:19.000Z | 2022-03-15T09:18:55.000Z | src/Cxx/Texture/AnimateVectors.cxx | yijianmingliu/VTKExamples | dc8aac47c4384f9a2de9facbdd1ab3249f62ec99 | [
"Apache-2.0"
] | 379 | 2017-05-21T09:06:43.000Z | 2021-03-29T20:30:50.000Z | src/Cxx/Texture/AnimateVectors.cxx | yijianmingliu/VTKExamples | dc8aac47c4384f9a2de9facbdd1ab3249f62ec99 | [
"Apache-2.0"
] | 170 | 2017-05-17T14:47:41.000Z | 2022-03-31T13:16:26.000Z | #include <vtkActor.h>
#include <vtkCamera.h>
#include <vtkGlyph3D.h>
#include <vtkLineSource.h>
#include <vtkNamedColors.h>
#include <vtkOutlineFilter.h>
#include <vtkPolyDataMapper.h>
#include <vtkProperty.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <vtkStructuredPointsReader.h>
#include <vtkTexture.h>
#include <vtkThresholdPoints.h>
#include <vector>
int main (int argc, char *argv[])
{
if (argc < 3)
{
std::cout << "Usage: " << argv[0] << " carotid.vtk vecAnim1.vtk ..." << std::endl;
return EXIT_FAILURE;
}
vtkSmartPointer<vtkNamedColors> colors =
vtkSmartPointer<vtkNamedColors>::New();
// Setup render window, renderer, and interactor
vtkSmartPointer<vtkRenderer> renderer =
vtkSmartPointer<vtkRenderer>::New();
vtkSmartPointer<vtkRenderWindow> renderWindow =
vtkSmartPointer<vtkRenderWindow>::New();
renderWindow->AddRenderer(renderer);
vtkSmartPointer<vtkRenderWindowInteractor> interactor =
vtkSmartPointer<vtkRenderWindowInteractor>::New();
interactor->SetRenderWindow(renderWindow);
// read data
//
// create pipeline
//
vtkSmartPointer<vtkStructuredPointsReader> reader =
vtkSmartPointer<vtkStructuredPointsReader>::New();
reader->SetFileName(argv[1]);
vtkSmartPointer<vtkThresholdPoints> threshold =
vtkSmartPointer<vtkThresholdPoints>::New();
threshold->SetInputConnection(reader->GetOutputPort());
threshold->ThresholdByUpper(200);
vtkSmartPointer<vtkLineSource> line =
vtkSmartPointer<vtkLineSource>::New();
line->SetResolution(1);
vtkSmartPointer<vtkGlyph3D> lines =
vtkSmartPointer<vtkGlyph3D>::New();
lines->SetInputConnection(threshold->GetOutputPort());
lines->SetSourceConnection(line->GetOutputPort());
lines->SetScaleFactor(0.005);
lines->SetScaleModeToScaleByScalar();
lines->Update();
vtkSmartPointer<vtkPolyDataMapper> vectorMapper =
vtkSmartPointer<vtkPolyDataMapper>::New();
vectorMapper->SetInputConnection(lines->GetOutputPort());
vectorMapper->SetScalarRange(lines->GetOutput()->GetScalarRange());
vtkSmartPointer<vtkActor> vectorActor =
vtkSmartPointer<vtkActor>::New();
vectorActor->SetMapper(vectorMapper);
vectorActor->GetProperty()->SetOpacity(0.99);
vectorActor->GetProperty()->SetLineWidth(1.5);
// outline
vtkSmartPointer<vtkOutlineFilter> outline =
vtkSmartPointer<vtkOutlineFilter>::New();
outline->SetInputConnection(reader->GetOutputPort());
vtkSmartPointer<vtkPolyDataMapper> outlineMapper =
vtkSmartPointer<vtkPolyDataMapper>::New();
outlineMapper->SetInputConnection(outline->GetOutputPort());
vtkSmartPointer<vtkActor> outlineActor =
vtkSmartPointer<vtkActor>::New();
outlineActor->SetMapper(outlineMapper);
outlineActor->GetProperty()->SetColor(colors->GetColor3d("Black").GetData());
// texture maps
std::vector<vtkSmartPointer<vtkTexture> > textureMaps;
for (int i = 2; i < argc; ++i)
{
vtkSmartPointer<vtkStructuredPointsReader> tmap =
vtkSmartPointer<vtkStructuredPointsReader>::New();
tmap->SetFileName(argv[i]);
vtkSmartPointer<vtkTexture> texture =
vtkSmartPointer<vtkTexture>::New();
texture->SetInputConnection(tmap->GetOutputPort());
texture->InterpolateOff();
texture->RepeatOff();
textureMaps.push_back(texture);
}
vectorActor->SetTexture(textureMaps[0]);
// Add the actors to the renderer, set the background and size
//
renderer->AddActor(vectorActor);
renderer->AddActor(outlineActor);
vtkSmartPointer<vtkCamera> cam1 =
vtkSmartPointer<vtkCamera>::New();
cam1->SetClippingRange(17.4043, 870.216);
cam1->SetFocalPoint(136.71, 104.025, 23);
cam1->SetPosition(204.747, 258.939, 63.7925);
cam1->SetViewUp(-0.102647, -0.210897, 0.972104);
cam1->Zoom(1.5);
renderer->SetActiveCamera(cam1);
renderer->SetBackground(colors->GetColor3d("Wheat").GetData());
renderWindow->SetSize(640, 480);
// go into loop
for (int j = 0; j < 100; ++j)
{
for (size_t i = 0; i < textureMaps.size(); ++i)
{
vectorActor->SetTexture(textureMaps[i]);
renderWindow->Render();
}
}
interactor->Start();
return EXIT_SUCCESS;
}
| 30.838235 | 86 | 0.729614 | [
"render",
"vector"
] |
a34a77a8f48845ba0aa6f63bf7a416b157e426f4 | 30,030 | cpp | C++ | gdal/ogr/ogrsf_frmts/nas/nashandler.cpp | jdroenner/gdal | 7dcbbaa0f4f09ded9b36ad1f17f799793e28ed4c | [
"MIT"
] | null | null | null | gdal/ogr/ogrsf_frmts/nas/nashandler.cpp | jdroenner/gdal | 7dcbbaa0f4f09ded9b36ad1f17f799793e28ed4c | [
"MIT"
] | null | null | null | gdal/ogr/ogrsf_frmts/nas/nashandler.cpp | jdroenner/gdal | 7dcbbaa0f4f09ded9b36ad1f17f799793e28ed4c | [
"MIT"
] | null | null | null | /**********************************************************************
*
* Project: NAS Reader
* Purpose: Implementation of NASHandler class.
* Author: Frank Warmerdam, warmerdam@pobox.com
*
**********************************************************************
* Copyright (c) 2002, Frank Warmerdam
* Copyright (c) 2010-2012, Even Rouault <even dot rouault at mines-paris dot org>
*
* 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 <ctype.h>
#include "nasreaderp.h"
#include "cpl_conv.h"
#include "cpl_string.h"
CPL_CVSID("$Id$");
static const int MAX_TOKEN_SIZE = 1000;
/*
Update modes:
<geaenderteObjekte>
<wfs:Transaction version="1.0.0" service="WFS">
<wfs:Delete typeName="AX_BesondereFlurstuecksgrenze">
<ogc:Filter>
<ogc:FeatureId fid="DENW18AL0000nANA20120117T130819Z" />
</ogc:Filter>
</wfs:Delete>
<wfsext:Replace vendorId="AdV" safeToIgnore="false">
<AP_PTO gml:id="DENW18AL0000pewY20131011T071138Z">
[...]
</AP_PTO>
<ogc:Filter>
<ogc:FeatureId fid="DENW18AL0000pewY20120117T143330Z" />
</ogc:Filter>
</wfsext:Replace>
<wfs:Update typeName="AX_KommunalesGebiet">
<wfs:Property>
<wfs:Name>adv:lebenszeitintervall/adv:AA_Lebenszeitintervall/adv:endet</wfs:Name>
<wfs:Value>2012-08-14T12:32:30Z</wfs:Value>
</wfs:Property>
<wfs:Property>
<wfs:Name>adv:anlass</wfs:Name>
<wfs:Value>000000</wfs:Value>
</wfs:Property>
<wfs:Property>
<wfs:Name>adv:anlass</wfs:Name>
<wfs:Value>010102</wfs:Value>
</wfs:Property>
<ogc:Filter>
<ogc:FeatureId fid="DENW11AL000062WD20111016T122010Z" />
</ogc:Filter>
</wfs:Update>
</wfs:Transaction>
</geaenderteObjekte>
*/
/************************************************************************/
/* NASHandler() */
/************************************************************************/
NASHandler::NASHandler( NASReader *poReader ) :
m_poReader(poReader),
m_pszCurField(NULL),
m_pszGeometry(NULL),
m_nGeomAlloc(0),
m_nGeomLen(0),
m_nGeometryDepth(0),
m_nDepth(0),
m_nDepthFeature(0),
m_bIgnoreFeature(false),
m_bInUpdate(false),
m_bInUpdateProperty(false),
m_nDepthElement(0)
{ }
/************************************************************************/
/* ~NASHandler() */
/************************************************************************/
NASHandler::~NASHandler()
{
CPLFree( m_pszCurField );
CPLFree( m_pszGeometry );
}
/************************************************************************/
/* GetAttributes() */
/************************************************************************/
CPLString NASHandler::GetAttributes(const Attributes* attrs)
{
CPLString osRes;
for(unsigned int i=0; i < attrs->getLength(); i++)
{
osRes += " ";
char *pszString = tr_strdup(attrs->getQName(i));
osRes += pszString;
CPLFree( pszString );
osRes += "=\"";
pszString = tr_strdup(attrs->getValue(i));
osRes += pszString;
CPLFree( pszString );
osRes += "\"";
}
return osRes;
}
/************************************************************************/
/* startElement() */
/************************************************************************/
void NASHandler::startElement( const XMLCh* const /* uri */,
const XMLCh* const localname,
const XMLCh* const /* qname */,
const Attributes& attrs )
{
char szElementName[MAX_TOKEN_SIZE];
GMLReadState *poState = m_poReader->GetState();
tr_strcpy( szElementName, localname );
if ( ( m_bIgnoreFeature && m_nDepth >= m_nDepthFeature ) ||
( m_osIgnoredElement != "" && m_nDepth >= m_nDepthElement ) )
{
m_nDepth ++;
return;
}
// ignore attributes of external references and "objektkoordinaten"
// (see PostNAS #3 and #15)
if ( EQUAL( szElementName, "zeigtAufExternes" ) ||
EQUAL( szElementName, "objektkoordinaten" ) )
{
m_osIgnoredElement = szElementName;
m_nDepthElement = m_nDepth;
m_nDepth ++;
return;
}
#ifdef DEBUG_VERBOSE
CPLDebug( "NAS",
"%*sstartElement %s m_bIgnoreFeature:%d depth:%d "
"depthFeature:%d featureClass:%s",
m_nDepth, "", szElementName,
m_bIgnoreFeature, m_nDepth, m_nDepthFeature,
poState->m_poFeature ? poState->m_poFeature->
GetClass()->GetElementName() : "(no feature)"
);
#endif
/* -------------------------------------------------------------------- */
/* If we are in the midst of collecting a feature attribute */
/* value, then this must be a complex attribute which we don't */
/* try to collect for now, so just terminate the field */
/* collection. */
/* -------------------------------------------------------------------- */
if( m_pszCurField != NULL )
{
CPLFree( m_pszCurField );
m_pszCurField = NULL;
}
/* -------------------------------------------------------------------- */
/* If we are collecting geometry, or if we determine this is a */
/* geometry element then append to the geometry info. */
/* -------------------------------------------------------------------- */
const char *pszLast = NULL;
if( m_pszGeometry != NULL
|| IsGeometryElement( szElementName ) )
{
const int nLNLen = tr_strlen( localname );
CPLString osAttributes = GetAttributes( &attrs );
/* should save attributes too! */
if( m_pszGeometry == NULL )
m_nGeometryDepth = poState->m_nPathLength;
if( m_pszGeometry == NULL ||
m_nGeomLen + nLNLen + 4 + (int)osAttributes.size() > m_nGeomAlloc )
{
m_nGeomAlloc = (int) (m_nGeomAlloc * 1.3 + nLNLen + osAttributes.size() + 1000);
m_pszGeometry = (char *)
CPLRealloc( m_pszGeometry, m_nGeomAlloc);
}
strcpy( m_pszGeometry+m_nGeomLen, "<" );
tr_strcpy( m_pszGeometry+m_nGeomLen+1, localname );
if( osAttributes.size() > 0 )
{
strcat( m_pszGeometry+m_nGeomLen, " " );
strcat( m_pszGeometry+m_nGeomLen, osAttributes );
}
strcat( m_pszGeometry+m_nGeomLen, ">" );
m_nGeomLen += static_cast<int>(strlen(m_pszGeometry+m_nGeomLen));
}
/* -------------------------------------------------------------------- */
/* Is this the ogc:Filter element in a update operation */
/* (wfs:Delete, wfsext:Replace or wfs:Update)? */
/* specialized sort of feature. */
/* -------------------------------------------------------------------- */
else if( EQUAL(szElementName,"Filter")
&& (pszLast = m_poReader->GetState()->GetLastComponent()) != NULL
&& (EQUAL(pszLast,"Delete") || EQUAL(pszLast,"Replace") ||
EQUAL(pszLast,"Update")) )
{
const char* pszFilteredClassName = m_poReader->GetFilteredClassName();
if ( pszFilteredClassName != NULL &&
strcmp("Delete", pszFilteredClassName) != 0 )
{
m_bIgnoreFeature = true;
m_nDepthFeature = m_nDepth;
m_nDepth ++;
return;
}
if( m_osLastTypeName == "" )
{
CPLError( CE_Failure, CPLE_AssertionFailed,
"m_osLastTypeName == \"\"");
m_bIgnoreFeature = true;
m_nDepthFeature = m_nDepth;
m_nDepth ++;
return;
}
if( EQUAL( pszLast, "Replace" ) &&
( m_osLastReplacingFID == "" || m_osLastSafeToIgnore == "" ) )
{
CPLError( CE_Failure, CPLE_AssertionFailed,
"m_osLastReplacingFID == \"\" || "
"m_osLastSafeToIgnore == \"\"" );
m_bIgnoreFeature = true;
m_nDepthFeature = m_nDepth;
m_nDepth ++;
return;
}
if( EQUAL( pszLast, "Update" ) && m_osLastEnded == "" )
{
CPLError( CE_Failure, CPLE_AssertionFailed,
"m_osLastEnded == \"\"" );
m_bIgnoreFeature = true;
m_nDepthFeature = m_nDepth;
m_nDepth ++;
return;
}
m_bIgnoreFeature = false;
m_poReader->PushFeature( "Delete", attrs );
m_nDepthFeature = m_nDepth;
m_nDepth ++;
m_poReader->SetFeaturePropertyDirectly(
"typeName", CPLStrdup(m_osLastTypeName) );
m_poReader->SetFeaturePropertyDirectly( "context", CPLStrdup(pszLast) );
if( EQUAL( pszLast, "Replace" ) )
{
//CPLAssert( m_osLastReplacingFID != "" );
//CPLAssert( m_osLastSafeToIgnore != "" );
m_poReader->SetFeaturePropertyDirectly(
"replacedBy", CPLStrdup(m_osLastReplacingFID) );
m_poReader->SetFeaturePropertyDirectly(
"safeToIgnore", CPLStrdup(m_osLastSafeToIgnore) );
}
else if( EQUAL( pszLast, "Update" ) )
{
m_poReader->SetFeaturePropertyDirectly(
"endet", CPLStrdup(m_osLastEnded) );
for( std::list<CPLString>::iterator it = m_LastOccasions.begin();
it != m_LastOccasions.end();
++it )
{
m_poReader->SetFeaturePropertyDirectly(
"anlass", CPLStrdup(*it) );
}
m_osLastEnded = "";
m_LastOccasions.clear();
}
return;
}
/* -------------------------------------------------------------------- */
/* Is it a feature? If so push a whole new state, and return. */
/* -------------------------------------------------------------------- */
else if( m_poReader->IsFeatureElement( szElementName ) )
{
m_osLastTypeName = szElementName;
const char* pszFilteredClassName = m_poReader->GetFilteredClassName();
pszLast = m_poReader->GetState()->GetLastComponent();
if( pszLast != NULL && EQUAL(pszLast,"Replace") )
{
XMLCh Name[100];
tr_strcpy( Name, "gml:id" );
int nIndex = attrs.getIndex( Name );
if( nIndex == -1 || m_osLastReplacingFID !="" )
{
CPLError( CE_Failure, CPLE_AssertionFailed,
"nIndex == -1 || m_osLastReplacingFID !=\"\"" );
m_bIgnoreFeature = true;
m_nDepthFeature = m_nDepth;
m_nDepth ++;
return;
}
// Capture "gml:id" attribute as part of the property value -
// primarily this is for the wfsext:Replace operation's attribute.
char *pszReplacingFID = tr_strdup( attrs.getValue( nIndex ) );
m_osLastReplacingFID = pszReplacingFID;
CPLFree( pszReplacingFID );
#ifdef DEBUG_VERBOSE
CPLDebug( "NAS", "%*s### Replace typeName=%s replacedBy=%s",
m_nDepth, "", m_osLastTypeName.c_str(),
m_osLastReplacingFID.c_str() );
#endif
}
if ( pszFilteredClassName != NULL &&
strcmp(szElementName, pszFilteredClassName) != 0 )
{
m_bIgnoreFeature = true;
m_nDepthFeature = m_nDepth;
m_nDepth ++;
return;
}
m_bIgnoreFeature = false;
m_poReader->PushFeature( szElementName, attrs );
m_nDepthFeature = m_nDepth;
m_nDepth ++;
return;
}
/* -------------------------------------------------------------------- */
/* If it is the wfs:Delete or wfs:Update element, then remember */
/* the typeName attribute so we can assign it to the feature that */
/* will be produced when we process the Filter element. */
/* -------------------------------------------------------------------- */
else if( EQUAL(szElementName,"Delete") || EQUAL(szElementName,"Update") )
{
XMLCh Name[100];
tr_strcpy( Name, "typeName" );
int nIndex = attrs.getIndex( Name );
if( nIndex != -1 )
{
char *pszTypeName = tr_strdup( attrs.getValue( nIndex ) );
m_osLastTypeName = pszTypeName;
CPLFree( pszTypeName );
}
m_osLastSafeToIgnore = "";
m_osLastReplacingFID = "";
if( EQUAL(szElementName,"Update") )
{
m_bInUpdate = true;
}
}
else if ( m_bInUpdate && EQUAL(szElementName, "Property") )
{
m_bInUpdateProperty = true;
}
else if ( m_bInUpdateProperty && ( EQUAL(szElementName, "Name" ) ||
EQUAL(szElementName, "Value" ) ) )
{
// collect attribute name or value
CPLFree( m_pszCurField );
m_pszCurField = CPLStrdup("");
}
/* -------------------------------------------------------------------- */
/* If it is the wfsext:Replace element, then remember the */
/* safeToIgnore attribute so we can assign it to the feature */
/* that will be produced when we process the Filter element. */
/* -------------------------------------------------------------------- */
else if( EQUAL(szElementName,"Replace") )
{
XMLCh Name[100];
tr_strcpy( Name, "safeToIgnore" );
int nIndex = attrs.getIndex( Name );
if( nIndex != -1 )
{
char *pszSafeToIgnore = tr_strdup( attrs.getValue( nIndex ) );
m_osLastSafeToIgnore = pszSafeToIgnore;
CPLFree( pszSafeToIgnore );
}
else
{
CPLError( CE_Warning, CPLE_AppDefined,
"NAS: safeToIgnore attribute missing" );
m_osLastSafeToIgnore = "false";
}
m_osLastReplacingFID = "";
}
/* -------------------------------------------------------------------- */
/* If it is (or at least potentially is) a simple attribute, */
/* then start collecting it. */
/* -------------------------------------------------------------------- */
else if( m_poReader->IsAttributeElement( szElementName ) )
{
CPLFree( m_pszCurField );
m_pszCurField = CPLStrdup("");
// Capture href as OB property.
m_poReader->CheckForRelations( szElementName, attrs, &m_pszCurField );
// Capture "fid" attribute as part of the property value -
// primarily this is for wfs:Delete operation's FeatureId attribute.
if( EQUAL(szElementName,"FeatureId") )
m_poReader->CheckForFID( attrs, &m_pszCurField );
}
/* -------------------------------------------------------------------- */
/* Push the element onto the current state's path. */
/* -------------------------------------------------------------------- */
poState->PushPath( szElementName );
m_nDepth ++;
}
/************************************************************************/
/* endElement() */
/************************************************************************/
void NASHandler::endElement( const XMLCh* const /* uri */ ,
const XMLCh* const localname,
const XMLCh* const /* qname */)
{
char szElementName[MAX_TOKEN_SIZE];
GMLReadState *poState = m_poReader->GetState();
tr_strcpy( szElementName, localname );
m_nDepth --;
if (m_bIgnoreFeature && m_nDepth >= m_nDepthFeature)
{
if (m_nDepth == m_nDepthFeature)
{
m_bIgnoreFeature = false;
m_nDepthFeature = 0;
}
return;
}
if ( m_osIgnoredElement != "" && m_nDepth >= m_nDepthElement )
{
if ( m_nDepth == m_nDepthElement )
{
m_osIgnoredElement = "";
m_nDepthElement = 0;
}
return;
}
#ifdef DEBUG_VERBOSE
CPLDebug("NAS",
"%*sendElement %s m_bIgnoreFeature:%d depth:%d depthFeature:%d featureClass:%s",
m_nDepth, "", szElementName,
m_bIgnoreFeature, m_nDepth, m_nDepthFeature,
poState->m_poFeature ? poState->m_poFeature->GetClass()->GetElementName() : "(no feature)"
);
#endif
if( m_bInUpdateProperty )
{
if( EQUAL( szElementName, "Name" ) )
{
CPLAssert( m_osLastPropertyName == "" );
m_osLastPropertyName = m_pszCurField;
m_pszCurField = NULL;
}
else if( EQUAL( szElementName, "Value" ) )
{
CPLAssert( m_osLastPropertyValue == "" );
m_osLastPropertyValue = m_pszCurField;
m_pszCurField = NULL;
}
else if( EQUAL( szElementName, "Property" ) )
{
if( EQUAL( m_osLastPropertyName, "adv:lebenszeitintervall/adv:AA_Lebenszeitintervall/adv:endet" ) )
{
CPLAssert( m_osLastPropertyValue != "" );
m_osLastEnded = m_osLastPropertyValue;
}
else if( EQUAL( m_osLastPropertyName, "adv:anlass" ) )
{
CPLAssert( m_osLastPropertyValue != "" );
m_LastOccasions.push_back( m_osLastPropertyValue );
}
else
{
CPLError( CE_Warning, CPLE_AppDefined,
"NAS: Expected property name or value instead of %s",
m_osLastPropertyName.c_str() );
}
m_osLastPropertyName = "";
m_osLastPropertyValue = "";
m_bInUpdateProperty = false;
}
poState->PopPath();
return;
}
if ( m_bInUpdate && EQUAL( szElementName, "Update" ) )
{
m_bInUpdate = false;
}
/* -------------------------------------------------------------------- */
/* Is this closing off an attribute value? We assume so if */
/* we are collecting an attribute value and got to this point. */
/* We don't bother validating that the closing tag matches the */
/* opening tag. */
/* -------------------------------------------------------------------- */
if( m_pszCurField != NULL )
{
CPLAssert( poState->m_poFeature != NULL );
m_poReader->SetFeaturePropertyDirectly( poState->osPath.c_str(), m_pszCurField );
m_pszCurField = NULL;
}
/* -------------------------------------------------------------------- */
/* If we are collecting Geometry than store it, and consider if */
/* this is the end of the geometry. */
/* -------------------------------------------------------------------- */
if( m_pszGeometry != NULL )
{
int nLNLen = tr_strlen( localname );
/* should save attributes too! */
if( m_nGeomLen + nLNLen + 4 > m_nGeomAlloc )
{
m_nGeomAlloc = (int) (m_nGeomAlloc * 1.3 + nLNLen + 1000);
m_pszGeometry = (char *)
CPLRealloc( m_pszGeometry, m_nGeomAlloc);
}
strcat( m_pszGeometry+m_nGeomLen, "</" );
tr_strcpy( m_pszGeometry+m_nGeomLen+2, localname );
strcat( m_pszGeometry+m_nGeomLen+nLNLen+2, ">" );
m_nGeomLen += static_cast<int>(strlen(m_pszGeometry+m_nGeomLen));
if( poState->m_nPathLength == m_nGeometryDepth+1 )
{
if( poState->m_poFeature != NULL )
{
CPLXMLNode* psNode = CPLParseXMLString(m_pszGeometry);
if (psNode)
{
/* workaround for common malformed gml:pos with just a
* elevation value instead of a full 3D coordinate:
*
* <gml:Point gml:id="BII2H">
* <gml:pos srsName="urn:adv:crs:ETRS89_h">41.394</gml:pos>
* </gml:Point>
*
*/
const char *pszPos =
CPLGetXMLValue( psNode, "=Point.pos", NULL );
if( pszPos != NULL && strstr(pszPos, " ") == NULL )
{
CPLSetXMLValue( psNode, "pos", CPLSPrintf("0 0 %s", pszPos) );
}
if ( poState->m_poFeature->GetGeometryList() &&
poState->m_poFeature->GetGeometryList()[0] )
{
int iId = poState->m_poFeature->GetClass()->GetPropertyIndex( "gml_id" );
const GMLProperty *poIdProp = poState->m_poFeature->GetProperty(iId);
#ifdef DEBUG_VERBOSE
char *pszOldGeom = CPLSerializeXMLTree( poState->m_poFeature->GetGeometryList()[0] );
CPLDebug("NAS", "Overwriting other geometry (%s; replace:%s; with:%s)",
poIdProp && poIdProp->nSubProperties>0 && poIdProp->papszSubProperties[0] ? poIdProp->papszSubProperties[0] : "(null)",
m_pszGeometry,
pszOldGeom
);
CPLFree( pszOldGeom );
#else
CPLError( CE_Warning, CPLE_AppDefined, "NAS: Overwriting other geometry (%s)",
poIdProp && poIdProp->nSubProperties>0 && poIdProp->papszSubProperties[0] ? poIdProp->papszSubProperties[0] : "(null)" );
#endif
}
poState->m_poFeature->SetGeometryDirectly( psNode );
}
else
CPLError( CE_Warning, CPLE_AppDefined, "NAS: Invalid geometry skipped" );
}
else
CPLError( CE_Warning, CPLE_AppDefined, "NAS: Skipping geometry without feature" );
CPLFree( m_pszGeometry );
m_pszGeometry = NULL;
m_nGeomAlloc = m_nGeomLen = 0;
}
}
/* -------------------------------------------------------------------- */
/* If we are collecting a feature, and this element tag matches */
/* element name for the class, then we have finished the */
/* feature, and we pop the feature read state. */
/* -------------------------------------------------------------------- */
const char *pszLast = NULL;
if( m_nDepth == m_nDepthFeature && poState->m_poFeature != NULL
&& EQUAL(szElementName,
poState->m_poFeature->GetClass()->GetElementName()) )
{
m_nDepthFeature = 0;
m_poReader->PopState();
}
/* -------------------------------------------------------------------- */
/* Ends of a wfs:Delete or wfs:Update should be triggered on the */
/* close of the <Filter> element. */
/* -------------------------------------------------------------------- */
else if( m_nDepth == m_nDepthFeature
&& poState->m_poFeature != NULL
&& EQUAL(szElementName,"Filter")
&& (pszLast=poState->m_poFeature->GetClass()->GetElementName())
!= NULL
&& ( EQUAL(pszLast, "Delete") || EQUAL(pszLast, "Update") ) )
{
m_nDepthFeature = 0;
m_poReader->PopState();
}
/* -------------------------------------------------------------------- */
/* Otherwise, we just pop the element off the local read states */
/* element stack. */
/* -------------------------------------------------------------------- */
else
{
if( EQUAL(szElementName,poState->GetLastComponent()) )
poState->PopPath();
else
{
CPLAssert( false );
}
}
}
/************************************************************************/
/* characters() */
/************************************************************************/
#if XERCES_VERSION_MAJOR >= 3
void NASHandler::characters( const XMLCh *const chars_in,
const XMLSize_t /* length */ )
#else
void NASHandler::characters( const XMLCh* const chars_in,
const unsigned int /* length */ )
#endif
{
const XMLCh *chars = chars_in;
if( m_pszCurField != NULL )
{
const int nCurFieldLength = static_cast<int>(strlen(m_pszCurField));
if (nCurFieldLength == 0)
{
// Ignore white space
while( *chars == ' ' || *chars == 10 || *chars == 13 ||
*chars == '\t')
chars++;
}
char *pszTranslated = tr_strdup(chars);
if( m_pszCurField == NULL )
{
m_pszCurField = pszTranslated;
}
else
{
m_pszCurField = static_cast<char *>(
CPLRealloc( m_pszCurField,
nCurFieldLength+strlen(pszTranslated)+1 ) );
strcpy( m_pszCurField + nCurFieldLength, pszTranslated );
CPLFree( pszTranslated );
}
}
else if( m_pszGeometry != NULL )
{
if (m_nGeomLen == 0)
{
// Ignore white space
while( *chars == ' ' || *chars == 10 || *chars == 13 ||
*chars == '\t')
chars++;
}
const int nCharsLen = tr_strlen(chars);
if( m_nGeomLen + nCharsLen*4 + 4 > m_nGeomAlloc )
{
m_nGeomAlloc = (int) (m_nGeomAlloc * 1.3 + nCharsLen*4 + 1000);
m_pszGeometry = (char *)
CPLRealloc( m_pszGeometry, m_nGeomAlloc);
}
tr_strcpy( m_pszGeometry+m_nGeomLen, chars );
m_nGeomLen += static_cast<int>(strlen(m_pszGeometry+m_nGeomLen));
}
}
/************************************************************************/
/* fatalError() */
/************************************************************************/
void NASHandler::fatalError( const SAXParseException &exception)
{
char *pszErrorMessage = tr_strdup( exception.getMessage() );
CPLError( CE_Failure, CPLE_AppDefined,
"XML Parsing Error: %s at line %d, column %d\n",
pszErrorMessage,
static_cast<int>(exception.getLineNumber()),
static_cast<int>(exception.getColumnNumber()) );
CPLFree( pszErrorMessage );
}
/************************************************************************/
/* IsGeometryElement() */
/************************************************************************/
bool NASHandler::IsGeometryElement( const char *pszElement )
{
return strcmp(pszElement,"Polygon") == 0
|| strcmp(pszElement,"MultiPolygon") == 0
|| strcmp(pszElement,"MultiPoint") == 0
|| strcmp(pszElement,"MultiLineString") == 0
|| strcmp(pszElement,"MultiSurface") == 0
|| strcmp(pszElement,"GeometryCollection") == 0
|| strcmp(pszElement,"Point") == 0
|| strcmp(pszElement,"Curve") == 0
|| strcmp(pszElement,"MultiCurve") == 0
|| strcmp(pszElement,"CompositeCurve") == 0
|| strcmp(pszElement,"Surface") == 0
|| strcmp(pszElement,"PolygonPatch") == 0
|| strcmp(pszElement,"LineString") == 0;
}
// vim: set sw=4 expandtab :
| 36.801471 | 154 | 0.463736 | [
"geometry",
"3d"
] |
a34aa39a8c7b792f01c4ae07423eac7278e75e9e | 3,306 | cpp | C++ | design_hls/Park_Inverse/test_park_inverse.cpp | JoelNeys/IIoT-EDDP | ab95ee2762840c35b12342c717100c27579ef1f4 | [
"BSD-3-Clause"
] | 63 | 2018-02-20T17:01:38.000Z | 2021-11-15T16:26:23.000Z | design_hls/Park_Inverse/test_park_inverse.cpp | Reg-Chin/IIoT-EDDP | ffe49cf8607397580857fe0e885aba2b8341f8ca | [
"BSD-3-Clause"
] | 3 | 2018-12-05T08:57:02.000Z | 2021-06-06T09:04:34.000Z | design_hls/Park_Inverse/test_park_inverse.cpp | Reg-Chin/IIoT-EDDP | ffe49cf8607397580857fe0e885aba2b8341f8ca | [
"BSD-3-Clause"
] | 29 | 2017-10-18T11:22:37.000Z | 2021-11-15T16:26:28.000Z | /*
The 3-Clause BSD License
SPDX short identifier: BSD-3-Clause
Copyright 2016-2017 Trenz Electronic GmbH
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*!
* \file test_park_inverse.cpp
* \brief Testbench for the inverse Park's transform
* \author Oleksandr Kiyenko
* \version 1.0
* \date 2017
* \copyright SPDX: BSD-3-Clause 2016-2017 Trenz Electronic GmbH
*/
#include "park_inverse.h"
#include <math.h>
/** \brief Number of values to test with. */
#define TEST_SIZE 10
/** \brief Mathematical constant \f$\pi\f$. */
#define M_PI 3.14159265358979323846
/** \brief Values of \f$V_d\f$ to test Park_Inverse() with. */
int Vd[TEST_SIZE] = {-600, 2000, 100, 555, -255, 3333, -765, 333, 200, -543};
/** \brief Values of \f$V_q\f$ to test Park_Inverse() with. */
int Vq[TEST_SIZE] = {-888, 3000, -500, 7000, 1000, -123, -800, 9000, 789, -444};
using namespace hls;
/**
* \brief Main function of the C testbench.
*
* The function Park_Inverse() will be called with the values of \f$V_d\f$ and \f$V_q\f$ in #Vd and #Vq
* and the results will be printed along with separately calculated values.
*/
int main(){
hls::stream<int32_t> inputStream;
hls::stream<int32_t> outputStream;
int32_t tx_data, rx_data;
int16_t Vdlpha, Vqeta;
int16_t Theta;
float Vdf, Vqf, Thetaf;
Theta = 100;
for(int i=0; i<TEST_SIZE; i++){
tx_data = (int32_t(Vq[i]) << 16) | (int32_t(Vd[i]) & 0x0000FFFF);
inputStream << tx_data;
Park_Inverse(inputStream, outputStream, Theta);
outputStream.read(rx_data);
Vdlpha = int16_t(rx_data & 0xFFFF);
Vqeta = int16_t(rx_data >> 16);
Thetaf = ((2*M_PI*2)/1000.0)*Theta;
Vdf = float(Vd[i])*cos(Thetaf) - float(Vq[i]) * sin(Thetaf);
Vqf = float(Vq[i])*cos(Thetaf) + float(Vd[i]) * sin(Thetaf);
printf("Values is Vd=%d Vq=%d (%f %f)\n",Vdlpha, Vqeta, Vdf, Vqf);
}
}
| 42.384615 | 756 | 0.714761 | [
"transform"
] |
a34ab4085e5f70de302ad9698971c9da476b88f9 | 4,445 | cpp | C++ | libnd4j/include/ops/declarable/impl/BroadcastableOp.cpp | Celebrate-future/deeplearning4j | d93976922a9af838457a15e69ef1218c3d9adc45 | [
"Apache-2.0"
] | 1 | 2021-09-01T06:59:10.000Z | 2021-09-01T06:59:10.000Z | libnd4j/include/ops/declarable/impl/BroadcastableOp.cpp | Celebrate-future/deeplearning4j | d93976922a9af838457a15e69ef1218c3d9adc45 | [
"Apache-2.0"
] | 1 | 2021-03-18T12:52:25.000Z | 2021-03-18T12:52:25.000Z | libnd4j/include/ops/declarable/impl/BroadcastableOp.cpp | Celebrate-future/deeplearning4j | d93976922a9af838457a15e69ef1218c3d9adc45 | [
"Apache-2.0"
] | null | null | null | /* ******************************************************************************
*
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
//
// Created by raver on 6/6/2018.
//
#include <system/op_boilerplate.h>
#include <system/pointercast.h>
#include <ops/declarable/BroadcastableOp.h>
#include <helpers/ShapeUtils.h>
namespace sd {
namespace ops {
BroadcastableOp::BroadcastableOp(const char *name, int numTArgs, int numIArgs) : DeclarableCustomOp::DeclarableCustomOp(2, 1, name, false, numTArgs, numIArgs) {
//
}
ShapeList *BroadcastableOp::calculateOutputShape(ShapeList *inputShape, sd::graph::Context &block) {
auto shapeList = SHAPELIST();
auto x = inputShape->at(0);
auto y = inputShape->at(1);
auto outputs = _descriptor->getOutputTypesForOutput(0);
sd::DataType dtype = block.dataType(0);
if (block.dataType(0) != sd::DataType::BOOL && !(outputs.size() == 1 && outputs[0] == sd::DataType::BOOL)) {
if (Environment::getInstance().isExperimentalBuild()) {
if (shape::length(y) > shape::length(x)) {
dtype = DataTypeUtils::pickPairwiseResultType(y, x);
} else {
dtype = DataTypeUtils::pickPairwiseResultType(x, y);
}
} else {
dtype = ArrayOptions::dataType(x);
}
} else
dtype = sd::DataType::BOOL;
if(shape::isEmpty(x) || shape::isEmpty(y)) {
// this is edge case, [3, 4] + [] = []
if ((shape::isEmpty(x) && shape::rank(x) == 0) || (shape::isEmpty(y) && shape::rank(y) == 0)) {
shapeList->push_back(ConstantShapeHelper::getInstance().createShapeInfo(ShapeDescriptor::emptyDescriptor(dtype)));
return shapeList;
}
const Nd4jLong *newshape = nullptr;
ShapeUtils::evalBroadcastShapeInfo(x, y, true, newshape, block.workspace());
shapeList->push_back(ConstantShapeHelper::getInstance().createShapeInfo(ShapeDescriptor(newshape, dtype)));
} else if (shape::isScalar(x) && shape::isScalar(y)) {
if (shape::rank(x) >= shape::rank(y)) {
shapeList->push_back(ConstantShapeHelper::getInstance().createShapeInfo(ShapeDescriptor(x, dtype)));
} else {
shapeList->push_back(ConstantShapeHelper::getInstance().createShapeInfo(ShapeDescriptor(y, dtype)));
}
} else if (shape::equalsSoft(x, y)) {
shapeList->push_back(ConstantShapeHelper::getInstance().createShapeInfo(ShapeDescriptor(x, dtype)));
} else if (shape::isScalar(x) && !shape::isScalar(y)) {
shapeList->push_back(ConstantShapeHelper::getInstance().createShapeInfo(ShapeDescriptor(y, dtype)));
} else if (!shape::isScalar(x) && shape::isScalar(y)) {
shapeList->push_back(ConstantShapeHelper::getInstance().createShapeInfo(ShapeDescriptor(x, dtype)));
} else if (ShapeUtils::areShapesBroadcastable(x, y)) {
const Nd4jLong *newshape = nullptr;
ShapeUtils::evalBroadcastShapeInfo(x, y, true, newshape, block.workspace());
shapeList->push_back(ConstantShapeHelper::getInstance().createShapeInfo(ShapeDescriptor(newshape, dtype)));
} else {
// in this case we'll throw exception later
shapeList->push_back(ConstantShapeHelper::getInstance().createShapeInfo(ShapeDescriptor(x, dtype)));
}
return shapeList;
}
}
} | 50.511364 | 168 | 0.586052 | [
"shape"
] |
a34ae03182a462db1a1717d8cd249b2fae3246ad | 27,755 | cpp | C++ | third_party/katana/lib/usdKatana/readPointInstancer.cpp | YuqiaoZhang/USD | bf3a21e6e049486441440ebf8c0387db2538d096 | [
"BSD-2-Clause"
] | 5 | 2017-11-06T10:21:18.000Z | 2020-04-02T13:20:55.000Z | third_party/katana/lib/usdKatana/readPointInstancer.cpp | YuqiaoZhang/USD | bf3a21e6e049486441440ebf8c0387db2538d096 | [
"BSD-2-Clause"
] | 1 | 2020-07-07T22:39:42.000Z | 2020-07-07T22:39:42.000Z | third_party/katana/lib/usdKatana/readPointInstancer.cpp | YuqiaoZhang/USD | bf3a21e6e049486441440ebf8c0387db2538d096 | [
"BSD-2-Clause"
] | null | null | null | //
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#include "usdKatana/attrMap.h"
#include "usdKatana/readPointInstancer.h"
#include "usdKatana/readXformable.h"
#include "usdKatana/usdInPrivateData.h"
#include "usdKatana/utils.h"
#include "pxr/usd/usdGeom/pointInstancer.h"
#include "pxr/usd/usdGeom/xform.h"
#include "pxr/usd/usd/modelAPI.h"
#include "pxr/usd/usdShade/material.h"
#include "pxr/usd/kind/registry.h"
#include "pxr/base/gf/transform.h"
#include "pxr/base/gf/matrix4d.h"
#include <FnAPI/FnAPI.h>
#include <FnGeolibServices/FnBuiltInOpArgsUtil.h>
#include <FnGeolib/util/Path.h>
#include <FnLogging/FnLogging.h>
#include <boost/unordered_set.hpp>
#include <pystring/pystring.h>
#if KATANA_VERSION_MAJOR >= 3
#include "vtKatana/array.h"
#endif // KATANA_VERSION_MAJOR >= 3
PXR_NAMESPACE_OPEN_SCOPE
FnLogSetup("PxrUsdKatanaReadPointInstancer");
namespace
{
typedef std::map<SdfPath, UsdPrim> _PathToPrimMap;
typedef std::map<SdfPath, GfRange3d> _PathToRangeMap;
typedef std::map<TfToken, GfRange3d, TfTokenFastArbitraryLessThan>
_PurposeToRangeMap;
// Log an error and set attrs to show an error message in the Scene Graph.
//
void
_LogAndSetError(
PxrUsdKatanaAttrMap& attrs,
const std::string& message)
{
FnLogError(message);
attrs.set("errorMessage",
FnKat::StringAttribute(
"[ERROR PxrUsdKatanaReadPointInstancer]: " + message));
}
// Log a warning and set attrs to show a warning message in the Scene Graph.
void
_LogAndSetWarning(
PxrUsdKatanaAttrMap &attrs,
const std::string& message)
{
FnLogWarn(message);
attrs.set("warningMessage",
FnKat::StringAttribute(
"[WARNING PxrUsdKatanaReadPointInstancer]: " + message));
}
// XXX This is based on UsdGeomPointInstancer::ComputeExtentAtTime. Ideally,
// we would just use UsdGeomPointInstancer, however it does not account for
// multi-sampled transforms (see bug 147526).
//
bool
_ComputeExtentAtTime(
VtVec3fArray& extent,
PxrUsdKatanaUsdInArgsRefPtr usdInArgs,
const std::vector<VtArray<GfMatrix4d>>& xforms,
const std::vector<double>& motionSampleTimes,
const VtIntArray& protoIndices,
const SdfPathVector& protoPaths,
const _PathToPrimMap& primCache,
const std::vector<bool>& mask)
{
GfRange3d extentRange;
const size_t numSampleTimes = motionSampleTimes.size();
for (size_t i = 0; i < protoIndices.size(); ++i) {
if (!mask.empty() && !mask[i]) {
continue;
}
const int protoIndex = protoIndices[i];
const SdfPath &protoPath = protoPaths[protoIndex];
_PathToPrimMap::const_iterator pcIt = primCache.find(protoPath);
const UsdPrim &protoPrim = pcIt->second;
if (!protoPrim) {
continue;
}
// Leverage usdInArgs for calculating the proto prim's bound. Note
// that we apply the prototype's local transform to account for any
// offsets.
//
std::vector<GfBBox3d> sampledBounds = usdInArgs->ComputeBounds(
protoPrim, motionSampleTimes, /* applyLocalTransform */ true);
for (size_t a = 0; a < numSampleTimes; ++a) {
// Apply the instance transform to the bounding box for this
// time sample. We don't apply the parent transform here, as the
// bounds need to be in parent-local space.
//
GfBBox3d thisBounds(sampledBounds[a]);
thisBounds.Transform(xforms[a][i]);
extentRange.UnionWith(thisBounds.ComputeAlignedRange());
}
}
if (extentRange.IsEmpty()) {
return false;
}
const GfVec3d extentMin = extentRange.GetMin();
const GfVec3d extentMax = extentRange.GetMax();
extent = VtVec3fArray(2);
extent[0] = GfVec3f(extentMin[0], extentMin[1], extentMin[2]);
extent[1] = GfVec3f(extentMax[0], extentMax[1], extentMax[2]);
return true;
}
} // anon namespace
void
PxrUsdKatanaReadPointInstancer(
const UsdGeomPointInstancer& instancer,
const PxrUsdKatanaUsdInPrivateData& data,
PxrUsdKatanaAttrMap& instancerAttrMap,
PxrUsdKatanaAttrMap& sourcesAttrMap,
PxrUsdKatanaAttrMap& instancesAttrMap,
PxrUsdKatanaAttrMap& inputAttrMap)
{
const double currentTime = data.GetCurrentTime();
PxrUsdKatanaReadXformable(instancer, data, instancerAttrMap);
// Get primvars for setting later. Unfortunatley, the only way to get them
// out of the attr map is to build it, which will cause its contents to be
// cleared. We'll need to restore its contents before continuing.
//
FnKat::GroupAttribute instancerAttrs = instancerAttrMap.build();
FnKat::GroupAttribute primvarAttrs =
instancerAttrs.getChildByName("geometry.arbitrary");
for (int64_t i = 0; i < instancerAttrs.getNumberOfChildren(); ++i)
{
instancerAttrMap.set(instancerAttrs.getChildName(i),
instancerAttrs.getChildByIndex(i));
}
instancerAttrMap.set("type", FnKat::StringAttribute("usd point instancer"));
const std::string fileName = data.GetUsdInArgs()->GetFileName();
instancerAttrMap.set("info.usd.fileName", FnKat::StringAttribute(fileName));
FnKat::GroupAttribute inputAttrs = inputAttrMap.build();
const std::string katOutputPath = FnKat::StringAttribute(
inputAttrs.getChildByName("outputLocationPath")).getValue("", false);
if (katOutputPath.empty())
{
_LogAndSetError(instancerAttrMap, "No output location path specified");
return;
}
//
// Validate instancer data.
//
const auto instancerSdfPath = instancer.GetPath();
const std::string instancerPath = instancerSdfPath.GetString();
UsdStageWeakPtr stage = instancer.GetPrim().GetStage();
// Prototypes (required)
//
SdfPathVector protoPaths;
instancer.GetPrototypesRel().GetTargets(&protoPaths);
if (protoPaths.empty())
{
_LogAndSetError(instancerAttrMap, "Instancer has no prototypes");
return;
}
_PathToPrimMap primCache;
for (auto protoPath : protoPaths) {
const UsdPrim &protoPrim = stage->GetPrimAtPath(protoPath);
primCache[protoPath] = protoPrim;
}
// Indices (required)
//
VtIntArray protoIndices;
if (!instancer.GetProtoIndicesAttr().Get(&protoIndices, currentTime))
{
_LogAndSetWarning(instancerAttrMap,
"Instancer has no prototype indices");
return;
}
const size_t numInstances = protoIndices.size();
if (numInstances == 0)
{
_LogAndSetWarning(instancerAttrMap,
"Instancer has no prototype indices");
return;
}
for (auto protoIndex : protoIndices)
{
if (protoIndex < 0 || static_cast<size_t>(protoIndex) >= protoPaths.size())
{
_LogAndSetError(instancerAttrMap, TfStringPrintf(
"Out of range prototype index %d", protoIndex));
return;
}
}
// Mask (optional)
//
std::vector<bool> pruneMaskValues =
instancer.ComputeMaskAtTime(currentTime);
if (!pruneMaskValues.empty() and pruneMaskValues.size() != numInstances)
{
_LogAndSetError(instancerAttrMap,
"Mismatch in length of indices and mask");
return;
}
// Positions (required)
//
UsdAttribute positionsAttr = instancer.GetPositionsAttr();
if (!positionsAttr.HasValue())
{
_LogAndSetError(instancerAttrMap, "Instancer has no positions");
return;
}
//
// Compute instance transform matrices.
//
// Special case: Ensure that there is more than one sample if velocity is
// authored. This will accommodate cases where positions is not sufficiently
// sampled to produce motion, but motion can be inferred via velocities.
//
// XXX Mere presence of the velocities attr does not guarantee that it will
// be used in the final instance transforms computation (the velocities attr
// must pass additional checks made inside usdGeom's samplingUtils). We are
// not currently performing these additional checks.
//
bool ensureMotion = false;
if (UsdAttribute velocitiesAttr = instancer.GetVelocitiesAttr())
{
if (velocitiesAttr.HasValue())
{
ensureMotion = true;
}
}
// Gather frame-relative sample times and add them to the current time to
// generate absolute sample times.
//
const std::vector<double> &motionSampleTimes =
data.GetMotionSampleTimes(positionsAttr, ensureMotion);
const size_t sampleCount = motionSampleTimes.size();
std::vector<UsdTimeCode> sampleTimes(sampleCount);
std::transform(motionSampleTimes.begin(), motionSampleTimes.end(),
sampleTimes.begin(), [currentTime](double motionSampleTime){
return UsdTimeCode(currentTime + motionSampleTime);});
std::vector<VtArray<GfMatrix4d>> xformSamples(sampleCount);
instancer.ComputeInstanceTransformsAtTimes(
&xformSamples,
sampleTimes,
UsdTimeCode(currentTime),
UsdGeomPointInstancer::IncludeProtoXform,
UsdGeomPointInstancer::IgnoreMask);
const size_t numXformSamples = xformSamples.size();
if (numXformSamples == 0) {
_LogAndSetError(instancerAttrMap, "Could not compute "
"sample/topology-invarying instance "
"transform matrix");
return;
}
//
// Compute prototype bounds.
//
bool aggregateBoundsValid = false;
std::vector<double> aggregateBounds;
// XXX Replace with UsdGeomPointInstancer::ComputeExtentAtTime.
//
VtVec3fArray aggregateExtent;
if (_ComputeExtentAtTime(
aggregateExtent, data.GetUsdInArgs(), xformSamples,
motionSampleTimes, protoIndices, protoPaths, primCache,
pruneMaskValues)) {
aggregateBoundsValid = true;
aggregateBounds.resize(6);
aggregateBounds[0] = aggregateExtent[0][0]; // min x
aggregateBounds[1] = aggregateExtent[1][0]; // max x
aggregateBounds[2] = aggregateExtent[0][1]; // min y
aggregateBounds[3] = aggregateExtent[1][1]; // max y
aggregateBounds[4] = aggregateExtent[0][2]; // min z
aggregateBounds[5] = aggregateExtent[1][2]; // max z
}
//
// Build sources (prototypes). Keep track of which instances use them.
//
FnGeolibServices::StaticSceneCreateOpArgsBuilder sourcesBldr(false);
std::vector<int> instanceIndices;
instanceIndices.reserve(numInstances);
std::vector<std::string> instanceSources;
instanceSources.reserve(protoPaths.size());
std::map<std::string, int> instanceSourceIndexMap;
std::vector<int> omitList;
omitList.reserve(numInstances);
std::map<SdfPath, std::string> protoPathsToKatPaths;
std::map<std::string, std::vector<std::string>> usdPrimPathsTracker;
for (size_t i = 0; i < numInstances; ++i)
{
int index = protoIndices[i];
// Check to see if we are pruned.
//
bool isPruned = (!pruneMaskValues.empty() and
pruneMaskValues[i] == false);
if (isPruned)
{
omitList.push_back(i);
}
const SdfPath &protoPath = protoPaths[index];
// Compute the Katana path to this prototype.
//
std::string katProtoPath;
std::map<SdfPath, std::string>::const_iterator pptkpIt =
protoPathsToKatPaths.find(protoPath);
if (pptkpIt != protoPathsToKatPaths.end())
{
katProtoPath = pptkpIt->second;
}
else
{
_PathToPrimMap::const_iterator pcIt = primCache.find(protoPath);
const UsdPrim &protoPrim = pcIt->second;
if (!protoPrim) {
continue;
}
// Determine where (what path) to start building the prototype prim
// such that the Look prims that it depends on will also get built.
// This could be the prototype path itself or an ancestor path.
//
SdfPathVector commonPrefixes;
// If the proto prim itself doesn't have any bindings or isn't a
// (sub)component, we'll walk upwards until we find a prim that
// does/is. Stop walking if we reach the instancer or the usdInArgs
// root.
//
UsdPrim prim = protoPrim;
while (prim and prim != instancer.GetPrim() and
prim != data.GetUsdInArgs()->GetRootPrim())
{
UsdRelationship materialBindingsRel =
UsdShadeMaterial::GetBindingRel(prim);
SdfPathVector materialPaths;
bool hasMaterialBindings = (materialBindingsRel and
materialBindingsRel.GetForwardedTargets(
&materialPaths) and !materialPaths.empty());
TfToken kind;
std::string assetName;
auto assetAPI = UsdModelAPI(prim);
// If the prim is a (sub)component, it should have materials
// defined below it.
bool hasMaterialChildren = (
assetAPI.GetAssetName(&assetName) and
assetAPI.GetKind(&kind) and (
KindRegistry::IsA(kind, KindTokens->component) or
KindRegistry::IsA(kind, KindTokens->subcomponent)));
if (hasMaterialChildren)
{
// The prim has material children, so start building at the
// prim's path.
//
commonPrefixes.push_back(prim.GetPath());
break;
}
if (hasMaterialBindings)
{
for (auto materialPath : materialPaths)
{
const SdfPath &commonPrefix =
protoPath.GetCommonPrefix(materialPath);
if (commonPrefix.GetString() == "/" || instancerSdfPath.HasPrefix(commonPrefix))
{
// XXX Unhandled case.
// The prim and its material are not under the same
// parent; start building at the prim's path
// (although it is likely that bindings will be
// broken).
//
commonPrefixes.push_back(prim.GetPath());
}
else
{
// Start building at the common ancestor between the
// prim and its material.
//
commonPrefixes.push_back(commonPrefix);
}
}
break;
}
prim = prim.GetParent();
}
// Fail-safe in case no common prefixes were found.
//
if (commonPrefixes.empty())
{
commonPrefixes.push_back(protoPath);
}
// XXX Unhandled case.
// We'll use the first common ancestor even if there is more than
// one (which shouldn't happen if the prototype prim and its bindings
// are under the same parent).
//
SdfPath::RemoveDescendentPaths(&commonPrefixes);
const std::string buildPath = commonPrefixes[0].GetString();
// See if the path is a child of the point instancer. If so, we'll
// match its hierarchy. If not, we'll put it under a 'prototypes'
// group.
//
std::string relBuildPath;
if (pystring::startswith(buildPath, instancerPath + "/"))
{
relBuildPath = pystring::replace(
buildPath, instancerPath + "/", "");
}
else
{
relBuildPath = "prototypes/" +
FnGeolibUtil::Path::GetLeafName(buildPath);
}
// Start generating the Katana path to the prototype.
//
katProtoPath = katOutputPath + "/" + relBuildPath;
// Tell the BuildIntermediate op to start building at the common
// ancestor, but don't clobber the paths of any other prims that
// need to be built out too.
//
const std::string relBuildPathUpOne =
FnGeolibUtil::Path::GetLocationParent(relBuildPath);
if (usdPrimPathsTracker.find(relBuildPathUpOne) ==
usdPrimPathsTracker.end())
{
usdPrimPathsTracker[relBuildPathUpOne].push_back(buildPath);
}
else
{
auto& primPaths = usdPrimPathsTracker[relBuildPathUpOne];
if (std::find(primPaths.begin(), primPaths.end(), buildPath) ==
primPaths.end())
{
primPaths.push_back(buildPath);
}
}
sourcesBldr.setAttrAtLocation(relBuildPathUpOne,
"usdPrimPath", FnKat::StringAttribute(
usdPrimPathsTracker[relBuildPathUpOne]));
// Build an AttributeSet op that will delete the prototype's
// transform, since we've already folded it into the instance
// transforms via IncludeProtoXform.
//
FnGeolibServices::AttributeSetOpArgsBuilder delXformBldr;
delXformBldr.deleteAttr("xform");
std::string relProtoPath = relBuildPath;
if (protoPath.GetString() != buildPath)
{
// Finish generating the Katana path to the prototype.
//
katProtoPath = katProtoPath + pystring::replace(
protoPath.GetString(), buildPath, "");
relProtoPath = relProtoPath + pystring::replace(
protoPath.GetString(), buildPath, "");
}
// Dermine whether or not we can use the prototype prim itself as
// the instance source or if we should insert an empty group into
// the hierarchy to hold the instance source type. The latter will
// be true if the prototype's native Katana type needs to be
// preserved, for example, if the prototype is a gprim.
//
// XXX Since we can't make an assumption about what Katana type the
// PxrUsdIn ops will author, we'll have to make a best guess. For
// now, consider Xform prims without an authored kind to be usable
// as instance sources.
//
TfToken kind;
const bool useProtoAsInstanceSource =
protoPrim.IsA<UsdGeomXform>() &&
!UsdModelAPI(protoPrim).GetKind(&kind);
if (useProtoAsInstanceSource)
{
delXformBldr.setLocationPaths(katProtoPath);
sourcesBldr.addSubOpAtLocation(
relProtoPath,
"AttributeSet", delXformBldr.build());
}
else
{
// Tell PxrUsdIn to create an empty group when it gets to the
// prototype's location.
//
sourcesBldr.setAttrAtLocation(relProtoPath,
"insertEmptyGroup", FnKat::IntAttribute(1));
// Since the empty group will have the same name as the
// prototype, we can add the prototype's name to its original
// Katana path to get its post-insertion Katana path.
//
const std::string protoName = protoPrim.GetName();
delXformBldr.setLocationPaths(katProtoPath + "/" + protoName);
sourcesBldr.addSubOpAtLocation(
relProtoPath + "/" + protoName,
"AttributeSet", delXformBldr.build());
}
// Build an AttributeSet op that will set the instance source type
// on the prototype or the empty group (if we inserted one).
//
FnGeolibServices::AttributeSetOpArgsBuilder setTypeBldr;
setTypeBldr.setAttr("type",
FnKat::StringAttribute("instance source"));
setTypeBldr.setLocationPaths(katProtoPath);
sourcesBldr.addSubOpAtLocation(relProtoPath,
"AttributeSet", setTypeBldr.build());
// Create a mapping that will link the instance's index to its
// prototype's Katana path.
//
instanceSourceIndexMap[katProtoPath] = instanceSources.size();
instanceSources.push_back(katProtoPath);
// Finally, store the Katana path in the map so we won't have to do
// this work again.
//
protoPathsToKatPaths[protoPath] = katProtoPath;
}
instanceIndices.push_back(instanceSourceIndexMap[katProtoPath]);
}
//
// Build instances.
//
FnGeolibServices::StaticSceneCreateOpArgsBuilder instancesBldr(false);
instancesBldr.createEmptyLocation("instances", "instance array");
instancesBldr.setAttrAtLocation("instances",
"geometry.instanceSource",
FnKat::StringAttribute(instanceSources, 1));
instancesBldr.setAttrAtLocation("instances",
"geometry.instanceIndex",
FnKat::IntAttribute(&instanceIndices[0],
instanceIndices.size(), 1));
#if KATANA_VERSION_MAJOR >= 3
// If motion is backwards, make sure to reverse time samples.
std::map<float, VtArray<GfMatrix4d>> timeToSampleMap;
for (size_t a = 0; a < numXformSamples; ++a) {
double relSampleTime = motionSampleTimes[a];
timeToSampleMap.insert(
{data.IsMotionBackward()
? PxrUsdKatanaUtils::ReverseTimeSample(relSampleTime)
: relSampleTime,
xformSamples[a]});
}
auto instanceMatrixAttr = VtKatanaMapOrCopy(timeToSampleMap);
instancesBldr.setAttrAtLocation("instances", "geometry.instanceMatrix",
instanceMatrixAttr);
#else
FnKat::DoubleBuilder instanceMatrixBldr(16);
for (size_t a = 0; a < numXformSamples; ++a) {
double relSampleTime = motionSampleTimes[a];
// Shove samples into the builder at the frame-relative sample time. If
// motion is backwards, make sure to reverse time samples.
std::vector<double> &matVec = instanceMatrixBldr.get(
data.IsMotionBackward()
? PxrUsdKatanaUtils::ReverseTimeSample(relSampleTime)
: relSampleTime);
matVec.reserve(16 * numInstances);
for (size_t i = 0; i < numInstances; ++i) {
GfMatrix4d instanceXform = xformSamples[a][i];
const double *matArray = instanceXform.GetArray();
for (int j = 0; j < 16; ++j) {
matVec.push_back(matArray[j]);
}
}
}
instancesBldr.setAttrAtLocation("instances",
"geometry.instanceMatrix", instanceMatrixBldr.build());
#endif // KATANA_VERSION_MAJOR > 3
if (!omitList.empty())
{
instancesBldr.setAttrAtLocation("instances",
"geometry.omitList",
FnKat::IntAttribute(&omitList[0], omitList.size(), 1));
}
instancesBldr.setAttrAtLocation("instances",
"geometry.pointInstancerId",
FnKat::StringAttribute(katOutputPath));
//
// Transfer primvars.
//
FnKat::GroupBuilder instancerPrimvarsBldr;
FnKat::GroupBuilder instancesPrimvarsBldr;
for (int64_t i = 0; i < primvarAttrs.getNumberOfChildren(); ++i)
{
const std::string primvarName = primvarAttrs.getChildName(i);
FnKat::GroupAttribute primvarAttr = primvarAttrs.getChildByIndex(i);
if (FnKat::StringAttribute(primvarAttr.getChildByName("scope")
).getValue("", false) == "primitive")
{
// If this primvar is constant, leave it on the instancer.
//
instancerPrimvarsBldr.set(primvarName, primvarAttr);
}
else
{
// If this primvar is non-constant, move it down to the instances,
// but make it constant so that it can be sliced and used by each
// instance.
//
instancesPrimvarsBldr.set(primvarName, primvarAttr);
instancesPrimvarsBldr.set(primvarName + ".scope",
FnKat::StringAttribute("primitive"));
}
}
instancerAttrMap.set("geometry.arbitrary", instancerPrimvarsBldr.build());
instancesBldr.setAttrAtLocation("instances",
"geometry.arbitrary", instancesPrimvarsBldr.build());
//
// Set the final aggregate bounds.
//
if (aggregateBoundsValid)
{
instancerAttrMap.set("bound", FnKat::DoubleAttribute(&aggregateBounds[0], 6, 2));
}
//
// Set proxy attrs.
//
instancerAttrMap.set("proxies", PxrUsdKatanaUtils::GetViewerProxyAttr(data));
//
// Transfer builder results to our attr maps.
//
FnKat::GroupAttribute sourcesAttrs = sourcesBldr.build();
for (int64_t i = 0; i < sourcesAttrs.getNumberOfChildren(); ++i)
{
sourcesAttrMap.set(
sourcesAttrs.getChildName(i),
sourcesAttrs.getChildByIndex(i));
}
FnKat::GroupAttribute instancesAttrs = instancesBldr.build();
for (int64_t i = 0; i < instancesAttrs.getNumberOfChildren(); ++i)
{
instancesAttrMap.set(
instancesAttrs.getChildName(i),
instancesAttrs.getChildByIndex(i));
}
}
PXR_NAMESPACE_CLOSE_SCOPE
| 36.95739 | 104 | 0.593875 | [
"geometry",
"vector",
"transform"
] |
a34d0cb74c794d8b30233aac8e7a062b632dfefe | 9,556 | cc | C++ | llvm-gcc-4.2-2.9/libstdc++-v3/testsuite/21_strings/basic_string/operators/wchar_t/2.cc | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | 1 | 2016-04-09T02:58:13.000Z | 2016-04-09T02:58:13.000Z | llvm-gcc-4.2-2.9/libstdc++-v3/testsuite/21_strings/basic_string/operators/wchar_t/2.cc | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | null | null | null | llvm-gcc-4.2-2.9/libstdc++-v3/testsuite/21_strings/basic_string/operators/wchar_t/2.cc | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | null | null | null | // 1998-10-01, 1999-06-25 bkoz
// Copyright (C) 1998, 1999, 2003 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING. If not, write to the Free
// Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
// USA.
// 21.3.7.1 basic_string non-member functions
// 21.3.7.2 operator==
/*
template<class charT, class traits, class Allocator>
bool operator==(const basic_string<charT,traits,Allocator>& lhs,
const basic_string<charT,traits,Allocator>& rhs);
template<class charT, class traits, class Allocator>
bool operator==(const charT* lhs,
const basic_string<charT,traits,Allocator>& rhs);
template<class charT, class traits, class Allocator>
bool operator==(const basic_string<charT,traits,Allocator>& lhs,
const charT* rhs);
*/
// 21.3.7.3 operator!=
/*
template<class charT, class traits, class Allocator>
bool operator!=(const basic_string<charT,traits,Allocator>& lhs,
const basic_string<charT,traits,Allocator>& rhs);
template<class charT, class traits, class Allocator>
bool operator!=(const charT* lhs,
const basic_string<charT,traits,Allocator>& rhs);
template<class charT, class traits, class Allocator>
bool operator!=(const basic_string<charT,traits,Allocator>& lhs,
const charT* rhs);
*/
// 21.3.7.4 operator<
/*
template<class charT, class traits, class Allocator>
bool operator< (const basic_string<charT,traits,Allocator>& lhs,
const basic_string<charT,traits,Allocator>& rhs);
template<class charT, class traits, class Allocator>
bool operator< (const basic_string<charT,traits,Allocator>& lhs,
const charT* rhs);
template<class charT, class traits, class Allocator>
bool operator< (const charT* lhs,
const basic_string<charT,traits,Allocator>& rhs);
*/
// 21.3.7.5 operator>
/*
template<class charT, class traits, class Allocator>
bool operator> (const basic_string<charT,traits,Allocator>& lhs,
const basic_string<charT,traits,Allocator>& rhs);
template<class charT, class traits, class Allocator>
bool operator> (const basic_string<charT,traits,Allocator>& lhs,
const charT* rhs);
template<class charT, class traits, class Allocator>
bool operator> (const charT* lhs,
const basic_string<charT,traits,Allocator>& rhs);
*/
//21.3.7.6 operator<=
/*
template<class charT, class traits, class Allocator>
bool operator<=(const basic_string<charT,traits,Allocator>& lhs,
const basic_string<charT,traits,Allocator>& rhs);
template<class charT, class traits, class Allocator>
bool operator<=(const basic_string<charT,traits,Allocator>& lhs,
const charT* rhs);
template<class charT, class traits, class Allocator>
bool operator<=(const charT* lhs,
const basic_string<charT,traits,Allocator>& rhs);
*/
// 21.3.7.7 operator>=
/*
template<class charT, class traits, class Allocator>
bool operator>=(const basic_string<charT,traits,Allocator>& lhs,
const basic_string<charT,traits,Allocator>& rhs);
template<class charT, class traits, class Allocator>
bool operator>=(const basic_string<charT,traits,Allocator>& lhs,
const charT* rhs);
template<class charT, class traits, class Allocator>
bool operator>=(const charT* lhs,
const basic_string<charT,traits,Allocator>& rhs);
*/
#include <string>
#include <testsuite_hooks.h>
int test01(void)
{
bool test __attribute__((unused)) = true;
std::wstring str_0(L"costa rica");
std::wstring str_1(L"costa marbella");
std::wstring str_2(L"cost");
std::wstring str_3(L"costa ricans");
std::wstring str_4;
str_4 = str_0;
//comparisons between string objects
VERIFY( !(str_0 == str_1) );
VERIFY( !(str_0 == str_2) );
VERIFY( !(str_0 == str_3) );
VERIFY( !(str_1 == str_0) );
VERIFY( !(str_2 == str_0) );
VERIFY( !(str_3 == str_0) );
VERIFY( str_4 == str_0 );
VERIFY( str_0 == str_4 );
VERIFY( str_0 != str_1 );
VERIFY( str_0 != str_2 );
VERIFY( str_0 != str_3 );
VERIFY( str_1 != str_0 );
VERIFY( str_2 != str_0 );
VERIFY( str_3 != str_0 );
VERIFY( !(str_0 != str_4) );
VERIFY( !(str_4 != str_0) );
VERIFY( str_0 > str_1 ); //true cuz r>m
VERIFY( str_0 > str_2 );
VERIFY( !(str_0 > str_3) );
VERIFY( !(str_1 > str_0) ); //false cuz m<r
VERIFY( !(str_2 > str_0) );
VERIFY( str_3 > str_0 );
VERIFY( !(str_0 > str_4) );
VERIFY( !(str_4 > str_0) );
VERIFY( !(str_0 < str_1) ); //false cuz r>m
VERIFY( !(str_0 < str_2) );
VERIFY( str_0 < str_3 );
VERIFY( str_1 < str_0 ); //true cuz m<r
VERIFY( str_2 < str_0 );
VERIFY( !(str_3 < str_0) );
VERIFY( !(str_0 < str_4) );
VERIFY( !(str_4 < str_0) );
VERIFY( str_0 >= str_1 ); //true cuz r>m
VERIFY( str_0 >= str_2 );
VERIFY( !(str_0 >= str_3) );
VERIFY( !(str_1 >= str_0) );//false cuz m<r
VERIFY( !(str_2 >= str_0) );
VERIFY( str_3 >= str_0 );
VERIFY( str_0 >= str_4 );
VERIFY( str_4 >= str_0 );
VERIFY( !(str_0 <= str_1) );//false cuz r>m
VERIFY( !(str_0 <= str_2) );
VERIFY( str_0 <= str_3 );
VERIFY( str_1 <= str_0 );//true cuz m<r
VERIFY( str_2 <= str_0 );
VERIFY( !(str_3 <= str_0) );
VERIFY( str_0 <= str_4 );
VERIFY( str_4 <= str_0 );
//comparisons between string object and string literal
VERIFY( !(str_0 == L"costa marbella") );
VERIFY( !(str_0 == L"cost") );
VERIFY( !(str_0 == L"costa ricans") );
VERIFY( !(L"costa marbella" == str_0) );
VERIFY( !(L"cost" == str_0) );
VERIFY( !(L"costa ricans" == str_0) );
VERIFY( L"costa rica" == str_0 );
VERIFY( str_0 == L"costa rica" );
VERIFY( str_0 != L"costa marbella" );
VERIFY( str_0 != L"cost" );
VERIFY( str_0 != L"costa ricans" );
VERIFY( L"costa marbella" != str_0 );
VERIFY( L"cost" != str_0 );
VERIFY( L"costa ricans" != str_0 );
VERIFY( !(L"costa rica" != str_0) );
VERIFY( !(str_0 != L"costa rica") );
VERIFY( str_0 > L"costa marbella" ); //true cuz r>m
VERIFY( str_0 > L"cost" );
VERIFY( !(str_0 > L"costa ricans") );
VERIFY( !(L"costa marbella" > str_0) );//false cuz m<r
VERIFY( !(L"cost" > str_0) );
VERIFY( L"costa ricans" > str_0 );
VERIFY( !(L"costa rica" > str_0) );
VERIFY( !(str_0 > L"costa rica") );
VERIFY( !(str_0 < L"costa marbella") );//false cuz r>m
VERIFY( !(str_0 < L"cost") );
VERIFY( str_0 < L"costa ricans" );
VERIFY( L"costa marbella" < str_0 );//true cuz m<r
VERIFY( L"cost" < str_0 );
VERIFY( !(L"costa ricans" < str_0) );
VERIFY( !(L"costa rica" < str_0) );
VERIFY( !(str_0 < L"costa rica") );
VERIFY( str_0 >= L"costa marbella" );//true cuz r>m
VERIFY( str_0 >= L"cost" );
VERIFY( !(str_0 >= L"costa ricans") );
VERIFY( !(L"costa marbella" >= str_0) );//false cuz m<r
VERIFY( !(L"cost" >= str_0) );
VERIFY( L"costa ricans" >= str_0 );
VERIFY( L"costa rica" >= str_0 );
VERIFY( str_0 >= L"costa rica" );
VERIFY( !(str_0 <= L"costa marbella") );//false cuz r>m
VERIFY( !(str_0 <= L"cost") );
VERIFY( str_0 <= L"costa ricans" );
VERIFY( L"costa marbella" <= str_0 );//true cuz m<r
VERIFY( L"cost" <= str_0 );
VERIFY( !(L"costa ricans" <= str_0) );
VERIFY( L"costa rica" <= str_0 );
VERIFY( str_0 <= L"costa rica" );
// 21.3.7.1 operator+
/*
template<class charT, class traits, class Allocator>
basic_string<charT,traits,Allocator>
operator+(const basic_string<charT,traits,Allocator>& lhs,
const basic_string<charT,traits,Allocator>& rhs);
template<class charT, class traits, class Allocator>
basic_string<charT,traits,Allocator>
operator+(const charT* lhs,
const basic_string<charT,traits,Allocator>& rhs);
template<class charT, class traits, class Allocator>
basic_string<charT,traits,Allocator>
operator+(const basic_string<charT,traits,Allocator>& lhs,
const charT* rhs);
template<class charT, class traits, class Allocator>
basic_string<charT,traits,Allocator>
operator+(charT lhs, const basic_string<charT,traits,Allocator>& rhs);
template<class charT, class traits, class Allocator>
basic_string<charT,traits,Allocator>
operator+(const basic_string<charT,traits,Allocator>& lhs, charT rhs);
*/
str_4 = str_0 + L"ns";
VERIFY( str_4 == str_3 );
const std::wstring str_5(L" marbella");
str_4 = L"costa" + str_5;
VERIFY( str_4 == str_1 );
std::wstring str_6(L"ns");
str_4 = str_0 + str_6;
VERIFY( str_4 == str_3 );
str_4 = str_0 + L'n';
str_4 = str_4 + L's';
VERIFY( str_4 == str_3 );
str_4 = L'a' + str_6;
str_4 = L'c' + str_4;
str_4 = L'i' + str_4;
str_4 = L'r' + str_4;
str_4 = L' ' + str_4;
str_4 = L'a' + str_4;
str_4 = L't' + str_4;
str_4 = L's' + str_4;
str_4 = L'o' + str_4;
str_4 = L'c' + str_4;
VERIFY( str_4 == str_3 );
return 0;
}
int main()
{
test01();
return 0;
}
| 32.283784 | 79 | 0.642319 | [
"object"
] |
a34db14e15a8fb1a931394ba2cd5018451ec60dd | 9,859 | cc | C++ | remoting/client/plugin/pepper_input_handler.cc | nagineni/chromium-crosswalk | 5725642f1c67d0f97e8613ec1c3e8107ab53fdf8 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 4 | 2017-04-05T01:51:34.000Z | 2018-02-15T03:11:54.000Z | remoting/client/plugin/pepper_input_handler.cc | nagineni/chromium-crosswalk | 5725642f1c67d0f97e8613ec1c3e8107ab53fdf8 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-12-13T19:44:12.000Z | 2021-12-13T19:44:12.000Z | remoting/client/plugin/pepper_input_handler.cc | nagineni/chromium-crosswalk | 5725642f1c67d0f97e8613ec1c3e8107ab53fdf8 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 4 | 2017-04-05T01:52:03.000Z | 2022-02-13T17:58:45.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "remoting/client/plugin/pepper_input_handler.h"
#include "base/logging.h"
#include "ppapi/c/dev/ppb_keyboard_input_event_dev.h"
#include "ppapi/cpp/image_data.h"
#include "ppapi/cpp/input_event.h"
#include "ppapi/cpp/module_impl.h"
#include "ppapi/cpp/mouse_cursor.h"
#include "ppapi/cpp/point.h"
#include "remoting/proto/event.pb.h"
namespace remoting {
PepperInputHandler::PepperInputHandler(
pp::Instance* instance,
protocol::InputStub* input_stub)
: pp::MouseLock(instance),
instance_(instance),
input_stub_(input_stub),
callback_factory_(this),
has_focus_(false),
mouse_lock_state_(MouseLockDisallowed),
wheel_delta_x_(0),
wheel_delta_y_(0),
wheel_ticks_x_(0),
wheel_ticks_y_(0) {
}
PepperInputHandler::~PepperInputHandler() {
}
// Helper function to get the USB key code using the Dev InputEvent interface.
uint32_t GetUsbKeyCode(pp::KeyboardInputEvent pp_key_event) {
const PPB_KeyboardInputEvent_Dev* key_event_interface =
reinterpret_cast<const PPB_KeyboardInputEvent_Dev*>(
pp::Module::Get()->GetBrowserInterface(
PPB_KEYBOARD_INPUT_EVENT_DEV_INTERFACE));
if (!key_event_interface)
return 0;
return key_event_interface->GetUsbKeyCode(pp_key_event.pp_resource());
}
bool PepperInputHandler::HandleInputEvent(const pp::InputEvent& event) {
switch (event.GetType()) {
case PP_INPUTEVENT_TYPE_CONTEXTMENU: {
// We need to return true here or else we'll get a local (plugin) context
// menu instead of the mouseup event for the right click.
return true;
}
case PP_INPUTEVENT_TYPE_KEYDOWN:
case PP_INPUTEVENT_TYPE_KEYUP: {
pp::KeyboardInputEvent pp_key_event(event);
uint32_t modifiers = event.GetModifiers();
uint32_t lock_states = 0;
if (modifiers & PP_INPUTEVENT_MODIFIER_CAPSLOCKKEY)
lock_states |= protocol::KeyEvent::LOCK_STATES_CAPSLOCK;
if (modifiers & PP_INPUTEVENT_MODIFIER_NUMLOCKKEY)
lock_states |= protocol::KeyEvent::LOCK_STATES_NUMLOCK;
protocol::KeyEvent key_event;
key_event.set_usb_keycode(GetUsbKeyCode(pp_key_event));
key_event.set_pressed(event.GetType() == PP_INPUTEVENT_TYPE_KEYDOWN);
key_event.set_lock_states(lock_states);
input_stub_->InjectKeyEvent(key_event);
return true;
}
case PP_INPUTEVENT_TYPE_MOUSEDOWN:
case PP_INPUTEVENT_TYPE_MOUSEUP: {
pp::MouseInputEvent pp_mouse_event(event);
protocol::MouseEvent mouse_event;
switch (pp_mouse_event.GetButton()) {
case PP_INPUTEVENT_MOUSEBUTTON_LEFT:
mouse_event.set_button(protocol::MouseEvent::BUTTON_LEFT);
break;
case PP_INPUTEVENT_MOUSEBUTTON_MIDDLE:
mouse_event.set_button(protocol::MouseEvent::BUTTON_MIDDLE);
break;
case PP_INPUTEVENT_MOUSEBUTTON_RIGHT:
mouse_event.set_button(protocol::MouseEvent::BUTTON_RIGHT);
break;
case PP_INPUTEVENT_MOUSEBUTTON_NONE:
break;
}
if (mouse_event.has_button()) {
bool is_down = (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN);
mouse_event.set_button_down(is_down);
mouse_event.set_x(pp_mouse_event.GetPosition().x());
mouse_event.set_y(pp_mouse_event.GetPosition().y());
// Add relative movement if the mouse is locked.
if (mouse_lock_state_ == MouseLockOn) {
pp::Point delta = pp_mouse_event.GetMovement();
mouse_event.set_delta_x(delta.x());
mouse_event.set_delta_y(delta.y());
}
input_stub_->InjectMouseEvent(mouse_event);
}
return true;
}
case PP_INPUTEVENT_TYPE_MOUSEMOVE:
case PP_INPUTEVENT_TYPE_MOUSEENTER:
case PP_INPUTEVENT_TYPE_MOUSELEAVE: {
pp::MouseInputEvent pp_mouse_event(event);
protocol::MouseEvent mouse_event;
mouse_event.set_x(pp_mouse_event.GetPosition().x());
mouse_event.set_y(pp_mouse_event.GetPosition().y());
// Add relative movement if the mouse is locked.
if (mouse_lock_state_ == MouseLockOn) {
pp::Point delta = pp_mouse_event.GetMovement();
mouse_event.set_delta_x(delta.x());
mouse_event.set_delta_y(delta.y());
}
input_stub_->InjectMouseEvent(mouse_event);
return true;
}
case PP_INPUTEVENT_TYPE_WHEEL: {
pp::WheelInputEvent pp_wheel_event(event);
// Don't handle scroll-by-page events, for now.
if (pp_wheel_event.GetScrollByPage())
return false;
// Add this event to our accumulated sub-pixel deltas and clicks.
pp::FloatPoint delta = pp_wheel_event.GetDelta();
wheel_delta_x_ += delta.x();
wheel_delta_y_ += delta.y();
pp::FloatPoint ticks = pp_wheel_event.GetTicks();
wheel_ticks_x_ += ticks.x();
wheel_ticks_y_ += ticks.y();
// If there is at least a pixel's movement, emit an event. We don't
// ever expect to accumulate one tick's worth of scrolling without
// accumulating a pixel's worth at the same time, so this is safe.
int delta_x = static_cast<int>(wheel_delta_x_);
int delta_y = static_cast<int>(wheel_delta_y_);
if (delta_x != 0 || delta_y != 0) {
wheel_delta_x_ -= delta_x;
wheel_delta_y_ -= delta_y;
protocol::MouseEvent mouse_event;
mouse_event.set_wheel_delta_x(delta_x);
mouse_event.set_wheel_delta_y(delta_y);
// Always include the ticks in the event, even if insufficient pixel
// scrolling has accumulated for a single tick. This informs hosts
// that can't inject pixel-based scroll events that the client will
// accumulate them into tick-based scrolling, which gives a better
// overall experience than trying to do this host-side.
int ticks_x = static_cast<int>(wheel_ticks_x_);
int ticks_y = static_cast<int>(wheel_ticks_y_);
wheel_ticks_x_ -= ticks_x;
wheel_ticks_y_ -= ticks_y;
mouse_event.set_wheel_ticks_x(ticks_x);
mouse_event.set_wheel_ticks_y(ticks_y);
input_stub_->InjectMouseEvent(mouse_event);
}
return true;
}
case PP_INPUTEVENT_TYPE_CHAR:
// Consume but ignore character input events.
return true;
default: {
LOG(INFO) << "Unhandled input event: " << event.GetType();
break;
}
}
return false;
}
void PepperInputHandler::AllowMouseLock() {
DCHECK_EQ(mouse_lock_state_, MouseLockDisallowed);
mouse_lock_state_ = MouseLockOff;
}
void PepperInputHandler::DidChangeFocus(bool has_focus) {
has_focus_ = has_focus;
if (has_focus_)
RequestMouseLock();
}
void PepperInputHandler::SetMouseCursor(scoped_ptr<pp::ImageData> image,
const pp::Point& hotspot) {
cursor_image_ = image.Pass();
cursor_hotspot_ = hotspot;
if (mouse_lock_state_ != MouseLockDisallowed && !cursor_image_) {
RequestMouseLock();
} else {
CancelMouseLock();
}
}
void PepperInputHandler::MouseLockLost() {
DCHECK(mouse_lock_state_ == MouseLockOn ||
mouse_lock_state_ == MouseLockCancelling);
mouse_lock_state_ = MouseLockOff;
UpdateMouseCursor();
}
void PepperInputHandler::RequestMouseLock() {
// Request mouse lock only if the plugin is focused, the host-supplied cursor
// is empty and no callback is pending.
if (has_focus_ && !cursor_image_ && mouse_lock_state_ == MouseLockOff) {
pp::CompletionCallback callback =
callback_factory_.NewCallback(&PepperInputHandler::OnMouseLocked);
int result = pp::MouseLock::LockMouse(callback);
DCHECK_EQ(result, PP_OK_COMPLETIONPENDING);
// Hide cursor to avoid it becoming a black square (see crbug.com/285809).
pp::MouseCursor::SetCursor(instance_, PP_MOUSECURSOR_TYPE_NONE);
mouse_lock_state_ = MouseLockRequestPending;
}
}
void PepperInputHandler::CancelMouseLock() {
switch (mouse_lock_state_) {
case MouseLockDisallowed:
case MouseLockOff:
UpdateMouseCursor();
break;
case MouseLockCancelling:
break;
case MouseLockRequestPending:
// The mouse lock request is pending. Delay UnlockMouse() call until
// the callback is called.
mouse_lock_state_ = MouseLockCancelling;
break;
case MouseLockOn:
pp::MouseLock::UnlockMouse();
// Note that mouse-lock has been cancelled. We will continue to receive
// locked events until MouseLockLost() is called back.
mouse_lock_state_ = MouseLockCancelling;
break;
default:
NOTREACHED();
}
}
void PepperInputHandler::UpdateMouseCursor() {
DCHECK(mouse_lock_state_ == MouseLockDisallowed ||
mouse_lock_state_ == MouseLockOff);
if (cursor_image_) {
pp::MouseCursor::SetCursor(instance_, PP_MOUSECURSOR_TYPE_CUSTOM,
*cursor_image_,
cursor_hotspot_);
} else {
// If there is no cursor shape stored, either because the host never
// supplied one, or we were previously in mouse-lock mode, then use
// a standard arrow pointer.
pp::MouseCursor::SetCursor(instance_, PP_MOUSECURSOR_TYPE_POINTER);
}
}
void PepperInputHandler::OnMouseLocked(int error) {
DCHECK(mouse_lock_state_ == MouseLockRequestPending ||
mouse_lock_state_ == MouseLockCancelling);
bool should_cancel = (mouse_lock_state_ == MouseLockCancelling);
// See if the operation succeeded.
if (error == PP_OK) {
mouse_lock_state_ = MouseLockOn;
} else {
mouse_lock_state_ = MouseLockOff;
UpdateMouseCursor();
}
// Cancel as needed.
if (should_cancel)
CancelMouseLock();
}
} // namespace remoting
| 32.973244 | 79 | 0.692565 | [
"shape"
] |
a34e34ffc75ac62410b23bc79e01cd5e42175026 | 6,009 | hpp | C++ | host-bmc/custom_dbus.hpp | anoo1/pldm-1 | fa0bf01f0a5d194875f65c54df5ca4e8888958fa | [
"Apache-2.0"
] | null | null | null | host-bmc/custom_dbus.hpp | anoo1/pldm-1 | fa0bf01f0a5d194875f65c54df5ca4e8888958fa | [
"Apache-2.0"
] | null | null | null | host-bmc/custom_dbus.hpp | anoo1/pldm-1 | fa0bf01f0a5d194875f65c54df5ca4e8888958fa | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "com/ibm/License/Entry/LicenseEntry/server.hpp"
#include "common/utils.hpp"
#include <sdbusplus/server.hpp>
#include <xyz/openbmc_project/Inventory/Decorator/LocationCode/server.hpp>
#include <xyz/openbmc_project/Inventory/Item/CpuCore/server.hpp>
#include <xyz/openbmc_project/Inventory/Item/server.hpp>
#include <xyz/openbmc_project/Object/Enable/server.hpp>
#include <xyz/openbmc_project/State/Decorator/Availability/server.hpp>
#include <xyz/openbmc_project/State/Decorator/OperationalStatus/server.hpp>
#include <map>
#include <memory>
#include <string>
namespace pldm
{
namespace dbus
{
using ObjectPath = std::string;
using LocationIntf = sdbusplus::server::object::object<
sdbusplus::xyz::openbmc_project::Inventory::Decorator::server::
LocationCode>;
using OperationalStatusIntf =
sdbusplus::server::object::object<sdbusplus::xyz::openbmc_project::State::
Decorator::server::OperationalStatus>;
using ItemIntf = sdbusplus::server::object::object<
sdbusplus::xyz::openbmc_project::Inventory::server::Item>;
using CoreIntf = sdbusplus::server::object::object<
sdbusplus::xyz::openbmc_project::Inventory::Item::server::CpuCore>;
using EnableIface = sdbusplus::server::object::object<
sdbusplus::xyz::openbmc_project::Object::server::Enable>;
using LicIntf = sdbusplus::server::object::object<
sdbusplus::com::ibm::License::Entry::server::LicenseEntry>;
using AvailabilityIntf = sdbusplus::server::object::object<
sdbusplus::xyz::openbmc_project::State::Decorator::server::Availability>;
/** @class CustomDBus
* @brief This is a custom D-Bus object, used to add D-Bus interface and
* update the corresponding properties value.
*/
class CustomDBus
{
private:
CustomDBus()
{}
public:
CustomDBus(const CustomDBus&) = delete;
CustomDBus(CustomDBus&&) = delete;
CustomDBus& operator=(const CustomDBus&) = delete;
CustomDBus& operator=(CustomDBus&&) = delete;
~CustomDBus() = default;
static CustomDBus& getCustomDBus()
{
static CustomDBus customDBus;
return customDBus;
}
public:
/** @brief Set the LocationCode property
*
* @param[in] path - The object path
*
* @param[in] value - The value of the LocationCode property
*/
void setLocationCode(const std::string& path, std::string value);
/** @brief Get the LocationCode property
*
* @param[in] path - The object path
*
* @return std::string - The value of the LocationCode property
*/
std::string getLocationCode(const std::string& path) const;
/** @brief Set the Functional property
*
* @param[in] path - The object path
*
* @param[in] status - PLDM operational fault status
*/
void setOperationalStatus(const std::string& path, uint8_t status);
/** @brief Get the Functional property
*
* @param[in] path - The object path
*
* @return status - PLDM operational fault status
*/
bool getOperationalStatus(const std::string& path) const;
/** @brief Set the Inventory Item property
* @param[in] path - The object path
*/
void updateItemPresentStatus(const std::string& path);
/** @brief Implement CpuCore Interface
* @param[in] path - The object path
*
* @note This API will also implement the following interface
* xyz.openbmc_project.Object.Enable::Enabled dbus property
* which is mapped with the "Processor:Enabled" Redfish property
* to do either enable or disable the particular resource
* via Redfish client so the Enabled dbus property needs to host
* in the PLDM created core inventory item object.
*/
void implementCpuCoreInterface(const std::string& path);
/**
* @brief Implement the xyz.openbmc_project.Object.Enable interface
*
* @param[in] path - The object path to implement Enable interface
*/
void implementObjectEnableIface(const std::string& path);
/** @brief Implement the license interface properties
*
* @param[in] path - The object path
*
* @param[in] authdevno - License name
*
* @param[in] name - License name
*
* @param[in] serialno - License serial number
*
* @param[in] exptime - License expiration time
*
* @param[in] type - License type
*
* @param[in] authtype - License authorization type
*
* @note This API implements the following interface
* com.ibm.License.Entry.LicenseEntry and associated
* dbus properties.
*/
void implementLicInterfaces(
const std::string& path, const uint32_t& authdevno,
const std::string& name, const std::string& serialno,
const uint64_t& exptime,
const sdbusplus::com::ibm::License::Entry::server::LicenseEntry::Type&
type,
const sdbusplus::com::ibm::License::Entry::server::LicenseEntry::
AuthorizationType& authtype);
/** @brief Set the availability state property
*
* @param[in] path - The object path
*
* @param[in] state - Availability state
*/
void setAvailabilityState(const std::string& path, const bool& state);
private:
std::map<ObjectPath, std::unique_ptr<LocationIntf>> location;
std::map<ObjectPath, std::unique_ptr<OperationalStatusIntf>>
operationalStatus;
std::map<ObjectPath, std::unique_ptr<AvailabilityIntf>> availabilityState;
std::unordered_map<ObjectPath, std::unique_ptr<ItemIntf>> presentStatus;
std::unordered_map<ObjectPath, std::unique_ptr<CoreIntf>> cpuCore;
std::unordered_map<ObjectPath, std::unique_ptr<LicIntf>> codLic;
/** @brief Used to hold the objects which will contain EnableIface */
std::unordered_map<ObjectPath, std::unique_ptr<EnableIface>> _enabledStatus;
};
} // namespace dbus
} // namespace pldm
| 34.142045 | 80 | 0.672658 | [
"object"
] |
a353a97452e0b22ecbd1838d77423eef2283c181 | 45,698 | cpp | C++ | windows/advcore/ctf/uim/ic.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | windows/advcore/ctf/uim/ic.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | windows/advcore/ctf/uim/ic.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //
// ic.cpp
//
#include "private.h"
#include "ic.h"
#include "range.h"
#include "tim.h"
#include "prop.h"
#include "tsi.h"
#include "rprop.h"
#include "funcprv.h"
#include "immxutil.h"
#include "acp2anch.h"
#include "dim.h"
#include "rangebk.h"
#include "view.h"
#include "compose.h"
#include "anchoref.h"
#include "dam.h"
#define TW_ICOWNERSINK_COOKIE 0x80000000 // high bit must be set to avoid conflict with GenericAdviseSink!
#define TW_ICKBDSINK_COOKIE 0x80000001 // high bit must be set to avoid conflict with GenericAdviseSink!
DBG_ID_INSTANCE(CInputContext);
/* 12e53b1b-7d7f-40bd-8f88-4603ee40cf58 */
extern const IID IID_PRIV_CINPUTCONTEXT = { 0x12e53b1b, 0x7d7f, 0x40bd, {0x8f, 0x88, 0x46, 0x03, 0xee, 0x40, 0xcf, 0x58} };
const IID *CInputContext::_c_rgConnectionIIDs[IC_NUM_CONNECTIONPTS] =
{
&IID_ITfTextEditSink,
&IID_ITfTextLayoutSink,
&IID_ITfStatusSink,
&IID_ITfStartReconversionNotifySink,
&IID_ITfEditTransactionSink,
};
//+---------------------------------------------------------------------------
//
// ctor
//
//----------------------------------------------------------------------------
CInputContext::CInputContext(TfClientId tid)
: CCompartmentMgr(tid, COMPTYPE_IC)
{
Dbg_MemSetThisNameIDCounter(TEXT("CInputContext"), PERF_CONTEXT_COUNTER);
// we sometimes use _dwLastLockReleaseID-1, which must still be > IGNORE_LAST_LOCKRELEASED
// Issue: need to handle wrap-around case
_dwLastLockReleaseID = (DWORD)((int)IGNORE_LAST_LOCKRELEASED + 2);
}
//+---------------------------------------------------------------------------
//
// _Init
//
//----------------------------------------------------------------------------
HRESULT CInputContext::_Init(CThreadInputMgr *tim,
CDocumentInputManager *dm, ITextStoreAnchor *ptsi,
ITfContextOwnerCompositionSink *pOwnerComposeSink)
{
CTextStoreImpl *ptsiACP;
_dm = dm; // no need to AddRef, cleared when the dm dies
// scramble the _ec a bit to help debug calling EditSession on the wrong ic
_ec = (TfEditCookie)((DWORD)(UINT_PTR)this<<8);
if (_ec < EC_MIN) // for portability, win32 pointers can't have values this low
{
_ec = EC_MIN;
}
if (ptsi == NULL)
{
if ((ptsiACP = new CTextStoreImpl(this)) == NULL)
return E_OUTOFMEMORY;
_ptsi = new CACPWrap(ptsiACP);
ptsiACP->Release();
if (_ptsi == NULL)
return E_OUTOFMEMORY;
_fCiceroTSI = TRUE;
}
else
{
_ptsi = ptsi;
_ptsi->AddRef();
Assert(_fCiceroTSI == FALSE);
}
_pOwnerComposeSink = pOwnerComposeSink;
if (_pOwnerComposeSink != NULL)
{
_pOwnerComposeSink->AddRef();
}
Assert(_pMSAAState == NULL);
if (tim->_IsMSAAEnabled())
{
_InitMSAAHook(tim->_GetAAAdaptor());
}
Assert(_dwEditSessionFlags == 0);
Assert(_dbg_fInOnLockGranted == FALSE);
Assert(_fLayoutChanged == FALSE);
Assert(_dwStatusChangedFlags == 0);
Assert(_fStatusChanged == FALSE);
_tidInEditSession = TF_CLIENTID_NULL;
Assert(_pPropTextOwner == NULL);
_dwSysFuncPrvCookie = GENERIC_ERROR_COOKIE;
_gaKeyEventFilterTIP[LEFT_FILTERTIP] = TF_INVALID_GUIDATOM;
_gaKeyEventFilterTIP[RIGHT_FILTERTIP] = TF_INVALID_GUIDATOM;
_fInvalidKeyEventFilterTIP = TRUE;
_pEditRecord = new CEditRecord(this); // perf: delay load
if (!_pEditRecord)
return E_OUTOFMEMORY;
Assert(_pActiveView == NULL);
return S_OK;
}
//+---------------------------------------------------------------------------
//
// dtor
//
//----------------------------------------------------------------------------
CInputContext::~CInputContext()
{
CProperty *pProp;
int i;
SPAN *span;
// being paranoid...these should be NULL
Assert(_pICKbdSink == NULL);
// nix any allocated properties
while (_pPropList != NULL)
{
pProp = _pPropList;
_pPropList = _pPropList->_pNext;
delete pProp;
}
// nix any cached app changes
for (i=0; i<_rgAppTextChanges.Count(); i++)
{
span = _rgAppTextChanges.GetPtr(i);
span->paStart->Release();
span->paEnd->Release();
}
Assert(_pMSAAState == NULL); // should have already cleaned up msaa hook
Assert(_pOwnerComposeSink == NULL); // should cleared in _UnadviseSinks
SafeRelease(_pOwnerComposeSink);
Assert(_ptsi == NULL); // should be NULL, cleared in _UnadviseSinks
SafeRelease(_ptsi);
Assert(_pCompositionList == NULL); // all compositions should be terminated
Assert(_rgLockQueue.Count() == 0); // all queue items should be freed
//
// all pending flag should be cleared
// Otherwise psfn->_dwfLockRequestICRef could be broken..
//
Assert(_dwPendingLockRequest == 0);
}
//+---------------------------------------------------------------------------
//
// _AdviseSinks
//
// Called when this ic is pushed.
//
//----------------------------------------------------------------------------
void CInputContext::_AdviseSinks()
{
if (_ptsi != NULL)
{
// attach our ITextStoreAnchorSink
_ptsi->AdviseSink(IID_ITextStoreAnchorSink, SAFECAST(this, ITextStoreAnchorSink *), TS_AS_ALL_SINKS);
}
}
//+---------------------------------------------------------------------------
//
// _UnadviseSinks
//
// Called when this ic is popped.
// All references to the ITextStore impl should be released here.
//
//----------------------------------------------------------------------------
void CInputContext::_UnadviseSinks(CThreadInputMgr *tim)
{
// kill any compositions
_AbortCompositions();
SafeReleaseClear(_pEditRecord);
SafeReleaseClear(_pActiveView);
// for now just skip any pending edit sessions
// do this here in case any of the edit sessions
// have a ref to this ic
_AbortQueueItems();
if (_ptsi != NULL)
{
// detach our ITextStoreAnchorSink
_ptsi->UnadviseSink(SAFECAST(this, ITextStoreAnchorSink *));
// if there is an ic owner sink, unadvise it now while we still can
// this is to help buggy clients
_UnadviseOwnerSink();
// if we're msaa hooked, unhook now
// must do this before Releasing _ptsi
if (_pMSAAState != NULL)
{
Assert(tim->_GetAAAdaptor() != NULL);
_UninitMSAAHook(tim->_GetAAAdaptor());
}
// and let the ptsi go
_ptsi->Release();
_ptsi = NULL;
}
SafeReleaseClear(_pOwnerComposeSink);
// our owning doc is no longer valid
_dm = NULL;
}
//+---------------------------------------------------------------------------
//
// AdviseSink
//
//----------------------------------------------------------------------------
STDAPI CInputContext::AdviseSink(REFIID riid, IUnknown *punk, DWORD *pdwCookie)
{
ITfContextOwner *pICOwnerSink;
CTextStoreImpl *ptsi;
IServiceProvider *psp;
HRESULT hr;
if (pdwCookie == NULL)
return E_INVALIDARG;
*pdwCookie = GENERIC_ERROR_COOKIE;
if (punk == NULL)
return E_INVALIDARG;
if (!_IsConnected())
return TF_E_DISCONNECTED;
if (IsEqualIID(riid, IID_ITfContextOwner))
{
// there can be only one ic owner sink, so special case it
if (!_IsCiceroTSI())
{
Assert(0); // sink should only used for def tsi
return E_UNEXPECTED;
}
// use QueryService to get the tsi since msaa may be wrapping it
if (_ptsi->QueryInterface(IID_IServiceProvider, (void **)&psp) != S_OK)
{
Assert(0);
return E_UNEXPECTED;
}
hr = psp->QueryService(GUID_SERVICE_TF, IID_PRIV_CTSI, (void **)&ptsi);
psp->Release();
if (hr != S_OK)
{
Assert(0);
return E_UNEXPECTED;
}
pICOwnerSink = NULL;
if (ptsi->_HasOwner())
{
hr = CONNECT_E_ADVISELIMIT;
goto ExitOwner;
}
if (FAILED(punk->QueryInterface(IID_ITfContextOwner,
(void **)&pICOwnerSink)))
{
hr = E_UNEXPECTED;
goto ExitOwner;
}
ptsi->_AdviseOwner(pICOwnerSink);
ExitOwner:
ptsi->Release();
SafeRelease(pICOwnerSink);
if (hr == S_OK)
{
*pdwCookie = TW_ICOWNERSINK_COOKIE;
}
return hr;
}
else if (IsEqualIID(riid, IID_ITfContextKeyEventSink))
{
// there can be only one ic kbd sink, so special case it
if (_pICKbdSink != NULL)
return CONNECT_E_ADVISELIMIT;
if (FAILED(punk->QueryInterface(IID_ITfContextKeyEventSink,
(void **)&_pICKbdSink)))
return E_UNEXPECTED;
*pdwCookie = TW_ICKBDSINK_COOKIE;
return S_OK;
}
return GenericAdviseSink(riid, punk, _c_rgConnectionIIDs, _rgSinks, IC_NUM_CONNECTIONPTS, pdwCookie);
}
//+---------------------------------------------------------------------------
//
// UnadviseSink
//
//----------------------------------------------------------------------------
STDAPI CInputContext::UnadviseSink(DWORD dwCookie)
{
if (dwCookie == TW_ICOWNERSINK_COOKIE)
{
// there can be only one ic owner sink, so special case it
return _UnadviseOwnerSink();
}
else if (dwCookie == TW_ICKBDSINK_COOKIE)
{
// there can be only one ic owner sink, so special case it
if (_pICKbdSink == NULL)
return CONNECT_E_NOCONNECTION;
SafeReleaseClear(_pICKbdSink);
return S_OK;
}
return GenericUnadviseSink(_rgSinks, IC_NUM_CONNECTIONPTS, dwCookie);
}
//+---------------------------------------------------------------------------
//
// AdviseSingleSink
//
//----------------------------------------------------------------------------
STDAPI CInputContext::AdviseSingleSink(TfClientId tid, REFIID riid, IUnknown *punk)
{
CTip *ctip;
CLEANUPSINK *pCleanup;
CThreadInputMgr *tim;
ITfCleanupContextSink *pSink;
if (punk == NULL)
return E_INVALIDARG;
if ((tim = CThreadInputMgr::_GetThis()) == NULL)
return E_FAIL;
if (!tim->_GetCTipfromGUIDATOM(tid, &ctip) && (tid != g_gaApp))
return E_INVALIDARG;
if (IsEqualIID(riid, IID_ITfCleanupContextSink))
{
if (_GetCleanupListIndex(tid) >= 0)
return CONNECT_E_ADVISELIMIT;
if (punk->QueryInterface(IID_ITfCleanupContextSink, (void **)&pSink) != S_OK)
return E_NOINTERFACE;
if ((pCleanup = _rgCleanupSinks.Append(1)) == NULL)
{
pSink->Release();
return E_OUTOFMEMORY;
}
pCleanup->tid = tid;
pCleanup->pSink = pSink;
return S_OK;
}
return CONNECT_E_CANNOTCONNECT;
}
//+---------------------------------------------------------------------------
//
// UnadviseSingleSink
//
//----------------------------------------------------------------------------
STDAPI CInputContext::UnadviseSingleSink(TfClientId tid, REFIID riid)
{
int i;
if (IsEqualIID(riid, IID_ITfCleanupContextSink))
{
if ((i = _GetCleanupListIndex(tid)) < 0)
return CONNECT_E_NOCONNECTION;
_rgCleanupSinks.GetPtr(i)->pSink->Release();
_rgCleanupSinks.Remove(i, 1);
return S_OK;
}
return CONNECT_E_NOCONNECTION;
}
//+---------------------------------------------------------------------------
//
// _UnadviseOwnerSink
//
//----------------------------------------------------------------------------
HRESULT CInputContext::_UnadviseOwnerSink()
{
IServiceProvider *psp;
CTextStoreImpl *ptsi;
HRESULT hr;
if (!_IsCiceroTSI())
return E_UNEXPECTED; // only our default tsi can accept an owner sink
if (!_IsConnected()) // _ptsi is not safe if disconnected
return TF_E_DISCONNECTED;
// use QueryService to get the tsi since msaa may be wrapping it
if (_ptsi->QueryInterface(IID_IServiceProvider, (void **)&psp) != S_OK)
{
Assert(0);
return E_UNEXPECTED;
}
hr = psp->QueryService(GUID_SERVICE_TF, IID_PRIV_CTSI, (void **)&ptsi);
psp->Release();
if (hr != S_OK)
{
Assert(0);
return E_UNEXPECTED;
}
if (!ptsi->_HasOwner())
{
hr = CONNECT_E_NOCONNECTION;
goto Exit;
}
ptsi->_UnadviseOwner();
hr = S_OK;
Exit:
ptsi->Release();
return hr;
}
//+---------------------------------------------------------------------------
//
// GetProperty
//
//----------------------------------------------------------------------------
STDAPI CInputContext::GetProperty(REFGUID rguidProp, ITfProperty **ppv)
{
CProperty *property;
HRESULT hr;
if (!_IsConnected())
return TF_E_DISCONNECTED;
hr = _GetProperty(rguidProp, &property);
*ppv = property;
return hr;
}
//+---------------------------------------------------------------------------
//
// _GetProperty
//
//----------------------------------------------------------------------------
HRESULT CInputContext::_GetProperty(REFGUID rguidProp, CProperty **ppv)
{
CProperty *pProp = _FindProperty(rguidProp);
DWORD dwAuthority = PROPA_NONE;
TFPROPERTYSTYLE propStyle;
DWORD dwPropFlags;
if (ppv == NULL)
return E_INVALIDARG;
*ppv = pProp;
if (pProp != NULL)
{
(*ppv)->AddRef();
return S_OK;
}
//
// Overwrite propstyle for known properties.
//
if (IsEqualGUID(rguidProp, GUID_PROP_ATTRIBUTE))
{
propStyle = TFPROPSTYLE_STATIC;
dwAuthority = PROPA_FOCUSRANGE | PROPA_TEXTOWNER | PROPA_WONT_SERIALZE;
dwPropFlags = PROPF_VTI4TOGUIDATOM;
}
else if (IsEqualGUID(rguidProp, GUID_PROP_READING))
{
propStyle = TFPROPSTYLE_CUSTOM;
dwPropFlags = 0;
}
else if (IsEqualGUID(rguidProp, GUID_PROP_COMPOSING))
{
propStyle = TFPROPSTYLE_STATICCOMPACT;
dwAuthority = PROPA_READONLY | PROPA_WONT_SERIALZE;
dwPropFlags = 0;
}
else if (IsEqualGUID(rguidProp, GUID_PROP_LANGID))
{
propStyle = TFPROPSTYLE_STATICCOMPACT;
dwPropFlags = 0;
}
else if (IsEqualGUID(rguidProp, GUID_PROP_TEXTOWNER))
{
propStyle = TFPROPSTYLE_STATICCOMPACT;
dwAuthority = PROPA_TEXTOWNER;
dwPropFlags = PROPF_ACCEPTCORRECTION | PROPF_VTI4TOGUIDATOM;
}
else
{
propStyle = _GetPropStyle(rguidProp);
dwPropFlags = 0;
// nb: after a property is created, the PROPF_MARKUP_COLLECTION is never
// again set. We make sure to call ITfDisplayAttributeCollectionProvider::GetCollection
// before activating tips that use the property GUID.
if (CDisplayAttributeMgr::_IsInCollection(rguidProp))
{
dwPropFlags = PROPF_MARKUP_COLLECTION;
}
}
//
// Allow NULL propStyle for only predefined properties.
// Check the property style is correct.
//
if (!propStyle)
{
Assert(0);
return E_FAIL;
}
pProp = new CProperty(this, rguidProp, propStyle, dwAuthority, dwPropFlags);
if (pProp)
{
pProp->_pNext = _pPropList;
_pPropList = pProp;
// Update _pPropTextOner now.
if (IsEqualGUID(rguidProp, GUID_PROP_TEXTOWNER))
_pPropTextOwner = pProp;
}
if (*ppv = pProp)
{
(*ppv)->AddRef();
return S_OK;
}
return E_OUTOFMEMORY;
}
//+---------------------------------------------------------------------------
//
// GetTextOwnerProperty
//
//----------------------------------------------------------------------------
CProperty *CInputContext::GetTextOwnerProperty()
{
ITfProperty *prop;
// GetProperty initializes _pPropTextOwner.
if (!_pPropTextOwner)
{
GetProperty(GUID_PROP_TEXTOWNER, &prop);
SafeRelease(prop);
}
Assert(_pPropTextOwner);
return _pPropTextOwner;
}
//+---------------------------------------------------------------------------
//
// _FindProperty
//
//----------------------------------------------------------------------------
CProperty *CInputContext::_FindProperty(TfGuidAtom gaProp)
{
CProperty *pProp = _pPropList;
// perf: should this be faster?
while (pProp)
{
if (pProp->GetPropGuidAtom() == gaProp)
return pProp;
pProp = pProp->_pNext;
}
return NULL;
}
//+---------------------------------------------------------------------------
//
// _PropertyTextUpdate
//
//----------------------------------------------------------------------------
void CInputContext::_PropertyTextUpdate(DWORD dwFlags, IAnchor *paStart, IAnchor *paEnd)
{
CProperty *pProp = _pPropList;
DWORD dwPrevESFlag = _dwEditSessionFlags;
_dwEditSessionFlags |= TF_ES_INNOTIFY;
while (pProp)
{
// clear the values over the edited text
pProp->Clear(paStart, paEnd, dwFlags, TRUE /* fTextUpdate */);
if (pProp->GetPropStyle() == TFPROPSTYLE_STATICCOMPACT ||
pProp->GetPropStyle() == TFPROPSTYLE_CUSTOM_COMPACT)
{
pProp->Defrag(paStart, paEnd);
}
pProp = pProp->_pNext;
}
_dwEditSessionFlags = dwPrevESFlag;
}
//+---------------------------------------------------------------------------
//
// _GetStartOrEnd
//
//----------------------------------------------------------------------------
HRESULT CInputContext::_GetStartOrEnd(TfEditCookie ec, BOOL fStart, ITfRange **ppStart)
{
CRange *range;
IAnchor *paStart;
IAnchor *paEnd;
HRESULT hr;
if (ppStart == NULL)
return E_INVALIDARG;
*ppStart = NULL;
if (!_IsConnected())
return TF_E_DISCONNECTED;
if (!_IsValidEditCookie(ec, TF_ES_READ))
{
Assert(0);
return TF_E_NOLOCK;
}
hr = fStart ? _ptsi->GetStart(&paStart) : _ptsi->GetEnd(&paStart);
if (hr == E_NOTIMPL)
return E_NOTIMPL;
if (hr != S_OK)
return E_FAIL;
hr = E_FAIL;
if (FAILED(paStart->Clone(&paEnd)))
goto Exit;
if ((range = new CRange) == NULL)
{
hr = E_OUTOFMEMORY;
goto Exit;
}
if (!range->_InitWithDefaultGravity(this, OWN_ANCHORS, paStart, paEnd))
{
range->Release();
goto Exit;
}
*ppStart = (ITfRangeAnchor *)range;
hr = S_OK;
Exit:
if (hr != S_OK)
{
SafeRelease(paStart);
SafeRelease(paEnd);
}
return hr;
}
//+---------------------------------------------------------------------------
//
// CreateRange
//
//----------------------------------------------------------------------------
STDAPI CInputContext::CreateRange(IAnchor *paStart, IAnchor *paEnd, ITfRangeAnchor **ppRange)
{
CRange *range;
if (ppRange == NULL)
return E_INVALIDARG;
*ppRange = NULL;
if (paStart == NULL || paEnd == NULL)
return E_INVALIDARG;
if (CompareAnchors(paStart, paEnd) > 0)
return E_INVALIDARG;
if ((range = new CRange) == NULL)
return E_OUTOFMEMORY;
if (!range->_InitWithDefaultGravity(this, COPY_ANCHORS, paStart, paEnd))
{
range->Release();
return E_FAIL;
}
*ppRange = range;
return S_OK;
}
//+---------------------------------------------------------------------------
//
// CreateRange
//
//----------------------------------------------------------------------------
STDAPI CInputContext::CreateRange(LONG acpStart, LONG acpEnd, ITfRangeACP **ppRange)
{
IServiceProvider *psp;
CRange *range;
CACPWrap *pACPWrap;
IAnchor *paStart;
IAnchor *paEnd;
HRESULT hr;
if (ppRange == NULL)
return E_INVALIDARG;
pACPWrap = NULL;
*ppRange = NULL;
paEnd = NULL;
hr = E_FAIL;
if (acpStart > acpEnd)
return E_INVALIDARG;
if (_ptsi->QueryInterface(IID_IServiceProvider, (void **)&psp) == S_OK)
{
if (psp->QueryService(GUID_SERVICE_TF, IID_PRIV_ACPWRAP, (void **)&pACPWrap) == S_OK)
{
// the actual impl is acp based, so this is easy
if ((paStart = pACPWrap->_CreateAnchorACP(acpStart, TS_GR_BACKWARD)) == NULL)
goto Exit;
if ((paEnd = pACPWrap->_CreateAnchorACP(acpEnd, TS_GR_FORWARD)) == NULL)
goto Exit;
}
else
{
// in case QueryService sets it on failure to garbage...
pACPWrap = NULL;
}
psp->Release();
}
if (paEnd == NULL) // failure above?
{
Assert(0); // who's calling this?
// caller should know whether or not it has an acp text store.
// we don't, so we won't support this case.
hr = E_FAIL;
goto Exit;
}
if ((range = new CRange) == NULL)
{
hr = E_OUTOFMEMORY;
goto Exit;
}
if (!range->_InitWithDefaultGravity(this, OWN_ANCHORS, paStart, paEnd))
{
range->Release();
goto Exit;
}
*ppRange = range;
hr = S_OK;
Exit:
SafeRelease(pACPWrap);
if (hr != S_OK)
{
SafeRelease(paStart);
SafeRelease(paEnd);
}
return hr;
}
//+---------------------------------------------------------------------------
//
// _Pushed
//
//----------------------------------------------------------------------------
void CInputContext::_Pushed()
{
CThreadInputMgr *tim;
if ((tim = CThreadInputMgr::_GetThis()) != NULL)
tim->_NotifyCallbacks(TIM_INITIC, NULL, this);
}
//+---------------------------------------------------------------------------
//
// _Popped
//
//----------------------------------------------------------------------------
void CInputContext::_Popped()
{
CThreadInputMgr *tim;
if ((tim = CThreadInputMgr::_GetThis()) != NULL)
tim->_NotifyCallbacks(TIM_UNINITIC, NULL, this);
//
// We release all properties and property stores.
//
CProperty *pProp;
while (_pPropList != NULL)
{
pProp = _pPropList;
_pPropList = _pPropList->_pNext;
pProp->Release();
}
// we just free up the cached text property, so make sure
// we don't try to use it later!
_pPropTextOwner = NULL;
//
// We release all compartments.
//
CleanUp();
}
//+---------------------------------------------------------------------------
//
// _GetPropStyle
//
//----------------------------------------------------------------------------
const GUID *CInputContext::_c_rgPropStyle[] =
{
&GUID_TFCAT_PROPSTYLE_CUSTOM,
// {0x24af3031,0x852d,0x40a2,{0xbc,0x09,0x89,0x92,0x89,0x8c,0xe7,0x22}},
&GUID_TFCAT_PROPSTYLE_STATIC,
// {0x565fb8d8,0x6bd4,0x4ca1,{0xb2,0x23,0x0f,0x2c,0xcb,0x8f,0x4f,0x96}},
&GUID_TFCAT_PROPSTYLE_STATICCOMPACT,
// {0x85f9794b,0x4d19,0x40d8,{0x88,0x64,0x4e,0x74,0x73,0x71,0xa6,0x6d}}
&GUID_TFCAT_PROPSTYLE_CUSTOM_COMPACT,
};
TFPROPERTYSTYLE CInputContext::_GetPropStyle(REFGUID rguidProp)
{
GUID guidStyle = GUID_NULL;
CCategoryMgr::s_FindClosestCategory(rguidProp,
&guidStyle,
_c_rgPropStyle,
ARRAYSIZE(_c_rgPropStyle));
if (IsEqualGUID(guidStyle, GUID_TFCAT_PROPSTYLE_CUSTOM))
return TFPROPSTYLE_CUSTOM;
else if (IsEqualGUID(guidStyle, GUID_TFCAT_PROPSTYLE_STATIC))
return TFPROPSTYLE_STATIC;
else if (IsEqualGUID(guidStyle, GUID_TFCAT_PROPSTYLE_STATICCOMPACT))
return TFPROPSTYLE_STATICCOMPACT;
else if (IsEqualGUID(guidStyle, GUID_TFCAT_PROPSTYLE_CUSTOM_COMPACT))
return TFPROPSTYLE_CUSTOM_COMPACT;
return TFPROPSTYLE_NULL;
}
//+---------------------------------------------------------------------------
//
// Serialize
//
//----------------------------------------------------------------------------
STDAPI CInputContext::Serialize(ITfProperty *pProp, ITfRange *pRange, TF_PERSISTENT_PROPERTY_HEADER_ACP *pHdr, IStream *pStream)
{
ITextStoreACPServices *ptss;
HRESULT hr;
if (pHdr == NULL)
return E_INVALIDARG;
memset(pHdr, 0, sizeof(*pHdr));
if (!_IsCiceroTSI())
return E_UNEXPECTED;
if (_ptsi->QueryInterface(IID_ITextStoreACPServices, (void **)&ptss) != S_OK)
return E_FAIL;
hr = ptss->Serialize(pProp, pRange, pHdr, pStream);
ptss->Release();
return hr;
}
//+---------------------------------------------------------------------------
//
// Unserialize
//
//----------------------------------------------------------------------------
STDAPI CInputContext::Unserialize(ITfProperty *pProp, const TF_PERSISTENT_PROPERTY_HEADER_ACP *pHdr, IStream *pStream, ITfPersistentPropertyLoaderACP *pLoader)
{
ITextStoreACPServices *ptss;
HRESULT hr;
if (!_IsCiceroTSI())
return E_UNEXPECTED;
if (_ptsi->QueryInterface(IID_ITextStoreACPServices, (void **)&ptss) != S_OK)
return E_FAIL;
hr = ptss->Unserialize(pProp, pHdr, pStream, pLoader);
ptss->Release();
return hr;
}
//+---------------------------------------------------------------------------
//
// GetDocumentMgr
//
//----------------------------------------------------------------------------
STDAPI CInputContext::GetDocumentMgr(ITfDocumentMgr **ppDm)
{
CDocumentInputManager *dm;
if (ppDm == NULL)
return E_INVALIDARG;
*ppDm = NULL;
if ((dm = _GetDm()) == NULL)
return S_FALSE; // the ic has been popped
*ppDm = dm;
(*ppDm)->AddRef();
return S_OK;
}
//+---------------------------------------------------------------------------
//
// EnumProperties
//
//----------------------------------------------------------------------------
STDAPI CInputContext::EnumProperties(IEnumTfProperties **ppEnum)
{
CEnumProperties *pEnum;
if (ppEnum == NULL)
return E_INVALIDARG;
*ppEnum = NULL;
if (!_IsConnected())
return TF_E_DISCONNECTED;
pEnum = new CEnumProperties;
if (!pEnum)
return E_OUTOFMEMORY;
if (!pEnum->_Init(this))
return E_FAIL;
*ppEnum = pEnum;
return S_OK;
}
//+---------------------------------------------------------------------------
//
// GetStart
//
//----------------------------------------------------------------------------
STDAPI CInputContext::GetStart(TfEditCookie ec, ITfRange **ppStart)
{
return _GetStartOrEnd(ec, TRUE, ppStart);
}
//+---------------------------------------------------------------------------
//
// GetEnd
//
//----------------------------------------------------------------------------
STDAPI CInputContext::GetEnd(TfEditCookie ec, ITfRange **ppEnd)
{
return _GetStartOrEnd(ec, FALSE, ppEnd);
}
//+---------------------------------------------------------------------------
//
// GetStatus
//
//----------------------------------------------------------------------------
STDAPI CInputContext::GetStatus(TS_STATUS *pdcs)
{
if (pdcs == NULL)
return E_INVALIDARG;
memset(pdcs, 0, sizeof(*pdcs));
if (!_IsConnected())
return TF_E_DISCONNECTED;
return _GetTSI()->GetStatus(pdcs);
}
//+---------------------------------------------------------------------------
//
// CreateRangeBackup
//
//----------------------------------------------------------------------------
STDAPI CInputContext::CreateRangeBackup(TfEditCookie ec, ITfRange *pRange, ITfRangeBackup **ppBackup)
{
CRangeBackup *pRangeBackup;
CRange *range;
HRESULT hr;
if (!ppBackup)
return E_INVALIDARG;
*ppBackup = NULL;
if (!_IsConnected())
return TF_E_DISCONNECTED;
if (!_IsValidEditCookie(ec, TF_ES_READ))
{
Assert(0);
return TF_E_NOLOCK;
}
if (!pRange)
return E_INVALIDARG;
if ((range = GetCRange_NA(pRange)) == NULL)
return E_INVALIDARG;
if (!VerifySameContext(this, range))
return E_INVALIDARG;
range->_QuickCheckCrossedAnchors();
pRangeBackup = new CRangeBackup(this);
if (!pRangeBackup)
return E_OUTOFMEMORY;
if (FAILED(hr = pRangeBackup->Init(ec, range)))
{
pRangeBackup->Clear();
pRangeBackup->Release();
return E_FAIL;
}
*ppBackup = pRangeBackup;
return hr;
}
//+---------------------------------------------------------------------------
//
// QueryService
//
//----------------------------------------------------------------------------
STDAPI CInputContext::QueryService(REFGUID guidService, REFIID riid, void **ppv)
{
IServiceProvider *psp;
HRESULT hr;
if (ppv == NULL)
return E_INVALIDARG;
*ppv = NULL;
if (IsEqualGUID(guidService, GUID_SERVICE_TEXTSTORE) &&
IsEqualIID(riid, IID_IServiceProvider))
{
// caller wants to talk to the text store
if (_ptsi == NULL)
return E_FAIL;
// we use an extra level of indirection, asking the IServiceProvider for an IServiceProvider
// because we want to leave the app free to not expose the ITextStore object
// otherwise tips could QI the IServiceProvider for ITextStore
if (_ptsi->QueryInterface(IID_IServiceProvider, (void **)&psp) != S_OK || psp == NULL)
return E_FAIL;
hr = psp->QueryService(GUID_SERVICE_TEXTSTORE, IID_IServiceProvider, ppv);
psp->Release();
return hr;
}
if (!IsEqualGUID(guidService, GUID_SERVICE_TF) ||
!IsEqualIID(riid, IID_PRIV_CINPUTCONTEXT))
{
// SVC_E_NOSERVICE is proper return code for wrong service....
// but it's not defined anywhere. So use E_NOINTERFACE for both
// cases as trident is rumored to do
return E_NOINTERFACE;
}
*ppv = this;
AddRef();
return S_OK;
}
//+---------------------------------------------------------------------------
//
// AdviseMouseSink
//
//----------------------------------------------------------------------------
STDAPI CInputContext::AdviseMouseSink(ITfRange *range, ITfMouseSink *pSink, DWORD *pdwCookie)
{
CRange *pCRange;
CRange *pClone;
ITfMouseTrackerAnchor *pTrackerAnchor;
ITfMouseTrackerACP *pTrackerACP;
HRESULT hr;
if (pdwCookie == NULL)
return E_INVALIDARG;
*pdwCookie = 0;
if (range == NULL || pSink == NULL)
return E_INVALIDARG;
if ((pCRange = GetCRange_NA(range)) == NULL)
return E_INVALIDARG;
if (!VerifySameContext(this, pCRange))
return E_INVALIDARG;
if (!_IsConnected())
return TF_E_DISCONNECTED;
pTrackerACP = NULL;
if (_ptsi->QueryInterface(IID_ITfMouseTrackerAnchor, (void **)&pTrackerAnchor) != S_OK)
{
pTrackerAnchor = NULL;
// we also try IID_ITfMouseTrackerACP for the benefit of wrapped implementations who
// just want to forward the request off to an ACP app
if (_ptsi->QueryInterface(IID_ITfMouseTrackerACP, (void **)&pTrackerACP) != S_OK)
return E_NOTIMPL;
}
hr = E_FAIL;
// need to pass on a clone, so app can hang onto range/anchors
if ((pClone = pCRange->_Clone()) == NULL)
goto Exit;
hr = (pTrackerAnchor != NULL) ?
pTrackerAnchor->AdviseMouseSink(pClone->_GetStart(), pClone->_GetEnd(), pSink, pdwCookie) :
pTrackerACP->AdviseMouseSink((ITfRangeACP *)pClone, pSink, pdwCookie);
pClone->Release();
Exit:
SafeRelease(pTrackerAnchor);
SafeRelease(pTrackerACP);
return hr;
}
//+---------------------------------------------------------------------------
//
// UnadviseMouseSink
//
//----------------------------------------------------------------------------
STDAPI CInputContext::UnadviseMouseSink(DWORD dwCookie)
{
ITfMouseTrackerAnchor *pTrackerAnchor;
ITfMouseTrackerACP *pTrackerACP;
HRESULT hr;
if (!_IsConnected())
return TF_E_DISCONNECTED;
if (_ptsi->QueryInterface(IID_ITfMouseTrackerAnchor, (void **)&pTrackerAnchor) == S_OK)
{
hr = pTrackerAnchor->UnadviseMouseSink(dwCookie);
pTrackerAnchor->Release();
}
else if (_ptsi->QueryInterface(IID_ITfMouseTrackerACP, (void **)&pTrackerACP) == S_OK)
{
// we also try IID_ITfMouseTrackerACP for the benefit of wrapped implementations who
// just want to forward the request off to an ACP app
hr = pTrackerACP->UnadviseMouseSink(dwCookie);
pTrackerACP->Release();
}
else
{
hr = E_NOTIMPL;
}
return hr;
}
//+---------------------------------------------------------------------------
//
// GetActiveView
//
//----------------------------------------------------------------------------
STDAPI CInputContext::GetActiveView(ITfContextView **ppView)
{
CContextView *pView;
TsViewCookie vcActiveView;
HRESULT hr;
if (ppView == NULL)
return E_INVALIDARG;
*ppView = NULL;
if (!_IsConnected())
return TF_E_DISCONNECTED;
hr = _ptsi->GetActiveView(&vcActiveView);
if (hr != S_OK)
{
Assert(0); // why did it fail?
if (hr != E_NOTIMPL)
return E_FAIL;
// for E_NOTIMPL, we will assume a single view and supply
// a constant value here
vcActiveView = 0;
}
// Issue: for now, just supporting an active view
// need to to handle COM identity correctly for mult views
if (_pActiveView == NULL)
{
if ((_pActiveView = new CContextView(this, vcActiveView)) == NULL)
return E_OUTOFMEMORY;
}
pView = _pActiveView;
pView->AddRef();
*ppView = pView;
return S_OK;
}
//+---------------------------------------------------------------------------
//
// EnumView
//
//----------------------------------------------------------------------------
STDAPI CInputContext::EnumViews(IEnumTfContextViews **ppEnum)
{
if (ppEnum == NULL)
return E_INVALIDARG;
*ppEnum = NULL;
if (!_IsConnected())
return TF_E_DISCONNECTED;
// Issue: support this
Assert(0);
return E_NOTIMPL;
}
//+---------------------------------------------------------------------------
//
// QueryInsertEmbedded
//
//----------------------------------------------------------------------------
STDAPI CInputContext::QueryInsertEmbedded(const GUID *pguidService, const FORMATETC *pFormatEtc, BOOL *pfInsertable)
{
if (pfInsertable == NULL)
return E_INVALIDARG;
*pfInsertable = FALSE;
if (!_IsConnected())
return TF_E_DISCONNECTED;
return _ptsi->QueryInsertEmbedded(pguidService, pFormatEtc, pfInsertable);
}
//+---------------------------------------------------------------------------
//
// InsertTextAtSelection
//
//----------------------------------------------------------------------------
STDAPI CInputContext::InsertTextAtSelection(TfEditCookie ec, DWORD dwFlags,
const WCHAR *pchText, LONG cch,
ITfRange **ppRange)
{
IAS_OBJ iasobj;
iasobj.type = IAS_OBJ::IAS_TEXT;
iasobj.state.text.pchText = pchText;
iasobj.state.text.cch = cch;
return _InsertXAtSelection(ec, dwFlags, &iasobj, ppRange);
}
//+---------------------------------------------------------------------------
//
// InsertEmbeddedAtSelection
//
//----------------------------------------------------------------------------
STDAPI CInputContext::InsertEmbeddedAtSelection(TfEditCookie ec, DWORD dwFlags,
IDataObject *pDataObject,
ITfRange **ppRange)
{
IAS_OBJ iasobj;
iasobj.type = IAS_OBJ::IAS_DATAOBJ;
iasobj.state.obj.pDataObject = pDataObject;
return _InsertXAtSelection(ec, dwFlags, &iasobj, ppRange);
}
//+---------------------------------------------------------------------------
//
// _InsertXAtSelection
//
//----------------------------------------------------------------------------
HRESULT CInputContext::_InsertXAtSelection(TfEditCookie ec, DWORD dwFlags,
IAS_OBJ *pObj,
ITfRange **ppRange)
{
IAnchor *paStart;
IAnchor *paEnd;
CRange *range;
CComposition *pComposition;
HRESULT hr;
BOOL fNoDefaultComposition;
if (ppRange == NULL)
return E_INVALIDARG;
*ppRange = NULL;
if (pObj->type == IAS_OBJ::IAS_TEXT)
{
if (pObj->state.text.pchText == NULL && pObj->state.text.cch != 0)
return E_INVALIDARG;
if (!(dwFlags & TS_IAS_QUERYONLY) && (pObj->state.text.pchText == NULL || pObj->state.text.cch == 0))
return E_INVALIDARG;
}
else
{
Assert(pObj->type == IAS_OBJ::IAS_DATAOBJ);
if (!(dwFlags & TS_IAS_QUERYONLY) && pObj->state.obj.pDataObject == NULL)
return E_INVALIDARG;
}
if ((dwFlags & (TS_IAS_NOQUERY | TS_IAS_QUERYONLY)) == (TS_IAS_NOQUERY | TS_IAS_QUERYONLY))
return E_INVALIDARG;
if ((dwFlags & ~(TS_IAS_NOQUERY | TS_IAS_QUERYONLY | TF_IAS_NO_DEFAULT_COMPOSITION)) != 0)
return E_INVALIDARG;
if (!_IsConnected())
return TF_E_DISCONNECTED;
if (!_IsValidEditCookie(ec, (dwFlags & TF_IAS_QUERYONLY) ? TF_ES_READ : TF_ES_READWRITE))
{
Assert(0);
return TF_E_NOLOCK;
}
// we need to clear out the TF_IAS_NO_DEFAULT_COMPOSITION bit because it is not legal
// for ITextStore methods
fNoDefaultComposition = (dwFlags & TF_IAS_NO_DEFAULT_COMPOSITION);
dwFlags &= ~TF_IAS_NO_DEFAULT_COMPOSITION;
if (pObj->type == IAS_OBJ::IAS_TEXT)
{
if (pObj->state.text.cch < 0)
{
pObj->state.text.cch = wcslen(pObj->state.text.pchText);
}
hr = _ptsi->InsertTextAtSelection(dwFlags, pObj->state.text.pchText, pObj->state.text.cch, &paStart, &paEnd);
}
else
{
Assert(pObj->type == IAS_OBJ::IAS_DATAOBJ);
hr = _ptsi->InsertEmbeddedAtSelection(dwFlags, pObj->state.obj.pDataObject, &paStart, &paEnd);
}
if (hr == S_OK)
{
if (!(dwFlags & TS_IAS_QUERYONLY))
{
CComposition::_IsRangeCovered(this, _GetClientInEditSession(ec), paStart, paEnd, &pComposition);
_DoPostTextEditNotifications(pComposition, ec, 0, 1, paStart, paEnd, NULL);
// try to start a composition
// any active compositions?
if (!fNoDefaultComposition && pComposition == NULL)
{
// not covered, need to (try to) create a composition
hr = _StartComposition(ec, paStart, paEnd, NULL, &pComposition);
if (hr == S_OK && pComposition != NULL)
{
// we just wanted to set the composing property, so end this one immediately
pComposition->EndComposition(ec);
pComposition->Release();
}
}
}
}
else
{
// the InsertAtSelection call failed in the app
switch (hr)
{
case TS_E_NOSELECTION:
case TS_E_READONLY:
return hr;
case E_NOTIMPL:
// the app hasn't implemented InsertAtSelection, so we'll fake it using GetSelection/SetText
if (!_InsertXAtSelectionAggressive(ec, dwFlags, pObj, &paStart, &paEnd))
return E_FAIL;
break;
default:
return E_FAIL;
}
}
if (!(dwFlags & TF_IAS_NOQUERY))
{
if (paStart == NULL || paEnd == NULL)
{
Assert(0); // text store returning bogus values
return E_FAIL;
}
if ((range = new CRange) == NULL)
return E_OUTOFMEMORY;
if (!range->_InitWithDefaultGravity(this, OWN_ANCHORS, paStart, paEnd))
{
range->Release();
return E_FAIL;
}
*ppRange = (ITfRangeAnchor *)range;
}
return S_OK;
}
//+---------------------------------------------------------------------------
//
// _InsertXAtSelectionAggressive
//
//----------------------------------------------------------------------------
BOOL CInputContext::_InsertXAtSelectionAggressive(TfEditCookie ec, DWORD dwFlags, IAS_OBJ *pObj, IAnchor **ppaStart, IAnchor **ppaEnd)
{
CRange *range;
TF_SELECTION sel;
ULONG pcFetched;
HRESULT hr;
// this is more expensive then using ITextStore methods directly, but by using a CRange we
// get all the composition/notification code for free
if (GetSelection(ec, TF_DEFAULT_SELECTION, 1, &sel, &pcFetched) != S_OK)
return FALSE;
hr = E_FAIL;
if (pcFetched != 1)
goto Exit;
if (dwFlags & TS_IAS_QUERYONLY)
{
hr = S_OK;
goto OutParams;
}
if (pObj->type == IAS_OBJ::IAS_TEXT)
{
hr = sel.range->SetText(ec, 0, pObj->state.text.pchText, pObj->state.text.cch);
}
else
{
Assert(pObj->type == IAS_OBJ::IAS_DATAOBJ);
hr = sel.range->InsertEmbedded(ec, 0, pObj->state.obj.pDataObject);
}
if (hr == S_OK)
{
OutParams:
range = GetCRange_NA(sel.range);
*ppaStart = range->_GetStart();
(*ppaStart)->AddRef();
*ppaEnd = range->_GetEnd();
(*ppaEnd)->AddRef();
}
Exit:
sel.range->Release();
return (hr == S_OK);
}
//+---------------------------------------------------------------------------
//
// _DoPostTextEditNotifications
//
//----------------------------------------------------------------------------
void CInputContext::_DoPostTextEditNotifications(CComposition *pComposition,
TfEditCookie ec, DWORD dwFlags,
ULONG cchInserted,
IAnchor *paStart, IAnchor *paEnd,
CRange *range)
{
CProperty *property;
VARIANT var;
if (range != NULL)
{
Assert(paStart == NULL);
Assert(paEnd == NULL);
paStart = range->_GetStart();
paEnd = range->_GetEnd();
}
if (cchInserted > 0)
{
// an insert could have crossed some anchors
_IncLastLockReleaseID(); // force a re-check for everyone!
if (range != NULL)
{
range->_QuickCheckCrossedAnchors(); // and check this guy right away
}
}
// the app won't notify us about changes we initiate, so do that now
_OnTextChangeInternal(dwFlags, paStart, paEnd, COPY_ANCHORS);
// let properties know about the update
_PropertyTextUpdate(dwFlags, paStart, paEnd);
// Set text owner property
if (cchInserted > 0
&& !IsEqualAnchor(paStart, paEnd))
{
// text owner property
TfClientId tid = _GetClientInEditSession(ec);
if ((tid != g_gaApp) && (tid != g_gaSystem) &&
(property = GetTextOwnerProperty()))
{
var.vt = VT_I4;
var.lVal = tid;
Assert(var.lVal != TF_CLIENTID_NULL);
property->_SetDataInternal(ec, paStart, paEnd, &var);
}
// composition property
if (range != NULL &&
_GetProperty(GUID_PROP_COMPOSING, &property) == S_OK) // perf: consider caching property ptr
{
var.vt = VT_I4;
var.lVal = TRUE;
property->_SetDataInternal(ec, paStart, paEnd, &var);
property->Release();
}
}
// composition update
if (pComposition != NULL && _GetOwnerCompositionSink() != NULL)
{
_GetOwnerCompositionSink()->OnUpdateComposition(pComposition, NULL);
}
}
| 26.912839 | 160 | 0.50407 | [
"object"
] |
a35550091556eb4c05c1d4819f0077256ebcd42f | 12,893 | cpp | C++ | src/ImageManipulation.cpp | madhu511/Audacity | 4b5542afdf20c02389d6f07aeff1baa3bcdb10ea | [
"CC-BY-3.0"
] | 3 | 2018-01-02T13:34:25.000Z | 2019-08-05T09:21:22.000Z | src/ImageManipulation.cpp | madhu511/Audacity | 4b5542afdf20c02389d6f07aeff1baa3bcdb10ea | [
"CC-BY-3.0"
] | null | null | null | src/ImageManipulation.cpp | madhu511/Audacity | 4b5542afdf20c02389d6f07aeff1baa3bcdb10ea | [
"CC-BY-3.0"
] | 1 | 2019-06-17T09:52:11.000Z | 2019-06-17T09:52:11.000Z | /**********************************************************************
Audacity: A Digital Audio Editor
ImageManipulation.cpp
Dominic Mazzoni
James Crook
wxWidgets license (Dominic to confirm).
********************************************************************//*!
\file ImageManipulation.cpp
Provides Image Manipulation functions.
wxWidgets misses some important functions involving cutting and
pasting bitmaps, and (in version 2.6.1) is patchy in support of alpha
channel. This collection of functions fills that gap.
*//*********************************************************************/
#include <wx/image.h>
#include "Audacity.h"
#include "ImageManipulation.h"
/// This looks at the first pixel in the image, and shifts
/// the entire image by the vector difference between that
/// pixel and the dstColour. For better control, use
/// ChangeImageColour(wxImage, wxColour*, wxColour*) below
std::unique_ptr<wxImage> ChangeImageColour(wxImage * srcImage, wxColour & dstColour)
{
unsigned char *src = srcImage->GetData();
wxColour c;
c.Set(src[0], src[1], src[2]);
return ChangeImageColour(srcImage, c, dstColour);
}
///This will explicitly shift the image color from
///srcColour to dstColour.
std::unique_ptr<wxImage> ChangeImageColour(wxImage * srcImage,
wxColour & srcColour,
wxColour & dstColour)
{
// This function takes a source image, which it assumes to
// be grayscale, and smoothly changes the overall color
// to the specified color, and returns the result as a
// NEW image. This works well for grayscale 3D images.
// Audacity uses this routines to make the buttons
// (skip-start, play, stop, record, skip-end) adapt to
// the color scheme of the user.
unsigned char *src = srcImage->GetData();
int width = srcImage->GetWidth();
int height = srcImage->GetHeight();
auto dstImage = std::make_unique<wxImage>(width, height);
unsigned char *dst = dstImage->GetData();
//Get the source color
int srcVal[3], srcOpp[3];
srcVal[0] = srcColour.Red();
srcVal[1] = srcColour.Green();
srcVal[2] = srcColour.Blue();
int dstVal[3], dstOpp[3];
dstVal[0] = dstColour.Red();
dstVal[1] = dstColour.Green();
dstVal[2] = dstColour.Blue();
int i;
for (i = 0; i < 3; i++) {
srcOpp[i] = 256 - srcVal[i]; // avoid zero!
dstOpp[i] = 255 - dstVal[i];
}
int c = 0;
for (i = 0; i < width * height * 3; i++) {
int s = (int) *src;
if (s >= srcVal[c])
*dst++ = dstVal[c] + dstOpp[c] * (s - srcVal[c]) / srcOpp[c];
else
*dst++ = dstVal[c] * s / srcVal[c];
src++;
c = (c + 1) % 3;
}
return std::move(dstImage);
}
/// Takes a background image, foreground image, and mask
/// (i.e. the alpha channel for the foreground), and
/// returns an NEW image where the foreground has been
/// overlaid onto the background using alpha-blending,
/// at location (xoff, yoff).
std::unique_ptr<wxImage> OverlayImage(wxImage * background, wxImage * foreground,
wxImage * mask, int xoff, int yoff)
{
unsigned char *bg = background->GetData();
unsigned char *fg = foreground->GetData();
unsigned char *mk = mask->GetData();
int bgWidth = background->GetWidth();
int bgHeight = background->GetHeight();
int fgWidth = foreground->GetWidth();
int fgHeight = foreground->GetHeight();
int mkWidth = mask->GetWidth();
int mkHeight = mask->GetHeight();
//Now, determine the dimensions of the images to be masked together
//on top of the background. This should be equal to the area of the
//smaller of the foreground and the mask, as long as it is
//within the area of the background, given the offset.
//Make sure the foreground size is no bigger than the mask
int wCutoff = (fgWidth < mkWidth) ? fgWidth : mkWidth;
int hCutoff = (fgHeight < mkHeight) ? fgHeight : mkHeight;
// If the masked foreground + offset is bigger than the background, masking
// should only occur within these bounds of the foreground image
wCutoff = (bgWidth - xoff > wCutoff) ? wCutoff : bgWidth - xoff;
hCutoff = (bgHeight - yoff > hCutoff) ? hCutoff : bgHeight - yoff;
//Make a NEW image the size of the background
auto dstImage = std::make_unique<wxImage>(bgWidth, bgHeight);
unsigned char *dst = dstImage->GetData();
memcpy(dst, bg, bgWidth * bgHeight * 3);
// Go through the foreground image bit by bit and mask it on to the
// background, at an offset of xoff,yoff.
// BUT...Don't go beyond the size of the background image,
// the foreground image, or the mask
int x, y;
for (y = 0; y < hCutoff; y++) {
unsigned char *bkp = bg + 3 * ((y + yoff) * bgWidth + xoff);
unsigned char *dstp = dst + 3 * ((y + yoff) * bgWidth + xoff);
for (x = 0; x < wCutoff; x++) {
int value = mk[3 * (y * mkWidth + x)];
int opp = 255 - value;
for (int c = 0; c < 3; c++)
dstp[x * 3 + c] =
((bkp[x * 3 + c] * opp) +
(fg[3 * (y * fgWidth + x) + c] * value)) / 255;
}
}
return std::move(dstImage);
}
/// Takes a background image, foreground image, and mask
/// (i.e. the alpha channel for the foreground), and
/// returns an NEW image where the foreground has been
/// overlaid onto the background using alpha-blending,
/// at location (xoff, yoff).
std::unique_ptr<wxImage> OverlayImage(teBmps eBack, teBmps eForeground,
int xoff, int yoff)
{
wxImage imgBack(theTheme.Image( eBack ));
wxImage imgFore(theTheme.Image( eForeground ));
// TMP: dmazzoni - just so the code runs even though not all of
// our images have transparency...
if (!imgFore.HasAlpha())
return std::make_unique<wxImage>(imgBack);
wxASSERT( imgFore.HasAlpha() );
unsigned char *bg = imgBack.GetData();
unsigned char *fg = imgFore.GetData();
unsigned char *mk = imgFore.GetAlpha();
int bgWidth = imgBack.GetWidth();
int bgHeight = imgBack.GetHeight();
int fgWidth = imgFore.GetWidth();
int fgHeight = imgFore.GetHeight();
//Now, determine the dimensions of the images to be masked together
//on top of the background. This should be equal to the area of the
//smaller of the foreground and the mask, as long as it is
//within the area of the background, given the offset.
//Make sure the foreground size is no bigger than the mask
int wCutoff = fgWidth;
int hCutoff = fgHeight;
// If the masked foreground + offset is bigger than the background, masking
// should only occur within these bounds of the foreground image
wCutoff = (bgWidth - xoff > wCutoff) ? wCutoff : bgWidth - xoff;
hCutoff = (bgHeight - yoff > hCutoff) ? hCutoff : bgHeight - yoff;
//Make a NEW image the size of the background
auto dstImage = std::make_unique<wxImage>(bgWidth, bgHeight);
unsigned char *dst = dstImage->GetData();
memcpy(dst, bg, bgWidth * bgHeight * 3);
// Go through the foreground image bit by bit and mask it on to the
// background, at an offset of xoff,yoff.
// BUT...Don't go beyond the size of the background image,
// the foreground image, or the mask
int x, y;
for (y = 0; y < hCutoff; y++) {
unsigned char *bkp = bg + 3 * ((y + yoff) * bgWidth + xoff);
unsigned char *dstp = dst + 3 * ((y + yoff) * bgWidth + xoff);
for (x = 0; x < wCutoff; x++) {
int value = mk[(y * fgWidth + x)];// Don't multiply by 3...
int opp = 255 - value;
for (int c = 0; c < 3; c++)
dstp[x * 3 + c] =
((bkp[x * 3 + c] * opp) +
(fg[3 * (y * fgWidth + x) + c] * value)) / 255;
}
}
return dstImage;
}
// Creates an image with a solid background color
std::unique_ptr<wxImage> CreateBackground(int width, int height, wxColour colour)
{
auto i = std::make_unique<wxImage>(width, height);
unsigned char *ip;
int srcVal[3];
int x;
srcVal[0] = colour.Red();
srcVal[1] = colour.Green();
srcVal[2] = colour.Blue();
ip = i->GetData();
for(x=0; x<width*height; x++) {
*ip++ = srcVal[0];
*ip++ = srcVal[1];
*ip++ = srcVal[2];
}
return std::move(i);
}
// Creates an image with the Mac OS X Aqua stripes, to be used
// as a background
std::unique_ptr<wxImage> CreateAquaBackground(int width, int height, int offset)
{
auto image = std::make_unique<wxImage>(width, height);
unsigned char *ip = image->GetData();
unsigned char val[4] = {231, 239, 255, 239};
unsigned char v;
int x, y;
for(y=0; y<height; y++) {
v = val[(y+offset)%4];
for(x=0; x<width*3; x++)
*ip++ = v;
}
return std::move(image);
}
std::unique_ptr<wxImage> CreateSysBackground
#ifdef USE_AQUA_THEME
(int width, int height, int offset, wxColour colour)
#else
(int width, int height, int WXUNUSED(offset), wxColour colour)
#endif
{
#ifdef USE_AQUA_THEME
return CreateAquaBackground(width, height, offset);
#else
return CreateBackground(width, height, colour);
#endif
}
/// Pastes one image into another including the alpha channel.
/// Differs from OverlayImage in that:
/// Happens in place to existing background image.
/// Pastes image on top; no blending with existing background is done.
void PasteSubImage( wxImage * background, wxImage * foreground, int xoff, int yoff )
{
unsigned char *bg = background->GetData();
unsigned char *fg = foreground->GetData();
unsigned char *bgAlpha = background->HasAlpha() ? background->GetAlpha() : NULL;
unsigned char *fgAlpha = foreground->HasAlpha() ? foreground->GetAlpha() : NULL;
// For testing... Set as if no alpha in foreground....
// fgAlpha = NULL;
int bgWidth = background->GetWidth();
int bgHeight = background->GetHeight();
int fgWidth = foreground->GetWidth();
int fgHeight = foreground->GetHeight();
int wCutoff = fgWidth;
int hCutoff = fgHeight;
// If the masked foreground + offset is bigger than the background, masking
// should only occur within these bounds of the foreground image
wCutoff = (bgWidth - xoff > wCutoff) ? wCutoff : bgWidth - xoff;
hCutoff = (bgHeight - yoff > hCutoff) ? hCutoff : bgHeight - yoff;
// Go through the foreground image bit by bit and place it on to the
// background, at an offset of xoff,yoff.
// Don't go beyond the size of the background image,
// or the foreground image.
int y;
unsigned char *bkp;
unsigned char *fgp;
unsigned char *bgAlphap;
unsigned char *fgAlphap;
for (y = 0; y < hCutoff; y++) {
// RGB bytes
bkp = bg + 3 * ((y + yoff) * bgWidth + xoff);
fgp = fg + 3 * ( y * fgWidth);
memcpy( bkp, fgp, 3 * wCutoff );
// Alpha bytes.
if( bgAlpha )
{
bgAlphap = bgAlpha + ((y+yoff) * bgWidth + xoff );
if( fgAlpha )
{
fgAlphap = fgAlpha + (y * fgWidth );
memcpy( bgAlphap, fgAlphap, wCutoff );
}
else
{
memset( bgAlphap, 255, wCutoff );
}
}
}
}
/// Gets a rectangle from within another image, INCLUDING the alpha channel
/// \bug in wxWidgets, wxImage::GetSubImage should do this itself.
wxImage GetSubImageWithAlpha( const wxImage & Src, const wxRect &rect )
{
//First part of this code is lifted from wxImage::GetSubImage() source code.
wxImage image;
wxCHECK_MSG( Src.Ok(), image, wxT("invalid image") );
wxCHECK_MSG( (rect.GetLeft()>=0) && (rect.GetTop()>=0) && (
rect.GetRight()<=Src.GetWidth()) && (rect.GetBottom()<=Src.GetHeight()),
image, wxT("invalid subimage size") );
int subwidth=rect.GetWidth();
const int subheight=rect.GetHeight();
image.Create( subwidth, subheight, false );
unsigned char *subdata = image.GetData(), *data=Src.GetData();
wxCHECK_MSG( subdata, image, wxT("unable to create image") );
// JKC: Quick hack - don't deal with masks - need to understand macro M_IMGDATA first.
// if (Src.M_IMGDATA->m_hasMask)
// image.SetMaskColour( Src.M_IMGDATA->m_maskRed, Src.M_IMGDATA->m_maskGreen, Src.M_IMGDATA->m_maskBlue );
int subleft=3*rect.GetLeft();
int width=3*Src.GetWidth();
subwidth*=3;
data+=rect.GetTop()*width+subleft;
for (long j = 0; j < subheight; ++j)
{
memcpy( subdata, data, subwidth);
subdata+=subwidth;
data+=width;
}
// OK, so we've copied the RGB data.
// Now do the Alpha channel.
wxASSERT( Src.HasAlpha() );
image.InitAlpha();
subleft/=3;
width/=3;
subwidth/=3;
data =Src.GetAlpha();
subdata =image.GetAlpha();
data+=rect.GetTop()*width+subleft;
for (long j = 0; j < subheight; ++j)
{
memcpy( subdata, data, subwidth);
subdata+=subwidth;
data+=width;
}
return image;
}
| 31.293689 | 111 | 0.621578 | [
"vector",
"3d",
"solid"
] |
a356f5890e67536083e076b3c20de6b9a7b8d3d7 | 25,743 | cpp | C++ | src/sat/smt/bv_solver.cpp | FabianWolff/z3 | 549753845e26836e62699da3bdfbeaf66dfa2c81 | [
"MIT"
] | null | null | null | src/sat/smt/bv_solver.cpp | FabianWolff/z3 | 549753845e26836e62699da3bdfbeaf66dfa2c81 | [
"MIT"
] | null | null | null | src/sat/smt/bv_solver.cpp | FabianWolff/z3 | 549753845e26836e62699da3bdfbeaf66dfa2c81 | [
"MIT"
] | null | null | null | /*++
Copyright (c) 2020 Microsoft Corporation
Module Name:
bv_solver.cpp
Abstract:
Solving utilities for bit-vectors.
Author:
Nikolaj Bjorner (nbjorner) 2020-09-02
based on smt/theory_bv
--*/
#include "ast/ast_ll_pp.h"
#include "sat/smt/bv_solver.h"
#include "sat/smt/euf_solver.h"
#include "sat/smt/sat_th.h"
#include "tactic/tactic_exception.h"
namespace bv {
class solver::bit_trail : public trail<euf::solver> {
solver& s;
solver::var_pos vp;
sat::literal lit;
public:
bit_trail(solver& s, var_pos vp) : s(s), vp(vp), lit(s.m_bits[vp.first][vp.second]) {}
virtual void undo(euf::solver& euf) {
s.m_bits[vp.first][vp.second] = lit;
}
};
class solver::bit_occs_trail : public trail<euf::solver> {
bit_atom& a;
var_pos_occ* m_occs;
public:
bit_occs_trail(solver& s, bit_atom& a): a(a), m_occs(a.m_occs) {}
virtual void undo(euf::solver& euf) {
IF_VERBOSE(1, verbose_stream() << "add back occurrences " << & a << "\n");
a.m_occs = m_occs;
}
};
solver::solver(euf::solver& ctx, theory_id id) :
euf::th_euf_solver(ctx, id),
bv(m),
m_autil(m),
m_ackerman(*this),
m_bb(m, get_config()),
m_find(*this) {
ctx.get_egraph().set_th_propagates_diseqs(id);
}
void solver::fixed_var_eh(theory_var v1) {
numeral val1, val2;
VERIFY(get_fixed_value(v1, val1));
unsigned sz = m_bits[v1].size();
value_sort_pair key(val1, sz);
theory_var v2;
bool is_current =
m_fixed_var_table.find(key, v2) &&
v2 < static_cast<int>(get_num_vars()) &&
is_bv(v2) &&
get_bv_size(v2) == sz &&
get_fixed_value(v2, val2) && val1 == val2;
if (!is_current)
m_fixed_var_table.insert(key, v1);
else if (var2enode(v1)->get_root() != var2enode(v2)->get_root()) {
SASSERT(get_bv_size(v1) == get_bv_size(v2));
TRACE("bv", tout << "detected equality: v" << v1 << " = v" << v2 << "\n" << pp(v1) << pp(v2););
m_stats.m_num_th2core_eq++;
add_fixed_eq(v1, v2);
ctx.propagate(var2enode(v1), var2enode(v2), mk_bit2bv_justification(v1, v2));
}
}
void solver::add_fixed_eq(theory_var v1, theory_var v2) {
if (!get_config().m_bv_eq_axioms)
return;
m_ackerman.used_eq_eh(v1, v2);
}
bool solver::get_fixed_value(theory_var v, numeral& result) const {
result.reset();
unsigned i = 0;
for (literal b : m_bits[v]) {
switch (ctx.s().value(b)) {
case l_false:
break;
case l_undef:
return false;
case l_true:
result += power2(i);
break;
}
++i;
}
return true;
}
/**
\brief Find an unassigned bit for m_wpos[v], if such bit cannot be found invoke fixed_var_eh
*/
void solver::find_wpos(theory_var v) {
literal_vector const& bits = m_bits[v];
unsigned sz = bits.size();
unsigned& wpos = m_wpos[v];
for (unsigned i = 0; i < sz; ++i) {
unsigned idx = (i + wpos) % sz;
if (s().value(bits[idx]) == l_undef) {
wpos = idx;
TRACE("bv", tout << "moved wpos of v" << v << " to " << wpos << "\n";);
return;
}
}
TRACE("bv", tout << "v" << v << " is a fixed variable.\n";);
fixed_var_eh(v);
}
/**
*\brief v[idx] = ~v'[idx], then v /= v' is a theory axiom.
*/
void solver::find_new_diseq_axioms(bit_atom& a, theory_var v, unsigned idx) {
if (!get_config().m_bv_eq_axioms)
return;
literal l = m_bits[v][idx];
l.neg();
for (auto vp : a) {
theory_var v2 = vp.first;
unsigned idx2 = vp.second;
if (idx == idx2 && m_bits[v2][idx2] == l && get_bv_size(v2) == get_bv_size(v))
mk_new_diseq_axiom(v, v2, idx);
}
}
/**
\brief v1[idx] = ~v2[idx], then v1 /= v2 is a theory axiom.
*/
void solver::mk_new_diseq_axiom(theory_var v1, theory_var v2, unsigned idx) {
if (!get_config().m_bv_eq_axioms)
return;
// TBD: disabled until new literal creation is supported
return;
SASSERT(m_bits[v1][idx] == ~m_bits[v2][idx]);
TRACE("bv", tout << "found new diseq axiom\n" << pp(v1) << pp(v2););
m_stats.m_num_diseq_static++;
expr_ref eq(m.mk_eq(var2expr(v1), var2expr(v2)), m);
add_unit(~ctx.internalize(eq, false, false, m_is_redundant));
}
std::ostream& solver::display(std::ostream& out, theory_var v) const {
expr* e = var2expr(v);
out << "v";
out.width(4);
out << std::left << v;
out << " ";
out.width(4);
out << e->get_id() << " -> ";
out.width(4);
out << var2enode(find(v))->get_expr_id();
out << std::right;
out.flush();
atom* a = nullptr;
if (is_bv(v)) {
numeral val;
if (get_fixed_value(v, val))
out << " (= " << val << ")";
for (literal lit : m_bits[v]) {
out << " " << lit << ":" << mk_bounded_pp(literal2expr(lit), m, 1);
}
}
else if (m.is_bool(e) && (a = m_bool_var2atom.get(expr2literal(e).var(), nullptr))) {
if (a->is_bit()) {
for (var_pos vp : a->to_bit())
out << " " << var2enode(vp.first)->get_expr_id() << "[" << vp.second << "]";
}
else
out << "def-atom";
}
else
out << " " << mk_bounded_pp(e, m, 1);
out << "\n";
return out;
}
void solver::new_eq_eh(euf::th_eq const& eq) {
force_push();
TRACE("bv", tout << "new eq " << eq.v1() << " == " << eq.v2() << "\n";);
if (is_bv(eq.v1()))
m_find.merge(eq.v1(), eq.v2());
}
void solver::new_diseq_eh(euf::th_eq const& ne) {
theory_var v1 = ne.v1(), v2 = ne.v2();
if (!is_bv(v1))
return;
if (!get_config().m_bv_eq_axioms)
return;
TRACE("bv", tout << "diff: " << v1 << " != " << v2 << "\n";);
unsigned sz = m_bits[v1].size();
for (unsigned i = 0; i < sz; ++i) {
sat::literal a = m_bits[v1][i];
sat::literal b = m_bits[v2][i];
if (a == ~b)
return;
auto va = s().value(a);
auto vb = s().value(b);
if (va != l_undef && vb != l_undef && va != vb)
return;
}
if (s().at_search_lvl()) {
force_push();
assert_ackerman(v1, v2);
}
else
m_ackerman.used_diseq_eh(v1, v2);
}
double solver::get_reward(literal l, sat::ext_constraint_idx idx, sat::literal_occs_fun& occs) const { return 0; }
bool solver::is_extended_binary(sat::ext_justification_idx idx, literal_vector& r) { return false; }
bool solver::is_external(bool_var v) { return true; }
bool solver::propagate(literal l, sat::ext_constraint_idx idx) { return false; }
void solver::get_antecedents(literal l, sat::ext_justification_idx idx, literal_vector& r, bool probing) {
auto& c = bv_justification::from_index(idx);
TRACE("bv", display_constraint(tout, idx););
switch (c.m_kind) {
case bv_justification::kind_t::bv2bit:
SASSERT(s().value(c.m_antecedent) == l_true);
r.push_back(c.m_antecedent);
ctx.add_antecedent(var2enode(c.m_v1), var2enode(c.m_v2));
break;
case bv_justification::kind_t::bit2bv:
SASSERT(m_bits[c.m_v1].size() == m_bits[c.m_v2].size());
for (unsigned i = m_bits[c.m_v1].size(); i-- > 0; ) {
sat::literal a = m_bits[c.m_v1][i];
sat::literal b = m_bits[c.m_v2][i];
SASSERT(a == b || s().value(a) != l_undef);
SASSERT(s().value(a) == s().value(b));
if (a == b)
continue;
if (s().value(a) == l_false) {
a.neg();
b.neg();
}
r.push_back(a);
r.push_back(b);
}
break;
}
if (!probing && ctx.use_drat())
log_drat(c);
}
void solver::log_drat(bv_justification const& c) {
// introduce dummy literal for equality.
sat::literal leq(s().num_vars() + 1, false);
expr* e1 = var2expr(c.m_v1);
expr* e2 = var2expr(c.m_v2);
expr_ref eq(m.mk_eq(e1, e2), m);
ctx.get_drat().def_begin('e', eq->get_id(), std::string("="));
ctx.get_drat().def_add_arg(e1->get_id());
ctx.get_drat().def_add_arg(e2->get_id());
ctx.get_drat().def_end();
ctx.get_drat().bool_def(leq.var(), eq->get_id());
sat::literal_vector lits;
auto add_bit = [&](sat::literal lit) {
if (s().value(lit) == l_true)
lit.neg();
lits.push_back(lit);
};
switch (c.m_kind) {
case bv_justification::kind_t::bv2bit:
lits.push_back(~leq);
lits.push_back(~c.m_antecedent);
lits.push_back(c.m_consequent);
break;
case bv_justification::kind_t::bit2bv:
lits.push_back(leq);
for (unsigned i = m_bits[c.m_v1].size(); i-- > 0; ) {
sat::literal a = m_bits[c.m_v1][i];
sat::literal b = m_bits[c.m_v2][i];
if (a != b) {
add_bit(a);
add_bit(b);
}
}
break;
}
ctx.get_drat().add(lits, status());
ctx.get_drat().log_gc_var(leq.var());
}
void solver::asserted(literal l) {
atom* a = get_bv2a(l.var());
TRACE("bv", tout << "asserted: " << l << "\n";);
if (a && a->is_bit()) {
force_push();
for (auto vp : a->to_bit())
m_prop_queue.push_back(vp);
}
}
bool solver::unit_propagate() {
if (m_prop_queue_head == m_prop_queue.size())
return false;
force_push();
ctx.push(value_trail<euf::solver, unsigned>(m_prop_queue_head));
for (; m_prop_queue_head < m_prop_queue.size() && !s().inconsistent(); ++m_prop_queue_head)
propagate_bits(m_prop_queue[m_prop_queue_head]);
return true;
}
void solver::propagate_bits(var_pos entry) {
theory_var v1 = entry.first;
unsigned idx = entry.second;
SASSERT(idx < m_bits[v1].size());
if (m_wpos[v1] == idx)
find_wpos(v1);
literal bit1 = m_bits[v1][idx];
lbool val = s().value(bit1);
TRACE("bv", tout << "propagating v" << v1 << " #" << var2enode(v1)->get_expr_id() << "[" << idx << "] = " << val << "\n";);
if (val == l_undef)
return;
if (val == l_false)
bit1.neg();
for (theory_var v2 = m_find.next(v1); v2 != v1 && !s().inconsistent(); v2 = m_find.next(v2)) {
literal bit2 = m_bits[v2][idx];
SASSERT(m_bits[v1][idx] != ~m_bits[v2][idx]);
TRACE("bv", tout << "propagating #" << var2enode(v2)->get_expr_id() << "[" << idx << "] = " << s().value(bit2) << "\n";);
if (val == l_false)
bit2.neg();
if (l_true != s().value(bit2))
assign_bit(bit2, v1, v2, idx, bit1, false);
}
}
sat::check_result solver::check() {
force_push();
SASSERT(m_prop_queue.size() == m_prop_queue_head);
return sat::check_result::CR_DONE;
}
void solver::push_core() {
th_euf_solver::push_core();
m_prop_queue_lim.push_back(m_prop_queue.size());
}
void solver::pop_core(unsigned n) {
SASSERT(m_num_scopes == 0);
unsigned old_sz = m_prop_queue_lim.size() - n;
m_prop_queue.shrink(m_prop_queue_lim[old_sz]);
m_prop_queue_lim.shrink(old_sz);
th_euf_solver::pop_core(n);
old_sz = get_num_vars();
m_bits.shrink(old_sz);
m_wpos.shrink(old_sz);
m_zero_one_bits.shrink(old_sz);
}
void solver::pre_simplify() {}
void solver::simplify() {
m_ackerman.propagate();
}
bool solver::set_root(literal l, literal r) {
atom* a = get_bv2a(l.var());
atom* b = get_bv2a(r.var());
if (!a || !a->is_bit())
return true;
if (b && !b->is_bit())
return false;
for (auto vp : a->to_bit()) {
sat::literal l2 = m_bits[vp.first][vp.second];
if (l2.var() == r.var())
continue;
SASSERT(l2.var() == l.var());
VERIFY(l2.var() == l.var());
sat::literal r2 = (l.sign() == l2.sign()) ? r : ~r;
ctx.push(vector2_value_trail<euf::solver, bits_vector, sat::literal>(m_bits, vp.first, vp.second));
m_bits[vp.first][vp.second] = r2;
set_bit_eh(vp.first, r2, vp.second);
}
ctx.push(bit_occs_trail(*this, a->to_bit()));
a->to_bit().m_occs = nullptr;
// validate_atoms();
return true;
}
/**
* Instantiate Ackerman axioms for bit-vectors that have become equal after roots have been added.
*/
void solver::flush_roots() {
struct eq {
solver& s;
eq(solver& s) :s(s) {}
bool operator()(theory_var v1, theory_var v2) const {
return s.m_bits[v1] == s.m_bits[v2];
}
};
struct hash {
solver& s;
hash(solver& s) :s(s) {}
bool operator()(theory_var v) const {
literal_vector const& a = s.m_bits[v];
return string_hash(reinterpret_cast<char*>(a.c_ptr()), a.size() * sizeof(sat::literal), 3);
}
};
eq eq_proc(*this);
hash hash_proc(*this);
map<theory_var, theory_var, hash, eq> table(hash_proc, eq_proc);
for (theory_var v = 0; v < static_cast<theory_var>(get_num_vars()); ++v) {
if (!m_bits[v].empty()) {
theory_var w = table.insert_if_not_there(v, v);
if (v != w && m_find.find(v) != m_find.find(w))
assert_ackerman(v, w);
}
}
TRACE("bv", tout << "infer new equations for bit-vectors that are now equal\n";);
}
void solver::clauses_modifed() {}
lbool solver::get_phase(bool_var v) { return l_undef; }
std::ostream& solver::display(std::ostream& out) const {
unsigned num_vars = get_num_vars();
if (num_vars > 0)
out << "bv-solver:\n";
for (unsigned v = 0; v < num_vars; v++)
out << pp(v);
return out;
}
std::ostream& solver::display_justification(std::ostream& out, sat::ext_justification_idx idx) const {
return display_constraint(out, idx);
}
std::ostream& solver::display_constraint(std::ostream& out, sat::ext_constraint_idx idx) const {
auto& c = bv_justification::from_index(idx);
switch (c.m_kind) {
case bv_justification::kind_t::bv2bit:
return out << c.m_consequent << " <= " << c.m_antecedent << " v" << c.m_v1 << " == v" << c.m_v2 << "\n";
case bv_justification::kind_t::bit2bv:
return out << m_bits[c.m_v1] << " == " << m_bits[c.m_v2] << " => v" << c.m_v1 << " == v" << c.m_v2 << "\n";
default:
UNREACHABLE();
break;
}
return out;
}
void solver::collect_statistics(statistics& st) const {
st.update("bv conflicts", m_stats.m_num_conflicts);
st.update("bv diseqs", m_stats.m_num_diseq_static);
st.update("bv dynamic diseqs", m_stats.m_num_diseq_dynamic);
st.update("bv bit2core", m_stats.m_num_bit2core);
st.update("bv->core eq", m_stats.m_num_th2core_eq);
st.update("bv ackerman", m_stats.m_ackerman);
}
sat::extension* solver::copy(sat::solver* s) { UNREACHABLE(); return nullptr; }
euf::th_solver* solver::fresh(sat::solver* s, euf::solver& ctx) {
bv::solver* result = alloc(bv::solver, ctx, get_id());
ast_translation tr(m, ctx.get_manager());
for (unsigned i = 0; i < get_num_vars(); ++i) {
expr* e1 = var2expr(i);
expr* e2 = tr(e1);
euf::enode* n2 = ctx.get_enode(e2);
SASSERT(n2);
result->mk_var(n2);
result->m_bits[i].append(m_bits[i]);
result->m_zero_one_bits[i].append(m_zero_one_bits[i]);
}
for (theory_var i = 0; i < static_cast<theory_var>(get_num_vars()); ++i)
if (find(i) != i)
result->m_find.merge(i, find(i));
result->m_prop_queue.append(m_prop_queue);
for (unsigned i = 0; i < m_bool_var2atom.size(); ++i) {
atom* a = m_bool_var2atom[i];
if (!a)
continue;
if (a->is_bit()) {
bit_atom* new_a = new (result->get_region()) bit_atom();
m_bool_var2atom.setx(i, new_a, nullptr);
for (auto vp : a->to_bit())
new_a->m_occs = new (result->get_region()) var_pos_occ(vp.first, vp.second, new_a->m_occs);
}
else {
def_atom* new_a = new (result->get_region()) def_atom(a->to_def().m_var, a->to_def().m_def);
m_bool_var2atom.setx(i, new_a, nullptr);
}
validate_atoms();
}
return result;
}
void solver::pop_reinit() {}
bool solver::validate() { return true; }
void solver::init_use_list(sat::ext_use_list& ul) {}
bool solver::is_blocked(literal l, sat::ext_constraint_idx) { return false; }
bool solver::check_model(sat::model const& m) const { return true; }
unsigned solver::max_var(unsigned w) const { return w; }
void solver::add_value(euf::enode* n, model& mdl, expr_ref_vector& values) {
SASSERT(bv.is_bv(n->get_expr()));
if (bv.is_numeral(n->get_expr())) {
values[n->get_root_id()] = n->get_expr();
return;
}
theory_var v = n->get_th_var(get_id());
rational val;
unsigned i = 0;
for (auto l : m_bits[v]) {
switch (s().value(l)) {
case l_true:
val += power2(i);
break;
default:
break;
}
++i;
}
values[n->get_root_id()] = bv.mk_numeral(val, m_bits[v].size());
}
trail_stack<euf::solver>& solver::get_trail_stack() {
return ctx.get_trail_stack();
}
void solver::merge_eh(theory_var r1, theory_var r2, theory_var v1, theory_var v2) {
TRACE("bv", tout << "merging: v" << v1 << " #" << var2enode(v1)->get_expr_id() << " v" << v2 << " #" << var2enode(v2)->get_expr_id() << "\n";);
if (!merge_zero_one_bits(r1, r2)) {
TRACE("bv", tout << "conflict detected\n";);
return; // conflict was detected
}
SASSERT(m_bits[v1].size() == m_bits[v2].size());
unsigned sz = m_bits[v1].size();
for (unsigned idx = 0; !s().inconsistent() && idx < sz; idx++) {
literal bit1 = m_bits[v1][idx];
literal bit2 = m_bits[v2][idx];
CTRACE("bv", bit1 == ~bit2, tout << pp(v1) << pp(v2) << "idx: " << idx << "\n";);
SASSERT(bit1 != ~bit2);
lbool val1 = s().value(bit1);
lbool val2 = s().value(bit2);
TRACE("bv", tout << "merge v" << v1 << " " << bit1 << ":= " << val1 << " " << bit2 << ":= " << val2 << "\n";);
if (val1 == val2)
continue;
CTRACE("bv", (val1 != l_undef && val2 != l_undef), tout << "inconsistent "; tout << pp(v1) << pp(v2) << "idx: " << idx << "\n";);
if (val1 == l_false)
assign_bit(~bit2, v1, v2, idx, ~bit1, true);
else if (val1 == l_true)
assign_bit(bit2, v1, v2, idx, bit1, true);
else if (val2 == l_false)
assign_bit(~bit1, v2, v1, idx, ~bit2, true);
else if (val2 == l_true)
assign_bit(bit1, v2, v1, idx, bit2, true);
}
}
sat::justification solver::mk_bv2bit_justification(theory_var v1, theory_var v2, sat::literal c, sat::literal a) {
void* mem = get_region().allocate(bv_justification::get_obj_size());
sat::constraint_base::initialize(mem, this);
auto* constraint = new (sat::constraint_base::ptr2mem(mem)) bv_justification(v1, v2, c, a);
return sat::justification::mk_ext_justification(s().scope_lvl(), constraint->to_index());
}
sat::ext_justification_idx solver::mk_bit2bv_justification(theory_var v1, theory_var v2) {
void* mem = get_region().allocate(bv_justification::get_obj_size());
sat::constraint_base::initialize(mem, this);
auto* constraint = new (sat::constraint_base::ptr2mem(mem)) bv_justification(v1, v2);
return constraint->to_index();
}
void solver::assign_bit(literal consequent, theory_var v1, theory_var v2, unsigned idx, literal antecedent, bool propagate_eqc) {
m_stats.m_num_bit2core++;
SASSERT(ctx.s().value(antecedent) == l_true);
SASSERT(m_bits[v2][idx].var() == consequent.var());
SASSERT(consequent.var() != antecedent.var());
s().assign(consequent, mk_bv2bit_justification(v1, v2, consequent, antecedent));
if (s().value(consequent) == l_false) {
m_stats.m_num_conflicts++;
SASSERT(s().inconsistent());
}
else {
if (false && get_config().m_bv_eq_axioms) {
expr_ref eq(m.mk_eq(var2expr(v1), var2expr(v2)), m);
flet<bool> _is_redundant(m_is_redundant, true);
literal eq_lit = ctx.internalize(eq, false, false, m_is_redundant);
add_clause(~antecedent, ~eq_lit, consequent);
add_clause(antecedent, ~eq_lit, ~consequent);
}
if (m_wpos[v2] == idx)
find_wpos(v2);
bool_var cv = consequent.var();
atom* a = get_bv2a(cv);
if (a && a->is_bit())
for (auto curr : a->to_bit())
if (propagate_eqc || find(curr.first) != find(v2) || curr.second != idx)
m_prop_queue.push_back(curr);
}
}
void solver::unmerge_eh(theory_var v1, theory_var v2) {
// v1 was the root of the equivalence class
// I must remove the zero_one_bits that are from v2.
zero_one_bits& bits = m_zero_one_bits[v1];
if (bits.empty())
return;
for (unsigned j = bits.size(); j-- > 0; ) {
zero_one_bit& bit = bits[j];
if (find(bit.m_owner) == v1) {
bits.shrink(j + 1);
return;
}
}
bits.shrink(0);
}
bool solver::merge_zero_one_bits(theory_var r1, theory_var r2) {
zero_one_bits& bits2 = m_zero_one_bits[r2];
if (bits2.empty())
return true;
zero_one_bits& bits1 = m_zero_one_bits[r1];
unsigned bv_size = get_bv_size(r1);
SASSERT(bv_size == get_bv_size(r2));
m_merge_aux[0].reserve(bv_size + 1, euf::null_theory_var);
m_merge_aux[1].reserve(bv_size + 1, euf::null_theory_var);
struct scoped_reset {
solver& s;
zero_one_bits& bits1;
scoped_reset(solver& s, zero_one_bits& bits1) :s(s), bits1(bits1) {}
~scoped_reset() {
for (auto& zo : bits1)
s.m_merge_aux[zo.m_is_true][zo.m_idx] = euf::null_theory_var;
}
};
scoped_reset _sr(*this, bits1);
DEBUG_CODE(for (unsigned i = 0; i < bv_size; i++) SASSERT(m_merge_aux[0][i] == euf::null_theory_var || m_merge_aux[1][i] == euf::null_theory_var););
// save info about bits1
for (auto& zo : bits1)
m_merge_aux[zo.m_is_true][zo.m_idx] = zo.m_owner;
// check if bits2 is consistent with bits1, and copy new bits to bits1
for (auto& zo : bits2) {
theory_var v2 = zo.m_owner;
theory_var v1 = m_merge_aux[!zo.m_is_true][zo.m_idx];
if (v1 != euf::null_theory_var) {
// conflict was detected ... v1 and v2 have complementary bits
SASSERT(m_bits[v1][zo.m_idx] == ~(m_bits[v2][zo.m_idx]));
SASSERT(m_bits[v1].size() == m_bits[v2].size());
mk_new_diseq_axiom(v1, v2, zo.m_idx);
return false;
}
// copy missing variable to bits1
if (m_merge_aux[zo.m_is_true][zo.m_idx] == euf::null_theory_var)
bits1.push_back(zo);
}
// reset m_merge_aux vector
DEBUG_CODE(for (unsigned i = 0; i < bv_size; i++) { SASSERT(m_merge_aux[0][i] == euf::null_theory_var || m_merge_aux[1][i] == euf::null_theory_var); });
return true;
}
rational const& solver::power2(unsigned i) const {
while (m_power2.size() <= i)
m_power2.push_back(m_bb.power(m_power2.size()));
return m_power2[i];
}
}
| 37.254703 | 160 | 0.519442 | [
"vector",
"model"
] |
a357087df4f9cd2888441d7285c460c3138742ee | 78,270 | cxx | C++ | drivers/storage/volsnap/vss/server/modules/backupext/vsxml/vs_wmxml.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | drivers/storage/volsnap/vss/server/modules/backupext/vsxml/vs_wmxml.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | drivers/storage/volsnap/vss/server/modules/backupext/vsxml/vs_wmxml.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
Module Name:
vs_wmxml.cxx
Abstract:
Implementation of Writer Metadata XML wrapper classes
Brian Berkowitz [brianb] 3/13/2000
TBD:
Add comments.
Revision History:
Name Date Comments
brianb 03/13/2000 Created
brianb 03/22/2000 Added support CVssGatherWriterMetadata
brianb 04/04/2000 Removed debug printf
mikejohn 04/11/2000 Fix some loop iteration problems
brianb 04/21/2000 code cleanup
mikejohn 06/13/2000 minor tracing changes
--*/
#include "stdafx.hxx"
#include "vs_inc.hxx"
#include "vs_idl.hxx"
#include "vssmsg.h"
#include "vswriter.h"
#include "vsbackup.h"
#include "vs_wmxml.hxx"
#include "rpcdce.h"
#include "wmxml.c"
////////////////////////////////////////////////////////////////////////
// Standard foo for file name aliasing. This code block must be after
// all includes of VSS header files.
//
#ifdef VSS_FILE_ALIAS
#undef VSS_FILE_ALIAS
#endif
#define VSS_FILE_ALIAS "BUEWXMLC"
//
////////////////////////////////////////////////////////////////////////
static LPCWSTR x_wszElementRoot = L"root";
static LPCWSTR x_wszElementWriterMetadata = L"WRITER_METADATA";
static LPCWSTR x_wszAttrXmlns = L"xmlns";
static LPCWSTR x_wszValueXmlns = L"x-schema:#VssWriterMetadataInfo";
static LPCWSTR x_wszDocProlog = L"<root>";
static LPCWSTR x_wszDocEpilog = L"</root>";
// identification element and its attributes
static LPCWSTR x_wszElementIdentification = L"IDENTIFICATION";
static LPCWSTR x_wszAttrWriterId = L"writerId";
static LPCWSTR x_wszAttrInstanceId = L"instanceId";
static LPCWSTR x_wszAttrFriendlyName = L"friendlyName";
static LPCWSTR x_wszAttrUsage = L"usage";
static LPCWSTR x_wszAttrDataSource = L"dataSource";
// backup location elements
static LPCWSTR x_wszElementBackupLocations = L"BACKUP_LOCATIONS";
static LPCWSTR x_wszElementIncludeFiles = L"INCLUDE_FILES";
static LPCWSTR x_wszElementExcludeFiles = L"EXCLUDE_FILES";
static LPCWSTR x_wszElementDatabase = L"DATABASE";
static LPCWSTR x_wszElementFilegroup = L"FILE_GROUP";
// RESTORE_METHOD element and it's attributes
static LPCWSTR x_wszElementRestoreMethod = L"RESTORE_METHOD";
static LPCWSTR x_wszAttrMethod = L"method";
static LPCWSTR x_wszAttrService = L"service";
static LPCWSTR x_wszAttrUserProcedure = L"userProcedure";
static LPCWSTR x_wszAttrWriterRestore = L"writerRestore";
static LPCWSTR x_wszAttrRebootRequired = L"rebootRequired";
static LPCWSTR x_wszElementAlternateMapping = L"ALTERNATE_LOCATION_MAPPING";
// attributes and elements associated with DATABASE and FILE_GROUP components
static LPCWSTR x_wszAttrLogicalPath = L"logicalPath";
static LPCWSTR x_wszAttrComponentName = L"componentName";
static LPCWSTR x_wszAttrCaption = L"caption";
static LPCWSTR x_wszAttrRestoreMetadata = L"restoreMetadata";
static LPCWSTR x_wszAttrNotifyOnBackupComplete = L"notifyOnBackupComplete";
static LPCWSTR x_wszAttrIcon = L"icon";
static LPCWSTR x_wszAttrSelectable = L"selectable";
static LPCWSTR x_wszAttrSelectableForRestore = L"selectableForRestore";
static LPCWSTR x_wszElementDatabaseFiles = L"DATABASE_FILES";
static LPCWSTR x_wszElementDatabaseLogfiles = L"DATABASE_LOGFILES";
static LPCWSTR x_wszElementFilelist = L"FILE_LIST";
static LPCWSTR x_wszElementDependency = L"DEPENDENCY";
static LPCWSTR x_wszAttrCompFlags = L"componentFlags";
static LPCWSTR x_wszAttrFilespecBackupType = L"filespecBackupType";
static LPCWSTR x_wszAttrOnWriterId = L"onWriterId";
static LPCWSTR x_wszAttrOnLogicalPath = L"onLogicalPath";
static LPCWSTR x_wszAttrOnComponentName = L"onComponentName";
// attributes for a FILE_LIST, INCLUDE_FILES, EXCLUDE_FILES,
// or ALTERNATE_DESTINATION_MAPPING elements
static LPCWSTR x_wszAttrPath = L"path";
static LPCWSTR x_wszAttrFilespec = L"filespec";
static LPCWSTR x_wszAttrRecursive = L"recursive";
static LPCWSTR x_wszAttrAlternatePath = L"alternatePath";
// various attributes and values associated with toplevel WRITER_METADATA
// element
static LPCWSTR x_wszAttrVersion = L"version";
static LPCWSTR x_wszVersionNo = L"1.1";
static LPCWSTR x_wszAttrBackupSchema = L"backupSchema";
bool CVssExamineWriterMetadata::LoadDocument(BSTR bstrXML)
{
CVssFunctionTracer ft(VSSDBG_XML, L"CVssExamineWriterMetadata::LoadDocument");
BSTR bstr = NULL;
try
{
// compute length of supplied XML document
UINT cwcXML = (UINT) wcslen(bstrXML);
// compute length of constructed document consisting of
// a root node, schema, and supplied document
UINT cwcDoc = cwcXML +
(UINT) g_cwcWriterMetadataXML +
(UINT) wcslen(x_wszDocProlog) +
(UINT) wcslen(x_wszDocEpilog);
// allocate string
bstr = SysAllocStringLen(NULL, cwcDoc);
// check for allocation failure
if (bstr == NULL)
ft.Throw(VSSDBG_XML, E_OUTOFMEMORY, L"Couldn't allocate BSTR");
// setup pointer to beginning of string
WCHAR *pwc = bstr;
// copy in <root>
wcscpy(pwc, x_wszDocProlog);
pwc += wcslen(x_wszDocProlog);
// copy in schema
memcpy(pwc, g_WriterMetadataXML, g_cwcWriterMetadataXML* sizeof(WCHAR));
pwc += g_cwcWriterMetadataXML;
// copy in supplied WRITER_METADATA element
memcpy(pwc, bstrXML, cwcXML * sizeof(WCHAR));
pwc += cwcXML;
// copy in </root>
wcscpy(pwc, x_wszDocEpilog);
// load document from string
bool bLoaded = m_doc.LoadFromXML(bstr);
// free allocated string
SysFreeString(bstr);
bstr = NULL;
// check load success
if (!bLoaded)
return false;
// find root element
if (!m_doc.FindElement(x_wszElementRoot, TRUE))
return false;
// find WRITER_METADATA element
if (!m_doc.FindElement(x_wszElementWriterMetadata, TRUE))
return false;
// set toplevel node to WRITER_METADATA element
m_doc.SetToplevel();
return true;
}
catch(...)
{
// free allocated string
if (bstr != NULL)
SysFreeString(bstr);
throw;
}
}
// initialize metadata document from an XML string. Return S_FALSE if
// the document is not correctly formed.
bool CVssExamineWriterMetadata::Initialize
(
IN BSTR bstrXML // WRITER_METADATA element
)
{
CVssFunctionTracer ft(VSSDBG_XML, L"CVssExamineWriterMetadata::Initialize");
if (bstrXML == NULL)
return false;
// temporary string containing XML document including schema
InitializeHelper(ft);
return LoadDocument(bstrXML);
}
// obtain information from the IDENTIFICATION element
// implements IVssExamineWriterMetadata::GetIdentity
//
// Returns:
// S_OK if the operation is successful
// E_INVALIDARG if either pidInstance, pidWriter, pbstrWriterName, pUsage,
// or pSource is NULL
// VSS_CORRUPT_XML_DOCUMENT if the XML document is invalid.
// E_OUTOFMEMORY if an allocation failure occurs
STDMETHODIMP CVssExamineWriterMetadata::GetIdentity
(
OUT VSS_ID *pidInstance, // instance id
OUT VSS_ID *pidWriter, // id of writer class
OUT BSTR *pbstrWriterName, // name of writer
OUT VSS_USAGE_TYPE *pUsage, // usage type for writer
OUT VSS_SOURCE_TYPE *pSource // type of data source for writer
)
{
CVssFunctionTracer ft
(
VSSDBG_XML,
L"CVssExamineWriterMetadata::GetIdentity"
);
try
{
// null output parameters
if (pUsage)
*pUsage = VSS_UT_UNDEFINED;
if (pSource)
*pSource = VSS_ST_UNDEFINED;
VssZeroOut(pidInstance);
VssZeroOut(pidWriter);
VssZeroOut(pbstrWriterName);
// check arguments
if (pidInstance == NULL ||
pidWriter == NULL ||
pbstrWriterName == NULL ||
pUsage == NULL ||
pSource == NULL)
ft.Throw
(
VSSDBG_XML,
E_INVALIDARG,
L"NULL output parameter."
);
CVssSafeAutomaticLock lock(m_csDOM);
// reposition to top of document
m_doc.ResetToDocument();
// look for child IDENTIFICATION element
if (!m_doc.FindElement(x_wszElementIdentification, TRUE))
MissingElement(ft, x_wszElementIdentification);
VSS_ID idInstance;
VSS_ID idWriter;
CComBSTR bstrWriterName;
VSS_USAGE_TYPE usage;
VSS_SOURCE_TYPE source;
// obtain instanceId attribute value
get_VSS_IDValue(ft, x_wszAttrInstanceId, &idInstance);
// obtain writerId attribute value
get_VSS_IDValue(ft, x_wszAttrWriterId, &idWriter);
// obtain friendlyName attribute value
get_stringValue(x_wszAttrFriendlyName, &bstrWriterName);
CComBSTR bstrVal;
// extract usage Attribute value
if (!m_doc.FindAttribute(x_wszAttrUsage, &bstrVal))
MissingAttribute(ft, x_wszAttrUsage);
// convert string value to VSS_USAGE_TYPE
usage = ConvertToUsageType(ft, bstrVal);
bstrVal.Empty();
// extract source attribute value
if (!m_doc.FindAttribute(x_wszAttrDataSource, &bstrVal))
MissingAttribute(ft, x_wszAttrDataSource);
// convert string to VSS_SOURCE_TYPE
source = ConvertToSourceType(ft, bstrVal);
// assign output parameters
*pUsage = usage;
*pSource = source;
*pidInstance = idInstance;
*pidWriter = idWriter;
*pbstrWriterName = bstrWriterName.Detach();
}
VSS_STANDARD_CATCH(ft)
return ft.hr;
}
// get count of components, files to include and files to exclude.
// implements IVssExamineWriterMetadata::GetFileCounts
//
// Returns:
// S_OK if the operation is successful
// E_INVALIDARG if pcIncludeFiles, pcExcludeFiles, or pcComponents is NULL
// E_OUTOFMEMORY if an allocation failure occurs
STDMETHODIMP CVssExamineWriterMetadata::GetFileCounts
(
OUT UINT *pcIncludeFiles, // count of INCLUDE_FILES elements
OUT UINT *pcExcludeFiles, // count of EXCLUDE_FILES elements
OUT UINT *pcComponents // count of DATABASE and FILE_GROUP elements
)
{
CVssFunctionTracer ft
(
VSSDBG_XML,
L"CVssExamineWriterMetadata::GetFileCounts"
);
try
{
VssZeroOut(pcExcludeFiles);
VssZeroOut(pcComponents);
// check output parametrs
if (pcIncludeFiles == NULL ||
pcExcludeFiles == NULL ||
pcComponents == NULL)
ft.Throw(VSSDBG_XML, E_INVALIDARG, L"NULL output parameter.");
// initalize output parameters
*pcIncludeFiles = 0;
CVssSafeAutomaticLock lock(m_csDOM);
// reposition to top of document
m_doc.ResetToDocument();
// position on first BACKUP_LOCATIONS child element
if (m_doc.FindElement(x_wszElementBackupLocations, TRUE) &&
m_doc.Next())
{
UINT cIncludeFiles = 0;
UINT cExcludeFiles = 0;
UINT cComponents = 0;
do
{
// get current node
CComPtr<IXMLDOMNode> pNode = m_doc.GetCurrentNode();
DOMNodeType dnt;
// get node type
ft.hr = pNode->get_nodeType(&dnt);
ft.CheckForError(VSSDBG_XML, L"IXMLDOMNode::get_nodeType");
// if node type is not element, then skip it
if (dnt != NODE_ELEMENT)
continue;
// get node name
CComBSTR bstrName;
ft.hr = pNode->get_nodeName(&bstrName);
ft.CheckForError(VSSDBG_XML, L"IXMLDOMNode::get_nodeName");
// update counts based on element type
if (wcscmp(bstrName, x_wszElementIncludeFiles) == 0)
cIncludeFiles += 1;
else if (wcscmp(bstrName, x_wszElementExcludeFiles) == 0)
cExcludeFiles += 1;
else if (wcscmp(bstrName, x_wszElementDatabase) == 0 ||
wcscmp(bstrName, x_wszElementFilegroup) == 0)
cComponents += 1;
} while(m_doc.Next(FALSE, FALSE));
*pcIncludeFiles = cIncludeFiles;
*pcExcludeFiles = cExcludeFiles;
*pcComponents = cComponents;
}
}
VSS_STANDARD_CATCH(ft)
return ft.hr;
}
// obtain a specific kind of file INCLUDE_FILES or EXCLUDE_FILES
HRESULT CVssExamineWriterMetadata::GetFileType
(
CVssFunctionTracer &ft,
IN UINT iFile, // which element to extract
IN LPCWSTR wszFileType, // which elements to filter
OUT IVssWMFiledesc **ppFiledesc // file descriptor
)
{
CVssWMFiledesc *pFiledesc = NULL;
try
{
// null output parameter
if (ppFiledesc)
*ppFiledesc = NULL;
// check output parameter
if (ppFiledesc == NULL)
ft.Throw(VSSDBG_XML, E_INVALIDARG, L"NULL output parameter.");
if (wszFileType == NULL)
ft.Throw(VSSDBG_XML, E_INVALIDARG, L"NULL required input parameter.");
CVssSafeAutomaticLock lock(m_csDOM);
// reposition to top of document
m_doc.ResetToDocument();
// find BACKUP_LOCATIONS element
if (!m_doc.FindElement(x_wszElementBackupLocations, TRUE))
ft.Throw
(
VSSDBG_XML,
VSS_E_OBJECT_NOT_FOUND,
L"BACKUP_LOCATIONS element was not found."
);
// find element type within BACKUP_LOCATIONS
if (!m_doc.FindElement(wszFileType, TRUE))
ft.Throw
(
VSSDBG_XML,
VSS_E_OBJECT_NOT_FOUND,
L"%s element was not found",
wszFileType
);
// skip to selected element
for(UINT i = 0; i < iFile; i++)
{
if (!m_doc.FindElement(wszFileType, FALSE))
ft.Throw
(
VSSDBG_XML,
VSS_E_OBJECT_NOT_FOUND,
L"%s element was not found"
);
}
// construct Filedesc for selected element
pFiledesc = new CVssWMFiledesc(m_doc.GetCurrentNode());
// check for allocation failure
if (pFiledesc == NULL)
ft.Throw
(
VSSDBG_XML,
E_OUTOFMEMORY,
L"Can't create CVssWMFiledesc due to allocation failure."
);
// 2nd phase of construction
pFiledesc->Initialize(ft);
// transfer ownership of pointer
*ppFiledesc = (IVssWMFiledesc *) pFiledesc;
// set reference count to 1
((IVssWMFiledesc *) pFiledesc)->AddRef();
pFiledesc = NULL;
}
VSS_STANDARD_CATCH(ft)
delete pFiledesc;
return ft.hr;
}
// return an INCLUDE_FILES element
// implements IVssExamineWriterMetadata::GetIncludeFile
// caller is responsible for calling IVssWMFiledesc::Release on the output parameter
//
// Returns:
// S_OK if the operation is successful
// E_INVALIDARG if ppFiledesc is NULL.
// VSS_E_OBJECT_NOT_FOUND if the specified exclude file doesn't exist
// E_OUTOFMEMORY if an allocation failure occurs
STDMETHODIMP CVssExamineWriterMetadata::GetIncludeFile
(
IN UINT iFile, // which element to select
OUT IVssWMFiledesc **ppFiledesc // output constructed Filedesc
)
{
CVssFunctionTracer ft
(
VSSDBG_XML,
L"CVssExamineWriterMetadata::GetIncludeFile"
);
// call helper routine
return GetFileType(ft, iFile, x_wszElementIncludeFiles, ppFiledesc);
}
// return an EXCLUDE_FILES element
// implements IVssExamineWriterMetadata::GetExcludeFile
// caller is responsible for calling IVssWMFiledesc::Release on the output parameter
//
// Returns:
// S_OK if the operation is successful
// E_INVALIDARG if ppFiledesc is NULL.
// VSS_E_OBJECT_NOT_FOUND if the specified exclude file doesn't exist
// E_OUTOFMEMORY if an allocation failure occurs
STDMETHODIMP CVssExamineWriterMetadata::GetExcludeFile
(
IN UINT iFile,
OUT IVssWMFiledesc **ppFiledesc
)
{
CVssFunctionTracer ft
(
VSSDBG_XML,
L"CVssExamineWriterMetadata::GetExcludeFile"
);
return GetFileType(ft, iFile, x_wszElementExcludeFiles, ppFiledesc);
}
// obtain a component (DATABASE or FILE_GROUP)
// implements IVssExamineWriterMetadata::GetComponent
// caller is responsible for calling IVssWMComponent::Release on the output parameter
//
// Returns:
// S_OK if the operation is successful
// E_INVALIDARG if ppComponent is NULL
// VSS_E_OBJECT_NOT_FOUND if the specified component is not found
// VSS_E_CORRUPT_XML_DOCUMENT if the XML document is corrupt
// E_OUTOFMEMORY if an allocation failure occurs
STDMETHODIMP CVssExamineWriterMetadata::GetComponent
(
IN UINT iComponent, // which component to select
OUT IVssWMComponent **ppComponent // returned component
)
{
CVssFunctionTracer ft
(
VSSDBG_XML,
L"CVssExamineWriterMetadata::GetComponent"
);
CVssWMComponent *pComponent = NULL;
try
{
// check output parameter
if (ppComponent == NULL)
ft.Throw(VSSDBG_XML, E_INVALIDARG, L"NULL output parameter.");
// set output parameter to NULL
*ppComponent = NULL;
CVssSafeAutomaticLock lock(m_csDOM);
// reset position to top of document
m_doc.ResetToDocument();
// position on BACKUP_LOCATIONS element
if (!m_doc.FindElement(x_wszElementBackupLocations, TRUE))
ft.Throw
(
VSSDBG_XML,
VSS_E_OBJECT_NOT_FOUND,
L"BACKUP_LOCATIONS element was not found"
);
// position on first child element of BACKUP_LOCATIONS
if (!m_doc.Next(TRUE, FALSE))
ft.Throw
(
VSSDBG_XML,
VSS_E_OBJECT_NOT_FOUND,
L"Component was not found"
);
// current node
CComPtr<IXMLDOMNode> pNode = NULL;
for(UINT i = 0; i <= iComponent; )
{
DOMNodeType dnt;
// obtain current node
pNode = m_doc.GetCurrentNode();
// obtain node type
ft.hr = pNode->get_nodeType(&dnt);
ft.CheckForError(VSSDBG_XML, L"IXMLDOMNode::get_nodeType");
// skip node if not an ELEMENT
if (dnt == NODE_ELEMENT)
{
// get element name
CComBSTR bstrName;
ft.hr = pNode->get_nodeName(&bstrName);
ft.CheckForError(VSSDBG_XML, L"IXMLDOMNode::get_nodeName");
// check that element is a copmonent (either DATABASE
// or FILE_GROUP)
if (wcscmp(bstrName, x_wszElementDatabase) == 0 ||
wcscmp(bstrName, x_wszElementFilegroup) == 0)
{
// increment count of components found and determine
// it this is the selected component
i++;
if (i > iComponent)
break;
}
}
// position on next element
if(!m_doc.Next(FALSE, FALSE))
ft.Throw
(
VSSDBG_XML,
VSS_E_OBJECT_NOT_FOUND,
L"Component %d was not found",
iComponent
);
}
pComponent = new CVssWMComponent((IXMLDOMNode *) pNode);
// check for allocation failure
if (pComponent == NULL)
ft.Throw
(
VSSDBG_XML,
E_OUTOFMEMORY,
L"Cannot allocate CVssWMComponent due to allocation failure."
);
// 2nd phase of initialization
pComponent->Initialize(ft);
// move pointer to output parameter
*ppComponent = (IVssWMComponent *) pComponent;
// set reference count to 1.
((IVssWMComponent *) pComponent)->AddRef();
pComponent = NULL;
}
VSS_STANDARD_CATCH(ft)
delete pComponent;
return ft.hr;
}
// get RESTORE_METHOD element info. Return S_FALSE if not found
// implements IVssExamineWriterMetadata::GetRestoreMethod
// caller is responsible for calling SysFreeString on pbstrService
// and pbstrUserProcedure
//
// Returns:
// S_OK if the operation is successful
// S_FALSE if there is no restore method
// E_INVALIDARG if any of the output parameters are NULL.
// VSS_E_CORRUPTXMLDOCUMENT if the XML document is invalid.
// E_OUTOFMEMORY if an allocation failure occurs
STDMETHODIMP CVssExamineWriterMetadata::GetRestoreMethod
(
OUT VSS_RESTOREMETHOD_ENUM *pMethod, // method enumeration
OUT BSTR *pbstrService, // service name (valid for VSS_RME_STOP_RESTORE_RESTART
OUT BSTR *pbstrUserProcedure, // URL/URI to a user procedure to be performed manually
OUT VSS_WRITERRESTORE_ENUM *pWriterRestore, // whether writer particpates in the restore
OUT bool *pbRebootRequired, // is a reboot after restore required
OUT UINT *pcMappings // # of ALTERNATE_LOCATION_MAPPING elements
)
{
CVssFunctionTracer ft
(
VSSDBG_XML,
L"CVssExamineWriterMetadata::GetRestoreMethod"
);
try
{
// initialize output parameters
if (pWriterRestore)
*pWriterRestore = VSS_WRE_UNDEFINED;
if (pbRebootRequired)
*pbRebootRequired = false;
VssZeroOut(pbstrUserProcedure);
VssZeroOut(pbstrService);
VssZeroOut(pcMappings);
// check output parameters
if (pMethod == NULL ||
pbstrService == NULL ||
pbstrUserProcedure == NULL ||
pWriterRestore == NULL ||
pbRebootRequired == NULL ||
pcMappings == NULL)
ft.Throw(VSSDBG_XML, E_INVALIDARG, L"NULL output parameter.");
*pMethod = VSS_RME_UNDEFINED;
VSS_RESTOREMETHOD_ENUM method;
VSS_WRITERRESTORE_ENUM writerRestore;
CComBSTR bstrUserProcedure;
CComBSTR bstrService;
unsigned cMappings = 0;
bool bRebootRequired;
CVssSafeAutomaticLock lock(m_csDOM);
// reposition at top of the document
m_doc.ResetToDocument();
// find RESTORE_METHOD element, return S_FALSE if not found
if (!m_doc.FindElement(x_wszElementRestoreMethod, TRUE))
ft.hr = S_FALSE;
else
{
// get "method" attribute
CComBSTR bstrVal = NULL;
if (!m_doc.FindAttribute(x_wszAttrMethod, &bstrVal))
MissingAttribute(ft, x_wszAttrMethod);
// convert string to VSS_RESTOREMETHOD_ENUM
method = ConvertToRestoreMethod(ft, bstrVal);
bstrVal.Empty();
// extract service attribute value
get_stringValue(x_wszAttrService, &bstrService);
// extract userProcedure attribute value
get_stringValue(x_wszAttrUserProcedure, &bstrUserProcedure);
// extract writerRestore attribute value as a string
get_stringValue(x_wszAttrWriterRestore, &bstrVal);
// convert string to VSS_WRITERRESTORE_ENUM
writerRestore = ConvertToWriterRestore(ft, bstrVal);
// extract rebootRequired attribute
get_boolValue(ft, x_wszAttrRebootRequired, &bRebootRequired);
// get first ALTERNATE_LOCATION_MAPPING elemnent
if (m_doc.FindElement(x_wszElementAlternateMapping, TRUE))
{
// count number of elements
do
{
// increment count of mappings
cMappings += 1;
} while(m_doc.FindElement(x_wszElementAlternateMapping, FALSE));
}
// assign output parameters
*pMethod = method;
*pWriterRestore = writerRestore;
*pbstrUserProcedure = bstrUserProcedure.Detach();
*pbstrService = bstrService.Detach();
*pcMappings = cMappings;
*pbRebootRequired = bRebootRequired;
}
}
VSS_STANDARD_CATCH(ft)
return ft.hr;
}
// get a specific alternative location mapping
// implements IVssExamineWriterMetadata::GetAlternateLocationMapping
// caller is responsible for calling IVssWMFiledesc::Release on the output parameter
//
// Returns:
// S_OK if the operation is successful
// E_INVALIDARG if ppFiledesc is NULL
// VSS_E_OBJECT_NOT_FOUND if the specified alternate location mapping
// is not found.
// E_OUTOFMEMORY if an allocation failure occurs
STDMETHODIMP CVssExamineWriterMetadata::GetAlternateLocationMapping
(
IN UINT iMapping, // which mapping to extract
OUT IVssWMFiledesc **ppFiledesc // file descriptor for mapping
)
{
CVssFunctionTracer ft
(
VSSDBG_XML,
L"CVssExamineWriterMetadata::GetAlternateLocationMapping"
);
CVssWMFiledesc *pFiledesc = NULL;
try
{
// check output parameter
if (ppFiledesc == NULL)
ft.Throw(VSSDBG_XML, E_INVALIDARG, L"NULL output parameter");
// set output parameter to NULL
*ppFiledesc = NULL;
CVssSafeAutomaticLock lock(m_csDOM);
// reposition to top of document
m_doc.ResetToDocument();
// find RESTORE_METHOD element
if (!m_doc.FindElement(x_wszElementRestoreMethod, TRUE))
ft.Throw
(
VSSDBG_XML,
VSS_E_OBJECT_NOT_FOUND,
L"Cannot find RESTORE_METHOD element"
);
// find first ALTERNATIVE_LOCATION_MAPPING element
if (!m_doc.FindElement(x_wszElementAlternateMapping, TRUE))
ft.Throw
(
VSSDBG_XML,
VSS_E_OBJECT_NOT_FOUND,
L"Cannot find ALTERNATE_LOCATION_MAPPING element"
);
// search for selected element
for(UINT i = 0; i < iMapping; i++)
{
if (!m_doc.FindElement(x_wszElementAlternateMapping, FALSE))
ft.Throw
(
VSSDBG_XML,
VSS_E_OBJECT_NOT_FOUND,
L"Cannot find ALTERNATE_LOCATION_MAPPING element"
);
}
// obtain current node
CComPtr<IXMLDOMNode> pNode = m_doc.GetCurrentNode();
// return mapping as a CVssWMFiledesc
pFiledesc = new CVssWMFiledesc((IXMLDOMNode *) pNode);
// check for allocation failure
if (pFiledesc == NULL)
ft.Throw
(
VSSDBG_XML,
E_OUTOFMEMORY,
L"Cannot create CVssAlternateLocationMapping due to allocation failure."
);
// call 2nd phase of construction
pFiledesc->Initialize(ft);
// transfer pointer to output parameter
*ppFiledesc = (IVssWMFiledesc *) pFiledesc;
// set reference count to 1
((IVssWMFiledesc *) pFiledesc)->AddRef();
pFiledesc = NULL;
}
VSS_STANDARD_CATCH(ft)
delete pFiledesc;
return ft.hr;
}
STDMETHODIMP CVssExamineWriterMetadata::GetBackupSchema
(
OUT DWORD *pdwSchemaMask
)
{
CVssFunctionTracer ft(VSSDBG_XML, L"CVssExamineWriterMetadata::GetBackupSchema");
try
{
if (pdwSchemaMask == NULL)
ft.Throw(VSSDBG_XML, E_INVALIDARG, L"NULL out parameter");
CVssSafeAutomaticLock lock(m_csDOM);
// reposition to top of document
m_doc.ResetToDocument();
get_dwordValue(ft, x_wszAttrBackupSchema, pdwSchemaMask);
}
VSS_STANDARD_CATCH(ft)
return ft.hr;
}
// obtain the XML document itself
// implements IVssExamineWriterMetadata::GetDocument
// caller is responsible for calling IXMLDOMDocument::Release on the output parameter
//
// Returns:
// S_OK if the operation is successful
// E_INVALDARG if ppDoc is NULL.
// E_OUTOFMEMORY if an allocation failure occurs
STDMETHODIMP CVssExamineWriterMetadata::GetDocument(IXMLDOMDocument **ppDoc)
{
CVssFunctionTracer ft(VSSDBG_XML, L"CVssExamineWriterMetadata::GetDocument");
try
{
// validate output parameter
if (ppDoc == NULL)
ft.Throw(VSSDBG_XML, E_INVALIDARG, L"NULL output parameter.");
// set output parameter
*ppDoc = m_doc.GetInterface();
BS_ASSERT(*ppDoc);
// increment reference count on output parameter
m_doc.GetInterface()->AddRef();
}
VSS_STANDARD_CATCH(ft)
return ft.hr;
}
// save writer metadata as XML string
// implements IVssExamineWriterMetadata::SaveAsXML
// caller is responsible for calling SysFreeString on the output parameter
//
// Returns:
// S_OK if the operation is successful
// E_INVALIDARG if pbstrXML is NULL.
// E_OUTOFMEMORY if an allocation failure occurs
STDMETHODIMP CVssExamineWriterMetadata::SaveAsXML(BSTR *pbstrXML)
{
CVssFunctionTracer ft
(
VSSDBG_XML,
L"CVssExamineWriterMetadata::SaveAsXML"
);
try
{
// validate output parametr
if (pbstrXML == NULL)
ft.Throw(VSSDBG_XML, E_INVALIDARG, L"NULL output parameter.");
// set output parameter to NULL
*pbstrXML = NULL;
CVssSafeAutomaticLock lock(m_csDOM);
// construct XML string
*pbstrXML = m_doc.SaveAsXML();
}
VSS_STANDARD_CATCH(ft)
return ft.hr;
}
// load document from XLM string
// implements IVssExamineWriterMetadata::LoadFromXML
//
// Returns:
// S_OK if the operation is successful
// S_FALSE if the document failed to load.
// E_INVALIDARG if bstrXML is NULL.
// E_OUTOFMEMORY if an allocation failure occurs
STDMETHODIMP CVssExamineWriterMetadata::LoadFromXML(BSTR bstrXML)
{
CVssFunctionTracer ft
(
VSSDBG_XML,
L"CVssExamineWriterMetadata::LoadFromXML"
);
try
{
if (bstrXML == NULL)
ft.Throw(VSSDBG_XML, E_INVALIDARG, L"Required input parameter is NULL.");
CVssSafeAutomaticLock lock(m_csDOM);
bool f = LoadDocument(bstrXML);
ft.hr = f ? S_OK : S_FALSE;
}
VSS_STANDARD_CATCH(ft)
return ft.hr;
}
// IUnknown::QueryInterface
STDMETHODIMP CVssExamineWriterMetadata::QueryInterface(REFIID, void **)
{
return E_NOTIMPL;
}
// IUnknown::AddRef
STDMETHODIMP_(ULONG) CVssExamineWriterMetadata::AddRef()
{
LONG cRef = InterlockedIncrement(&m_cRef);
return (ULONG) cRef;
}
// IUnknown::Release
STDMETHODIMP_(ULONG) CVssExamineWriterMetadata::Release()
{
LONG cRef = InterlockedDecrement(&m_cRef);
BS_ASSERT(cRef >= 0);
if (cRef == 0)
{
// reference count is 0, delete the object
delete this;
return 0;
}
else
return (ULONG) cRef;
}
// return basic information about the component
// implements IVssWMComponent::GetComponentInfo
// caller must call IVssWMComponent::FreeComponentInfo on the output parameter
//
// Returns:
// S_OK if the operation is successful
// E_INVALIDARG if ppInfo is NULL
// VSS_E_CORRUPT_XML_DOCUMENT if the XML document is invalid.
// E_OUTOFMEMORY if an allocation failure occurs
STDMETHODIMP CVssWMComponent::GetComponentInfo(PVSSCOMPONENTINFO *ppInfo)
{
CVssFunctionTracer ft
(
VSSDBG_XML,
L"CVssWMComponent::GetComponentInfo"
);
// constructed component info
VSS_COMPONENTINFO *pInfo = NULL;
try
{
// validate output parameter
if (ppInfo == NULL)
ft.Throw(VSSDBG_XML, E_INVALIDARG, L"NULL output parameter");
// set output parameter to NULL
*ppInfo = NULL;
// allocate structure
pInfo = (VSS_COMPONENTINFO *) CoTaskMemAlloc(sizeof(VSS_COMPONENTINFO));
// check for allocation failure
if (pInfo == NULL)
ft.Throw
(
VSSDBG_XML,
E_OUTOFMEMORY,
L"Failed to create VSS_COMPONENTINFO"
);
// initialize structure
memset(pInfo, 0, sizeof(*pInfo));
CVssSafeAutomaticLock lock(m_csDOM);
// obtain current node
CComPtr<IXMLDOMNode> pNode = m_doc.GetCurrentNode();
// get node name
CComBSTR bstrName = NULL;
ft.hr = pNode->get_nodeName(&bstrName);
ft.CheckForError(VSSDBG_XML, L"IXMLDOMNode::get_nodeName");
// convert string to VSS_COMPONENT_TYPE
pInfo->type = ConvertToComponentType(ft, bstrName, false);
// obtain logical path
get_stringValue(x_wszAttrLogicalPath, &pInfo->bstrLogicalPath);
// obtain component name
get_stringValue(x_wszAttrComponentName, &pInfo->bstrComponentName);
// obtain component description
get_stringValue(x_wszAttrCaption, &pInfo->bstrCaption);
// get icon if it exists
pInfo->pbIcon = get_byteArrayValue(ft, x_wszAttrIcon, false, pInfo->cbIcon);
// get boolean restoreMetadata attribute value
get_boolValue(ft, x_wszAttrRestoreMetadata, &pInfo->bRestoreMetadata);
// get boolean notifyOnBackupComplete attribute value
get_boolValue(ft, x_wszAttrNotifyOnBackupComplete, &pInfo->bNotifyOnBackupComplete);
// get boolean selectable attribute value
get_boolValue(ft, x_wszAttrSelectable, &pInfo->bSelectable);
// get boolean selectable for restore attribute value
get_boolValue(ft, x_wszAttrSelectableForRestore, &pInfo->bSelectableForRestore);
// get component flags attribute value
get_dwordValue(ft, x_wszAttrCompFlags, &pInfo->dwComponentFlags);
// count subElements DATABASE_FILES, DATABASE_LOGFILES, and FILE_LIST
// descend to first child element
CXMLDocument doc(m_doc.GetCurrentNode(), m_doc.GetInterface());
if (doc.Next(TRUE, FALSE))
{
do
{
// get current node
CComPtr<IXMLDOMNode> pNode = doc.GetCurrentNode();
DOMNodeType dnt;
// determine node type
ft.hr = pNode->get_nodeType(&dnt);
ft.CheckForError(VSSDBG_XML, L"IXMLDOMNode::get_nodeType");
// skip node if not an element
if (dnt == NODE_ELEMENT)
{
CComBSTR bstrName = NULL;
ft.hr = pNode->get_nodeName(&bstrName);
ft.CheckForError(VSSDBG_XML, L"IXMLDOMNode::get_nodeName");
// update counters based on element type
if(wcscmp(bstrName, x_wszElementDatabaseFiles) == 0)
pInfo->cDatabases += 1;
else if (wcscmp(bstrName, x_wszElementDatabaseLogfiles) == 0)
pInfo->cLogFiles += 1;
else if (wcscmp(bstrName, x_wszElementFilelist) == 0)
pInfo->cFileCount += 1;
else if (wcscmp(bstrName, x_wszElementDependency) == 0)
pInfo->cDependencies += 1;
}
} while (doc.Next(FALSE, FALSE));
}
// set output parameter
*ppInfo = pInfo;
}
VSS_STANDARD_CATCH(ft);
// free structure if there is any failure
if (FAILED(ft.hr) && pInfo != NULL)
FreeComponentInfo(pInfo);
return ft.hr;
}
// free up component info structure
// implements IVssWMComponent::FreeComponentInfo
// frees information returned by IVssWMComponent::GetComponentInfo
//
// Returns:
// S_OK if the operation is successful
STDMETHODIMP CVssWMComponent::FreeComponentInfo(PVSSCOMPONENTINFO pInfoC)
{
CVssFunctionTracer ft(VSSDBG_XML, L"CVssWMComponent::FreeComponentInfo");
VSS_COMPONENTINFO *pInfo = (VSS_COMPONENTINFO *) pInfoC;
if (pInfo != NULL)
{
try
{
if (pInfo->bstrLogicalPath)
{
SysFreeString(pInfo->bstrLogicalPath);
pInfo->bstrLogicalPath = NULL;
}
if (pInfo->bstrComponentName)
{
SysFreeString(pInfo->bstrComponentName);
pInfo->bstrComponentName = NULL;
}
if (pInfo->bstrCaption)
{
SysFreeString(pInfo->bstrCaption);
pInfo->bstrCaption = NULL;
}
if (pInfo->pbIcon)
{
CoTaskMemFree(pInfo->pbIcon);
pInfo->pbIcon = NULL;
}
CoTaskMemFree(pInfo);
}
VSS_STANDARD_CATCH(ft)
}
return ft.hr;
}
// obtain a FILE_LIST element
// implements IVssWMComponent::GetFile
// caller must call IVssWMFiledesc::Release on the output parameter.
//
// Returns:
// S_OK if the operation is successful
// E_INVALIDARG if ppFiledesc is NULL.
// VSS_E_OBJECT_NOT_FOUND if specified log file is not found
// E_OUTOFMEMORY if an allocation failure occurs
STDMETHODIMP CVssWMComponent::GetFile
(
IN UINT iFile, // selected file in file group
OUT IVssWMFiledesc **ppFiledesc // output file descriptor
)
{
CVssFunctionTracer ft
(
VSSDBG_XML,
L"CVssWMComponent::GetFile"
);
return GetComponentFile(ft, x_wszElementFilelist, iFile, ppFiledesc);
}
// obtain a DATABASE_FILES element
// implements IVssWMComponent::GetDatabaseFile
// caller must call IVssWMFiledesc::Release on the output parameter.
//
// Returns:
// S_OK if the operation is successful
// E_INVALIDARG if ppFiledesc is NULL.
// VSS_E_OBJECT_NOT_FOUND if specified log file is not found
// E_OUTOFMEMORY if an allocation failure occurs
STDMETHODIMP CVssWMComponent::GetDatabaseFile
(
IN UINT iDBFile, // selected DATABASE_FILE element in DATABASE
OUT IVssWMFiledesc **ppFiledesc // output file descriptor
)
{
CVssFunctionTracer ft
(
VSSDBG_XML,
L"CVssWMComponent::GetDatabaseFile"
);
return GetComponentFile(ft, x_wszElementDatabaseFiles, iDBFile, ppFiledesc);
}
// obtain a DATABASE_LOGFILES element
// implements IVssWMComponent::GetDatabaseLogFile
// caller must call IVssWMFiledesc::Release on the output parameter.
//
// Returns:
// S_OK if the operation is successful
// E_INVALIDARG if ppFiledesc is NULL.
// VSS_E_OBJECT_NOT_FOUND if specified log file is not found
// E_OUTOFMEMORY if an allocation failure occurs
STDMETHODIMP CVssWMComponent::GetDatabaseLogFile
(
IN UINT iDbLogFile, // selected DATABASE_LOG_FILE element in DATABASE
OUT IVssWMFiledesc **ppFiledesc // output file descriptor
)
{
CVssFunctionTracer ft
(
VSSDBG_XML,
L"CVssWMComponent::GetDatabaseLogFile"
);
return GetComponentFile(ft, x_wszElementDatabaseLogfiles, iDbLogFile, ppFiledesc);
}
STDMETHODIMP CVssWMComponent::GetDependency
(
IN UINT iDependency,
OUT IVssWMDependency **ppDependency
)
{
CVssFunctionTracer ft(VSSDBG_XML, L"CVssWMComponent::GetDependency");
CVssWMDependency* pDependency = NULL;
try
{
// --- find first child element
m_doc.ResetToDocument();
if (!m_doc.FindElement(x_wszElementDependency, true))
{
ft.Throw
(
VSSDBG_XML,
VSS_E_OBJECT_NOT_FOUND,
L"Cannot find %s element", x_wszElementDependency
);
}
// skip to selected element
for(UINT i = 0; i < iDependency; i++)
{
if (!m_doc.FindElement(x_wszElementDependency, false))
ft.Throw
(
VSSDBG_XML,
VSS_E_OBJECT_NOT_FOUND,
L"Cannot find element %s.",
x_wszElementDependency
);
}
CComPtr<IXMLDOMNode> pNode = m_doc.GetCurrentNode();
// create CVssWMDependency from selected element
pDependency = new CVssWMDependency((IXMLDOMNode *) pNode);
// check for allocation failure
if (pDependency == NULL)
ft.Throw
(
VSSDBG_XML,
E_OUTOFMEMORY,
L"Cannot create CVssWMDependency due to allocation failure."
);
// 2nd phase of construction
pDependency->Initialize(ft);
// transfer pointer
*ppDependency= pDependency;
// set reference count to 1
pDependency->AddRef();
pDependency = NULL;
}
VSS_STANDARD_CATCH(ft)
// only deletes the pointer in an error case
delete pDependency;
return ft.hr;
}
// obtain a DATABASE_FILES, DATABASE_LOGFILES or FILE_LIST element
// internal function used by GetDatabaseFile, GetDatabaseLogFile, and GetFile
// Note that this fuction caches pointers into the writer document. So, if the document
// that this object is viewing changes for whatever reason, this instance of CVssWMComponent
// has been invalidated.
HRESULT CVssWMComponent::GetComponentFile
(
IN CVssFunctionTracer &ft,
IN LPCWSTR wszElementName, // element to retrieve DATABASE_FILE, DATABASE_LOG_FILE, or FILE_LIST
IN UINT iFile, // which element to retrieve
OUT IVssWMFiledesc **ppFiledesc // output file descriptor
)
{
CVssWMFiledesc *pFiledesc = NULL;
try
{
// validate output parameter
if (ppFiledesc == NULL)
ft.Throw(VSSDBG_XML, E_INVALIDARG, L"NULL output parameter.");
BS_ASSERT(wszElementName);
// initialize output parameter
*ppFiledesc = NULL;
CVssSafeAutomaticLock lock(m_csDOM);
// if we don't have a cached pointer to this element, reset the cache.
// also, reset the cache if we're accessing before the cache... MSXML
// implement a singly-linked list, so we don't want to be traveling
// backwards.
if (!m_lastElementName.IsValid() ||
wcscmp(wszElementName, m_lastElementName) != 0 ||
iFile < m_iLastFile)
{
m_lastElementName.CopyFrom(wszElementName);
m_iLastFile = 0;
// --- find first child element
m_doc.ResetToDocument();
if (!m_doc.FindElement(wszElementName, true))
ft.Throw
(
VSSDBG_XML,
VSS_E_OBJECT_NOT_FOUND,
L"Cannot find %s element",
wszElementName
);
}
// skip to selected element
for(UINT i = 0; i < iFile - m_iLastFile; i++)
{
if (!m_doc.FindElement(wszElementName, false))
ft.Throw
(
VSSDBG_XML,
VSS_E_OBJECT_NOT_FOUND,
L"Cannot find element %s.",
wszElementName
);
}
m_iLastFile = iFile; // cache the index of this file
// get selected element
CComPtr<IXMLDOMNode> pNode = m_doc.GetCurrentNode();
// create CVssWMFiledesc from selected element
pFiledesc = new CVssWMFiledesc((IXMLDOMNode *) pNode);
// check for allocation failure
if (pFiledesc == NULL)
ft.Throw
(
VSSDBG_XML,
E_OUTOFMEMORY,
L"Cannot create CVssWMFiledesc due to allocation failure."
);
// 2nd phase of construction
pFiledesc->Initialize(ft);
// transfer pointer
*ppFiledesc = (IVssWMFiledesc *) pFiledesc;
// set reference count to 1
((IVssWMFiledesc *) pFiledesc)->AddRef();
pFiledesc = NULL;
}
VSS_STANDARD_CATCH(ft)
// invalidate the cache if an error occurs
if (ft.HrFailed())
{
if (m_lastElementName.IsValid())
m_lastElementName.Close();
}
delete pFiledesc;
return ft.hr;
}
// IUnknown::QueryInterface
STDMETHODIMP CVssWMComponent::QueryInterface(REFIID, void **)
{
return E_NOTIMPL;
}
// IUnknown::AddRef
STDMETHODIMP_(ULONG) CVssWMComponent::AddRef()
{
LONG cRef = InterlockedIncrement(&m_cRef);
return (ULONG) cRef;
}
// IUnknown::Release
STDMETHODIMP_(ULONG) CVssWMComponent::Release()
{
LONG cRef = InterlockedDecrement(&m_cRef);
BS_ASSERT(cRef >= 0);
if (cRef == 0)
{
// reference count is 0, delete the object
delete this;
return 0;
}
else
return cRef;
}
// obtain path attribute
// implements IVssWMFiledesc::GetPath
// caller is responsible for calling SysFreeString on the output parameter
//
// Returns:
// S_OK if the operation is successful
// E_INVALIDARG if pbstrPath is NULL
// E_OUTOFMEMORY if an allocation failure occurs
STDMETHODIMP CVssWMFiledesc::GetPath(OUT BSTR *pbstrPath)
{
CVssFunctionTracer ft
(
VSSDBG_XML,
L"CVssWMFiledesc::GetPath"
);
return GetStringAttributeValue(ft, x_wszAttrPath, false, pbstrPath);
}
// obtain filespec attribute
// implements IVssWMFiledesc::GetFilespec
// caller is responsible for calling SysFreeString on the output parameter
//
// Returns:
// S_OK if the operation is successful
// E_INVALIDARG if pbstrFilespec is NULL
// VSS_E_CORRUPT_XML_DOCUMENT if the XML document is invalid.
// E_OUTOFMEMORY if an allocation failure occurs
STDMETHODIMP CVssWMFiledesc::GetFilespec(OUT BSTR *pbstrFilespec)
{
CVssFunctionTracer ft
(
VSSDBG_XML,
L"CVssWMFiledesc::GetFilespec"
);
return GetStringAttributeValue(ft, x_wszAttrFilespec, true, pbstrFilespec);
}
// obtain recursive attribute
// implements IVssWMFiledesc::GetRecursive
//
// Returns:
// S_OK if the operation is successful
// E_INVALIDARG if pbRecursive is NULL
// VSS_E_CORRUPT_XML_DOCUMENT if the XML document is invalid
// E_OUTOFMEMORY if an allocation failure occurs
STDMETHODIMP CVssWMFiledesc::GetRecursive(OUT bool *pbRecursive)
{
CVssFunctionTracer ft
(
VSSDBG_XML,
L"CVssWMFiledesc::GetRecursive"
);
return GetBooleanAttributeValue(ft, x_wszAttrRecursive, false, pbRecursive);
}
// obtain alternatePath attribute
// implements IVssWMFiledesc::GetAlternateLocation
// caller is responsible for calling SysFreeString on the output parameter
//
// Returns:
// S_OK if the operation is successful
// E_INVALIDARG if pbstrAlternateLocation is NULL
// E_OUTOFMEMORY if an allocation failure occurs
STDMETHODIMP CVssWMFiledesc::GetAlternateLocation(OUT BSTR *pbstrAlternateLocation)
{
CVssFunctionTracer ft
(
VSSDBG_XML,
L"CVssWMFiledesc::GetAlternateLocation"
);
return GetStringAttributeValue(ft, x_wszAttrAlternatePath, false, pbstrAlternateLocation);
}
STDMETHODIMP CVssWMFiledesc::GetBackupTypeMask(OUT DWORD *pdwTypeMask)
{
CVssFunctionTracer ft(VSSDBG_XML, L"CVssWMFiledesc::GetBackupTypeMask");
try
{
if (pdwTypeMask == NULL)
ft.Throw(VSSDBG_XML, E_INVALIDARG, L"NULL out parameter");
get_dwordValue(ft, x_wszAttrFilespecBackupType, pdwTypeMask);
}
VSS_STANDARD_CATCH(ft)
return ft.hr;
}
// IUnknown::QueryInterface
STDMETHODIMP CVssWMFiledesc::QueryInterface(REFIID, void **)
{
return E_NOTIMPL;
}
// IUnknown::AddRef
STDMETHODIMP_(ULONG) CVssWMFiledesc::AddRef()
{
LONG cRef = InterlockedIncrement(&m_cRef);
return (ULONG) cRef;
}
// IUnknown::Release
STDMETHODIMP_(ULONG) CVssWMFiledesc::Release()
{
LONG cRef = InterlockedDecrement(&m_cRef);
BS_ASSERT(cRef >= 0);
if (cRef == 0)
{
// reference count is 0, delete the object
delete this;
return 0;
}
else
return (ULONG) cRef;
}
STDMETHODIMP CVssWMDependency::GetWriterId(OUT VSS_ID *pWriterId)
{
CVssFunctionTracer ft(VSSDBG_XML, L"CVssWMFiledesc::GetWriterId");
return GetVSS_IDAttributeValue(ft, x_wszAttrOnWriterId, true, pWriterId);
}
STDMETHODIMP CVssWMDependency::GetLogicalPath (OUT BSTR *pbstrLogicalPath)
{
CVssFunctionTracer ft(VSSDBG_XML, L"CVssWMFiledesc::GetLogicalPath");
return GetStringAttributeValue(ft, x_wszAttrOnLogicalPath, false, pbstrLogicalPath);
}
STDMETHODIMP CVssWMDependency::GetComponentName (OUT BSTR *pbstrComponentName)
{
CVssFunctionTracer ft(VSSDBG_XML, L"CVssWMFiledesc::GetComponentName");
return GetStringAttributeValue(ft, x_wszAttrOnComponentName, true, pbstrComponentName);
}
STDMETHODIMP CVssWMDependency::QueryInterface(REFIID riid, void **pvObj)
{
UNREFERENCED_PARAMETER(riid);
UNREFERENCED_PARAMETER(pvObj);
return E_NOTIMPL;
}
STDMETHODIMP_(ULONG) CVssWMDependency::AddRef()
{
LONG cRef = InterlockedIncrement(&m_cRef);
return (ULONG) cRef;
}
STDMETHODIMP_(ULONG) CVssWMDependency::Release()
{
LONG cRef = InterlockedDecrement(&m_cRef);
BS_ASSERT(cRef >= 0);
if (cRef == 0)
{
// reference count is 0, delete the object
delete this;
return 0;
}
else
return (ULONG) cRef;
}
// initialize the document by creating a toplevel WRITER_METADATA and
// child IDENTIFICATION element
// implemetns IVssCreateWriterMetadata::Initialize
//
// Returns:
// S_OK if the operation is successful
// E_INVALIDARG if usage or source are invalid or if wszFriendlyName is NULL.
// E_OUTOFMEMORY if an allocation failure occurs
HRESULT CVssCreateWriterMetadata::Initialize
(
IN VSS_ID idInstance, // GUID of instance
IN VSS_ID idWriter, // GUID of writer class
IN LPCWSTR wszFriendlyName, // friendly name of writer
IN VSS_USAGE_TYPE usage, // usage attribute
IN VSS_SOURCE_TYPE source // source attribute
)
{
CVssFunctionTracer ft
(
VSSDBG_XML,
L"CVssCreateWriterMetadata::Initialize"
);
try
{
LPCWSTR wszUsage;
LPCWSTR wszSource;
// validate input argument
if (wszFriendlyName == NULL)
ft.Throw(VSSDBG_XML, E_INVALIDARG, L"NULL string input parameter");
wszUsage = WszFromUsageType(ft, usage);
wszSource = WszFromSourceType(ft, source);
CXMLDocument doc;
InitializeHelper(ft);
CVssSafeAutomaticLock lock(m_csDOM);
m_doc.Initialize();
CXMLNode nodeDoc(m_doc.GetInterface(), m_doc.GetInterface());
// create toplevel WRITER_METADATA node
CXMLNode nodeTop = m_doc.CreateNode
(
x_wszElementWriterMetadata,
NODE_ELEMENT
);
// setup schema attribute
nodeTop.SetAttribute(x_wszAttrXmlns, x_wszValueXmlns);
// setup version attribute
nodeTop.SetAttribute(x_wszAttrVersion, x_wszVersionNo);
// create IDENTIFICATION node
CXMLNode nodeId = m_doc.CreateNode
(
x_wszElementIdentification,
NODE_ELEMENT
);
// set writerId attribute
nodeId.SetAttribute(x_wszAttrWriterId, idWriter);
// set instanceId attribue
nodeId.SetAttribute(x_wszAttrInstanceId, idInstance);
// set friendlyName attribute
nodeId.SetAttribute(x_wszAttrFriendlyName, wszFriendlyName);
// set usage attribute
nodeId.SetAttribute(x_wszAttrUsage, wszUsage);
// set dataSource attribute
nodeId.SetAttribute(x_wszAttrDataSource, wszSource);
// insert identification node in toplevel node
nodeTop.InsertNode(nodeId);
// insert toplevel node in document and set it as
// the toplevel node for navigation purposes
CXMLNode nodeToplevel = nodeDoc.InsertNode(nodeTop);
m_doc.SetToplevelNode(nodeToplevel);
}
VSS_STANDARD_CATCH(ft)
return ft.hr;
}
// add an INCLUDE_FILES element
// implements IVssCreateWriterMetadata::AddIncludeFiles
//
// Returns:
// S_OK if the operation is successful
// E_INVALIDARG if wszPath or wszFilespec is NULL.
// E_OUTOFMEMORY if an allocation failure occurs
STDMETHODIMP CVssCreateWriterMetadata::AddIncludeFiles
(
IN LPCWSTR wszPath, // path to root directory
IN LPCWSTR wszFilespec, // file specification
IN bool bRecursive, // is entire subtree or just directory included
IN LPCWSTR wszAlternateLocation // alternate location
)
{
CVssFunctionTracer ft
(
VSSDBG_XML,
L"CVssCreateWriterMetadata::AddIncludeFiles"
);
try
{
// validate input parameters
if (wszPath == NULL || wszFilespec == NULL)
ft.Throw(VSSDBG_XML, E_INVALIDARG, L"NULL required input parameter.");
CVssSafeAutomaticLock lock(m_csDOM);
// create/obtain BACKUP_LOCATIONS element
CXMLNode nodeBackupLocations = GetBackupLocationsNode();
// create child INCLUDE_FILES element
CXMLNode nodeInclude = m_doc.CreateNode
(
x_wszElementIncludeFiles,
NODE_ELEMENT
);
// set path attribute
nodeInclude.SetAttribute(x_wszAttrPath, wszPath);
// set filespec attribute
nodeInclude.SetAttribute(x_wszAttrFilespec, wszFilespec);
// set recursive attribute
nodeInclude.SetAttribute
(
x_wszAttrRecursive,
WszFromBoolean(bRecursive)
);
// set alternatePath attribute if specified
if (wszAlternateLocation)
nodeInclude.SetAttribute(x_wszAttrAlternatePath, wszAlternateLocation);
// insert INCLUDE_FILES node in BACKUP_LOCATIONS node
nodeBackupLocations.InsertNode(nodeInclude);
}
VSS_STANDARD_CATCH(ft)
return ft.hr;
}
// add an EXCLUDE_FILES element
// implements IVssCreateWriterMetadata::AddExcludeFiles
//
// Returns:
// S_OK if the operation is successful
// E_INVALIDARG if wszPath or wszFilespec is NULL.
// E_OUTOFMEMORY if an allocation failure occurs
STDMETHODIMP CVssCreateWriterMetadata::AddExcludeFiles
(
IN LPCWSTR wszPath,
IN LPCWSTR wszFilespec,
IN bool bRecursive
)
{
CVssFunctionTracer ft
(
VSSDBG_XML,
L"CVssCreateWriterMetadata::AddExcludeFiles"
);
try
{
// validate input parameters
if (wszPath == NULL || wszFilespec == NULL)
ft.Throw(VSSDBG_XML, E_INVALIDARG, L"NULL required input parameter.");
CVssSafeAutomaticLock lock(m_csDOM);
// create/obtain the BACKUP_LOCATIONS eleement
CXMLNode nodeBackupLocations = GetBackupLocationsNode();
// add an EXCLUDE_FILES element
CXMLNode nodeExclude = m_doc.CreateNode
(
x_wszElementExcludeFiles,
NODE_ELEMENT
);
// set path attribute
nodeExclude.SetAttribute(x_wszAttrPath, wszPath);
// set filespec attribute
nodeExclude.SetAttribute(x_wszAttrFilespec, wszFilespec);
// set recursive attribute
nodeExclude.SetAttribute
(
x_wszAttrRecursive,
WszFromBoolean(bRecursive)
);
// insert EXCLUDE_FILES node in BACKUP_LOCATIONS node
nodeBackupLocations.InsertNode(nodeExclude);
}
VSS_STANDARD_CATCH(ft)
return ft.hr;
}
// internal routine to find or create the BACKUP_LOCATIONS element
// caller should have helper DOM locked
CXMLNode CVssCreateWriterMetadata::GetBackupLocationsNode()
{
// reposition to top of document
m_doc.ResetToDocument();
CXMLNode nodeTop(m_doc.GetCurrentNode(), NULL);
// find BACKUP_LOCATIONS element. If it exists return it
if (m_doc.FindElement(x_wszElementBackupLocations, TRUE))
return CXMLNode(m_doc.GetCurrentNode(), m_doc.GetInterface());
// create BACKUP_LOCATIONS element under WRITER_METADATA element
CXMLNode node = m_doc.CreateNode
(
x_wszElementBackupLocations,
NODE_ELEMENT
);
return nodeTop.InsertNode(node);
}
// create a component
// implements IVssCreateWriterMetadata::AddComponent
//
// Returns:
// S_OK if the operation is successful
// E_INVALIDARG if wszComponentName is NULL or the specified component type is invalid.
// VSS_E_CORRUPTXMLDOCUMENT if the XML document is cortup.
// E_OUTOFMEMORY if an allocation failure occurs
STDMETHODIMP CVssCreateWriterMetadata::AddComponent
(
IN VSS_COMPONENT_TYPE ct, // either VSS_CT_DATABASE or VSS_CT_FILEGROUP
IN LPCWSTR wszLogicalPath, // logical path to component
IN LPCWSTR wszComponentName, // component name
IN LPCWSTR wszCaption, // description of component
IN const BYTE * pbIcon, // icon
IN UINT cbIcon, // size of icon
IN bool bRestoreMetadata, // is restore metadata supplied
IN bool bNotifyOnBackupComplete, // does writer expect to be notified on BackupComplete
IN bool bSelectable, // is component selectable for backup
IN bool bSelectableForRestore, // is component selectable for restore
IN DWORD dwComponentFlags
)
{
CVssFunctionTracer ft
(
VSSDBG_XML,
L"CVssCreateWriterMetadata::AddComponent"
);
try
{
// validate required input parameter
if (wszComponentName == NULL)
ft.Throw(VSSDBG_XML, E_INVALIDARG, L"NULL required input parameter.");
// determine element name from the component type
LPCWSTR wszElement;
wszElement = WszFromComponentType(ft, ct, false);
CVssSafeAutomaticLock lock(m_csDOM);
// obtain BACKUP_LOCATIONS node, creating it if necessary.
CXMLNode nodeBackupLocations = GetBackupLocationsNode();
CXMLDocument doc(nodeBackupLocations);
// find element type (either DATABASE or FILE_GROUP)
if (doc.FindElement(wszElement, TRUE))
{
do
{
CComBSTR bstrLogicalPath;
CComBSTR bstrComponentName;
// extract logicalPath attribute
bool bLogicalPath = doc.FindAttribute(x_wszAttrLogicalPath, &bstrLogicalPath);
// extract componentName attribute
if (!doc.FindAttribute(x_wszAttrComponentName, &bstrComponentName))
MissingAttribute(ft, x_wszAttrComponentName);
// if duplicate comonent is found then throw an error
if (wcscmp(wszComponentName, bstrComponentName) == 0 &&
((bLogicalPath &&
wszLogicalPath &&
wcscmp(wszLogicalPath, bstrLogicalPath) == 0) ||
(!bstrLogicalPath &&
(wszLogicalPath == NULL || wcslen(wszLogicalPath) == 0))))
ft.Throw
(
VSSDBG_XML,
VSS_E_OBJECT_ALREADY_EXISTS,
L"Component %s already exists",
wszComponentName
);
} while(doc.FindElement(wszElement, FALSE));
}
// create component node
CXMLNode node = m_doc.CreateNode
(
wszElement,
NODE_ELEMENT
);
// set logicalPath attribute if exists
if (wszLogicalPath)
node.SetAttribute(x_wszAttrLogicalPath, wszLogicalPath);
// set componetName attribute
node.SetAttribute(x_wszAttrComponentName, wszComponentName);
// set caption element if it exists
if (wszCaption)
node.SetAttribute(x_wszAttrCaption, wszCaption);
// set icon attribute if it exists
if (pbIcon != NULL && cbIcon > 0)
node.SetAttribute(x_wszAttrIcon, pbIcon, cbIcon);
// set restoreMetadata flags
node.SetAttribute
(
x_wszAttrRestoreMetadata,
WszFromBoolean(bRestoreMetadata)
);
// set notifyOnBackupComplete flag
node.SetAttribute
(
x_wszAttrNotifyOnBackupComplete,
WszFromBoolean(bNotifyOnBackupComplete)
);
// set selectable attribute
node.SetAttribute
(
x_wszAttrSelectable,
WszFromBoolean(bSelectable)
);
// set selectableForRestore attribute
node.SetAttribute
(
x_wszAttrSelectableForRestore,
WszFromBoolean(bSelectableForRestore)
);
// set component flags
node.SetAttribute
(
x_wszAttrCompFlags,
dwComponentFlags
);
// insert component node under BACKUP_LOCATIONS node
nodeBackupLocations.InsertNode(node);
}
VSS_STANDARD_CATCH(ft)
return ft.hr;
}
// create DATABASE_FILES element
// implements IVssCreateWriterMetadata::AddDatabaseFile
//
// Returns:
// S_OK if the operation is successful
// E_INVALIDARG if wszDatabaseName, wszPath, or wszFilespec is NULL.
// VSS_E_OBJECT_NOT_FOUND if the specified component doesn't exist
// VSS_E_CORRUPTXMLDOCUMENT if the XML document is cortup.
// E_OUTOFMEMORY if an allocation failure occurs
STDMETHODIMP CVssCreateWriterMetadata::AddDatabaseFiles
(
IN LPCWSTR wszLogicalPath, // logical path name of component
IN LPCWSTR wszDatabaseName, // add database name
IN LPCWSTR wszPath, // add path name
IN LPCWSTR wszFilespec, // add file specification
IN DWORD dwBackupTypeMask // how backup should be performed on this filespec
)
{
CVssFunctionTracer ft
(
VSSDBG_XML,
L"CVssCreateWriterMetadata::AddDatabaseFiles"
);
// call internal routine to do the work
return CreateComponentFiles
(
ft,
x_wszElementDatabase,
wszLogicalPath,
wszDatabaseName,
x_wszElementDatabaseFiles,
wszPath,
wszFilespec,
false,
NULL,
dwBackupTypeMask
);
}
// create a DATABASE_FILES, DATABASE_LOGFILES or FILE_LIST element under
// a component
// internal routine used by AddDatabaseFiles, AddFiles, and AddDatabaseLogFiles
HRESULT CVssCreateWriterMetadata::CreateComponentFiles
(
IN CVssFunctionTracer &ft,
IN LPCWSTR wszElement, // element name (DATABASE or FILE_GROUP)
IN LPCWSTR wszLogicalPath, // logical path of component
IN LPCWSTR wszComponentName, // component name
IN LPCWSTR wszElementFile, // element name (DATABASE_FILES, DATABASE_LOGFILES, FILELIST)
IN LPCWSTR wszPath, // path to root directory containing files
IN LPCWSTR wszFilespec, // file specification
IN bool bRecursive, // include subtree or just root directory
IN LPCWSTR wszAlternateLocation, // alternate location for files
IN DWORD dwBackupTypeMask // how backup should be performed on this filespec
)
{
try
{
// validate input parameters
if (wszElement == NULL ||
wszComponentName == NULL ||
wszPath == NULL ||
wszElementFile == NULL ||
wszFilespec == NULL)
ft.Throw(VSSDBG_XML, E_INVALIDARG, L"NULL required input parameter.");
// validate element consistency
if ((wcscmp(wszElement, x_wszElementDatabase) == 0 &&
wcscmp(wszElementFile, x_wszElementDatabaseFiles) != 0 &&
wcscmp(wszElementFile, x_wszElementDatabaseLogfiles) != 0) ||
(wcscmp(wszElement, x_wszElementFilegroup) == 0 &&
wcscmp(wszElementFile, x_wszElementFilelist) != 0))
ft.Throw(VSSDBG_XML, E_INVALIDARG, L"Invalid element type");
CVssSafeAutomaticLock lock(m_csDOM);
// reposition to top of document
m_doc.ResetToDocument();
// find BACKUP_LOCATIONS element
if (!m_doc.FindElement(x_wszElementBackupLocations, TRUE))
ft.Throw
(
VSSDBG_XML,
VSS_E_OBJECT_NOT_FOUND,
L"BackupLocations element is missing"
);
// find first component of the right type
if (!m_doc.FindElement(wszElement, TRUE))
ft.Throw
(
VSSDBG_XML,
VSS_E_OBJECT_NOT_FOUND,
L"Component %s::%s was not created",
wszElement,
wszComponentName
);
// look for matching component
bool bFound = false;
do
{
CComBSTR bstrLogicalPath;
CComBSTR bstrComponentName;
// extract logical path
bool fLogicalPath = m_doc.FindAttribute(x_wszAttrLogicalPath, &bstrLogicalPath);
// extract component name
if (!m_doc.FindAttribute(x_wszAttrComponentName, &bstrComponentName))
MissingAttribute(ft, x_wszAttrComponentName);
// compare logical path if it exists
if (wszLogicalPath != NULL && fLogicalPath)
{
// compare logical path
if (wcscmp(wszLogicalPath, bstrLogicalPath) != 0)
continue;
}
else if (wszLogicalPath == NULL &&
fLogicalPath &&
wcslen(bstrLogicalPath) > 0)
// logical path in document but component we are searching
// for has no logical path, skip this one
continue;
else if (wszLogicalPath != NULL && wcslen(wszLogicalPath) > 0)
// logical path we are searching for is specified but
// there is no logical path in the document
continue;
// if component name matches then we found target component,
// otherwise move to next component
if (wcscmp(bstrComponentName, wszComponentName) == 0)
{
bFound = true;
break;
}
} while(m_doc.FindElement(wszElement, FALSE));
// return error if component is not found
if (!bFound)
ft.Throw
(
VSSDBG_XML,
VSS_E_OBJECT_NOT_FOUND,
L"Component %s::%s was not created",
wszElement,
wszComponentName
);
// use component node as parent node
CXMLNode nodeComponent(m_doc.GetCurrentNode(), m_doc.GetInterface());
// create child node of the component
CXMLNode node = m_doc.CreateNode
(
wszElementFile,
NODE_ELEMENT
);
// set path attribute
node.SetAttribute(x_wszAttrPath, wszPath);
// set filespec attribute
node.SetAttribute(x_wszAttrFilespec, wszFilespec);
// set recursive attribute if it is Yes
if (bRecursive)
node.SetAttribute
(
x_wszAttrRecursive,
WszFromBoolean(bRecursive)
);
if (wszAlternateLocation)
node.SetAttribute(x_wszAttrAlternatePath, wszAlternateLocation);
// set the backup type mask
node.SetAttribute(x_wszAttrFilespecBackupType, dwBackupTypeMask);
// insert file element under component node
nodeComponent.InsertNode(node);
}
VSS_STANDARD_CATCH(ft)
return ft.hr;
}
// add a log file specification to a database component
// implements IVssCreateWriterMetadata::AddDatabaseLogFiles
//
// Returns:
// S_OK if the operation is successful
// E_INVALIDARG if wszDatabaseName is NULL, wszPath is NULL, or wszFilespec is NULL.
// VSS_E_OBJECT_NOT_FOUND if the specified component doesn't exist
// VSS_E_CORRUPTXMLDOCUMENT if the XML document is cortup.
// E_OUTOFMEMORY if an allocation failure occurs
STDMETHODIMP CVssCreateWriterMetadata::AddDatabaseLogFiles
(
IN LPCWSTR wszLogicalPath, // logical path of database
IN LPCWSTR wszDatabaseName, // database name
IN LPCWSTR wszPath, // path to directory containing log files
IN LPCWSTR wszFilespec, // file specification of log files
IN DWORD dwBackupTypeMask // how backup should be performed on this filespec
)
{
CVssFunctionTracer ft
(
VSSDBG_XML,
L"CVssCreateWriterMetadata::AddDatabaseLogFiles"
);
// call internal routine to do the work
return CreateComponentFiles
(
ft,
x_wszElementDatabase,
wszLogicalPath,
wszDatabaseName,
x_wszElementDatabaseLogfiles,
wszPath,
wszFilespec,
false,
NULL,
dwBackupTypeMask
);
}
// add files to a file group
// implements IVssCreateWriterMetadata::AddFilesToFileGroup
//
// Returns:
// S_OK if the operation is successful
// E_INVALIDARG if wszGroupName is NULL, wszPath is NULL, wszFilespec is NULL.
// VSS_E_OBJECT_NOT_FOUND if the specified component doesn't exist
// VSS_E_CORRUPTXMLDOCUMENT if the XML document is cortup.
// E_OUTOFMEMORY if an allocation failure occurs
STDMETHODIMP CVssCreateWriterMetadata::AddFilesToFileGroup
(
IN LPCWSTR wszLogicalPath, // logical path of file group
IN LPCWSTR wszGroupName, // group name
IN LPCWSTR wszPath, // path to root directory containing the files
IN LPCWSTR wszFilespec, // file specification of the files included in the file group
IN bool bRecursive, // are files in the subtree included or just in the directory
IN LPCWSTR wszAlternateLocation, // alternate location for files in the file group
IN DWORD dwBackupTypeMask // how backup should be performed on this filespec
)
{
CVssFunctionTracer ft
(
VSSDBG_XML,
L"CVssCreateWriterMetadata::AddFilesToFileGroup"
);
// call internal routine to do the work
return CreateComponentFiles
(
ft,
x_wszElementFilegroup,
wszLogicalPath,
wszGroupName,
x_wszElementFilelist,
wszPath,
wszFilespec,
bRecursive,
wszAlternateLocation,
dwBackupTypeMask
);
}
// create restore method
// implements IVssCreateWriterMetadata::SetRestoreMethod
//
// Returns:
// S_OK if the operation is successful
// E_INVALIDARG if method is invalid, writerRestore is invalid,
// E_OUTOFMEMORY if an allocation failure occurs
STDMETHODIMP CVssCreateWriterMetadata::SetRestoreMethod
(
IN VSS_RESTOREMETHOD_ENUM method, // method
IN LPCWSTR wszService, // service name, if method is VSS_RME_STOP_RESTORE_RESTART
IN LPCWSTR wszUserProcedure, // uri/url of manual instructions for user to follow to do the restore
IN VSS_WRITERRESTORE_ENUM writerRestore, // is writer involved in the restore process
IN bool bRebootRequired
)
{
CVssFunctionTracer ft
(
VSSDBG_XML,
L"CVssCreateWriterMetadata::SetRestoreMethod"
);
try
{
// convert VSS_RESTORMETHOD_ENUM to string
// validate it as well
LPCWSTR wszMethod = WszFromRestoreMethod(ft, method);
// convert VSS_WRITERRESTORE_ENUM to string
// validate it as well
LPCWSTR wszWriterRestore = WszFromWriterRestore(ft, writerRestore);
CVssSafeAutomaticLock lock(m_csDOM);
// reposition to top of document
m_doc.ResetToDocument();
// set parent node as WRITER_METADATA node
CXMLNode nodeTop(m_doc.GetCurrentNode(), m_doc.GetInterface());
// if RESTORE_METHOD element exists, then use that one
CXMLNode node;
bool bAlreadyExists = m_doc.FindElement(x_wszElementRestoreMethod, TRUE);
if (bAlreadyExists)
node = CXMLNode(m_doc.GetCurrentNode(), m_doc.GetInterface());
else
node = m_doc.CreateNode
(
x_wszElementRestoreMethod,
NODE_ELEMENT
);
// set method attribute
node.SetAttribute(x_wszAttrMethod, wszMethod);
// set service attribute if supplied
if (wszService)
node.SetAttribute(x_wszAttrService, wszService);
// set userProcedure attribute if supplied
if (wszUserProcedure)
node.SetAttribute(x_wszAttrUserProcedure, wszUserProcedure);
// set writerRestore attribute
node.SetAttribute(x_wszAttrWriterRestore, wszWriterRestore);
// set rebootRequired attribute
node.SetAttribute(x_wszAttrRebootRequired, WszFromBoolean(bRebootRequired));
// insert RESTORE_METHOD node under toplevel node
if (!bAlreadyExists)
nodeTop.InsertNode(node);
}
VSS_STANDARD_CATCH(ft)
return ft.hr;
}
// add alternate location mapping
// implements IVssCreateWriterMetadata::AddAlternateLocationMapping
//
// Returns:
// S_OK if the operation is successful
// E_INVALIDARG if wszSourcePath, wszSourceFiledesc, or wszDestination is NULL.
// E_OUTOFMEMORY if an allocation failure occurs
STDMETHODIMP CVssCreateWriterMetadata::AddAlternateLocationMapping
(
IN LPCWSTR wszSourcePath, // path to source root directory
IN LPCWSTR wszSourceFilespec, // file specification
IN bool bRecursive, // are files in the subtree relocated or just files in the directory
IN LPCWSTR wszDestination // new location of root directory
)
{
CVssFunctionTracer ft
(
VSSDBG_XML,
L"CVssCreateWriterMetadata::AddAlternateLocationMapping"
);
try
{
// validate input parameters
if (wszSourcePath == NULL ||
wszSourceFilespec == NULL ||
wszDestination == NULL)
ft.Throw(VSSDBG_XML, E_INVALIDARG, L"NULL required input parameter.");
CVssSafeAutomaticLock lock(m_csDOM);
// reposition to top of document
m_doc.ResetToDocument();
// find RESTORE_METHOD element
if (!m_doc.FindElement(x_wszElementRestoreMethod, TRUE))
ft.Throw
(
VSSDBG_XML,
VSS_E_OBJECT_NOT_FOUND,
L"RESTORE_METHOD element is not defined."
);
// set parent node as RESTORE_METHOD element
CXMLNode nodeRM(m_doc.GetCurrentNode(), m_doc.GetInterface());
// create ALTERNATE_LOCATION_MAPPING element to
// RESTORE_METHOD element
CXMLNode node = m_doc.CreateNode
(
x_wszElementAlternateMapping,
NODE_ELEMENT
);
// set path attribute
node.SetAttribute(x_wszAttrPath, wszSourcePath);
// add filespec attributte
node.SetAttribute(x_wszAttrFilespec, wszSourceFilespec);
// set alternatePath attribute
node.SetAttribute(x_wszAttrAlternatePath, wszDestination);
// set recursive attribute
node.SetAttribute(x_wszAttrRecursive, WszFromBoolean(bRecursive));
// insert ALTERNATE_LOCATION_MAPPING node under RESTORE_METHOD node
nodeRM.InsertNode(node);
}
VSS_STANDARD_CATCH(ft)
return ft.hr;
}
// add a dependency to another writer's component
STDMETHODIMP CVssCreateWriterMetadata::AddComponentDependency
(
IN LPCWSTR wszForLogicalPath,
IN LPCWSTR wszForComponentName,
IN VSS_ID onWriterId,
IN LPCWSTR wszOnLogicalPath,
IN LPCWSTR wszOnComponentName
)
{
CVssFunctionTracer ft(VSSDBG_XML, L"CVssCreateWriterMetadata::AddComponentDependency");
const long cComponents = 2;
LPCWSTR ComponentNames[2] = {x_wszElementDatabase,
x_wszElementFilegroup };
try
{
if (wszForComponentName == NULL ||
onWriterId == GUID_NULL ||
wszOnComponentName == NULL)
{
ft.Throw(VSSDBG_XML, E_INVALIDARG, L"NULL required input parameter.");
}
CVssSafeAutomaticLock lock(m_csDOM);
m_doc.ResetToDocument();
// find BACKUP_LOCATIONS element
if (!m_doc.FindElement(x_wszElementBackupLocations, TRUE))
ft.Throw
(
VSSDBG_XML,
VSS_E_OBJECT_NOT_FOUND,
L"BackupLocations element is missing"
);
// find first component of the right type
if (!m_doc.FindElementOneOf(ComponentNames, cComponents, TRUE))
ft.Throw
(
VSSDBG_XML,
VSS_E_OBJECT_NOT_FOUND,
L"Document contains no components"
);
// look for matching component
bool bFound = false;
do
{
CComBSTR bstrLogicalPath;
CComBSTR bstrComponentName;
// extract logical path
bool fLogicalPath = m_doc.FindAttribute(x_wszAttrLogicalPath, &bstrLogicalPath);
// extract component name
if (!m_doc.FindAttribute(x_wszAttrComponentName, &bstrComponentName))
MissingAttribute(ft, x_wszAttrComponentName);
// compare logical path if it exists
if (wszForLogicalPath != NULL && fLogicalPath)
{
// compare logical path
if (wcscmp(wszForLogicalPath, bstrLogicalPath) != 0)
continue;
}
else if (wszForLogicalPath == NULL &&
fLogicalPath &&
wcslen(bstrLogicalPath) > 0)
// logical path in document but component we are searching
// for has no logical path, skip this one
continue;
else if (wszForLogicalPath != NULL && wcslen(wszForLogicalPath) > 0)
// logical path we are searching for is specified but
// there is no logical path in the document
continue;
// if component name matches then we found target component,
// otherwise move to next component
if (wcscmp(bstrComponentName, wszForComponentName) == 0)
{
bFound = true;
break;
}
} while(m_doc.FindElementOneOf(ComponentNames, cComponents, FALSE));
// return error if component is not found
if (!bFound)
ft.Throw
(
VSSDBG_XML,
VSS_E_OBJECT_NOT_FOUND,
L"Component %s\\%s was not found",
wszForLogicalPath,
wszForComponentName
);
// use component node as parent node
CXMLNode nodeComponent(m_doc.GetCurrentNode(), m_doc.GetInterface());
// create child node of the component
CXMLNode node = m_doc.CreateNode
(
x_wszElementDependency,
NODE_ELEMENT
);
// set the id of the target writer
node.SetAttribute(x_wszAttrOnWriterId, onWriterId);
// set the logical path of the target component
if (wszOnLogicalPath != NULL)
node.SetAttribute(x_wszAttrOnLogicalPath, wszOnLogicalPath);
// set the name of the target component
node.SetAttribute(x_wszAttrOnComponentName, wszOnComponentName);
// insert file element under component node
nodeComponent.InsertNode(node);
}
VSS_STANDARD_CATCH(ft)
return ft.hr;
}
STDMETHODIMP CVssCreateWriterMetadata::SetBackupSchema
(
IN DWORD dwSchemaMask
)
{
CVssFunctionTracer ft(VSSDBG_XML, L"CVssCreateWriterMetadata::SetBackupSchema");
try
{
CVssSafeAutomaticLock lock(m_csDOM);
// reposition to top of document
m_doc.ResetToDocument();
CXMLNode node (m_doc.GetCurrentNode(), m_doc.GetInterface());
// set the schema attribute
node.SetAttribute(x_wszAttrBackupSchema, dwSchemaMask);
}
VSS_STANDARD_CATCH(ft)
return ft.hr;
}
// obtain the XML document itself
// implements IVssCreateWriterMetadata::GetDocument
//
// Returns:
// S_OK if the operation is successful
// E_INVALIDARG if ppDoc is NULL
// E_OUTOFMEMORY if an allocation failure occurs
STDMETHODIMP CVssCreateWriterMetadata::GetDocument(IXMLDOMDocument **ppDoc)
{
CVssFunctionTracer ft(VSSDBG_XML, L"CVssCreateWriterMetadata::GetDocument");
try
{
// validate output parameter
if (ppDoc == NULL)
ft.Throw(VSSDBG_XML, E_INVALIDARG, L"NULL output parameter.");
// get IXMLDOMDocument interface
*ppDoc = m_doc.GetInterface();
// increment reference count on interface
m_doc.GetInterface()->AddRef();
}
VSS_STANDARD_CATCH(ft)
return ft.hr;
}
// save WRITER_METADATA document as XML string
// implements IVssCreateWriterMetadata::SaveAsXML
//
// Returns:
// S_OK if the operation is successful
// E_INVALIDARG if pbstrXML is NULL.
// E_OUTOFMEMORY if an allocation failure occurs
STDMETHODIMP CVssCreateWriterMetadata::SaveAsXML(BSTR *pbstrXML)
{
CVssFunctionTracer ft
(
VSSDBG_XML,
L"CVssCreateWriterMetadata::SaveAsXML"
);
try
{
// validate output parameter
if (pbstrXML == NULL)
ft.Throw(VSSDBG_XML, E_INVALIDARG, L"NULL output parameter");
// initialize output paramter
*pbstrXML = NULL;
CVssSafeAutomaticLock lock(m_csDOM);
// construct string from document
*pbstrXML = m_doc.SaveAsXML();
}
VSS_STANDARD_CATCH(ft);
return ft.hr;
}
| 28.534451 | 103 | 0.663013 | [
"object"
] |
a357c7bf8e6e27a9dbf40cdf44f52b644fc1143b | 8,348 | cpp | C++ | src/utilities/idf/Test/WorkspaceObjectWatcher_GTest.cpp | muehleisen/OpenStudio | 3bfe89f6c441d1e61e50b8e94e92e7218b4555a0 | [
"blessing"
] | 3 | 2020-09-05T18:13:23.000Z | 2022-01-15T14:47:57.000Z | src/utilities/idf/Test/WorkspaceObjectWatcher_GTest.cpp | muehleisen/OpenStudio | 3bfe89f6c441d1e61e50b8e94e92e7218b4555a0 | [
"blessing"
] | 4 | 2016-06-27T21:25:59.000Z | 2020-04-28T14:00:21.000Z | src/utilities/idf/Test/WorkspaceObjectWatcher_GTest.cpp | jmarrec/OpenStudio | 5276feff0d8dbd6c8ef4e87eed626bc270a19b14 | [
"blessing"
] | 1 | 2021-06-05T18:16:02.000Z | 2021-06-05T18:16:02.000Z | /***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2021, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
*
* (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products
* derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works
* may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior
* written permission from Alliance for Sustainable Energy, LLC.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED
* STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***********************************************************************************************************************/
#include <gtest/gtest.h>
#include "IdfFixture.hpp"
#include "../WorkspaceObjectWatcher.hpp"
#include "../Workspace.hpp"
#include "../WorkspaceObject.hpp"
#include "../IdfExtensibleGroup.hpp"
#include <utilities/idd/Lights_FieldEnums.hxx>
#include <utilities/idd/IddEnums.hxx>
#include <resources.hxx>
using namespace std;
using namespace boost;
using namespace openstudio;
TEST_F(IdfFixture, WorkspaceObjectWatcher_CommentChanges) {
IdfObject object(IddObjectType::Lights);
Workspace workspace(StrictnessLevel::Draft, IddFileType::EnergyPlus);
OptionalWorkspaceObject owo = workspace.addObject(object);
ASSERT_TRUE(owo);
WorkspaceObject lights = *owo;
WorkspaceObjectWatcher watcher(lights);
EXPECT_FALSE(watcher.dirty());
lights.setComment("Change from default to this");
EXPECT_TRUE(watcher.dirty());
EXPECT_FALSE(watcher.dataChanged());
EXPECT_FALSE(watcher.relationshipChanged());
watcher.clearState();
EXPECT_FALSE(watcher.dirty());
EXPECT_FALSE(watcher.dataChanged());
EXPECT_FALSE(watcher.relationshipChanged());
lights.setFieldComment(1, "Change from default to that");
EXPECT_TRUE(watcher.dirty());
EXPECT_FALSE(watcher.dataChanged());
EXPECT_FALSE(watcher.relationshipChanged());
watcher.clearState();
EXPECT_FALSE(watcher.dirty());
EXPECT_FALSE(watcher.dataChanged());
EXPECT_FALSE(watcher.relationshipChanged());
lights.setFieldComment(1000, "Way out of bounds");
EXPECT_FALSE(watcher.dirty());
}
TEST_F(IdfFixture, WorkspaceObjectWatcher_DataFieldChanges) {
IdfObject object(IddObjectType::Lights);
Workspace workspace(StrictnessLevel::Draft, IddFileType::EnergyPlus);
OptionalWorkspaceObject owo = workspace.addObject(object);
ASSERT_TRUE(owo);
WorkspaceObject lights = *owo;
WorkspaceObjectWatcher watcher(lights);
EXPECT_FALSE(watcher.dirty());
EXPECT_TRUE(lights.setName("Lights"));
EXPECT_TRUE(watcher.dirty());
EXPECT_FALSE(watcher.dataChanged());
EXPECT_TRUE(watcher.nameChanged());
EXPECT_FALSE(watcher.relationshipChanged());
watcher.clearState();
EXPECT_TRUE(lights.createName(true));
EXPECT_TRUE(watcher.dirty());
EXPECT_FALSE(watcher.dataChanged());
EXPECT_TRUE(watcher.nameChanged());
EXPECT_FALSE(watcher.relationshipChanged());
watcher.clearState();
ASSERT_TRUE(lights.setString(4, "22.3"));
EXPECT_TRUE(watcher.dirty());
EXPECT_TRUE(watcher.dataChanged());
EXPECT_FALSE(watcher.nameChanged());
EXPECT_FALSE(watcher.relationshipChanged());
watcher.clearState();
EXPECT_FALSE(watcher.dirty());
EXPECT_FALSE(watcher.dataChanged());
EXPECT_FALSE(watcher.nameChanged());
EXPECT_FALSE(watcher.relationshipChanged());
EXPECT_FALSE(lights.setString(1000, "22.3"));
EXPECT_FALSE(watcher.dirty());
EXPECT_FALSE(watcher.dataChanged());
EXPECT_FALSE(watcher.nameChanged());
EXPECT_FALSE(watcher.relationshipChanged());
}
TEST_F(IdfFixture, WorkspaceObjectWatcher_RelationshipFieldChanges) {
IdfObject object(IddObjectType::DaylightingDevice_Tubular);
Workspace workspace(StrictnessLevel::Draft, IddFileType::EnergyPlus);
OptionalWorkspaceObject owo = workspace.addObject(object);
ASSERT_TRUE(owo);
WorkspaceObject tdd = *owo;
WorkspaceObjectWatcher watcher(tdd);
EXPECT_FALSE(watcher.dirty());
// add zone objects
object = IdfObject(IddObjectType::Zone);
owo = workspace.addObject(object);
ASSERT_TRUE(owo);
EXPECT_EQ("Zone 1", owo->name().get());
owo = workspace.addObject(object);
ASSERT_TRUE(owo);
EXPECT_EQ("Zone 2", owo->name().get());
owo = workspace.addObject(object);
ASSERT_TRUE(owo);
EXPECT_EQ("Zone 3", owo->name().get());
EXPECT_FALSE(watcher.dirty());
vector<string> vals;
vals.push_back("Zone 1");
vals.push_back("1.0");
IdfExtensibleGroup eg = tdd.pushExtensibleGroup(vals);
ASSERT_FALSE(eg.empty());
EXPECT_TRUE(watcher.dirty());
EXPECT_TRUE(watcher.dataChanged());
EXPECT_FALSE(watcher.nameChanged());
EXPECT_TRUE(watcher.relationshipChanged());
watcher.clearState();
EXPECT_FALSE(watcher.dirty());
EXPECT_FALSE(watcher.dataChanged());
EXPECT_FALSE(watcher.nameChanged());
EXPECT_FALSE(watcher.relationshipChanged());
EXPECT_TRUE(eg.setString(0, "Zone 2"));
EXPECT_TRUE(watcher.dirty());
EXPECT_FALSE(watcher.dataChanged());
EXPECT_FALSE(watcher.nameChanged());
EXPECT_TRUE(watcher.relationshipChanged());
watcher.clearState();
EXPECT_FALSE(watcher.dirty());
EXPECT_FALSE(watcher.dataChanged());
EXPECT_FALSE(watcher.nameChanged());
EXPECT_FALSE(watcher.relationshipChanged());
EXPECT_TRUE(eg.setDouble(1, 2.0));
EXPECT_TRUE(watcher.dirty());
EXPECT_TRUE(watcher.dataChanged());
EXPECT_FALSE(watcher.nameChanged());
EXPECT_FALSE(watcher.relationshipChanged());
watcher.clearState();
EXPECT_FALSE(watcher.dirty());
EXPECT_FALSE(watcher.dataChanged());
EXPECT_FALSE(watcher.nameChanged());
EXPECT_FALSE(watcher.relationshipChanged());
}
TEST_F(IdfFixture, WorkspaceObjectWatcher_RelationshipFieldChanges_TargetDeleted) {
IdfObject object(IddObjectType::Lights);
Workspace workspace(StrictnessLevel::Draft, IddFileType::EnergyPlus);
OptionalWorkspaceObject owo = workspace.addObject(object);
ASSERT_TRUE(owo);
WorkspaceObject workspaceObject = *owo;
WorkspaceObjectWatcher watcher(workspaceObject);
EXPECT_FALSE(watcher.dirty());
OptionalWorkspaceObject oZone = workspace.addObject(IdfObject(IddObjectType::Zone));
ASSERT_TRUE(oZone);
EXPECT_TRUE(workspaceObject.setPointer(LightsFields::ZoneorZoneListName, oZone->handle()));
EXPECT_TRUE(watcher.dirty());
EXPECT_FALSE(watcher.dataChanged());
EXPECT_FALSE(watcher.nameChanged());
EXPECT_TRUE(watcher.relationshipChanged());
watcher.clearState();
EXPECT_FALSE(watcher.dirty());
EXPECT_FALSE(watcher.dataChanged());
EXPECT_FALSE(watcher.nameChanged());
EXPECT_FALSE(watcher.relationshipChanged());
oZone->remove();
EXPECT_TRUE(watcher.dirty());
EXPECT_FALSE(watcher.dataChanged());
EXPECT_FALSE(watcher.nameChanged());
EXPECT_TRUE(watcher.relationshipChanged());
}
| 39.563981 | 125 | 0.746766 | [
"object",
"vector"
] |
a35a19b4f71c16e5352e6b219d142ed8b4738677 | 10,780 | cpp | C++ | storage/src/vespa/storage/distributor/persistencemessagetracker.cpp | bowlofstew/vespa | 5212c7a5568769eadb5c5d99b6a503a70c82af48 | [
"Apache-2.0"
] | null | null | null | storage/src/vespa/storage/distributor/persistencemessagetracker.cpp | bowlofstew/vespa | 5212c7a5568769eadb5c5d99b6a503a70c82af48 | [
"Apache-2.0"
] | 1 | 2021-01-21T01:37:37.000Z | 2021-01-21T01:37:37.000Z | storage/src/vespa/storage/distributor/persistencemessagetracker.cpp | bowlofstew/vespa | 5212c7a5568769eadb5c5d99b6a503a70c82af48 | [
"Apache-2.0"
] | null | null | null | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "persistencemessagetracker.h"
#include <vespa/storage/common/vectorprinter.h>
#include <vespa/storage/common/bucketoperationlogger.h>
#include <vespa/storageapi/message/persistence.h>
#include <vespa/log/log.h>
LOG_SETUP(".persistencemessagetracker");
namespace storage::distributor {
PersistenceMessageTrackerImpl::PersistenceMessageTrackerImpl(
PersistenceOperationMetricSet& metric,
std::shared_ptr<api::BucketInfoReply> reply,
DistributorComponent& link,
api::Timestamp revertTimestamp)
: MessageTracker(link.getClusterName()),
_metric(metric),
_reply(reply),
_manager(link),
_revertTimestamp(revertTimestamp),
_requestTimer(link.getClock()),
_priority(reply->getPriority()),
_success(true)
{
}
PersistenceMessageTrackerImpl::~PersistenceMessageTrackerImpl() {}
void
PersistenceMessageTrackerImpl::updateDB()
{
for (BucketInfoMap::iterator iter = _bucketInfo.begin();
iter != _bucketInfo.end();
iter++)
{
_manager.updateBucketDatabase(iter->first, iter->second);
}
for (BucketInfoMap::iterator iter = _remapBucketInfo.begin();
iter != _remapBucketInfo.end();
iter++)
{
_manager.updateBucketDatabase(iter->first, iter->second,
DatabaseUpdate::CREATE_IF_NONEXISTING);
}
}
void
PersistenceMessageTrackerImpl::updateMetrics()
{
const api::ReturnCode& result(_reply->getResult());
_metric.updateFromResult(result);
_metric.latency.addValue(_requestTimer.getElapsedTimeAsDouble());
}
void
PersistenceMessageTrackerImpl::fail(MessageSender& sender, const api::ReturnCode& result) {
if (_reply.get()) {
_reply->setResult(result);
updateMetrics();
sender.sendReply(_reply);
_reply.reset();
}
}
uint16_t
PersistenceMessageTrackerImpl::receiveReply(
MessageSender& sender,
api::BucketInfoReply& reply)
{
uint16_t node = handleReply(reply);
if (node != (uint16_t)-1) {
updateFromReply(sender, reply, node);
}
return node;
}
void
PersistenceMessageTrackerImpl::revert(
MessageSender& sender,
const std::vector<std::pair<document::BucketId, uint16_t> > revertNodes)
{
if (_revertTimestamp != 0) {
// Since we're reverting, all received bucket info is voided.
_bucketInfo.clear();
std::vector<api::Timestamp> reverts;
reverts.push_back(_revertTimestamp);
for (uint32_t i = 0; i < revertNodes.size(); i++) {
std::shared_ptr<api::RevertCommand> toRevert(
new api::RevertCommand(revertNodes[i].first, reverts));
toRevert->setPriority(_priority);
queueCommand(toRevert, revertNodes[i].second);
}
flushQueue(sender);
}
}
void
PersistenceMessageTrackerImpl::queueMessageBatch(const std::vector<MessageTracker::ToSend>& messages) {
_messageBatches.push_back(MessageBatch());
for (uint32_t i = 0; i < messages.size(); i++) {
if (_reply.get()) {
messages[i]._msg->getTrace().setLevel(_reply->getTrace().getLevel());
}
_messageBatches.back().push_back(messages[i]._msg->getMsgId());
queueCommand(messages[i]._msg, messages[i]._target);
}
}
bool
PersistenceMessageTrackerImpl::canSendReplyEarly() const
{
if (!_reply.get() || !_reply->getResult().success()) {
LOG(spam, "Can't return early because we have already replied or failed");
return false;
}
const lib::Distribution& distribution = _manager.getDistribution();
if (distribution.getInitialRedundancy() == 0) {
LOG(spam, "Not returning early because initial redundancy wasn't set");
return false;
}
for (uint32_t i = 0; i < _messageBatches.size(); i++) {
uint32_t messagesDone = 0;
for (uint32_t j = 0; j < _messageBatches[i].size(); j++) {
if (_sentMessages.find(_messageBatches[i][j]) == _sentMessages.end()) {
messagesDone++;
} else if (distribution.ensurePrimaryPersisted() && j == 0) {
// Primary must always be written.
LOG(debug, "Not returning early because primary node wasn't done");
return false;
}
}
if (messagesDone < distribution.getInitialRedundancy()) {
LOG(spam, "Not returning early because only %d messages out of %d are done",
messagesDone, distribution.getInitialRedundancy());
return false;
}
}
return true;
}
void
PersistenceMessageTrackerImpl::checkCopiesDeleted()
{
if (!_reply.get()) {
return;
}
// Don't check the buckets that have been remapped here, as we will
// create them.
for (BucketInfoMap::const_iterator iter = _bucketInfo.begin();
iter != _bucketInfo.end();
iter++)
{
BucketDatabase::Entry dbentry =
_manager.getBucketDatabase().get(iter->first);
if (!dbentry.valid()) {
continue;
}
std::vector<uint16_t> missing;
std::vector<uint16_t> total;
for (uint32_t i = 0; i < iter->second.size(); ++i) {
if (dbentry->getNode(iter->second[i].getNode()) == NULL) {
missing.push_back(iter->second[i].getNode());
}
total.push_back(iter->second[i].getNode());
}
if (!missing.empty()) {
std::ostringstream msg;
msg << iter->first << " was deleted from nodes ["
<< commaSeparated(missing)
<< "] after message was sent but before it was done. Sent to ["
<< commaSeparated(total)
<< "]";
LOG(debug, "%s", msg.str().c_str());
_reply->setResult(api::ReturnCode(api::ReturnCode::BUCKET_DELETED,
msg.str()));
break;
}
}
}
void
PersistenceMessageTrackerImpl::addBucketInfoFromReply(
uint16_t node,
const api::BucketInfoReply& reply)
{
const document::BucketId& bucket(reply.getBucketId());
const api::BucketInfo& bucketInfo(reply.getBucketInfo());
if (reply.hasBeenRemapped()) {
LOG(debug, "Bucket %s: Received remapped bucket info %s from node %d",
bucket.toString().c_str(),
bucketInfo.toString().c_str(),
node);
_remapBucketInfo[bucket].push_back(
BucketCopy(_manager.getUniqueTimestamp(),
node,
bucketInfo));
} else {
LOG(debug, "Bucket %s: Received bucket info %s from node %d",
bucket.toString().c_str(),
bucketInfo.toString().c_str(),
node);
_bucketInfo[bucket].push_back(
BucketCopy(_manager.getUniqueTimestamp(),
node,
bucketInfo));
}
}
void
PersistenceMessageTrackerImpl::logSuccessfulReply(uint16_t node,
const api::BucketInfoReply& reply) const
{
LOG(spam, "Bucket %s: Received successful reply %s",
reply.getBucketId().toString().c_str(),
reply.toString().c_str());
if (!reply.getBucketInfo().valid()) {
LOG(error,
"Reply %s from node %d contained invalid bucket "
"information %s. This is a bug! Please report "
"this to the Vespa team",
reply.toString().c_str(),
node,
reply.getBucketInfo().toString().c_str());
}
}
bool
PersistenceMessageTrackerImpl::shouldRevert() const
{
return _manager.getDistributorConfig().enableRevert
&& _revertNodes.size() && !_success && _reply.get();
}
void
PersistenceMessageTrackerImpl::sendReply(MessageSender& sender)
{
updateMetrics();
_trace.setStrict(false);
_reply->getTrace().getRoot().addChild(_trace);
sender.sendReply(_reply);
_reply = std::shared_ptr<api::BucketInfoReply>();
}
void
PersistenceMessageTrackerImpl::updateFailureResult(const api::BucketInfoReply& reply)
{
LOG(debug, "Bucket %s: Received failed reply %s with result %s",
reply.getBucketId().toString().c_str(),
reply.toString().c_str(),
reply.getResult().toString().c_str());
if (reply.getResult().getResult() >
_reply->getResult().getResult())
{
_reply->setResult(reply.getResult());
}
_success = false;
}
void
PersistenceMessageTrackerImpl::handleCreateBucketReply(
api::BucketInfoReply& reply,
uint16_t node)
{
LOG(spam, "Received CreateBucket reply for %s from node %u",
reply.getBucketId().toString().c_str(), node);
if (!reply.getResult().success()
&& reply.getResult().getResult() != api::ReturnCode::EXISTS)
{
LOG(spam, "Create bucket reply failed, so deleting it from bucket db");
_manager.removeNodeFromDB(reply.getBucketId(), node);
LOG_BUCKET_OPERATION_NO_LOCK(
reply.getBucketId(),
vespalib::make_string(
"Deleted bucket on node %u due to failing create bucket %s",
node, reply.getResult().toString().c_str()));
}
}
void
PersistenceMessageTrackerImpl::handlePersistenceReply(
api::BucketInfoReply& reply,
uint16_t node)
{
if (reply.getBucketInfo().valid()) {
addBucketInfoFromReply(node, reply);
}
if (reply.getResult().success()) {
logSuccessfulReply(node, reply);
_revertNodes.push_back(std::pair<document::BucketId, uint16_t>(
reply.getBucketId(), node));
} else if (!hasSentReply()) {
updateFailureResult(reply);
}
}
void
PersistenceMessageTrackerImpl::updateFromReply(
MessageSender& sender,
api::BucketInfoReply& reply,
uint16_t node)
{
_trace.addChild(reply.getTrace().getRoot());
if (reply.getType() == api::MessageType::CREATEBUCKET_REPLY) {
handleCreateBucketReply(reply, node);
} else {
handlePersistenceReply(reply, node);
}
if (finished()) {
bool doRevert(shouldRevert());
checkCopiesDeleted();
updateDB();
if (!hasSentReply()) {
sendReply(sender);
}
if (doRevert) {
revert(sender, _revertNodes);
}
} else if (canSendReplyEarly()) {
LOG(debug, "Sending reply early because initial redundancy has been reached");
checkCopiesDeleted();
sendReply(sender);
}
}
}
| 30.196078 | 118 | 0.607885 | [
"vector"
] |
a35c5cb734bd5fd13f3dea81e2ee3aa81bdfbe43 | 2,317 | cpp | C++ | limbo2/submissions/accepted/answer_jacob.cpp | csecutsc/utscode2 | 469367528cc5697e0c5c0ccee28420591335d899 | [
"Unlicense"
] | 4 | 2018-09-30T15:06:49.000Z | 2020-12-09T06:50:25.000Z | limbo2/submissions/accepted/answer_jacob.cpp | csecutsc/utscode2 | 469367528cc5697e0c5c0ccee28420591335d899 | [
"Unlicense"
] | null | null | null | limbo2/submissions/accepted/answer_jacob.cpp | csecutsc/utscode2 | 469367528cc5697e0c5c0ccee28420591335d899 | [
"Unlicense"
] | 1 | 2021-06-17T04:10:51.000Z | 2021-06-17T04:10:51.000Z | #define DEBUG 0
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <vector>
using namespace std;
#define LL long long
#define LD long double
#define PR pair<int, int>
#define Fox(i, n) for (i = 0; i < n; i++)
#define Fox1(i, n) for (i = 1; i <= n; i++)
#define FoxI(i, a, b) for (i = a; i <= b; i++)
#define FoxR(i, n) for (i = (n)-1; i >= 0; i--)
#define FoxR1(i, n) for (i = n; i > 0; i--)
#define FoxRI(i, a, b) for (i = b; i >= a; i--)
#define Foxen(i, s) for (i = s.begin(); i != s.end(); i++)
#define Min(a, b) a = min(a, b)
#define Max(a, b) a = max(a, b)
#define Sz(s) int((s).size())
#define All(s) (s).begin(), (s).end()
#define Fill(s, v) memset(s, v, sizeof(s))
#define pb push_back
#define mp make_pair
#define x first
#define y second
template <typename T>
T Abs(T x) {
return (x < 0 ? -x : x);
}
template <typename T>
T Sqr(T x) {
return (x * x);
}
string plural(string s) {
return (Sz(s) && s[Sz(s) - 1] == 'x' ? s + "en" : s + "s");
}
const int INF = (int)1e9;
const LD EPS = 1e-12;
const LD PI = acos(-1.0);
#if DEBUG
#define GETCHAR getchar
#else
#define GETCHAR getchar_unlocked
#endif
bool Read(int &x) {
char c, r = 0, n = 0;
x = 0;
for (;;) {
c = GETCHAR();
if ((c < 0) && (!r)) return (0);
if ((c == '-') && (!r))
n = 1;
else if ((c >= '0') && (c <= '9'))
x = x * 10 + c - '0', r = 1;
else if (r)
break;
}
if (n) x = -x;
return (1);
}
int main() {
if (DEBUG) freopen("in.txt", "r", stdin);
int T;
LL R, C, W, H, v;
bool d;
Read(T);
while (T--) {
scanf("%lld%lld", &R, &C);
if ((!R) && (!C)) {
printf("0\n");
continue;
}
W = H = 1;
d = 0;
while ((R >= H) || (C >= W)) {
if (!d)
W *= 2;
else
H *= 2;
d = !d;
}
v = W * H / 2;
if (d) {
W /= 2;
C -= W;
v += C * H + R;
} else {
H /= 2;
R -= H;
v += R * W + C;
}
printf("%lld\n", v);
}
return (0);
}
| 18.991803 | 61 | 0.497195 | [
"vector"
] |
a35efeee44ce8916f10199b13c7bb455e41067c1 | 16,144 | cc | C++ | content/browser/renderer_host/websocket_blob_sender_unittest.cc | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | 1 | 2020-09-15T08:43:34.000Z | 2020-09-15T08:43:34.000Z | content/browser/renderer_host/websocket_blob_sender_unittest.cc | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | null | null | null | content/browser/renderer_host/websocket_blob_sender_unittest.cc | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/renderer_host/websocket_blob_sender.h"
#include <string.h>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/callback.h"
#include "base/files/file.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/location.h"
#include "base/memory/ptr_util.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/task_runner.h"
#include "base/time/time.h"
#include "content/browser/blob_storage/chrome_blob_storage_context.h"
#include "content/public/browser/blob_handle.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/test/test_browser_context.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "net/base/completion_callback.h"
#include "net/base/net_errors.h"
#include "net/base/test_completion_callback.h"
#include "storage/common/fileapi/file_system_types.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
namespace content {
namespace {
const char kDummyUrl[] = "http://www.example.com/";
const char kBanana[] = "banana";
// This is small so that the tests do not waste too much time just copying bytes
// around. But it has to be larger than kMinimumNonFinalFrameSize defined in
// websocket_blob_sender.cc.
const size_t kInitialQuota = 16 * 1024;
using net::TestCompletionCallback;
// A fake channel for testing. Records the contents of the message that was sent
// through it. Quota is restricted, and is refreshed asynchronously in response
// to calls to SendFrame().
class FakeChannel : public WebSocketBlobSender::Channel {
public:
// |notify_new_quota| will be run asynchronously on the current MessageLoop
// every time GetSendQuota() increases.
FakeChannel() : weak_factory_(this) {}
// This method must be called before SendFrame() is.
void set_notify_new_quota(const base::Closure& notify_new_quota) {
notify_new_quota_ = notify_new_quota;
}
size_t GetSendQuota() const override { return current_send_quota_; }
ChannelState SendFrame(bool fin, const std::vector<char>& data) override {
++frames_sent_;
EXPECT_FALSE(got_fin_);
if (fin)
got_fin_ = true;
EXPECT_LE(data.size(), current_send_quota_);
message_.insert(message_.end(), data.begin(), data.end());
current_send_quota_ -= data.size();
base::MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(&FakeChannel::RefreshQuota, weak_factory_.GetWeakPtr()));
return net::WebSocketEventInterface::CHANNEL_ALIVE;
}
bool got_fin() const { return got_fin_; }
int frames_sent() const { return frames_sent_; }
const std::vector<char>& message() const { return message_; }
private:
void RefreshQuota() {
if (current_send_quota_ == kInitialQuota)
return;
current_send_quota_ = kInitialQuota;
DCHECK(!notify_new_quota_.is_null());
notify_new_quota_.Run();
}
base::Closure notify_new_quota_;
size_t current_send_quota_ = kInitialQuota;
int frames_sent_ = 0;
bool got_fin_ = false;
std::vector<char> message_;
base::WeakPtrFactory<FakeChannel> weak_factory_;
};
class WebSocketBlobSenderTest : public ::testing::Test {
protected:
// The Windows implementation of net::FileStream::Context requires a real IO
// MessageLoop.
WebSocketBlobSenderTest()
: threads_(TestBrowserThreadBundle::IO_MAINLOOP),
chrome_blob_storage_context_(
ChromeBlobStorageContext::GetFor(&browser_context_)),
fake_channel_(nullptr),
sender_() {}
~WebSocketBlobSenderTest() override {}
void SetUp() override {
// ChromeBlobStorageContext::GetFor() does some work asynchronously.
base::RunLoop().RunUntilIdle();
SetUpSender();
}
// This method can be overriden to use a different channel implementation.
virtual void SetUpSender() {
fake_channel_ = new FakeChannel;
sender_.reset(new WebSocketBlobSender(base::WrapUnique(fake_channel_)));
fake_channel_->set_notify_new_quota(base::Bind(
&WebSocketBlobSender::OnNewSendQuota, base::Unretained(sender_.get())));
}
storage::BlobStorageContext* context() {
return chrome_blob_storage_context_->context();
}
storage::FileSystemContext* GetFileSystemContext() {
StoragePartition* partition = BrowserContext::GetStoragePartitionForSite(
&browser_context_, GURL(kDummyUrl));
return partition->GetFileSystemContext();
}
// |string| is copied.
std::unique_ptr<BlobHandle> CreateMemoryBackedBlob(const char* string) {
std::unique_ptr<BlobHandle> handle =
chrome_blob_storage_context_->CreateMemoryBackedBlob(string,
strlen(string));
EXPECT_TRUE(handle);
return handle;
}
// Call sender_.Start() with the other parameters filled in appropriately for
// this test fixture.
int Start(const std::string& uuid,
uint64_t expected_size,
const net::CompletionCallback& callback) {
net::WebSocketEventInterface::ChannelState channel_state =
net::WebSocketEventInterface::CHANNEL_ALIVE;
return sender_->Start(
uuid, expected_size, context(), GetFileSystemContext(),
BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE).get(),
&channel_state, callback);
}
void NotCalledCallbackImpl(int rv) {
ADD_FAILURE()
<< "Callback that should not be called was called with argument " << rv;
}
net::CompletionCallback NotCalled() {
return base::Bind(&WebSocketBlobSenderTest::NotCalledCallbackImpl,
base::Unretained(this));
}
void ExpectOkAndQuit(base::RunLoop* run_loop, int result) {
EXPECT_EQ(net::OK, result);
run_loop->Quit();
}
net::CompletionCallback ExpectOkAndQuitCallback(base::RunLoop* run_loop) {
return base::Bind(&WebSocketBlobSenderTest::ExpectOkAndQuit,
base::Unretained(this), run_loop);
}
TestBrowserThreadBundle threads_;
TestBrowserContext browser_context_;
scoped_refptr<ChromeBlobStorageContext> chrome_blob_storage_context_;
// |fake_channel_| is owned by |sender_|.
FakeChannel* fake_channel_;
std::unique_ptr<WebSocketBlobSender> sender_;
};
TEST_F(WebSocketBlobSenderTest, Construction) {}
TEST_F(WebSocketBlobSenderTest, EmptyBlob) {
std::unique_ptr<BlobHandle> handle = CreateMemoryBackedBlob("");
// The APIs allow for this to be asynchronous but that is unlikely in
// practice.
int result = Start(handle->GetUUID(), UINT64_C(0), NotCalled());
// If this fails with result == -1, someone has changed the code to be
// asynchronous and this test should be adapted to match.
EXPECT_EQ(net::OK, result);
EXPECT_TRUE(fake_channel_->got_fin());
EXPECT_EQ(0U, fake_channel_->message().size());
}
TEST_F(WebSocketBlobSenderTest, SmallBlob) {
std::unique_ptr<BlobHandle> handle = CreateMemoryBackedBlob(kBanana);
EXPECT_EQ(net::OK, Start(handle->GetUUID(), UINT64_C(6), NotCalled()));
EXPECT_TRUE(fake_channel_->got_fin());
EXPECT_EQ(1, fake_channel_->frames_sent());
EXPECT_EQ(std::vector<char>(kBanana, kBanana + 6), fake_channel_->message());
}
TEST_F(WebSocketBlobSenderTest, SizeMismatch) {
std::unique_ptr<BlobHandle> handle = CreateMemoryBackedBlob(kBanana);
EXPECT_EQ(net::ERR_UPLOAD_FILE_CHANGED,
Start(handle->GetUUID(), UINT64_C(5), NotCalled()));
EXPECT_EQ(0, fake_channel_->frames_sent());
}
TEST_F(WebSocketBlobSenderTest, InvalidUUID) {
EXPECT_EQ(net::ERR_INVALID_HANDLE,
Start("sandwich", UINT64_C(0), NotCalled()));
}
TEST_F(WebSocketBlobSenderTest, LargeMessage) {
std::string message(kInitialQuota + 10, 'a');
std::unique_ptr<BlobHandle> handle = CreateMemoryBackedBlob(message.c_str());
base::RunLoop run_loop;
int rv = Start(handle->GetUUID(), message.size(),
ExpectOkAndQuitCallback(&run_loop));
EXPECT_EQ(net::ERR_IO_PENDING, rv);
EXPECT_EQ(1, fake_channel_->frames_sent());
run_loop.Run();
EXPECT_EQ(2, fake_channel_->frames_sent());
EXPECT_TRUE(fake_channel_->got_fin());
std::vector<char> expected_message(message.begin(), message.end());
EXPECT_EQ(expected_message, fake_channel_->message());
}
// A message exactly equal to the available quota should be sent in one frame.
TEST_F(WebSocketBlobSenderTest, ExactSizeMessage) {
std::string message(kInitialQuota, 'a');
std::unique_ptr<BlobHandle> handle = CreateMemoryBackedBlob(message.c_str());
EXPECT_EQ(net::OK, Start(handle->GetUUID(), message.size(), NotCalled()));
EXPECT_EQ(1, fake_channel_->frames_sent());
EXPECT_TRUE(fake_channel_->got_fin());
std::vector<char> expected_message(message.begin(), message.end());
EXPECT_EQ(expected_message, fake_channel_->message());
}
// If the connection is closed while sending a message, the WebSocketBlobSender
// object will be destroyed. It needs to handle this case without error.
TEST_F(WebSocketBlobSenderTest, AbortedSend) {
std::string message(kInitialQuota + 10, 'a');
std::unique_ptr<BlobHandle> handle = CreateMemoryBackedBlob(message.c_str());
int rv = Start(handle->GetUUID(), message.size(), NotCalled());
EXPECT_EQ(net::ERR_IO_PENDING, rv);
sender_.reset();
}
// Invalid file-backed blob.
TEST_F(WebSocketBlobSenderTest, InvalidFileBackedBlob) {
base::FilePath path(FILE_PATH_LITERAL(
"WebSocketBlobSentTest.InvalidFileBackedBlob.NonExistentFile"));
std::unique_ptr<BlobHandle> handle =
chrome_blob_storage_context_->CreateFileBackedBlob(path, 0u, 32u,
base::Time::Now());
EXPECT_TRUE(handle);
TestCompletionCallback callback;
int rv =
callback.GetResult(Start(handle->GetUUID(), 5u, callback.callback()));
EXPECT_EQ(net::ERR_FILE_NOT_FOUND, rv);
}
// A test fixture that does the additional work necessary to create working
// file-backed blobs.
class WebSocketFileBackedBlobSenderTest : public WebSocketBlobSenderTest {
protected:
void SetUp() override {
WebSocketBlobSenderTest::SetUp();
// temp_dir_ is recursively deleted on destruction.
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
}
void CreateFile(const std::string& contents,
const base::FilePath& path,
base::File::Info* info) {
ASSERT_EQ(contents.size(), static_cast<size_t>(base::WriteFile(
path, contents.data(), contents.size())));
ASSERT_TRUE(base::GetFileInfo(path, info));
}
std::unique_ptr<BlobHandle> CreateFileBackedBlob(
const std::string& contents) {
base::FilePath path = temp_dir_.path().AppendASCII("blob.dat");
base::File::Info info;
CreateFile(contents, path, &info);
if (HasFatalFailure())
return nullptr;
return chrome_blob_storage_context_->CreateFileBackedBlob(
path, 0u, contents.size(), info.last_modified);
}
base::ScopedTempDir temp_dir_;
};
TEST_F(WebSocketFileBackedBlobSenderTest, EmptyBlob) {
std::unique_ptr<BlobHandle> handle = CreateFileBackedBlob("");
ASSERT_TRUE(handle);
TestCompletionCallback callback;
int result = callback.GetResult(
Start(handle->GetUUID(), UINT64_C(0), callback.callback()));
EXPECT_EQ(net::OK, result);
EXPECT_TRUE(fake_channel_->got_fin());
EXPECT_EQ(0U, fake_channel_->message().size());
}
TEST_F(WebSocketFileBackedBlobSenderTest, SizeMismatch) {
std::unique_ptr<BlobHandle> handle = CreateFileBackedBlob(kBanana);
ASSERT_TRUE(handle);
TestCompletionCallback callback;
int result = Start(handle->GetUUID(), UINT64_C(8), callback.callback());
// This test explicitly aims to test the asynchronous code path, otherwise it
// would be identical to the other SizeMismatch test above.
EXPECT_EQ(net::ERR_IO_PENDING, result);
EXPECT_EQ(net::ERR_UPLOAD_FILE_CHANGED, callback.WaitForResult());
EXPECT_EQ(0, fake_channel_->frames_sent());
}
TEST_F(WebSocketFileBackedBlobSenderTest, LargeMessage) {
std::string message = "the green potato had lunch with the angry cat. ";
while (message.size() <= kInitialQuota) {
message = message + message;
}
std::unique_ptr<BlobHandle> handle = CreateFileBackedBlob(message);
ASSERT_TRUE(handle);
TestCompletionCallback callback;
int result = Start(handle->GetUUID(), message.size(), callback.callback());
EXPECT_EQ(net::OK, callback.GetResult(result));
std::vector<char> expected_message(message.begin(), message.end());
EXPECT_EQ(expected_message, fake_channel_->message());
}
// The WebSocketBlobSender needs to handle a connection close while doing file
// IO cleanly.
TEST_F(WebSocketFileBackedBlobSenderTest, Aborted) {
std::unique_ptr<BlobHandle> handle = CreateFileBackedBlob(kBanana);
int rv = Start(handle->GetUUID(), UINT64_C(6), NotCalled());
EXPECT_EQ(net::ERR_IO_PENDING, rv);
sender_.reset();
}
class DeletingFakeChannel : public WebSocketBlobSender::Channel {
public:
explicit DeletingFakeChannel(
std::unique_ptr<WebSocketBlobSender>* sender_to_delete)
: sender_(sender_to_delete) {}
size_t GetSendQuota() const override { return kInitialQuota; }
ChannelState SendFrame(bool fin, const std::vector<char>& data) override {
sender_->reset();
// |this| is deleted here.
return net::WebSocketEventInterface::CHANNEL_DELETED;
}
private:
std::unique_ptr<WebSocketBlobSender>* sender_;
};
class WebSocketBlobSenderDeletingTest : public WebSocketBlobSenderTest {
protected:
void SetUpSender() override {
sender_.reset(new WebSocketBlobSender(
base::WrapUnique(new DeletingFakeChannel(&sender_))));
}
};
// This test only does something useful when run under AddressSanitizer or a
// similar tool that can detect use-after-free bugs.
TEST_F(WebSocketBlobSenderDeletingTest, SenderDeleted) {
std::unique_ptr<BlobHandle> handle = CreateMemoryBackedBlob(kBanana);
EXPECT_EQ(net::ERR_CONNECTION_RESET,
Start(handle->GetUUID(), UINT64_C(6), NotCalled()));
EXPECT_FALSE(sender_);
}
// SendFrame() calls OnSendNewQuota() synchronously while filling the operating
// system's socket write buffer. The purpose of this Channel implementation is
// to verify that the synchronous case works correctly.
class SynchronousFakeChannel : public WebSocketBlobSender::Channel {
public:
// This method must be called before SendFrame() is.
void set_notify_new_quota(const base::Closure& notify_new_quota) {
notify_new_quota_ = notify_new_quota;
}
size_t GetSendQuota() const override { return kInitialQuota; }
ChannelState SendFrame(bool fin, const std::vector<char>& data) override {
message_.insert(message_.end(), data.begin(), data.end());
notify_new_quota_.Run();
return net::WebSocketEventInterface::CHANNEL_ALIVE;
}
const std::vector<char>& message() const { return message_; }
private:
base::Closure notify_new_quota_;
std::vector<char> message_;
};
class WebSocketBlobSenderSynchronousTest : public WebSocketBlobSenderTest {
protected:
void SetUpSender() override {
synchronous_fake_channel_ = new SynchronousFakeChannel;
sender_.reset(
new WebSocketBlobSender(base::WrapUnique(synchronous_fake_channel_)));
synchronous_fake_channel_->set_notify_new_quota(base::Bind(
&WebSocketBlobSender::OnNewSendQuota, base::Unretained(sender_.get())));
}
SynchronousFakeChannel* synchronous_fake_channel_ = nullptr;
};
TEST_F(WebSocketBlobSenderSynchronousTest, LargeMessage) {
std::string message(kInitialQuota + 10, 'a');
std::unique_ptr<BlobHandle> handle = CreateMemoryBackedBlob(message.c_str());
int rv = Start(handle->GetUUID(), message.size(), NotCalled());
EXPECT_EQ(net::OK, rv);
std::vector<char> expected_message(message.begin(), message.end());
EXPECT_EQ(expected_message, synchronous_fake_channel_->message());
}
} // namespace
} // namespace content
| 35.955457 | 80 | 0.731046 | [
"object",
"vector"
] |
a35f64a6c4b615b2dfe3a53222a1f22bb5132bec | 1,473 | cpp | C++ | 791. Custom Sort String.cpp | yuyangh/LeetCode | 5d81cbd975c0c1f2bbca0cb25cefe361a169e460 | [
"MIT"
] | 1 | 2020-10-11T08:10:53.000Z | 2020-10-11T08:10:53.000Z | 791. Custom Sort String.cpp | yuyangh/LeetCode | 5d81cbd975c0c1f2bbca0cb25cefe361a169e460 | [
"MIT"
] | null | null | null | 791. Custom Sort String.cpp | yuyangh/LeetCode | 5d81cbd975c0c1f2bbca0cb25cefe361a169e460 | [
"MIT"
] | null | null | null | //
// Created by Yuyang Huang on 9/6/21.
//
/*
* 791. Custom Sort String
* Medium
* You are given two strings order and s.
* All the words of order are unique and were sorted in some custom order previously.
* Permute the characters of s so that they match the order that order was sorted.
* More specifically, if a character x occurs before a character y in order,
* then x should occur before y in the permuted string.
*
* Return any permutation of s that satisfies this property.
*
* Example 1:
* Input: order = "cba", s = "abcd"
* Output: "cbad"
* Explanation:
* "a", "b", "c" appear in order, so the order of "a", "b", "c" should be "c", "b", and "a".
* Since "d" does not appear in order, it can be at any position in the returned string.
* "dcba", "cdba", "cbda" are also valid outputs.
*
* Example 2:
* Input: order = "cbafg", s = "abcd"
* Output: "cbad"
*
* Constraints:
* 1 <= order.length <= 26
* 1 <= s.length <= 200
* order and s consist of lowercase English letters.
* All the characters of order are unique.
*/
#include "LeetCodeLib.h"
class Solution {
public:
/*
* Time complexity: O(nlogn)
* Better approach: bucket sort with counting
*/
string customSortString(string order, string s) {
vector<int> dic(26,100);
for(int i=0;i<order.size();i++){
char letter=order[i];
dic[letter-'a']=i;
}
sort(s.begin(),s.end(),[&dic](char lhs, char rhs){
return dic[lhs-'a']<dic[rhs-'a'];
});
return s;
}
}; | 26.781818 | 92 | 0.645621 | [
"vector"
] |
a3615de0c66a3e8e72b822d12c8554a70bb71514 | 2,046 | cpp | C++ | examples/Cxx/ExampleXdmfItem.cpp | scottwedge/xdmf | f41196c966997a20f60525a3d2083490a63626a3 | [
"BSD-3-Clause"
] | 4 | 2015-12-07T08:11:06.000Z | 2020-06-15T01:39:07.000Z | examples/Cxx/ExampleXdmfItem.cpp | scottwedge/xdmf | f41196c966997a20f60525a3d2083490a63626a3 | [
"BSD-3-Clause"
] | 1 | 2020-04-26T16:50:37.000Z | 2020-04-26T16:50:37.000Z | examples/Cxx/ExampleXdmfItem.cpp | scottwedge/xdmf | f41196c966997a20f60525a3d2083490a63626a3 | [
"BSD-3-Clause"
] | 4 | 2016-04-04T20:54:31.000Z | 2020-06-15T01:39:08.000Z | #include "XdmfInformation.hpp"
#include "XdmfDomain.hpp"
#include "XdmfWriter.hpp"
int main(int, char **)
{
//Assume that exampleItem is a shared pointer to the ParentClass object
//Using an XdmfInformation as an example because all XdmfItems have XdmfInformation as a child class
shared_ptr<XdmfInformation> exampleItem = XdmfInformation::New("Parent", "This is a parent information");
shared_ptr<XdmfInformation> addChild = XdmfInformation::New("Child", "This is a child information");
exampleItem->insert(addChild);
unsigned int getIndex = 0;
shared_ptr<XdmfInformation> exampleChild = exampleItem->getInformation(getIndex);
shared_ptr<const XdmfInformation> exampleChildConst = exampleItem->getInformation(getIndex);
std::string findingInfo = "Find this";
shared_ptr<XdmfInformation> exampleStringChild = exampleItem->getInformation(findingInfo);
shared_ptr<const XdmfInformation> exampleStringChildConst = exampleItem->getInformation(findingInfo);
unsigned int exampleSize = exampleItem->getNumberInformations();
unsigned int removeIndex = 0;
exampleItem->removeInformation(removeIndex);
std::string removeInfo = "Remove this";
exampleItem->removeInformation(removeInfo);
//#initialization begin
//Using a shared pointer to an XdmfDomain object as an example
shared_ptr<XdmfDomain> exampleDomain = XdmfDomain::New();
//#initialization end
//#getItemTag begin
std::string exampleTag = exampleDomain->getItemTag();
//#getItemTag end
//#getItemProperties begin
std::map<std::string, std::string> propertyMap = exampleDomain->getItemProperties();
//#getItemProperties end
//#traverse begin
std::string writePath = "file path here";
shared_ptr<XdmfWriter> exampleWriter = XdmfWriter::New(writepath);
exampleDomain->traverse(exampleWriter);
//#traverse end
return 0;
}
| 33.540984 | 113 | 0.69306 | [
"object"
] |
a363e18e535b5d74182af58d4209262bb6cddd18 | 14,124 | cc | C++ | external/protobuf/src/google/protobuf/util/type_resolver_util.cc | edo3/safexcore | 38cb06b3c5cb5554620728d565f9cc8b493730e7 | [
"BSD-3-Clause"
] | 32 | 2019-02-27T06:57:07.000Z | 2021-08-29T10:56:19.000Z | external/protobuf/src/google/protobuf/util/type_resolver_util.cc | edo3/safexcore | 38cb06b3c5cb5554620728d565f9cc8b493730e7 | [
"BSD-3-Clause"
] | 4 | 2020-12-04T21:00:38.000Z | 2022-01-22T12:49:30.000Z | external/protobuf/src/google/protobuf/util/type_resolver_util.cc | edo3/safexcore | 38cb06b3c5cb5554620728d565f9cc8b493730e7 | [
"BSD-3-Clause"
] | 5 | 2019-08-20T13:45:04.000Z | 2022-03-01T18:23:49.000Z | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <google/protobuf/util/type_resolver_util.h>
#include <google/protobuf/type.pb.h>
#include <google/protobuf/wrappers.pb.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/util/internal/utility.h>
#include <google/protobuf/util/type_resolver.h>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/status.h>
namespace google {
namespace protobuf {
namespace util {
namespace {
using google::protobuf::Any;
using google::protobuf::BoolValue;
using google::protobuf::BytesValue;
using google::protobuf::DoubleValue;
using google::protobuf::Enum;
using google::protobuf::EnumValue;
using google::protobuf::Field;
using google::protobuf::FloatValue;
using google::protobuf::Int32Value;
using google::protobuf::Int64Value;
using google::protobuf::Option;
using google::protobuf::StringValue;
using google::protobuf::Type;
using google::protobuf::UInt32Value;
using google::protobuf::UInt64Value;
using util::Status;
using util::error::INVALID_ARGUMENT;
using util::error::NOT_FOUND;
class DescriptorPoolTypeResolver : public TypeResolver {
public:
DescriptorPoolTypeResolver(const string& url_prefix,
const DescriptorPool* pool)
: url_prefix_(url_prefix), pool_(pool) {}
Status ResolveMessageType(const string& type_url, Type* type) override {
string type_name;
Status status = ParseTypeUrl(type_url, &type_name);
if (!status.ok()) {
return status;
}
const Descriptor* descriptor = pool_->FindMessageTypeByName(type_name);
if (descriptor == NULL) {
return Status(util::error::NOT_FOUND,
"Invalid type URL, unknown type: " + type_name);
}
ConvertDescriptor(descriptor, type);
return Status();
}
Status ResolveEnumType(const string& type_url, Enum* enum_type) override {
string type_name;
Status status = ParseTypeUrl(type_url, &type_name);
if (!status.ok()) {
return status;
}
const EnumDescriptor* descriptor = pool_->FindEnumTypeByName(type_name);
if (descriptor == NULL) {
return Status(util::error::NOT_FOUND,
"Invalid type URL, unknown type: " + type_name);
}
ConvertEnumDescriptor(descriptor, enum_type);
return Status();
}
private:
void ConvertDescriptor(const Descriptor* descriptor, Type* type) {
type->Clear();
type->set_name(descriptor->full_name());
for (int i = 0; i < descriptor->field_count(); ++i) {
ConvertFieldDescriptor(descriptor->field(i), type->add_fields());
}
for (int i = 0; i < descriptor->oneof_decl_count(); ++i) {
type->add_oneofs(descriptor->oneof_decl(i)->name());
}
type->mutable_source_context()->set_file_name(descriptor->file()->name());
ConvertMessageOptions(descriptor->options(), type->mutable_options());
}
void ConvertMessageOptions(const MessageOptions& options,
RepeatedPtrField<Option>* output) {
return ConvertOptionsInternal(options, output);
}
void ConvertFieldOptions(const FieldOptions& options,
RepeatedPtrField<Option>* output) {
return ConvertOptionsInternal(options, output);
}
void ConvertEnumOptions(const EnumOptions& options,
RepeatedPtrField<Option>* output) {
return ConvertOptionsInternal(options, output);
}
void ConvertEnumValueOptions(const EnumValueOptions& options,
RepeatedPtrField<Option>* output) {
return ConvertOptionsInternal(options, output);
}
// Implementation details for Convert*Options.
void ConvertOptionsInternal(const Message& options,
RepeatedPtrField<Option>* output) {
const Reflection* reflection = options.GetReflection();
std::vector<const FieldDescriptor*> fields;
reflection->ListFields(options, &fields);
for (const FieldDescriptor* field : fields) {
if (field->is_repeated()) {
const int size = reflection->FieldSize(options, field);
for (int i = 0; i < size; i++) {
ConvertOptionField(reflection, options, field, i, output->Add());
}
} else {
ConvertOptionField(reflection, options, field, -1, output->Add());
}
}
}
static void ConvertOptionField(const Reflection* reflection,
const Message& options,
const FieldDescriptor* field, int index,
Option* out) {
out->set_name(field->is_extension() ? field->full_name() : field->name());
Any* value = out->mutable_value();
switch (field->cpp_type()) {
case FieldDescriptor::CPPTYPE_MESSAGE:
value->PackFrom(
field->is_repeated()
? reflection->GetRepeatedMessage(options, field, index)
: reflection->GetMessage(options, field));
return;
case FieldDescriptor::CPPTYPE_DOUBLE:
value->PackFrom(WrapValue<DoubleValue>(
field->is_repeated()
? reflection->GetRepeatedDouble(options, field, index)
: reflection->GetDouble(options, field)));
return;
case FieldDescriptor::CPPTYPE_FLOAT:
value->PackFrom(WrapValue<FloatValue>(
field->is_repeated()
? reflection->GetRepeatedFloat(options, field, index)
: reflection->GetFloat(options, field)));
return;
case FieldDescriptor::CPPTYPE_INT64:
value->PackFrom(WrapValue<Int64Value>(
field->is_repeated()
? reflection->GetRepeatedInt64(options, field, index)
: reflection->GetInt64(options, field)));
return;
case FieldDescriptor::CPPTYPE_UINT64:
value->PackFrom(WrapValue<UInt64Value>(
field->is_repeated()
? reflection->GetRepeatedUInt64(options, field, index)
: reflection->GetUInt64(options, field)));
return;
case FieldDescriptor::CPPTYPE_INT32:
value->PackFrom(WrapValue<Int32Value>(
field->is_repeated()
? reflection->GetRepeatedInt32(options, field, index)
: reflection->GetInt32(options, field)));
return;
case FieldDescriptor::CPPTYPE_UINT32:
value->PackFrom(WrapValue<UInt32Value>(
field->is_repeated()
? reflection->GetRepeatedUInt32(options, field, index)
: reflection->GetUInt32(options, field)));
return;
case FieldDescriptor::CPPTYPE_BOOL:
value->PackFrom(WrapValue<BoolValue>(
field->is_repeated()
? reflection->GetRepeatedBool(options, field, index)
: reflection->GetBool(options, field)));
return;
case FieldDescriptor::CPPTYPE_STRING: {
const string& val =
field->is_repeated()
? reflection->GetRepeatedString(options, field, index)
: reflection->GetString(options, field);
if (field->type() == FieldDescriptor::TYPE_STRING) {
value->PackFrom(WrapValue<StringValue>(val));
} else {
value->PackFrom(WrapValue<BytesValue>(val));
}
return;
}
case FieldDescriptor::CPPTYPE_ENUM: {
const EnumValueDescriptor* val =
field->is_repeated()
? reflection->GetRepeatedEnum(options, field, index)
: reflection->GetEnum(options, field);
value->PackFrom(WrapValue<Int32Value>(val->number()));
return;
}
}
}
template <typename WrapperT, typename T>
static WrapperT WrapValue(T value) {
WrapperT wrapper;
wrapper.set_value(value);
return wrapper;
}
void ConvertFieldDescriptor(const FieldDescriptor* descriptor, Field* field) {
field->set_kind(static_cast<Field::Kind>(descriptor->type()));
switch (descriptor->label()) {
case FieldDescriptor::LABEL_OPTIONAL:
field->set_cardinality(Field::CARDINALITY_OPTIONAL);
break;
case FieldDescriptor::LABEL_REPEATED:
field->set_cardinality(Field::CARDINALITY_REPEATED);
break;
case FieldDescriptor::LABEL_REQUIRED:
field->set_cardinality(Field::CARDINALITY_REQUIRED);
break;
}
field->set_number(descriptor->number());
field->set_name(descriptor->name());
field->set_json_name(descriptor->json_name());
if (descriptor->has_default_value()) {
field->set_default_value(DefaultValueAsString(descriptor));
}
if (descriptor->type() == FieldDescriptor::TYPE_MESSAGE ||
descriptor->type() == FieldDescriptor::TYPE_GROUP) {
field->set_type_url(GetTypeUrl(descriptor->message_type()));
} else if (descriptor->type() == FieldDescriptor::TYPE_ENUM) {
field->set_type_url(GetTypeUrl(descriptor->enum_type()));
}
if (descriptor->containing_oneof() != NULL) {
field->set_oneof_index(descriptor->containing_oneof()->index() + 1);
}
if (descriptor->is_packed()) {
field->set_packed(true);
}
ConvertFieldOptions(descriptor->options(), field->mutable_options());
}
void ConvertEnumDescriptor(const EnumDescriptor* descriptor,
Enum* enum_type) {
enum_type->Clear();
enum_type->set_name(descriptor->full_name());
enum_type->mutable_source_context()->set_file_name(
descriptor->file()->name());
for (int i = 0; i < descriptor->value_count(); ++i) {
const EnumValueDescriptor* value_descriptor = descriptor->value(i);
EnumValue* value = enum_type->mutable_enumvalue()->Add();
value->set_name(value_descriptor->name());
value->set_number(value_descriptor->number());
ConvertEnumValueOptions(value_descriptor->options(),
value->mutable_options());
}
ConvertEnumOptions(descriptor->options(), enum_type->mutable_options());
}
string GetTypeUrl(const Descriptor* descriptor) {
return url_prefix_ + "/" + descriptor->full_name();
}
string GetTypeUrl(const EnumDescriptor* descriptor) {
return url_prefix_ + "/" + descriptor->full_name();
}
Status ParseTypeUrl(const string& type_url, string* type_name) {
if (type_url.substr(0, url_prefix_.size() + 1) != url_prefix_ + "/") {
return Status(
util::error::INVALID_ARGUMENT,
StrCat("Invalid type URL, type URLs must be of the form '",
url_prefix_, "/<typename>', got: ", type_url));
}
*type_name = type_url.substr(url_prefix_.size() + 1);
return Status();
}
string DefaultValueAsString(const FieldDescriptor* descriptor) {
switch (descriptor->cpp_type()) {
case FieldDescriptor::CPPTYPE_INT32:
return StrCat(descriptor->default_value_int32());
break;
case FieldDescriptor::CPPTYPE_INT64:
return StrCat(descriptor->default_value_int64());
break;
case FieldDescriptor::CPPTYPE_UINT32:
return StrCat(descriptor->default_value_uint32());
break;
case FieldDescriptor::CPPTYPE_UINT64:
return StrCat(descriptor->default_value_uint64());
break;
case FieldDescriptor::CPPTYPE_FLOAT:
return SimpleFtoa(descriptor->default_value_float());
break;
case FieldDescriptor::CPPTYPE_DOUBLE:
return SimpleDtoa(descriptor->default_value_double());
break;
case FieldDescriptor::CPPTYPE_BOOL:
return descriptor->default_value_bool() ? "true" : "false";
break;
case FieldDescriptor::CPPTYPE_STRING:
if (descriptor->type() == FieldDescriptor::TYPE_BYTES) {
return CEscape(descriptor->default_value_string());
} else {
return descriptor->default_value_string();
}
break;
case FieldDescriptor::CPPTYPE_ENUM:
return descriptor->default_value_enum()->name();
break;
case FieldDescriptor::CPPTYPE_MESSAGE:
GOOGLE_LOG(DFATAL) << "Messages can't have default values!";
break;
}
return "";
}
string url_prefix_;
const DescriptorPool* pool_;
};
} // namespace
TypeResolver* NewTypeResolverForDescriptorPool(const string& url_prefix,
const DescriptorPool* pool) {
return new DescriptorPoolTypeResolver(url_prefix, pool);
}
} // namespace util
} // namespace protobuf
} // namespace google
| 38.276423 | 80 | 0.660507 | [
"vector"
] |
a36a5a5935a48ae6bfe89a22fd9d37db2d7677a3 | 917 | hpp | C++ | detail/fusion/boost/statistics/detail/fusion/serialization/include.hpp | rogard/boost_sandbox_statistics | 16aacbc716a31a9f7bb6c535b1c90dc343282a23 | [
"BSL-1.0"
] | null | null | null | detail/fusion/boost/statistics/detail/fusion/serialization/include.hpp | rogard/boost_sandbox_statistics | 16aacbc716a31a9f7bb6c535b1c90dc343282a23 | [
"BSL-1.0"
] | null | null | null | detail/fusion/boost/statistics/detail/fusion/serialization/include.hpp | rogard/boost_sandbox_statistics | 16aacbc716a31a9f7bb6c535b1c90dc343282a23 | [
"BSL-1.0"
] | null | null | null | //////////////////////////////////////////////////////////////////////////////
// detail::fusion::map::serialization::include.hpp //
// //
// (C) Copyright 2009 Erwann Rogard //
// Use, modification and distribution are 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_STATISTICS_DETAIL_FUSION_SERIALIZATION_INCLUDE_HPP_ER_2009
#define BOOST_STATISTICS_DETAIL_FUSION_SERIALIZATION_INCLUDE_HPP_ER_2009
#include <boost/statistics/detail/fusion/serialization/map.hpp>
#include <boost/statistics/detail/fusion/serialization/vector.hpp>
#endif | 61.133333 | 78 | 0.503817 | [
"vector"
] |
a36c0812c03de7e5dc7f0d166e0da66b1f0127cd | 4,440 | hpp | C++ | sycl/include/CL/sycl/program.hpp | nyalloc/llvm | 2d6dcd09b6a418c05c02b7beb6bb042ec73daf43 | [
"Apache-2.0"
] | null | null | null | sycl/include/CL/sycl/program.hpp | nyalloc/llvm | 2d6dcd09b6a418c05c02b7beb6bb042ec73daf43 | [
"Apache-2.0"
] | null | null | null | sycl/include/CL/sycl/program.hpp | nyalloc/llvm | 2d6dcd09b6a418c05c02b7beb6bb042ec73daf43 | [
"Apache-2.0"
] | null | null | null | //==--------------- program.hpp --- SYCL program ---------------------------==//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#pragma once
#include <CL/sycl/context.hpp>
#include <CL/sycl/detail/program_impl.hpp>
#include <CL/sycl/info/info_desc.hpp>
#include <CL/sycl/stl.hpp>
#include <memory>
namespace cl {
namespace sycl {
class context;
class device;
class kernel;
class program {
template <class Obj>
friend decltype(Obj::impl) detail::getSyclObjImpl(const Obj &SyclObject);
template <class T>
friend T detail::createSyclObjFromImpl(decltype(T::impl) ImplObj);
public:
program() = delete;
explicit program(const context &context)
: impl(std::make_shared<detail::program_impl>(
detail::getSyclObjImpl(context))) {}
program(const context &context, vector_class<device> deviceList)
: impl(std::make_shared<detail::program_impl>(
detail::getSyclObjImpl(context), deviceList)) {}
program(vector_class<program> programList, string_class linkOptions = "") {
std::vector<std::shared_ptr<detail::program_impl>> impls;
for (auto &x : programList) {
impls.push_back(detail::getSyclObjImpl(x));
}
impl = std::make_shared<detail::program_impl>(impls, linkOptions);
}
program(const context &context, cl_program clProgram)
: impl(std::make_shared<detail::program_impl>(
detail::getSyclObjImpl(context),
detail::pi::cast<detail::RT::PiProgram>(clProgram))) {}
program(const program &rhs) = default;
program(program &&rhs) = default;
program &operator=(const program &rhs) = default;
program &operator=(program &&rhs) = default;
bool operator==(const program &rhs) const { return impl == rhs.impl; }
bool operator!=(const program &rhs) const { return !operator==(rhs); }
cl_program get() const { return impl->get(); }
bool is_host() const { return impl->is_host(); }
template <typename kernelT>
void compile_with_kernel_type(string_class compileOptions = "") {
impl->compile_with_kernel_type<kernelT>(compileOptions);
}
void compile_with_source(string_class kernelSource,
string_class compileOptions = "") {
impl->compile_with_source(kernelSource, compileOptions);
}
template <typename kernelT>
void build_with_kernel_type(string_class buildOptions = "") {
impl->build_with_kernel_type<kernelT>(buildOptions);
}
void build_with_source(string_class kernelSource,
string_class buildOptions = "") {
impl->build_with_source(kernelSource, buildOptions);
}
void link(string_class linkOptions = "") { impl->link(linkOptions); }
template <typename kernelT> bool has_kernel() const {
return impl->has_kernel<kernelT>();
}
bool has_kernel(string_class kernelName) const {
return impl->has_kernel(kernelName);
}
template <typename kernelT> kernel get_kernel() const {
return impl->get_kernel<kernelT>(impl);
}
kernel get_kernel(string_class kernelName) const {
return impl->get_kernel(kernelName, impl);
}
template <info::program param>
typename info::param_traits<info::program, param>::return_type
get_info() const {
return impl->get_info<param>();
}
vector_class<vector_class<char>> get_binaries() const {
return impl->get_binaries();
}
context get_context() const { return impl->get_context(); }
vector_class<device> get_devices() const { return impl->get_devices(); }
string_class get_compile_options() const {
return impl->get_compile_options();
}
string_class get_link_options() const { return impl->get_link_options(); }
string_class get_build_options() const { return impl->get_build_options(); }
program_state get_state() const { return impl->get_state(); }
private:
program(std::shared_ptr<detail::program_impl> impl) : impl(impl) {}
std::shared_ptr<detail::program_impl> impl;
};
} // namespace sycl
} // namespace cl
namespace std {
template <> struct hash<cl::sycl::program> {
size_t operator()(const cl::sycl::program &prg) const {
return hash<std::shared_ptr<cl::sycl::detail::program_impl>>()(
cl::sycl::detail::getSyclObjImpl(prg));
}
};
} // namespace std
| 29.798658 | 80 | 0.679505 | [
"vector"
] |
a36cdde2123f9426576e5f5670c7e328076bb1e9 | 2,358 | cpp | C++ | libraries/entities-renderer/src/RenderableLineEntityItem.cpp | Penguin-Guru/vircadia | 021268696c73f699364fa93f5d6db03e6b1b8426 | [
"Apache-2.0"
] | 272 | 2021-01-07T03:06:08.000Z | 2022-03-25T03:54:07.000Z | libraries/entities-renderer/src/RenderableLineEntityItem.cpp | MetaverseCyy/vircadia | c36afe76e1113b6b9ec46e2f72e7e6ec45bde299 | [
"Apache-2.0"
] | 1,021 | 2020-12-12T02:33:32.000Z | 2022-03-31T23:36:37.000Z | libraries/entities-renderer/src/RenderableLineEntityItem.cpp | MetaverseCyy/vircadia | c36afe76e1113b6b9ec46e2f72e7e6ec45bde299 | [
"Apache-2.0"
] | 77 | 2020-12-15T06:59:34.000Z | 2022-03-23T22:18:04.000Z | //
// RenderableLineEntityItem.cpp
// libraries/entities-renderer/src/
//
// Created by Seth Alves on 5/11/15.
// Copyright 2015 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#include "RenderableLineEntityItem.h"
#include <gpu/Batch.h>
#include <PerfStat.h>
using namespace render;
using namespace render::entities;
void LineEntityRenderer::onRemoveFromSceneTyped(const TypedEntityPointer& entity) {
if (_lineVerticesID != GeometryCache::UNKNOWN_ID) {
auto geometryCache = DependencyManager::get<GeometryCache>();
if (geometryCache) {
geometryCache->releaseID(_lineVerticesID);
}
}
}
void LineEntityRenderer::doRenderUpdateAsynchronousTyped(const TypedEntityPointer& entity) {
_linePoints = entity->getLinePoints();
auto geometryCache = DependencyManager::get<GeometryCache>();
if (_lineVerticesID == GeometryCache::UNKNOWN_ID) {
_lineVerticesID = geometryCache->allocateID();
}
glm::vec4 lineColor(toGlm(entity->getColor()), 1.0f);
geometryCache->updateVertices(_lineVerticesID, _linePoints, lineColor);
}
void LineEntityRenderer::doRender(RenderArgs* args) {
if (_lineVerticesID == GeometryCache::UNKNOWN_ID) {
return;
}
PerformanceTimer perfTimer("RenderableLineEntityItem::render");
Q_ASSERT(args->_batch);
gpu::Batch& batch = *args->_batch;
const auto& modelTransform = getModelTransform();
Transform transform = Transform();
transform.setTranslation(modelTransform.getTranslation());
transform.setRotation(BillboardModeHelpers::getBillboardRotation(modelTransform.getTranslation(), modelTransform.getRotation(), _billboardMode,
args->_renderMode == RenderArgs::RenderMode::SHADOW_RENDER_MODE ? BillboardModeHelpers::getPrimaryViewFrustumPosition() : args->getViewFrustum().getPosition()));
batch.setModelTransform(transform);
if (_linePoints.size() > 1) {
DependencyManager::get<GeometryCache>()->bindSimpleProgram(batch, false, false, false, false, true,
_renderLayer != RenderLayer::WORLD || args->_renderMethod == Args::RenderMethod::FORWARD);
DependencyManager::get<GeometryCache>()->renderVertices(batch, gpu::LINE_STRIP, _lineVerticesID);
}
}
| 39.966102 | 169 | 0.73028 | [
"render",
"transform"
] |
a36e4fc4247189e56a364d4c8676fc5434417b8c | 81,726 | cc | C++ | tensorflow/lite/kernels/internal/tensor_utils_test.cc | scentini/tensorflow | 204ed332c0886a0e0ab10b22ba8d67b97e1c83c4 | [
"Apache-2.0"
] | 56 | 2018-06-21T13:47:23.000Z | 2020-05-13T09:31:47.000Z | tensorflow/lite/kernels/internal/tensor_utils_test.cc | scentini/tensorflow | 204ed332c0886a0e0ab10b22ba8d67b97e1c83c4 | [
"Apache-2.0"
] | null | null | null | tensorflow/lite/kernels/internal/tensor_utils_test.cc | scentini/tensorflow | 204ed332c0886a0e0ab10b22ba8d67b97e1c83c4 | [
"Apache-2.0"
] | 15 | 2018-09-06T14:18:32.000Z | 2020-05-14T06:35:30.000Z | /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/kernels/internal/tensor_utils.h"
#include <gmock/gmock.h>
#include "tensorflow/lite/c/builtin_op_data.h"
#include "tensorflow/lite/kernels/internal/quantization_util.h"
#include "tensorflow/lite/kernels/test_util.h"
#ifdef DOTPROD_BENCHMARKS
#include "testing/base/public/benchmark.h"
#endif // DOTPROD_BENCHMARKS
namespace tflite {
namespace tensor_utils {
TEST(uKernels, ClipTest) {
constexpr int kVectorSize = 10;
constexpr float kAbsLimit = 2.0;
static float input[kVectorSize] = {0.0, -0.5, 1.0, -1.5, 2.0,
-2.5, 3.0, -3.5, 4.0, -4.5};
std::vector<float> output(kVectorSize);
ClipVector(input, kVectorSize, kAbsLimit, output.data());
EXPECT_THAT(output,
ElementsAreArray(ArrayFloatNear(
{0.0, -0.5, 1.0, -1.5, 2.0, -2.0, 2.0, -2.0, 2.0, -2.0})));
}
TEST(uKernels, VectorScalarMultiply) {
constexpr int kVectorSize = 29;
static int8_t input[kVectorSize];
for (int i = 0; i < 29; ++i) {
input[i] = static_cast<int8_t>(i - 14);
}
const float scale = 0.1f;
std::vector<float> output(kVectorSize, 0.0f);
VectorScalarMultiply(input, kVectorSize, scale, output.data());
EXPECT_THAT(output,
ElementsAreArray(ArrayFloatNear(
{-1.4, -1.3, -1.2, -1.1, -1.0, -0.9, -0.8, -0.7, -0.6, -0.5,
-0.4, -0.3, -0.2, -0.1, 0, 0.1, 0.2, 0.3, 0.4, 0.5,
0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4})));
}
#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
// Test if a float array if full of zero values.
TEST(uKernels, IsZeroFloatTest) {
// Single NEON vector (= 4 floats)
{
const float four_zeros[4] = {0, 0, 0, 0};
EXPECT_TRUE(IsZeroVector(four_zeros, ARRAY_SIZE(four_zeros)));
}
{
const float four_nonzeros[4] = {1, 2, 3, 4};
EXPECT_FALSE(IsZeroVector(four_nonzeros, ARRAY_SIZE(four_nonzeros)));
}
// Multiple NEON vectors
{
const float eight_zeros[8] = {0, 0, 0, 0, 0, 0, 0, 0};
EXPECT_TRUE(IsZeroVector(eight_zeros, ARRAY_SIZE(eight_zeros)));
}
{
const float eight_nonzeros[8] = {1, 2, 3, 4, 5, 6, 7, 8};
EXPECT_FALSE(IsZeroVector(eight_nonzeros, ARRAY_SIZE(eight_nonzeros)));
}
{
const float multiple_four_mixed1[8] = {0, 0, 0, 0, 5, 6, 7, 8};
EXPECT_FALSE(
IsZeroVector(multiple_four_mixed1, ARRAY_SIZE(multiple_four_mixed1)));
}
{
const float multiple_four_mixed2[8] = {1, 2, 3, 4, 0, 0, 0, 0};
EXPECT_FALSE(
IsZeroVector(multiple_four_mixed2, ARRAY_SIZE(multiple_four_mixed2)));
}
// less than one NEON vector
{
const float three_zeros[3] = {0, 0, 0};
EXPECT_TRUE(IsZeroVector(three_zeros, ARRAY_SIZE(three_zeros)));
}
{
const float three_nonzeros[3] = {1, 2, 3};
EXPECT_FALSE(IsZeroVector(three_nonzeros, ARRAY_SIZE(three_nonzeros)));
}
{
const float three_mixed[3] = {1, 0, 3};
EXPECT_FALSE(IsZeroVector(three_mixed, ARRAY_SIZE(three_mixed)));
}
// Postamble after NEON vectors
{
const float seven_zeros[7] = {0, 0, 0, 0, 0, 0, 0};
EXPECT_TRUE(IsZeroVector(seven_zeros, ARRAY_SIZE(seven_zeros)));
}
{
const float seven_nonzeros[7] = {1, 2, 3, 4, 5, 6, 7};
EXPECT_FALSE(IsZeroVector(seven_nonzeros, ARRAY_SIZE(seven_nonzeros)));
}
{
const float nonzeros_after_zeros[7] = {0, 0, 0, 0, 5, 6, 7};
EXPECT_FALSE(
IsZeroVector(nonzeros_after_zeros, ARRAY_SIZE(nonzeros_after_zeros)));
}
}
// Test if an int8 array if full of zero values.
TEST(uKernels, IsZeroInt8Test) {
// Single NEON vector (= 16x int8_t)
{
const int8_t sixteen_zeros[16] = {0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0};
EXPECT_TRUE(IsZeroVector(sixteen_zeros, ARRAY_SIZE(sixteen_zeros)));
}
{
const int8_t sixteen_nonzeros[16] = {1, 2, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 13, 14, 15, 16};
EXPECT_FALSE(IsZeroVector(sixteen_nonzeros, ARRAY_SIZE(sixteen_nonzeros)));
}
// Multiple NEON vectors
{
const int8_t thritytwo_zeros[32] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
EXPECT_TRUE(IsZeroVector(thritytwo_zeros, ARRAY_SIZE(thritytwo_zeros)));
}
{
const int8_t thritytwo_nonzeros[32] = {
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
EXPECT_FALSE(
IsZeroVector(thritytwo_nonzeros, ARRAY_SIZE(thritytwo_nonzeros)));
}
{
const int8_t thritytwo_mixed1[32] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
EXPECT_FALSE(IsZeroVector(thritytwo_mixed1, ARRAY_SIZE(thritytwo_mixed1)));
}
{
const int8_t thritytwo_mixed2[32] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
EXPECT_FALSE(IsZeroVector(thritytwo_mixed2, ARRAY_SIZE(thritytwo_mixed2)));
}
// less than one NEON vector
{
const int8_t fifteen_zeros[15] = {0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0};
EXPECT_TRUE(IsZeroVector(fifteen_zeros, ARRAY_SIZE(fifteen_zeros)));
}
{
const int8_t fifteen_nonzeros[15] = {1, 2, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 13, 14, 15};
EXPECT_FALSE(IsZeroVector(fifteen_nonzeros, ARRAY_SIZE(fifteen_nonzeros)));
}
{
const int8_t fifteen_mixed[15] = {1, 0, 3, 0, 5, 0, 7, 0,
9, 0, 11, 0, 13, 0, 15};
EXPECT_FALSE(IsZeroVector(fifteen_mixed, ARRAY_SIZE(fifteen_mixed)));
}
// Postamble after NEON vectors
{
const int8_t seventeen_zeros[17] = {0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0};
EXPECT_TRUE(IsZeroVector(seventeen_zeros, ARRAY_SIZE(seventeen_zeros)));
}
{
const int8_t seventeen_nonzeros[17] = {1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17};
EXPECT_FALSE(
IsZeroVector(seventeen_nonzeros, ARRAY_SIZE(seventeen_nonzeros)));
}
{
const int8_t nonzeros_after_zeros[17] = {0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 17};
EXPECT_FALSE(
IsZeroVector(nonzeros_after_zeros, ARRAY_SIZE(nonzeros_after_zeros)));
}
}
#undef ARRAY_SIZE
TEST(uKernels, SymmetricQuantizeFloatsTest) {
constexpr int kVectorSize = 9;
static float input[kVectorSize] = {-640, -635.0, -630, 10.0, 2.0,
-5.0, -10.0, 0.0, 1000.0};
int8_t output[kVectorSize];
float min, max, scaling_factor;
SymmetricQuantizeFloats(input, kVectorSize, output, &min, &max,
&scaling_factor);
EXPECT_EQ(min, -640);
EXPECT_EQ(max, 1000);
// EQ won't work due to fpoint.
EXPECT_NEAR(scaling_factor, 1000 / 127.0, 1e-6);
EXPECT_THAT(output,
testing::ElementsAreArray({-81, -81, -80, 1, 0, -1, -1, 0, 127}));
}
TEST(uKernels, SymmetricQuantizeFloatsAllZerosTest) {
constexpr int kVectorSize = 9;
static float input[kVectorSize] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
int8_t output[kVectorSize];
float min, max, scaling_factor;
SymmetricQuantizeFloats(input, kVectorSize, output, &min, &max,
&scaling_factor);
EXPECT_EQ(min, 0);
EXPECT_EQ(max, 0);
EXPECT_EQ(scaling_factor, 1);
EXPECT_THAT(output, testing::ElementsAreArray({0, 0, 0, 0, 0, 0, 0, 0, 0}));
}
TEST(uKernels, SymmetricQuantizeFloatsAllAlmostZeroTest) {
constexpr int kVectorSize = 9;
static float input[kVectorSize] = {-1e-5, 3e-5, -7e-6, -9e-5, 1e-6,
4e-5, 9e-6, 2e-4, 0};
int8_t output[kVectorSize];
float min, max, scaling_factor;
SymmetricQuantizeFloats(input, kVectorSize, output, &min, &max,
&scaling_factor);
EXPECT_NEAR(min, -9e-05, 1e-6);
EXPECT_NEAR(max, 0.0002, 1e-6);
EXPECT_NEAR(scaling_factor, 1.57e-6, 1e-6);
EXPECT_THAT(output,
testing::ElementsAreArray({-6, 19, -4, -57, 1, 25, 6, 127, 0}));
}
TEST(uKernels, AsymmetricQuantizeFloatsTest) {
constexpr int kVectorSize = 9;
static float input[kVectorSize] = {-640, -635.0, -630, 10.0, 2.0,
-5.0, -10.0, 0.0, 1000.0};
int8_t output[kVectorSize];
double min = -640.0;
double max = 1000.0;
QuantizationParams quantization_params =
ChooseQuantizationParams<int8_t>(min, max);
float scale = quantization_params.scale;
int32_t offset = quantization_params.zero_point;
float test_scale;
int32_t test_offset;
AsymmetricQuantizeFloats(input, kVectorSize, output, &test_scale,
&test_offset);
// EQ won't work due to fpoint.
EXPECT_NEAR(test_scale, scale, 1e-6);
EXPECT_EQ(test_offset, offset);
EXPECT_THAT(output, testing::ElementsAreArray(
{-128, -127, -126, -26, -28, -29, -30, -28, 127}));
}
TEST(uKernels, AsymmetricQuantizeFloatsAllZerosTest) {
constexpr int kVectorSize = 9;
static float input[kVectorSize] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
int8_t output[kVectorSize];
float test_scale;
int32_t test_offset;
AsymmetricQuantizeFloats(input, kVectorSize, output, &test_scale,
&test_offset);
EXPECT_EQ(test_scale, 0);
EXPECT_EQ(test_offset, 0);
EXPECT_THAT(output, testing::ElementsAreArray({0, 0, 0, 0, 0, 0, 0, 0, 0}));
}
TEST(uKernels, AsymmetricQuantizeFloatsZeroRangeTest) {
constexpr int kVectorSize = 9;
static float input[kVectorSize] = {2000, 2000, 2000, 2000, 2000,
2000, 2000, 2000, 2000};
int8_t output[kVectorSize];
double min = 0;
double max = 2000;
QuantizationParams quantization_params =
ChooseQuantizationParams<int8_t>(min, max);
int32_t offset = quantization_params.zero_point;
float scale = quantization_params.scale;
float test_scale;
int32_t test_offset;
AsymmetricQuantizeFloats(input, kVectorSize, output, &test_scale,
&test_offset);
EXPECT_NEAR(test_scale, scale, 1e-6);
EXPECT_EQ(test_offset, offset);
EXPECT_THAT(output, testing::ElementsAreArray(
{127, 127, 127, 127, 127, 127, 127, 127, 127}));
}
TEST(uKernels, AsymmetricQuantizeFloatsAllAlmostZeroTest) {
constexpr int kVectorSize = 9;
static float input[kVectorSize] = {-1e-5, 3e-5, -7e-6, -9e-5, 1e-6,
4e-5, 9e-6, 2e-4, 0};
int8_t output[kVectorSize];
double min = -9e-05;
double max = 0.0002;
QuantizationParams quantization_params =
ChooseQuantizationParams<int8_t>(min, max);
int32_t offset = quantization_params.zero_point;
float scale = quantization_params.scale;
float test_scale;
int32_t test_offset;
AsymmetricQuantizeFloats(input, kVectorSize, output, &test_scale,
&test_offset);
EXPECT_NEAR(test_scale, scale, 1e-6);
EXPECT_EQ(test_offset, offset);
EXPECT_THAT(output, testing::ElementsAreArray(
{-58, -23, -55, -128, -48, -14, -41, 127, -49}));
}
TEST(uKernels, MatrixBatchVectorMultiplyAccumulateTest) {
constexpr int kRow = 3;
constexpr int kCol = 4;
constexpr int kBatch = 2;
static float matrix[kRow * kCol] = {1.0, 2.0, 3.0, 4.0, //
-1.0, -2.0, -3.0, -4.0, //
1.0, -2.0, 3.0, -4.0};
static float vector[kCol * kBatch] = {1.0, -1.0, 1.0, -1.0, //
2.0, -2.0, 2.0, -2.0};
std::vector<float> output(kRow * kBatch);
std::fill(output.begin(), output.end(), 3.0);
MatrixBatchVectorMultiplyAccumulate(matrix, kRow, kCol, vector, kBatch,
output.data(), /*result_stride=*/1);
EXPECT_THAT(output, ElementsAreArray(ArrayFloatNear({1., 5., 13., //
-1., 7., 23.})));
std::vector<float> output_with_stride2(kRow * kBatch * 2);
std::fill(output_with_stride2.begin(), output_with_stride2.end(), 3.0);
MatrixBatchVectorMultiplyAccumulate(matrix, kRow, kCol, vector, kBatch,
output_with_stride2.data(),
/*result_stride=*/2);
EXPECT_THAT(output_with_stride2,
ElementsAreArray(ArrayFloatNear({1., 3., 5., 3., 13., 3., //
-1., 3., 7., 3., 23., 3.})));
}
// Quantized matmul with 2 * 30 input and 9 * 30 matrix.
TEST(uKernels, QuantMatrixBatchVectorMultiplyAccumulate8x8_16Test) {
CpuBackendContext context;
const std::vector<int8_t> input = {
4, -41, 5, -41, 22, 17, -30, 24, 13, -47, 18, 9, -11, -30, 16,
-47, 12, 36, -20, 27, -3, 0, -51, -31, 3, -8, -38, 43, 23, 12,
11, -23, -26, 23, 14, -9, -44, 22, 21, -30, 3, -47, -26, -21, -24,
-44, 34, -11, -23, -28, 26, -38, 19, 35, 9, 23, 6, -42, -25, 28,
};
const std::vector<int32_t> input_zeropoint_times_weights = {
-620, -170, -395, 715, -1220, -1080, 1130, -260, -470,
};
const std::vector<int8_t> input_to_gate_weights = {
-10, -4, -8, 16, 4, -16, -1, 11, 1, 2, -25, 19, 7, 9, 2,
-24, -2, 10, -7, 7, -5, -2, 3, 4, 3, -4, -7, -11, -13, -18,
11, 10, 12, -9, 17, -15, -5, 20, -6, -11, 2, -6, -18, 15, 4,
4, -9, -2, -3, -9, -13, 17, -21, 5, 3, -12, 0, -4, 9, -5,
10, -2, 8, 1, -10, -6, 1, -9, 10, 11, -1, -5, 4, -7, -4,
-4, 4, 12, -7, -5, -9, -19, 6, -4, 12, -17, -22, 0, 9, -4,
-5, 5, -8, 8, 3, 15, -18, -18, 5, 3, -12, 5, -10, 7, 7,
-9, 17, 2, -11, -25, 3, 19, -6, 7, 1, 7, 5, -3, 11, 3,
0, -8, 8, -2, -2, -12, 14, -5, 7, 8, 16, 20, -16, -5, -5,
1, -10, -6, 14, 10, -12, 10, -6, 5, 0, 3, 8, -9, -13, -2,
4, 4, -16, -17, -9, 16, -5, 14, -9, -5, -12, 0, 17, 6, -1,
16, -20, 1, -11, -1, -10, -21, 13, 4, -12, -7, 0, -14, -6, 3,
-4, 6, -18, -3, -1, 14, -8, -6, -15, 5, 12, -3, -10, 4, 6,
-5, -20, 0, 3, -3, -7, 1, 2, -10, 7, -3, 6, 1, -12, 6,
4, -12, 2, 6, -20, 0, 5, 23, 15, 14, 9, 8, 20, -2, 9,
-8, -8, -7, -4, -8, -9, 7, -12, -2, 2, 1, -14, 31, 4, -14,
3, 10, -18, -17, -1, 18, 1, 12, 0, 7, -3, -5, 8, -9, 18,
17, 7, -15, 3, 20, 4, -8, 16, 6, -3, -3, 9, -4, -6, 4,
};
const int32_t multiplier = 2080364544;
const int32_t shift = -2;
std::vector<int32_t> scrach(2 * 9, 0);
std::vector<int16_t> output = {10, 2, 33, 4, 5, 6, 65, 4, 3,
52, 1, 2, 8, -1, -2, 11, 17, -18};
MatrixBatchVectorMultiplyAccumulate(
input.data(), input_zeropoint_times_weights.data(),
input_to_gate_weights.data(), multiplier, shift,
/*n_batch=*/2, /*n_input=*/30, /*n_output=*/9, /*output_zp=*/0,
scrach.data(), output.data(), &context);
const std::vector<int16_t> expected_output = {
-210, 331, 153, 139, -570, -657, 258, 515, -495,
91, -243, -73, 603, -744, -269, 169, -748, -174,
};
EXPECT_THAT(output, testing::ElementsAreArray(expected_output));
}
// Qautnized matmul with 2 * 30 input and 9 * 30 matrix.
TEST(uKernels, QuantMatrixBatchVectorMultiplyAccumulate8x8_8Test) {
CpuBackendContext context;
const std::vector<int8_t> input = {
4, -41, 5, -41, 22, 17, -30, 24, 13, -47, 18, 9, -11, -30, 16,
-47, 12, 36, -20, 27, -3, 0, -51, -31, 3, -8, -38, 43, 23, 12,
11, -23, -26, 23, 14, -9, -44, 22, 21, -30, 3, -47, -26, -21, -24,
-44, 34, -11, -23, -28, 26, -38, 19, 35, 9, 23, 6, -42, -25, 28,
};
const std::vector<int32_t> input_zeropoint_times_weights = {
0, 0, 0, 0, 0, 0, 0, 0, 0,
};
const std::vector<int8_t> input_to_gate_weights = {
13, -7, -20, -22, 8, -46, 9, -2, -18, -42, 40, 28, -7, 24, 34,
-7, -24, -24, 19, 14, -19, -6, -2, -3, 5, -36, -13, 6, -27, 36,
-23, 0, 20, -37, -23, 9, 17, -41, 33, -15, -18, -42, -41, -34, -16,
-6, 12, -14, -15, -20, -14, 21, -3, -1, -26, 54, 51, 35, -14, 9,
-2, 13, -6, 39, 34, -21, 39, -51, 19, -44, 52, 0, -2, -38, -35,
-33, 4, -22, -37, 27, -23, 3, -10, 5, 32, 6, 1, -35, 24, -19,
46, 43, -55, 5, 38, -14, 32, -43, -44, -17, -13, -28, 56, 28, -42,
4, 10, -7, 25, -15, -9, -25, -14, -15, 6, -10, -22, 40, -72, 18,
-6, -18, -2, 37, -13, -10, 11, -9, 32, -28, 19, -2, 4, -31, 50,
-15, 23, -34, -9, 41, -6, -34, 17, 2, 24, -15, 21, -17, -8, -20,
1, -63, 19, -40, 12, -5, 5, -6, 1, 19, -9, -23, 5, -34, 11,
26, 21, 54, 34, -43, -29, 1, 16, 31, -56, -28, 57, -15, -23, 37,
-17, -3, -6, 29, 18, 77, 17, -20, -14, -19, 8, -24, -7, -45, -3,
0, -25, -8, 6, 9, 3, -15, 51, 4, -15, -19, -16, -14, -47, -52,
25, 9, 58, 26, -9, -27, 49, -6, -21, 21, 18, 12, -9, -9, 14,
31, -26, -19, -50, 17, 35, 11, -10, 22, -16, -43, -2, 26, 55, -20,
-7, 21, 33, -20, 26, -15, -22, 30, 27, 3, -34, 26, 12, -1, 19,
26, -25, 10, 30, 30, -14, -23, -23, -35, -16, 26, -41, 11, 1, 21,
};
const int32_t multiplier = 1347771520;
const int32_t shift = -7;
const int32_t output_zp = -11;
std::vector<int8_t> output = {1, 2, 3, 4, 5, 6, 5, 4, 3,
2, 1, 2, 8, -1, -2, 11, 17, 18};
std::vector<int32_t> scrach(2 * 9, 0);
MatrixBatchVectorMultiplyAccumulate(
input.data(), input_zeropoint_times_weights.data(),
input_to_gate_weights.data(), multiplier, shift,
/*n_batch=*/2, /*n_input=*/30, /*n_output=*/9, output_zp, scrach.data(),
output.data(), &context);
const std::vector<int8_t> expected_output = {
5, -9, -2, -30, -5, -11, -22, -18, 18,
-19, 2, 11, -5, 9, -2, 10, -38, -22,
};
EXPECT_THAT(output, testing::ElementsAreArray(expected_output));
}
// Quantized matmul with 9 * 30 matrix.
TEST(uKernels, MatrixScalarMultiplyAccumulateTest) {
std::vector<int32_t> output = {
-620, -170, -395, 715, -1220, -1080, 1130, -260, -470,
};
const std::vector<int8_t> weight = {
-10, -4, -8, 16, 4, -16, -1, 11, 1, 2, -25, 19, 7, 9, 2,
-24, -2, 10, -7, 7, -5, -2, 3, 4, 3, -4, -7, -11, -13, -18,
11, 10, 12, -9, 17, -15, -5, 20, -6, -11, 2, -6, -18, 15, 4,
4, -9, -2, -3, -9, -13, 17, -21, 5, 3, -12, 0, -4, 9, -5,
10, -2, 8, 1, -10, -6, 1, -9, 10, 11, -1, -5, 4, -7, -4,
-4, 4, 12, -7, -5, -9, -19, 6, -4, 12, -17, -22, 0, 9, -4,
-5, 5, -8, 8, 3, 15, -18, -18, 5, 3, -12, 5, -10, 7, 7,
-9, 17, 2, -11, -25, 3, 19, -6, 7, 1, 7, 5, -3, 11, 3,
0, -8, 8, -2, -2, -12, 14, -5, 7, 8, 16, 20, -16, -5, -5,
1, -10, -6, 14, 10, -12, 10, -6, 5, 0, 3, 8, -9, -13, -2,
4, 4, -16, -17, -9, 16, -5, 14, -9, -5, -12, 0, 17, 6, -1,
16, -20, 1, -11, -1, -10, -21, 13, 4, -12, -7, 0, -14, -6, 3,
-4, 6, -18, -3, -1, 14, -8, -6, -15, 5, 12, -3, -10, 4, 6,
-5, -20, 0, 3, -3, -7, 1, 2, -10, 7, -3, 6, 1, -12, 6,
4, -12, 2, 6, -20, 0, 5, 23, 15, 14, 9, 8, 20, -2, 9,
-8, -8, -7, -4, -8, -9, 7, -12, -2, 2, 1, -14, 31, 4, -14,
3, 10, -18, -17, -1, 18, 1, 12, 0, 7, -3, -5, 8, -9, 18,
17, 7, -15, 3, 20, 4, -8, 16, 6, -3, -3, 9, -4, -6, 4,
};
MatrixScalarMultiplyAccumulate(weight.data(), 3, 9, 30, output.data());
const std::vector<int32_t> expected_output = {
-797, -227, -536, 739, -1187, -1314, 965, -140, -257,
};
EXPECT_THAT(output, testing::ElementsAreArray(expected_output));
}
// Quantized layer norm of n_batch = 2 and n_input = 15.
TEST(uKernels, QuantApplyLayerNormTest) {
const std::vector<int16_t> input = {
-310, 596, 34, -68, 475, 92, 672, -54, -913, -200,
-1194, -836, -620, -237, 991, 533, 721, -736, -8, -941,
-372, -1084, 591, 2557, -779, 175, 582, 956, -287, 944,
};
const std::vector<int16_t> layer_norm_weights = {
21849, 22882, 20626, 23854, 24779, 26354, 12980, 26231,
23716, 27271, 24937, 22647, 24715, 22854, 19646,
};
const std::vector<int32_t> bias_weight = {
-14175520, -13805465, -16027609, -13786809, -13321033,
-14399810, -15055368, -14536623, -14508746, -13784007,
-15206609, -15125830, -14996304, -14847597, -12814379,
};
const int32_t multiplier = 1895840000;
const int32_t shift = -13;
const int32_t limit = 1;
std::vector<int16_t> output(2 * 15, 0);
ApplyLayerNorm(input.data(), layer_norm_weights.data(), bias_weight.data(),
multiplier, shift, limit, 2, 15, output.data());
const std::vector<int16_t> expected_output = {
-9407, 5846, -4802, -5295, 4822, -2390, 930, -5283,
-20352, -7846, -26539, -18704, -15829, -8627, 10313, -2522,
-132, -16058, -8206, -19158, -13296, -14407, -1235, 20612,
-18591, -6738, -2274, 2602, -11622, 1565,
};
EXPECT_THAT(output, testing::ElementsAreArray(expected_output));
}
// Quantized tanh with Q0.15 input and Q0.15 output.
TEST(uKernels, QuantTanh0Test) {
const std::vector<int16_t> input = {
-145, 899, -176, -35, 264, 289, 8, 27, -37, -1310,
-120, 127, -16, 106, 370, -583, -299, 93, -548, 548,
653, -29, -53, 1058, -52, -164, -149, -635, 201, -1297,
-145, 899, -176, -35, 264, 289, 8, 27, -37, -1310,
-120, 127, -16, 106, 370, -583, -299, 93, -548, 548,
653, -29, -53, 1058, -52, -164, -149, -635, 201, -1297,
};
std::vector<int16_t> output(4 * 15, 0);
ApplyTanh0(input.data(), 4, 15, output.data());
const std::vector<int16_t> expected_output = {
-136, 904, -176, -40, 260, 292, 8, 28, -44, -1304,
-120, 120, -24, 112, 376, -576, -308, 88, -544, 544,
652, -32, -60, 1056, -56, -156, -144, -636, 192, -1300,
-136, 904, -176, -40, 260, 292, 8, 28, -44, -1304,
-120, 120, -24, 112, 376, -576, -308, 88, -544, 544,
652, -32, -60, 1056, -56, -156, -144, -636, 192, -1300,
};
EXPECT_THAT(output, testing::ElementsAreArray(expected_output));
}
// Quantized tanh with Q3.12 input and Q0.15 output.
TEST(uKernels, QuantTanh3Test) {
const std::vector<int16_t> input = {
-145, 899, -176, -35, 264, 289, 8, 27, -37, -1310,
-120, 127, -16, 106, 370, -583, -299, 93, -548, 548,
653, -29, -53, 1058, -52, -164, -149, -635, 201, -1297,
-145, 899, -176, -35, 264, 289, 8, 27, -37, -1310,
-120, 127, -16, 106, 370, -583, -299, 93, -548, 548,
653, -29, -53, 1058, -52, -164, -149, -635, 201, -1297,
};
std::vector<int16_t> output(4 * 15, 0);
ApplyTanh3(input.data(), 4, 15, output.data());
const std::vector<int16_t> expected_output = {
-1156, 7076, -1412, -276, 2104, 2308, 64, 220, -288, -10132,
-964, 1016, -120, 844, 2944, -4640, -2392, 736, -4352, 4352,
5180, -232, -428, 8276, -412, -1308, -1196, -5044, 1612, -10044,
-1156, 7076, -1412, -276, 2104, 2308, 64, 220, -288, -10132,
-964, 1016, -120, 844, 2944, -4640, -2392, 736, -4352, 4352,
5180, -232, -428, 8276, -412, -1308, -1196, -5044, 1612, -10044,
};
EXPECT_THAT(output, testing::ElementsAreArray(expected_output));
}
// Quantized tanh with Q4.11 input and Q0.15 output.
TEST(uKernels, QuantTanh4Test) {
const std::vector<int16_t> input = {
-5, 163, -31, -5, 54, 90, 1, 2, -4, -42, -8, 29, 0, 47, 150,
-26, -36, 9, -73, 25, 14, -2, -1, 29, -10, -12, -18, -29, 51, -92,
-5, 163, -31, -5, 54, 90, 1, 2, -4, -42, -8, 29, 0, 47, 150,
-26, -36, 9, -73, 25, 14, -2, -1, 29, -10, -12, -18, -29, 51, -92,
};
std::vector<int16_t> output(4 * 15, 0);
ApplyTanh4(input.data(), 4, 15, output.data());
const std::vector<int16_t> expected_output = {
-76, 2596, -496, -76, 856, 1436, 24, 36, -64, -672,
-120, 456, 0, 752, 2400, -412, -576, 148, -1168, 400,
216, -36, -24, 456, -164, -192, -292, -456, 820, -1476,
-76, 2596, -496, -76, 856, 1436, 24, 36, -64, -672,
-120, 456, 0, 752, 2400, -412, -576, 148, -1168, 400,
216, -36, -24, 456, -164, -192, -292, -456, 820, -1476,
};
EXPECT_THAT(output, testing::ElementsAreArray(expected_output));
}
// Quantized sigmoid with Q3.12 input and Q0.15 output.
TEST(uKernels, QuantSigmoidTest) {
const std::vector<int16_t> input = {
-10500, 1398, -6963, -7404, 485, -5401, -1757, -7668, -19248,
-9692, -24249, -17923, -15840, -10026, 5249, -89, 1787, -16178,
-6691, -19524, -13439, -24048, -1123, 32767, -17267, -3378, 823,
11482, -11139, 7508, -10500, 1398, -6963, -7404, 485, -5401,
-1757, -7668, -19248, -9692, -24249, -17923, -15840, -10026, 5249,
-89, 1787, -16178, -6691, -19524, -13439, -24048, -1123, 32767,
-17267, -3378, 823, 11482, -11139, 7508,
};
std::vector<int16_t> output(4 * 15, 0);
ApplySigmoid(input.data(), 4, 15, output.data());
const std::vector<int16_t> expected_output = {
2339, 19152, 5063, 4617, 17350, 6917, 12921, 4371, 299, 2813,
89, 409, 673, 2605, 25646, 16207, 19904, 615, 5353, 273,
1187, 91, 14153, 32756, 475, 9983, 18026, 30898, 2023, 28246,
2339, 19152, 5063, 4617, 17350, 6917, 12921, 4371, 299, 2813,
89, 409, 673, 2605, 25646, 16207, 19904, 615, 5353, 273,
1187, 91, 14153, 32756, 475, 9983, 18026, 30898, 2023, 28246,
};
EXPECT_THAT(output, testing::ElementsAreArray(expected_output));
}
// Quantized Multiply with 16bit output and 15 bit shift.
TEST(uKernels, QuantMul16bitOut15ShiftTest) {
const std::vector<int16_t> input1 = {
2491, 32767, -32768, 32767, -32768, 32767, 32767, -32768, -32768, 2157,
4545, 14835, 1285, 29498, 26788, 2907, 7877, 6331, 8775, 3001,
1399, 4683, 1437, 1853, 12163, 4927, 7977, 3001, 16612, 4791,
};
const std::vector<int16_t> input2 = {
-1156, 32767, -32768, -32768, 32767, 2308, 64, 220, -288, -10132,
-964, 1016, -120, 844, 2944, -4640, -2392, 736, -4352, 4352,
5180, -232, -428, 8276, -412, -1308, -1196, -5044, 1612, -10044,
};
std::vector<int16_t> output(2 * 15, 0);
CwiseMul(input1.data(), input2.data(), 2, 15, 15, output.data());
const std::vector<int16_t> expected_output = {
-88, 32766, -32768, -32767, -32767, 2308, 64, -220, 288, -667,
-134, 460, -5, 760, 2407, -412, -575, 142, -1165, 399,
221, -33, -19, 468, -153, -197, -291, -462, 817, -1469,
};
EXPECT_THAT(output, testing::ElementsAreArray(expected_output));
}
// Quantized Multiply with 16bit output and 19 bit shift.
TEST(uKernels, QuantMul16bitOut19ShiftTest) {
const std::vector<int16_t> input1 = {
2491, 32767, -32768, 32767, -32768, 32767, 32767, -32768, -32768, 2157,
4545, 14835, 1285, 29498, 26788, 2907, 7877, 6331, 8775, 3001,
1399, 4683, 1437, 1853, 12163, 4927, 7977, 3001, 16612, 4791,
};
const std::vector<int16_t> input2 = {
-1156, 32767, -32768, -32768, 32767, 2308, 64, 220, -288, -10132,
-964, 1016, -120, 844, 2944, -4640, -2392, 736, -4352, 4352,
5180, -232, -428, 8276, -412, -1308, -1196, -5044, 1612, -10044,
};
std::vector<int16_t> output(2 * 15, 0);
CwiseMul(input1.data(), input2.data(), 2, 15, 19, output.data());
const std::vector<int16_t> expected_output = {
-5, 2048, 2048, -2048, -2048, 144, 4, -14, 18, -42,
-8, 29, 0, 47, 150, -26, -36, 9, -73, 25,
14, -2, -1, 29, -10, -12, -18, -29, 51, -92,
};
EXPECT_THAT(output, testing::ElementsAreArray(expected_output));
}
// Quantized Multiply with arbitrary scale.
TEST(uKernels, QuantMul8bitArbitrarySclaeTest) {
// scale = 0.000028.
int multiplier = 1970324837;
int shift = -15;
const std::vector<int16_t> input1 = {
2491, 32767, -32768, 32767, -32768, 32767, 32767, -32768, -32768, 2157,
4545, 14835, 1285, 29498, 26788, 2907, 7877, 6331, 8775, 3001,
1399, 4683, 1437, 1853, 12163, 4927, 7977, 3001, 16612, 4791,
};
const std::vector<int16_t> input2 = {
-1156, 32767, -32768, -32768, 32767, 2308, 64, 220, -288, -10132,
-964, 1016, -120, 844, 2944, -4640, -2392, 736, -4352, 4352,
5180, -232, -428, 8276, -412, -1308, -1196, -5044, 1612, -10044,
};
std::vector<int8_t> output(2 * 15, 0);
CwiseMul(input1.data(), input2.data(), multiplier, shift, 2, 15, 3,
output.data());
const std::vector<int8_t> expected_output = {
-84, 127, 127, -128, -128, 127, 56, -128, 127, -128,
-126, 127, -7, 127, 127, -128, -128, 127, -128, 127,
127, -33, -20, 127, -128, -128, -128, -128, 127, -128,
};
EXPECT_THAT(output, testing::ElementsAreArray(expected_output));
}
// Quantized element wise Add with saturation.
TEST(uKernels, QuantAddTest) {
const std::vector<int16_t> input1 = {
2491, 32767, -32768, 32767, -32768, 32767, 32767, -32768, -32768, 20000,
-20000, 14835, 1285, 29498, 26788, 2907, 7877, 6331, 8775, 3001,
1399, 4683, 1437, 1853, 12163, 4927, 7977, 3001, 16612, 4791,
};
const std::vector<int16_t> input2 = {
-1156, 32767, -32768, -32768, 32767, 2308, 64, 220, -288, 20000,
-20000, 1016, -120, 844, 2944, -4640, -2392, 736, -4352, 4352,
5180, -232, -428, 8276, -412, -1308, -1196, -5044, 1612, -10044,
};
std::vector<int16_t> output(2 * 15, 0);
CwiseAdd(input1.data(), input2.data(), 2, 15, output.data());
const std::vector<int16_t> expected_output = {
1335, 32767, -32768, -1, -1, 32767, 32767, -32548, -32768, 32767,
-32768, 15851, 1165, 30342, 29732, -1733, 5485, 7067, 4423, 7353,
6579, 4451, 1009, 10129, 11751, 3619, 6781, -2043, 18224, -5253,
};
EXPECT_THAT(output, testing::ElementsAreArray(expected_output));
}
// Quantized clipping for 16 bit.
TEST(uKernels, QuantClip16Test) {
std::vector<int16_t> input = {
-10500, 1, -2, -7404, 200, -5401, -1757, -7668,
-19248, -9692, -24249, -17923, -15840, -10026, 5249, -89,
1787, -200, -6691, -19524, -13439, -24048, -1123, 32767,
-17267, -3378, 823, 11482, -11139, 7508,
};
CwiseClipping(input.data(), 300, 2, 15);
const std::vector<int16_t> expected_output = {
-300, 1, -2, -300, 200, -300, -300, -300, -300, -300,
-300, -300, -300, -300, 300, -89, 300, -200, -300, -300,
-300, -300, -300, 300, -300, -300, 300, 300, -300, 300,
};
EXPECT_THAT(input, testing::ElementsAreArray(expected_output));
}
// Quantized clipping for 8 bit.
TEST(uKernels, QuantClip8Test) {
std::vector<int8_t> input = {
4, -11, -5, -34, -10, -17, -27, -22, 15, 127, -128, 1, 3, 56, 3,
-21, 1, 9, -13, 10, 0, -1, -55, -40, 127, -128, 11, 4, 6, 32,
};
CwiseClipping(input.data(), 32, 2, 15);
const std::vector<int8_t> expected_output = {
4, -11, -5, -32, -10, -17, -27, -22, 15, 32, -32, 1, 3, 32, 3,
-21, 1, 9, -13, 10, 0, -1, -32, -32, 32, -32, 11, 4, 6, 32,
};
EXPECT_THAT(input, testing::ElementsAreArray(expected_output));
}
struct MatrixVectorData {
// Contains dense parameters.
std::vector<int8_t> matrix;
// Like matrix, but with about half of the parameters set to zero.
// Use this to create golden output for sparse matrix tests.
std::vector<int8_t> zeroed_matrix;
// zeroed_matrix described in sparse form.
std::vector<int8_t> sparse_matrix;
std::vector<uint8_t> ledger;
std::vector<int8_t> vectors;
std::vector<float> scale_factors;
std::vector<float> results;
// Per channel scale data.
std::vector<float> per_channel_scales;
std::vector<int32_t> input_offsets;
int rows;
int cols;
int batch;
};
MatrixVectorData SetupMatrixVectorData(int rows, int cols, int batch,
bool negative = false,
bool is_per_channel = false,
bool init_to_one = false) {
MatrixVectorData data;
data.rows = rows;
data.cols = cols;
data.batch = batch;
for (int i = 0; i < rows * cols; i++) {
int sign = 1;
if ((i % 3) == 0 && negative) sign = -1;
data.matrix.push_back(sign * (i % 70));
}
for (int i = 0; i < cols * batch; i++) {
int sign = 1;
if ((i % 5) == 0 && negative) sign = -1;
data.vectors.push_back(sign * (i % 50));
}
data.scale_factors = {1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8};
data.results.resize(rows * batch, init_to_one ? 1 : 0);
data.zeroed_matrix = data.matrix;
// Make a sparsification ledger.
for (int i = 0; i < rows; i++) {
int max_chunks = cols / 16;
int selected_chunks = (max_chunks / 2);
bool row_is_odd = (i % 2) > 0;
bool max_chunks_is_odd = (max_chunks % 2) > 0;
data.ledger.push_back(selected_chunks);
if (max_chunks_is_odd && row_is_odd) {
selected_chunks++;
}
// In odd rows, use odd chunk indexes.
// In even rows, use even chunk indexes.
for (int j = 0; j < max_chunks; j++) {
const int chunk_start = i * cols + (j * 16);
const int chunk_end = i * cols + (j * 16) + 16;
if ((j % 2) == (i % 2)) {
// Copy this chunk into the sparse matrix.
data.ledger.push_back(j);
for (int k = chunk_start; k < chunk_end; k++) {
data.sparse_matrix.push_back(data.matrix[k]);
}
} else {
// Zero this part out of zeroed_matrix.
for (int k = chunk_start; k < chunk_end; k++) {
data.zeroed_matrix[k] = 0;
}
}
}
}
if (is_per_channel) {
for (int i = 0; i < rows; i++) {
if (i % 2 == 0) {
data.per_channel_scales.push_back(0.5);
} else {
data.per_channel_scales.push_back(1.0);
}
}
for (int i = 0; i < batch; i++) {
for (int j = 0; j < cols; j++) {
data.vectors[i * cols + j] += i;
}
data.input_offsets.push_back(i);
}
}
return data;
}
std::vector<float> TestDotprodMatrixBatchVectorMultiply(
int rows, int cols, int batch, bool negative = false,
bool init_to_one = false) {
MatrixVectorData data =
SetupMatrixVectorData(rows, cols, batch, negative, false, init_to_one);
// All partial sums in this computation are small enough to fit in the
// mantissa of a float, and the scale factors are all integers, so we expect
// an exact result.
MatrixBatchVectorMultiplyAccumulate(
data.matrix.data(), rows, cols, data.vectors.data(),
data.scale_factors.data(), batch, &data.results[0], 1);
return data.results;
}
std::vector<float> TestSparseDotprodMatrixBatchVectorMultiply(
int rows, int cols, int batch, bool negative = false) {
MatrixVectorData data = SetupMatrixVectorData(rows, cols, batch, negative);
SparseMatrixBatchVectorMultiplyAccumulate(
data.sparse_matrix.data(), data.ledger.data(), rows, cols,
data.vectors.data(), data.scale_factors.data(), batch, &data.results[0],
1);
return data.results;
}
std::vector<float> TestPerChannelDotprodMatrixBatchVectorMultiply(
int rows, int cols, int batch, bool negative = false,
bool is_per_channel = true) {
MatrixVectorData data =
SetupMatrixVectorData(rows, cols, batch, negative, is_per_channel);
MatrixBatchVectorMultiplyAccumulate(
data.matrix.data(), rows, cols, data.vectors.data(),
data.scale_factors.data(), batch, &data.results[0], 1,
data.per_channel_scales.data(), data.input_offsets.data());
return data.results;
}
TEST(uKernels, DotprodMatrixBatchVectorMultiplyAccumulateTest) {
ASSERT_THAT(TestDotprodMatrixBatchVectorMultiply(4, 16, 1),
testing::ElementsAre(1240, 3160, 5080, 7000));
ASSERT_THAT(TestDotprodMatrixBatchVectorMultiply(4, 32, 2),
testing::ElementsAre(10416, 26288, 8490, 23312, 18276, 70756,
37416, 60916));
ASSERT_THAT(TestDotprodMatrixBatchVectorMultiply(4, 32, 3),
testing::ElementsAre(10416, 26288, 8490, 23312, 18276, 70756,
37416, 60916, 52080, 142704, 55878, 125712));
ASSERT_THAT(TestDotprodMatrixBatchVectorMultiply(8, 1024, 3),
testing::ElementsAreArray(
{841094, 853168, 866642, 840286, 860760, 862754,
843678, 872552, 1724476, 1769072, 1747588, 1738844,
1758240, 1742916, 1761612, 1755808, 2506896, 2564262,
2629188, 2515824, 2598390, 2569236, 2537352, 2645118}));
const bool kNegative = true;
ASSERT_THAT(TestDotprodMatrixBatchVectorMultiply(4, 64, 1, kNegative),
testing::ElementsAre(13696, 6904, 7764, 11806));
ASSERT_THAT(
TestDotprodMatrixBatchVectorMultiply(4, 32, 2, kNegative),
testing::ElementsAre(3436, 3522, 1590, 6972, 2516, 20520, 456, 10628));
// Initialize the results vector with 1s to verify that the code adds
// to the results vector instead of zero-ing it first.
const bool kInitToOne = true;
ASSERT_THAT(
TestDotprodMatrixBatchVectorMultiply(4, 32, 2, kNegative, kInitToOne),
testing::ElementsAre(3437, 3523, 1591, 6973, 2517, 20521, 457, 10629));
}
TEST(uKernels, PerChannelDotprodMatrixBatchVectorMultiplyAccumulateTest) {
ASSERT_THAT(TestPerChannelDotprodMatrixBatchVectorMultiply(4, 16, 1),
testing::ElementsAre(1240 / 2, 3160, 5080 / 2, 7000));
ASSERT_THAT(TestPerChannelDotprodMatrixBatchVectorMultiply(4, 32, 2),
testing::ElementsAre(10416 / 2, 26288, 8490 / 2, 23312, 18276 / 2,
70756, 37416 / 2, 60916));
ASSERT_THAT(TestPerChannelDotprodMatrixBatchVectorMultiply(4, 32, 3),
testing::ElementsAre(10416 / 2, 26288, 8490 / 2, 23312, 18276 / 2,
70756, 37416 / 2, 60916, 52080 / 2, 142704,
55878 / 2, 125712));
ASSERT_THAT(
TestPerChannelDotprodMatrixBatchVectorMultiply(8, 1024, 3),
testing::ElementsAreArray(
{841094 / 2, 853168, 866642 / 2, 840286, 860760 / 2, 862754,
843678 / 2, 872552, 1724476 / 2, 1769072, 1747588 / 2, 1738844,
1758240 / 2, 1742916, 1761612 / 2, 1755808, 2506896 / 2, 2564262,
2629188 / 2, 2515824, 2598390 / 2, 2569236, 2537352 / 2, 2645118}));
}
TEST(uKernels, DotprodMatrixBatchFourVectorMultiplyAccumulateDotprodTest) {
ASSERT_THAT(TestDotprodMatrixBatchVectorMultiply(2, 16, 4),
testing::ElementsAreArray(
{1240, 3160, 6320, 18352, 15240, 45576, 4200, 16232}));
ASSERT_THAT(TestDotprodMatrixBatchVectorMultiply(2, 64, 4),
testing::ElementsAreArray({45794, 38948, 88536, 84252, 157626,
165312, 209864, 246128}));
ASSERT_THAT(
TestDotprodMatrixBatchVectorMultiply(2, 64, 8),
testing::ElementsAreArray({45794, 38948, 88536, 84252, 157626, 165312,
209864, 246128, 219700, 195550, 279684, 278928,
413616, 445662, 374896, 365952}));
ASSERT_THAT(
TestDotprodMatrixBatchVectorMultiply(4, 64, 8),
testing::ElementsAreArray(
{45794, 38948, 34622, 32816, 88536, 84252, 85008, 90804,
157626, 165312, 180558, 203364, 209864, 246128, 236472, 208896,
219700, 195550, 184000, 185050, 279684, 278928, 293292, 322776,
413616, 445662, 495348, 513674, 374896, 365952, 321168, 296544}));
ASSERT_THAT(
TestDotprodMatrixBatchVectorMultiply(16, 1024, 4),
testing::ElementsAreArray(
{841094, 853168, 866642, 840286, 860760, 862754, 843678,
872552, 837586, 851270, 877414, 834188, 863062, 857846,
841780, 879054, 1724476, 1769072, 1747588, 1738844, 1758240,
1742916, 1761612, 1755808, 1737684, 1750780, 1747356, 1754152,
1748348, 1753324, 1743320, 1754316, 2506896, 2564262, 2629188,
2515824, 2598390, 2569236, 2537352, 2645118, 2508444, 2571480,
2610576, 2510442, 2618208, 2566584, 2544570, 2614536, 3458904,
3502688, 3474792, 3505976, 3499360, 3488264, 3485848, 3512832,
3500616, 3482520, 3489624, 3469008, 3495992, 3524376, 3465680,
3526264}));
ASSERT_THAT(
TestDotprodMatrixBatchVectorMultiply(4, 128, 4),
testing::ElementsAreArray({87920, 80024, 92288, 103712, 228148, 224820,
233812, 213124, 271284, 271788, 332772, 328236,
419328, 431328, 411968, 417248}));
ASSERT_THAT(
TestDotprodMatrixBatchVectorMultiply(4, 128, 8),
testing::ElementsAreArray(
{87920, 80024, 92288, 103712, 228148, 224820, 233812, 213124,
271284, 271788, 332772, 328236, 419328, 431328, 411968, 417248,
482680, 523840, 560800, 593560, 563940, 609924, 566868, 644772,
743708, 857780, 818972, 823284, 708384, 695008, 730912, 872096}));
const bool kNegative = true;
EXPECT_THAT(TestDotprodMatrixBatchVectorMultiply(1, 16, 1, kNegative),
testing::ElementsAre(450));
EXPECT_THAT(TestDotprodMatrixBatchVectorMultiply(2, 64, 8, kNegative),
testing::ElementsAreArray({13696, 6904, 9952, 12368, 22848, 61632,
40424, 46776, 57630, 38670, 62976,
49824, 39032, 71988, 60128, 148992}));
std::vector<float> results =
TestDotprodMatrixBatchVectorMultiply(256, 1024, 8);
int64_t sum = 0;
for (int i = 0; i < results.size(); i++) {
sum += static_cast<int64_t>(results[i]);
}
EXPECT_EQ(7980076336, sum);
}
TEST(uKernels,
PerChannelDotprodMatrixBatchFourVectorMultiplyAccumulateDotprodTest) {
ASSERT_THAT(
TestPerChannelDotprodMatrixBatchVectorMultiply(16, 1024, 4),
testing::ElementsAreArray(
{841094 / 2, 853168, 866642 / 2, 840286, 860760 / 2, 862754,
843678 / 2, 872552, 837586 / 2, 851270, 877414 / 2, 834188,
863062 / 2, 857846, 841780 / 2, 879054, 1724476 / 2, 1769072,
1747588 / 2, 1738844, 1758240 / 2, 1742916, 1761612 / 2, 1755808,
1737684 / 2, 1750780, 1747356 / 2, 1754152, 1748348 / 2, 1753324,
1743320 / 2, 1754316, 2506896 / 2, 2564262, 2629188 / 2, 2515824,
2598390 / 2, 2569236, 2537352 / 2, 2645118, 2508444 / 2, 2571480,
2610576 / 2, 2510442, 2618208 / 2, 2566584, 2544570 / 2, 2614536,
3458904 / 2, 3502688, 3474792 / 2, 3505976, 3499360 / 2, 3488264,
3485848 / 2, 3512832, 3500616 / 2, 3482520, 3489624 / 2, 3469008,
3495992 / 2, 3524376, 3465680 / 2, 3526264}));
ASSERT_THAT(TestPerChannelDotprodMatrixBatchVectorMultiply(4, 128, 4),
testing::ElementsAreArray(
{87920 / 2, 80024, 92288 / 2, 103712, 228148 / 2, 224820,
233812 / 2, 213124, 271284 / 2, 271788, 332772 / 2, 328236,
419328 / 2, 431328, 411968 / 2, 417248}));
ASSERT_THAT(TestPerChannelDotprodMatrixBatchVectorMultiply(4, 128, 8),
testing::ElementsAreArray(
{87920 / 2, 80024, 92288 / 2, 103712, 228148 / 2, 224820,
233812 / 2, 213124, 271284 / 2, 271788, 332772 / 2, 328236,
419328 / 2, 431328, 411968 / 2, 417248, 482680 / 2, 523840,
560800 / 2, 593560, 563940 / 2, 609924, 566868 / 2, 644772,
743708 / 2, 857780, 818972 / 2, 823284, 708384 / 2, 695008,
730912 / 2, 872096}));
}
TEST(uKernels, DotprodSparseMatrixBatchVectorMultiplyAccumulate) {
EXPECT_THAT(TestSparseDotprodMatrixBatchVectorMultiply(1, 16, 1),
testing::ElementsAre(0));
EXPECT_THAT(TestSparseDotprodMatrixBatchVectorMultiply(1, 32, 1),
testing::ElementsAre(1240));
EXPECT_THAT(TestSparseDotprodMatrixBatchVectorMultiply(1, 64, 1),
testing::ElementsAre(26544));
EXPECT_THAT(TestSparseDotprodMatrixBatchVectorMultiply(1, 64, 2),
testing::ElementsAre(26544, 24344));
EXPECT_THAT(TestSparseDotprodMatrixBatchVectorMultiply(4, 64, 4),
testing::ElementsAreArray(
{26544, 15866, 22140, 11408, 24344, 53248, 42704, 39900,
48000, 94146, 101892, 81876, 87712, 105160, 148304, 75936}));
const bool kNegative = true;
EXPECT_THAT(TestSparseDotprodMatrixBatchVectorMultiply(1, 64, 1, kNegative),
testing::ElementsAre(8764));
EXPECT_THAT(TestSparseDotprodMatrixBatchVectorMultiply(2, 64, 2, kNegative),
testing::ElementsAre(8764, 5196, 7204, 11148));
}
#ifdef __ANDROID__
TEST(uKernels, MatrixBatchVectorMultiplyAccumulateSymmetricQuantizedTest) {
// Note we use 29 columns as this exercises all the neon kernel: the
// 16-block SIMD code, the 8-block postamble, and the leftover postamble.
const int a_rows = 4, a_cols = 29;
const int kWeightsPerUint32 = 4;
/* clang-format off */
const float a_float_data[] = {
/* 1st row */
1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.1, 11.11, 12.12, 13.13,
14.14, 15.15, 16.16, 17.17, 18.18, 19.19, 20.2, 21.21, 22.22, 23.23,
24.24, 25.25, 26.26, 27.27, 28.28, 0,
/* 2nd row */
-1.1, -2.2, -3.3, -4.4, -5.5, -6.6, -7.7, -8.8, -9.9, -10.1, -11.11,
-12.12, -13.13, -14.14, -15.15, -16.16, -17.17, -18.18, -19.19, -20.2,
-21.21, -22.22, -23.23, -24.24, -25.25, -26.26, -27.27, -28.28, 0,
/* 3rd row */
1.1, -2.2, 3.3, -4.4, 5.5, -6.6, 7.7, -8.8, 9.9, -10.1, 11.11, -12.12,
13.13, -14.14, 15.15, -16.16, 17.17, -18.18, 19.19, -20.2, 21.21, -22.22,
23.23, -24.24, 25.25, -26.26, 27.27, -28.28, 0,
/* 4th row */
-1.1, 2.2, -3.3, 4.4, -5.5, 6.6, -7.7, 8.8, -9.9, 10.1, -11.11, 12.12,
-13.13, 14.14, -15.15, 16.16, -17.17, 18.18, -19.19, 20.2, -21.21, 22.22,
-23.23, 24.24, -25.25, 26.26, -27.27, 28.28, 0};
int8_t* a_int8_data = reinterpret_cast<int8_t*>(
aligned_malloc(a_rows * a_cols, kWeightsPerUint32));
float a_min, a_max;
float scaling_factor_a;
SymmetricQuantizeFloats(a_float_data, a_rows * a_cols, a_int8_data, &a_min,
&a_max, &scaling_factor_a);
const int8_t expected_a_int8_data[] = {
/* 1st row */
5, 10, 15, 20, 25, 30, 35, 40, 44, 45, 50, 54, 59, 64, 68, 73, 77, 82, 86,
91, 95, 100, 104, 109, 113, 118, 122, 127, 0,
/* 2nd row */
-5, -10, -15, -20, -25, -30, -35, -40, -44, -45, -50, -54, -59, -64, -68,
-73, -77, -82, -86, -91, -95, -100, -104, -109, -113, -118, -122, -127, 0,
/* 3rd row */
5, -10, 15, -20, 25, -30, 35, -40, 44, -45, 50, -54, 59, -64, 68, -73, 77,
-82, 86, -91, 95, -100, 104, -109, 113, -118, 122, -127, 0,
/* 4th row */
-5, 10, -15, 20, -25, 30, -35, 40, -44, 45, -50, 54, -59, 64, -68, 73, -77,
82, -86, 91, -95, 100, -104, 109, -113, 118, -122, 127, 0,
};
for (int i = 0; i < a_rows * a_cols; ++i) {
EXPECT_EQ(expected_a_int8_data[i], a_int8_data[i]);
}
const int b_rows = 29, b_cols = 1, batches = 2;
const float b_float_data[] = {
/* batch 1 */
1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0,
1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0,
1.0,
/* batch 2 */
2.5, -2.1, 3.0, -1.3, 1.3, -1.1, 2.0, -1.7, 1.9, -1.5, 0.5, -0.7, 0.8, -0.3,
2.8, -2.8, 1.1, -2.3, 1.9, -1.9, 2.1, -0.5, 2.4, -0.1, 1.0, -2.5, 0.7, -1.9,
0.2,
};
// Quantized values of B:
int8_t b_int8_data[b_rows * b_cols * batches];
float b_min, b_max;
float scaling_factor_b[batches];
SymmetricQuantizeFloats(b_float_data, b_rows * b_cols, b_int8_data, &b_min,
&b_max, &scaling_factor_b[0]);
SymmetricQuantizeFloats(&b_float_data[b_rows * b_cols], b_rows * b_cols,
&b_int8_data[b_rows * b_cols], &b_min, &b_max,
&scaling_factor_b[1]);
const int8_t expected_b_int8_data[] = {
/* batch 1 */
127, -127, 127, -127, 127, -127, 127, -127, 127, -127, 127, -127, 127, -127,
127, -127, 127, -127, 127, -127, 127, -127, 127, -127, 127, -127, 127, -127,
127,
/* batch 2 */
106, -89, 127, -55, 55, -47, 85, -72, 80, -64, 21, -30, 34, -13, 119, -119,
47, -97, 80, -80, 89, -21, 102, -4, 42, -106, 30, -80, 8,
};
/* clang-format on */
for (int i = 0; i < b_rows * b_cols * batches; ++i) {
EXPECT_EQ(expected_b_int8_data[i], b_int8_data[i]);
}
// Full float operation results in:
// -13.69, 13.69, 414.11, -414.11
// -6.325, 6.325, 631.263, -631.263
float c_float_data[a_rows * b_cols * batches];
for (int i = 0; i < a_rows * b_cols * batches; ++i) {
c_float_data[i] = 0.0;
}
// Testing product.
const float scaling_factor_c[2] = {
scaling_factor_a * scaling_factor_b[0],
scaling_factor_a * scaling_factor_b[1],
};
MatrixBatchVectorMultiplyAccumulate(a_int8_data, a_rows, a_cols, b_int8_data,
scaling_factor_c, batches, c_float_data,
/*result_stride=*/1);
// Assert we obtain the expected recovered float values.
const float expected_c_float_data[] = {
-14.474, 14.474, 414.402, -414.402, -6.92228, 6.92228, 632.042, -632.042,
};
for (int i = 0; i < a_rows * b_cols * batches; ++i) {
EXPECT_NEAR(expected_c_float_data[i], c_float_data[i], 0.001);
}
aligned_free(a_int8_data);
}
#endif // __ANDROID__
TEST(uKernels, SparseMatrixBatchVectorMultiplyAccumulateTest) {
const int kRow = 4;
const int kCol = 48;
const int kBatch = 2;
/* clang-format off */
float matrix[kRow * kCol] = {
/* 1st row */
1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.1, 11.11, 12.12, 13.13,
14.14, 15.15, 16.16, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 33.33, 34.34, 35.35, 36.36, 37.37, 38.38,
39.39, 40.40, 41.41, 42.42, 43.43, 44.44, 0, 0, 0, 0,
/* 2nd row */
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, -17.17, -18.18, -19.19, -20.2, -21.21, -22.22, -23.23, -24.24,
-25.25, -26.26, -27.27, -28.28, 0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0, 0, 0,
/* 3rd row */
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 17.17, -18.18, 19.19, -20.2, 21.21, -22.22, 23.23, -24.24, 25.25,
-26.26, 27.27, -28.28, 0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0, 0, 0,
/* 4th row */
-1.1, 2.2, -3.3, 4.4, -5.5, 6.6, -7.7, 8.8, -9.9, 10.1, -11.11, 12.12,
-13.13, 14.14, -15.15, 16.16, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -33.33, 34.34, -35.35, 36.36, -37.37,
38.38, -39.39, 40.40, -41.41, 42.42, -43.43, 44.44, 0, 0, 0, 0};
// BCSR format of the above matrix.
float matrix_values[] = {
/* 1st row */
1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.1, 11.11, 12.12, 13.13,
14.14, 15.15, 16.16, 33.33, 34.34, 35.35, 36.36, 37.37, 38.38, 39.39,
40.40, 41.41, 42.42, 43.43, 44.44, 0, 0, 0, 0,
/* 2nd row */
-17.17, -18.18, -19.19, -20.2, -21.21, -22.22, -23.23, -24.24, -25.25,
-26.26, -27.27, -28.28, 0, 0.0, 0.0, 0.0,
/* 3rd row */
17.17, -18.18, 19.19, -20.2, 21.21, -22.22, 23.23, -24.24, 25.25, -26.26,
27.27, -28.28, 0, 0.0, 0.0, 0.0,
/* 4th row */
-1.1, 2.2, -3.3, 4.4, -5.5, 6.6, -7.7, 8.8, -9.9, 10.1, -11.11, 12.12,
-13.13, 14.14, -15.15, 16.16, -33.33, 34.34, -35.35, 36.36, -37.37, 38.38,
-39.39, 40.40, -41.41, 42.42, -43.43, 44.44, 0, 0, 0, 0};
uint8_t ledger[] = {
2, 0, 2, // 1st row
1, 1, // 2nd row
1, 1, // 3rd row
2, 0, 2 // 4th row
};
float vector[kBatch * kCol] = {
/* 1st batch */
1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0,
1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0,
1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0,
1.0, -1.0, 1.0, -1.0, 1.0, -1.0,
/* 2nd batch */
2.5, 0.0, -2.1, 0.0, 3.0, 0.0, -1.3, 0.0, 1.3, 0.0, -1.1, 0.0, 2.0, 0.0,
-1.7, 0.0, 1.9, 0.0, -1.5, 0.0, 0.5, 0.0, -0.7, 0.0, 0.8, 0.0, -0.3, 0.0,
2.8, 0.0, -2.8, 0.0, 1.1, -2.3, 1.9, -1.9, 2.1, -0.5, 2.4, -0.1, 1.0, -2.5,
0.7, -1.9, 0.2, 0.0, 0.1, 0.2,
};
/* clang-format on */
std::vector<float> dense_output(kRow * kBatch, 0.0);
MatrixBatchVectorMultiplyAccumulate(matrix, kRow, kCol, vector, kBatch,
dense_output.data(), /*result_stride=*/1);
EXPECT_THAT(dense_output, ElementsAreArray(ArrayFloatNear(
{-13.69, 6.06001, 272.7, -608.03, -9.66602,
-10.201, 10.201, -713.897949},
1e-4)));
std::vector<float> sparse_output(kRow * kBatch, 0.0);
SparseMatrixBatchVectorMultiplyAccumulate(
matrix_values, ledger, kRow, kCol, vector, kBatch, sparse_output.data(),
/*result_stride=*/1);
EXPECT_THAT(sparse_output,
ElementsAreArray(ArrayFloatNear(dense_output, 1e-4)));
}
#ifdef __ANDROID__
TEST(uKernels,
SparseMatrixBatchVectorMultiplyAccumulateSymmetricQuantizedTest) {
const int kRow = 4;
const int kCol = 48;
const int kBatch = 2;
/* clang-format off */
const int8_t quantized_matrix[] = {
/* 1st row */
3, 6, 9, 13, 16, 19, 22, 25, 28, 29, 32, 35, 38, 40, 43, 46, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 98, 101, 104, 107, 110, 113, 115,
118, 121, 124, 127, 0, 0, 0, 0,
/* 2nd row */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -49, -52, -55, -58, -61,
-64, -66, -69, -72, -75, -78, -81, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
/* 3rd row */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 49, -52, 55, -58, 61, -64,
66, -69, 72, -75, 78, -81, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0,
/* 4th row */
-3, 6, -9, 13, -16, 19, -22, 25, -28, 29, -32, 35, -38, 40, -43, 46, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -95, 98, -101, 104, -107, 110,
-113, 115, -118, 121, -124, 127, 0, 0, 0, 0,
};
const int8_t quantized_matrix_values[] = {
/* 1st row */
3, 6, 9, 13, 16, 19, 22, 25, 28, 29, 32, 35, 38, 40, 43, 46, 95, 98, 101,
104, 107, 110, 113, 115, 118, 121, 124, 127, 0, 0, 0, 0,
/* 2nd row */
-49, -52, -55, -58, -61, -64, -66, -69, -72, -75, -78, -81, 0, 0, 0, 0,
/* 3rd row */
49, -52, 55, -58, 61, -64, 66, -69, 72, -75, 78, -81, 0, 0, 0, 0,
/* 4th row */
-3, 6, -9, 13, -16, 19, -22, 25, -28, 29, -32, 35, -38, 40, -43, 46, -95,
98, -101, 104, -107, 110, -113, 115, -118, 121, -124, 127, 0, 0, 0, 0,
};
uint8_t ledger[] = {
2, 0, 2, // 1st row
1, 1, // 2nd row
1, 1, // 3rd row
2, 0, 2 // 4th row
};
float matrix_scaling_factor = 0.349921;
const int8_t quantized_vector[] = {
/* 1st batch */
127, -127, 127, -127, 127, -127, 127, -127, 127, -127, 127, -127, 127,
-127, 127, -127, 127, -127, 127, -127, 127, -127, 127, -127, 127, -127,
127, -127, 127, -127, 127, -127, 127, -127, 127, -127, 127, -127, 127,
-127, 127, -127, 127, -127, 127, -127, 127, -127,
/* 2nd batch */
106, 0, -89, 0, 127, 0, -55, 0, 55, 0, -47, 0, 85, 0, -72, 0, 80, 0,
-64, 0, 21, 0, -30, 0, 34, 0, -13, 0, 119, 0, -119, 0, 47, -97, 80, -80,
89, -21, 102, -4, 42, -106, 30, -80, 8, 1, 2, 3,
};
float vector_scaling_factor[2] = {0.00787402, 0.023622};
/* clang-format on */
float result_scaling_factor[2] = {
matrix_scaling_factor * vector_scaling_factor[0],
matrix_scaling_factor * vector_scaling_factor[1],
};
std::vector<float> dense_output(kRow * kBatch, 0.0);
MatrixBatchVectorMultiplyAccumulate(quantized_matrix, kRow, kCol,
quantized_vector, result_scaling_factor,
kBatch, dense_output.data(),
/*result_stride=*/1);
EXPECT_THAT(dense_output,
ElementsAreArray(ArrayFloatNear(
{-13.646927, 6.298582, 272.938538, -607.813110, -6.637464,
-9.381721, 9.381721, -713.845642})));
std::vector<float> sparse_output(kRow * kBatch, 0.0);
SparseMatrixBatchVectorMultiplyAccumulate(
quantized_matrix_values, ledger, kRow, kCol, quantized_vector,
result_scaling_factor, kBatch, sparse_output.data(),
/*result_stride=*/1);
EXPECT_THAT(sparse_output,
ElementsAreArray(ArrayFloatNear(
{-13.646927, 6.298582, 272.938538, -607.813110, -6.637464,
-9.381721, 9.381721, -713.845642})));
}
#endif // __ANDROID__
TEST(uKernels, VectorVectorCwiseProductTest) {
constexpr int kVectorSize = 10;
static float input1[kVectorSize] = {0.0, -0.5, 1.0, -1.5, 2.0,
-2.5, 3.0, -3.5, 4.0, -4.5};
static float input2[kVectorSize] = {0.1, -0.1, 0.1, -0.1, 0.1,
-0.1, 0.1, -0.1, 0.1, -0.1};
std::vector<float> output(kVectorSize);
VectorVectorCwiseProduct(input1, input2, kVectorSize, output.data());
EXPECT_THAT(output,
ElementsAreArray(ArrayFloatNear(
{0.0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45})));
}
TEST(uKernels, VectorVectorCwiseProductAccumulateTest) {
constexpr int kVectorSize = 10;
static float input1[kVectorSize] = {0.0, -0.5, 1.0, -1.5, 2.0,
-2.5, 3.0, -3.5, 4.0, -4.5};
static float input2[kVectorSize] = {0.1, -0.1, 0.1, -0.1, 0.1,
-0.1, 0.1, -0.1, 0.1, -0.1};
std::vector<float> output(kVectorSize);
std::fill(output.begin(), output.end(), 1.0);
VectorVectorCwiseProductAccumulate(input1, input2, kVectorSize,
output.data());
EXPECT_THAT(output,
ElementsAreArray(ArrayFloatNear(
{1.0, 1.05, 1.1, 1.15, 1.2, 1.25, 1.3, 1.35, 1.4, 1.45})));
}
TEST(uKernels, VectorBatchVectorAddTest) {
constexpr int kVectorSize = 3;
constexpr int kBatchSize = 2;
static float input[kVectorSize] = {0.0, -0.5, 1.0};
std::vector<float> output = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0};
VectorBatchVectorAdd(input, kVectorSize, kBatchSize, output.data());
EXPECT_THAT(output,
testing::ElementsAreArray({1.0, 1.5, 4.0, 4.0, 4.5, 7.0}));
}
TEST(uKernels, VectorBatchVectorAssignTest) {
constexpr int kVectorSize = 5;
constexpr int kBatchSize = 3;
static float input[kVectorSize] = {0.0, -0.5, 1.0, -1.5, 2.0};
std::vector<float> output(kVectorSize * kBatchSize);
VectorBatchVectorAssign(input, kVectorSize, kBatchSize, output.data());
EXPECT_THAT(output, ElementsAreArray(ArrayFloatNear(
{0.0, -0.5, 1.0, -1.5, 2.0, 0.0, -0.5, 1.0, -1.5, 2.0,
0.0, -0.5, 1.0, -1.5, 2.0})));
}
TEST(uKernels, ApplySigmoidToVectorTest) {
constexpr int kVectorSize = 5;
static float input[kVectorSize] = {0.0, -0.5, 1.0, -1.5, 2.0};
std::vector<float> output(kVectorSize);
ApplySigmoidToVector(input, kVectorSize, output.data());
EXPECT_THAT(output, ElementsAreArray(ArrayFloatNear(
{0.5, 0.377541, 0.731059, 0.182426, 0.880797})));
}
TEST(uKernels, ApplyActivationToVectorTest) {
constexpr int kVectorSize = 5;
static float input[kVectorSize] = {0.0, -0.5, 1.0, -1.5, 2.0};
std::vector<float> output(kVectorSize);
ApplyActivationToVector(input, kVectorSize, kTfLiteActRelu, output.data());
EXPECT_THAT(output,
ElementsAreArray(ArrayFloatNear({0.0, 0.0, 1.0, 0.0, 2.0})));
ApplyActivationToVector(input, kVectorSize, kTfLiteActTanh, output.data());
EXPECT_THAT(output, ElementsAreArray(ArrayFloatNear(
{0.0, -0.462117, 0.761594, -0.905148, 0.964028})));
}
TEST(uKernels, Sub1VectorTest) {
constexpr int kVectorSize = 5;
static float input[kVectorSize] = {0.0, -0.5, 1.0, -1.5, 2.0};
std::vector<float> output(kVectorSize);
Sub1Vector(input, kVectorSize, output.data());
EXPECT_THAT(output,
ElementsAreArray(ArrayFloatNear({1.0, 1.5, 0.0, 2.5, -1.0})));
}
TEST(uKernels, Sub1VectorInt16Test) {
constexpr int kVectorSize = 30;
static int16_t input[kVectorSize] = {
32760, 300, 1, 2, 3, 4, 5, 6, 300, 1000,
32767, 32000, 300, 1, 2, 3, 4, 5, 56, 300,
1000, 32767, 32761, 1300, 1, 2, 3, 4, 5, 6,
};
std::vector<int16_t> output(kVectorSize);
Sub1Vector(input, kVectorSize, output.data());
EXPECT_THAT(
output,
testing::ElementsAreArray({
7, 32467, 32766, 32765, 32764, 32763, 32762, 32761, 32467, 31767,
0, 767, 32467, 32766, 32765, 32764, 32763, 32762, 32711, 32467,
31767, 0, 6, 31467, 32766, 32765, 32764, 32763, 32762, 32761,
}));
}
TEST(uKernels, VectorBatchVectorCwiseProductAccumulate) {
constexpr int kVectorSize = 29;
constexpr int kBatchSize = 4;
static float input[kVectorSize] = {
1.1f, 2.2f, 3.3f, 4.4f, 5.5f, 6.6f, 7.7f, 8.8f,
9.9f, 10.10f, 11.11f, 12.12f, 13.13f, 14.14f, 15.15f, 16.16f,
17.17f, 18.18f, 19.19f, 20.20f, 21.21f, 22.22f, 23.23f, 24.24f,
25.25f, 26.26f, 27.27f, 28.28f, 0.0f};
std::vector<float> output = {
/* batch 0 */
1.1f, 2.2f, 3.3f, 4.4f, 5.5f, 6.6f, 7.7f, 8.8f, 9.9f, 10.10f, 11.11f,
12.12f, 13.13f, 14.14f, 15.15f, 16.16f, 17.17f, 18.18f, 19.19f, 20.20f,
21.21f, 22.22f, 23.23f, 24.24f, 25.25f, 26.26f, 27.27f, 28.28f, 0.0f,
/* batch 1 */
-1.1f, -2.2f, -3.3f, -4.4f, -5.5f, -6.6f, -7.7f, -8.8f, -9.9f, -10.10f,
-11.11f, -12.12f, -13.13f, -14.14f, -15.15f, -16.16f, -17.17f, -18.18f,
-19.19f, -20.20f, -21.21f, -22.22f, -23.23f, -24.24f, -25.25f, -26.26f,
-27.27f, -28.28f, 0.0f,
/* batch 2 */
1.1f, -2.2f, 3.3f, -4.4f, 5.5f, -6.6f, 7.7f, -8.8f, 9.9f, -10.10f, 11.11f,
-12.12f, 13.13f, -14.14f, 15.15f, -16.16f, 17.17f, -18.18f, 19.19f,
-20.20f, 21.21f, -22.22f, 23.23f, -24.24f, 25.25f, -26.26f, 27.27f,
-28.28f, 0.0f,
/* batch 3 */
-1.1f, 2.2f, -3.3f, 4.4f, -5.5f, 6.6f, -7.7f, 8.8f, -9.9f, 10.10f,
-11.11f, 12.12f, -13.13f, 14.14f, -15.15f, 16.16f, -17.17f, 18.18f,
-19.19f, 20.20f, -21.21f, 22.22f, -23.23f, 24.24f, -25.25f, 26.26f,
-27.27f, 28.28f, 0.0f};
VectorBatchVectorCwiseProductAccumulate(input, kVectorSize, output.data(),
kBatchSize, output.data());
// Expect output = input * output + output.
const std::vector<float> expected_output = {
/* batch 0 */
2.31f, 7.04f, 14.19f, 23.76f, 35.75f, 50.16f, 66.99f, 86.24f, 107.91f,
112.11f, 134.5421f, 159.0144f, 185.5269f, 214.0796f, 244.6725f, 277.3056f,
311.9789f, 348.6924f, 387.4461f, 428.24f, 471.0741f, 515.9484f, 562.8629f,
611.8176f, 662.8125f, 715.8476f, 770.9229f, 828.0384f, 0.0f,
/* batch 1 */
-2.31f, -7.04f, -14.19f, -23.76f, -35.75f, -50.16f, -66.99f, -86.24f,
-107.91f, -112.11f, -134.5421f, -159.0144f, -185.5269f, -214.0796f,
-244.6725f, -277.3056f, -311.9789f, -348.6924f, -387.4461f, -428.24f,
-471.0741f, -515.9484f, -562.8629f, -611.8176f, -662.8125f, -715.8476f,
-770.9229f, -828.0384f, 0.0f,
/* batch 2 */
2.31f, -7.04f, 14.19f, -23.76f, 35.75f, -50.16f, 66.99f, -86.24f, 107.91f,
-112.11f, 134.5421f, -159.0144f, 185.5269f, -214.0796f, 244.6725f,
-277.3056f, 311.9789f, -348.6924f, 387.4461f, -428.24f, 471.0741f,
-515.9484f, 562.8629f, -611.8176f, 662.8125f, -715.8476f, 770.9229f,
-828.0384f, 0.0f,
/* batch 3 */
-2.31f, 7.04f, -14.19f, 23.76f, -35.75f, 50.16f, -66.99f, 86.24f,
-107.91f, 112.11f, -134.5421f, 159.0144f, -185.5269f, 214.0796f,
-244.6725f, 277.3056f, -311.9789f, 348.6924f, -387.4461f, 428.24f,
-471.0741f, 515.9484f, -562.8629f, 611.8176f, -662.8125f, 715.8476f,
-770.9229f, 828.0384f, 0.0f};
EXPECT_THAT(output, testing::ElementsAreArray(
ArrayFloatNear(expected_output, 6.5e-5f)));
}
TEST(uKernels, VectorBatchVectorCwiseProductNoAccumulate) {
constexpr int kVectorSize = 29;
constexpr int kBatchSize = 4;
static float input[kVectorSize] = {
1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.1,
11.11, 12.12, 13.13, 14.14, 15.15, 16.16, 17.17, 18.18, 19.19, 20.2,
21.21, 22.22, 23.23, 24.24, 25.25, 26.26, 27.27, 28.28, 0};
std::vector<float> output = {
/* batch 0 */
1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.1, 11.11, 12.12, 13.13,
14.14, 15.15, 16.16, 17.17, 18.18, 19.19, 20.2, 21.21, 22.22, 23.23,
24.24, 25.25, 26.26, 27.27, 28.28, 0,
/* batch 1 */
-1.1, -2.2, -3.3, -4.4, -5.5, -6.6, -7.7, -8.8, -9.9, -10.1, -11.11,
-12.12, -13.13, -14.14, -15.15, -16.16, -17.17, -18.18, -19.19, -20.2,
-21.21, -22.22, -23.23, -24.24, -25.25, -26.26, -27.27, -28.28, 0,
/* batch 2 */
1.1, -2.2, 3.3, -4.4, 5.5, -6.6, 7.7, -8.8, 9.9, -10.1, 11.11, -12.12,
13.13, -14.14, 15.15, -16.16, 17.17, -18.18, 19.19, -20.2, 21.21, -22.22,
23.23, -24.24, 25.25, -26.26, 27.27, -28.28, 0,
/* batch 3 */
-1.1, 2.2, -3.3, 4.4, -5.5, 6.6, -7.7, 8.8, -9.9, 10.1, -11.11, 12.12,
-13.13, 14.14, -15.15, 16.16, -17.17, 18.18, -19.19, 20.2, -21.21, 22.22,
-23.23, 24.24, -25.25, 26.26, -27.27, 28.28, 0};
VectorBatchVectorCwiseProduct(input, kVectorSize, output.data(), kBatchSize,
output.data());
// Expect output = input * output + output.
const std::vector<float> expected_output = {
/* batch 0 */
1.210000, 4.840000, 10.889999, 19.360001, 30.250000, 43.559998, 59.289997,
77.440002, 98.009995, 102.010010, 123.432091, 146.894394, 172.396896,
199.939606, 229.522491, 261.145599, 294.808899, 330.512421, 368.256134,
408.040039, 449.864075, 493.728363, 539.632874, 587.577576, 637.562500,
689.587585, 743.652954, 799.758423, 0.000000,
/* batch 1 */
-1.210000, -4.840000, -10.889999, -19.360001, -30.250000, -43.559998,
-59.289997, -77.440002, -98.009995, -102.010010, -123.432091, -146.894394,
-172.396896, -199.939606, -229.522491, -261.145599, -294.808899,
-330.512421, -368.256134, -408.040039, -449.864075, -493.728363,
-539.632874, -587.577576, -637.562500, -689.587585, -743.652954,
-799.758423, 0.000000,
/* batch 2 */
1.210000, -4.840000, 10.889999, -19.360001, 30.250000, -43.559998,
59.289997, -77.440002, 98.009995, -102.010010, 123.432091, -146.894394,
172.396896, -199.939606, 229.522491, -261.145599, 294.808899, -330.512421,
368.256134, -408.040039, 449.864075, -493.728363, 539.632874, -587.577576,
637.562500, -689.587585, 743.652954, -799.758423, 0.000000,
/* batch 3 */
-1.210000, 4.840000, -10.889999, 19.360001, -30.250000, 43.559998,
-59.289997, 77.440002, -98.009995, 102.010010, -123.432091, 146.894394,
-172.396896, 199.939606, -229.522491, 261.145599, -294.808899, 330.512421,
-368.256134, 408.040039, -449.864075, 493.728363, -539.632874, 587.577576,
-637.562500, 689.587585, -743.652954, 799.758423, 0.000000};
EXPECT_THAT(output, testing::ElementsAreArray(expected_output));
}
TEST(uKernels, BatchVectorBatchVectorDotProductTest) {
constexpr int kVectorSize = 5;
constexpr int kBatch = 2;
static float input1[kVectorSize * kBatch] = {0.0, -0.5, 1.0, -1.5, 2.0,
-2.5, 3.0, -3.5, 4.0, -4.5};
static float input2[kVectorSize * kBatch] = {0.1, -0.1, 0.1, -0.1, 0.1,
-0.1, 0.1, -0.1, 0.1, -0.1};
std::vector<float> output(kBatch);
BatchVectorBatchVectorDotProduct(input1, input2, kVectorSize, kBatch,
output.data(), /*result_stride=*/1);
EXPECT_THAT(output, ElementsAreArray(ArrayFloatNear({0.5, 1.75})));
}
TEST(uKernels, BatchVectorBatchVectorDotProductIntegerTest) {
constexpr int kVectorSize = 5;
constexpr int kBatch = 2;
static int16_t input1[kVectorSize * kBatch] = {0, 5, 10, -15, 20,
-25, 30, -35, 40, -45};
static int16_t input2[kVectorSize * kBatch] = {1, -1, 1, -1, 1,
-1, 1, -1, 1, 1};
std::vector<int32_t> output(kBatch);
BatchVectorBatchVectorDotProduct(input1, input2, kVectorSize, kBatch,
output.data(), /*result_stride=*/1);
EXPECT_THAT(output, ElementsAreArray(ArrayFloatNear({40, 85})));
}
TEST(uKernels, VectorShiftLeftTest) {
constexpr int kVectorSize = 5;
static float input[kVectorSize] = {0.0, -0.5, 1.0, -1.5, 2.0};
std::vector<float> result(kVectorSize);
VectorShiftLeft(input, kVectorSize, 3.0f);
result.assign(input, input + kVectorSize);
EXPECT_THAT(result,
ElementsAreArray(ArrayFloatNear({-0.5, 1.0, -1.5, 2.0, 3.0})));
}
TEST(uKernels, ReductionSumVectorTest) {
constexpr int kInputVectorSize = 10;
constexpr int kOutputVectorSize1 = 5;
constexpr int kReductionSize1 = 2;
static float input[kInputVectorSize] = {0.0, -0.5, 1.0, -1.5, 2.0,
0.0, -0.5, 1.0, 1.0, 2.0};
std::vector<float> result1(kOutputVectorSize1);
ReductionSumVector(input, result1.data(), kOutputVectorSize1,
kReductionSize1);
EXPECT_THAT(result1,
ElementsAreArray(ArrayFloatNear({-0.5, -0.5, 2.0, 0.5, 3.0})));
constexpr int kOutputVectorSize2 = 2;
constexpr int kReductionSize2 = 5;
std::vector<float> result2(kOutputVectorSize2);
ReductionSumVector(input, result2.data(), kOutputVectorSize2,
kReductionSize2);
EXPECT_THAT(result2, ElementsAreArray(ArrayFloatNear({1.0, 3.5})));
}
TEST(uKernels, ReductionSumVectorIntegerTest) {
constexpr int kInputVectorSize = 10;
constexpr int kOutputVectorSize1 = 5;
constexpr int kReductionSize1 = 2;
static int32_t input[kInputVectorSize] = {1, 2, 1, 5, -3, 2, 1, 2, 5, 10};
std::vector<int32_t> result1(kOutputVectorSize1);
ReductionSumVector(input, result1.data(), kOutputVectorSize1,
kReductionSize1);
EXPECT_THAT(result1, testing::ElementsAreArray({3, 6, -1, 3, 15}));
}
namespace {
// Parameterized test: mean, difference, tolerance.
// Input is constructed as [mean-2*diff, mean-diff, mean+diff, mean+2*diff]
class MeanStddevNormalizationTest
: public testing::TestWithParam<std::tuple<float, float, float>> {};
} // namespace
TEST_P(MeanStddevNormalizationTest, SeparateBatches) {
const float mean = std::get<0>(GetParam());
const float diff = std::get<1>(GetParam());
const float tolerance = std::get<2>(GetParam());
constexpr int kVectorSize = 4;
const float input[kVectorSize] = {mean - 2 * diff, mean - diff, mean + diff,
mean + 2 * diff};
float output[kVectorSize];
MeanStddevNormalization(input, output, kVectorSize, 1);
std::vector<float> expected_output;
if (diff == 0.0f) {
expected_output.assign({0.0f, 0.0f, 0.0f, 0.0f});
} else {
const float ksqrt16 = std::sqrt(1.6f);
const float ksqrt04 = std::sqrt(0.4f);
expected_output.assign({-ksqrt16, -ksqrt04, ksqrt04, ksqrt16});
}
EXPECT_THAT(output, testing::ElementsAreArray(
ArrayFloatNear(expected_output, tolerance)));
}
INSTANTIATE_TEST_SUITE_P(
uKernels, MeanStddevNormalizationTest,
testing::Values(
std::make_tuple(0.0f, 0.0f, 0.0f), // zero mean, zero variance
std::make_tuple(0.0f, 0.01f, 2.53e-5f), // zero mean, small variance
std::make_tuple(0.0f, 100.0f, 1.20e-7f), // zero mean, large variance
std::make_tuple(0.01f, 0.0f, 0.0f), // small mean, zero variance
std::make_tuple(0.01f, 0.01f, 2.53e-5f), // small mean, small variance
std::make_tuple(0.01f, 100.0f, 1.20e-7f), // small mean, large variance
std::make_tuple(100.0f, 0.0f, 0.0f), // large mean, zero variance
std::make_tuple(100.0f, 0.01f, 1.81e-4f), // large mean, small variance
std::make_tuple(100.0f, 100.0f, 1.20e-7f) // large mean, large variance
));
TEST(uKernels, MeanStddevNormalizationAllBatches) {
constexpr int kVectorSize = 4;
constexpr int kBatchSize = 9;
// None-zero input.
static float input[kVectorSize * kBatchSize] = {
0.0f, 0.0f, 0.0f, 0.0f, // zero mean, zero variance
-0.02f, -0.01f, 0.01f, 0.02f, // zero mean, small variance
-200.0f, -100.0f, 100.0f, 200.0f, // zero mean, large variance
0.01f, 0.01f, 0.01f, 0.01f, // small mean, zero variance
-0.01f, 0.0f, 0.02f, 0.03f, // small mean, small variance
-199.99f, -99.99f, 100.01f, 200.01f, // small mean, large variance
100.0f, 100.0f, 100.0f, 100.0f, // large mean, zero variance
99.98f, 99.99f, 100.01f, 100.02f, // large mean, small variance
-100.0f, 0.0f, 200.0f, 300.0f, // large mean, large variance
};
float output[kVectorSize * kBatchSize];
MeanStddevNormalization(input, output, kVectorSize, kBatchSize);
const float ksqrt16 = std::sqrt(1.6f);
const float ksqrt04 = std::sqrt(0.4f);
const std::vector<float> expected_output = {
0.0f, 0.0f, 0.0f, 0.0f, // zero mean, zero variance
-ksqrt16, -ksqrt04, ksqrt04, ksqrt16, // zero mean, small variance
-ksqrt16, -ksqrt04, ksqrt04, ksqrt16, // zero mean, large variance
0.0f, 0.0f, 0.0f, 0.0f, // small mean, zero variance
-ksqrt16, -ksqrt04, ksqrt04, ksqrt16, // small mean, small variance
-ksqrt16, -ksqrt04, ksqrt04, ksqrt16, // small mean, large variance
0.0f, 0.0f, 0.0f, 0.0f, // large mean, zero variance
-ksqrt16, -ksqrt04, ksqrt04, ksqrt16, // large mean, small variance
-ksqrt16, -ksqrt04, ksqrt04, ksqrt16, // large mean, large variance
};
EXPECT_THAT(output, testing::ElementsAreArray(
ArrayFloatNear(expected_output, 1.81e-4f)));
}
} // namespace tensor_utils
} // namespace tflite
#ifdef DOTPROD_BENCHMARKS
// Compile with --copt="-DGOOGLE_COMMANDLINEFLAGS_FULL_API=1" and
// --copt="-DDOTPROD_BENCHMARKS"
// Run with --benchmarks=all
void BM_DotprodBatchOneMultiply(benchmark::State& state) {
const int rows = state.range(0);
const int cols = state.range(1);
const int batch = state.range(2);
const int copies = state.range(3);
// For some benchmarks we make multiple matrix copies. This allows us to
// measure the performance differences of being entirely in cache vs.
// out of cache.
std::vector<tflite::tensor_utils::MatrixVectorData> datas;
for (int i = 0; i < copies; i++) {
datas.push_back(
tflite::tensor_utils::SetupMatrixVectorData(rows, cols, batch));
}
int copy = 0;
for (auto _ : state) {
copy = (copy + 1) % datas.size();
auto& data = datas[copy];
for (int i = 0; i < batch; i++) {
tflite::tensor_utils::MatrixBatchVectorMultiplyAccumulate(
data.matrix.data(), data.rows, data.cols,
data.vectors.data() + (data.cols * i), data.scale_factors.data(), 1,
&data.results[0], 1);
testing::DoNotOptimize(data.results[2]);
}
}
}
BENCHMARK(BM_DotprodBatchOneMultiply)
->Args({16, 16, 1, 1})
->Args({16, 16, 4, 1})
->Args({32, 32, 1, 1})
->Args({32, 32, 4, 1})
->Args({64, 64, 1, 1})
->Args({64, 64, 4, 1})
->Args({128, 128, 1, 1})
->Args({128, 128, 4, 1})
->Args({992, 992, 1, 1})
->Args({992, 992, 8, 1})
->Args({1024, 1024, 1, 1})
->Args({1024, 1024, 1, 8})
->Args({1024, 1024, 4, 1})
->Args({1024, 1024, 4, 8})
->Args({1024, 1024, 8, 1})
->Args({640, 2048, 1, 1})
->Args({640, 2048, 4, 1})
->Args({640, 2048, 8, 1})
->Args({640, 2048, 8, 8})
->Args({2048, 2048, 1, 1})
->Args({2048, 2048, 1, 8})
->Args({2048, 2048, 8, 1});
void BM_DotprodBatchFourMultiply(benchmark::State& state) {
const int rows = state.range(0);
const int cols = state.range(1);
const int batch = state.range(2);
const int copies = state.range(3);
// For some benchmarks we make multiple matrix copies. This allows us to
// measure the performance differences of being entirely in cache vs.
// out of cache.
std::vector<tflite::tensor_utils::MatrixVectorData> datas;
for (int i = 0; i < copies; i++) {
datas.push_back(
tflite::tensor_utils::SetupMatrixVectorData(rows, cols, batch));
}
int copy = 0;
for (auto _ : state) {
copy = (copy + 1) % datas.size();
auto& data = datas[copy];
tflite::tensor_utils::MatrixBatchVectorMultiplyAccumulate(
data.matrix.data(), data.rows, data.cols, data.vectors.data(),
data.scale_factors.data(), data.batch, &data.results[0], 1);
testing::DoNotOptimize(data.results[2]);
}
}
BENCHMARK(BM_DotprodBatchFourMultiply)
->Args({16, 16, 4, 1})
->Args({32, 32, 4, 1})
->Args({64, 64, 4, 1})
->Args({64, 256, 64, 1})
->Args({64, 256, 256, 1})
->Args({64, 256, 1024, 1})
->Args({64, 256, 12544, 1})
->Args({128, 128, 2, 1})
->Args({128, 128, 3, 1})
->Args({128, 128, 4, 1})
->Args({128, 128, 5, 1})
->Args({640, 640, 4, 1})
->Args({992, 992, 8, 1})
->Args({1024, 1024, 2, 1})
->Args({1024, 1024, 3, 1})
->Args({1024, 1024, 4, 1})
->Args({1024, 1024, 5, 1})
->Args({1024, 1024, 8, 1})
->Args({1024, 1024, 8, 8})
->Args({1024, 1024, 256, 1})
->Args({640, 2048, 2, 1})
->Args({640, 2048, 3, 1})
->Args({640, 2048, 4, 1})
->Args({640, 2048, 4, 8})
->Args({640, 2048, 8, 1})
->Args({2048, 2048, 3, 1})
->Args({2048, 2048, 4, 1})
->Args({2048, 2048, 4, 8})
->Args({2048, 2048, 5, 1})
->Args({2048, 2048, 8, 1});
void BM_DotprodSparseMultiply(benchmark::State& state) {
const int rows = state.range(0);
const int cols = state.range(1);
const int batch = state.range(2);
const int copies = state.range(3);
// For some benchmarks we make multiple matrix copies. This allows us to
// measure the performance differences of being entirely in cache vs.
// out of cache.
std::vector<tflite::tensor_utils::MatrixVectorData> datas;
for (int i = 0; i < copies; i++) {
datas.push_back(
tflite::tensor_utils::SetupMatrixVectorData(rows, cols, batch));
}
int copy = 0;
for (auto _ : state) {
copy = (copy + 1) % datas.size();
auto& data = datas[copy];
tflite::tensor_utils::SparseMatrixBatchVectorMultiplyAccumulate(
data.sparse_matrix.data(), data.ledger.data(), data.rows, data.cols,
data.vectors.data(), data.scale_factors.data(), data.batch,
&data.results[0], 1);
testing::DoNotOptimize(data.results[2]);
}
}
BENCHMARK(BM_DotprodSparseMultiply)
->Args({128, 128, 1, 1})
->Args({128, 128, 4, 1})
->Args({640, 640, 4, 1})
->Args({992, 992, 8, 1})
->Args({1024, 1024, 1, 1})
->Args({1024, 1024, 4, 1})
->Args({1024, 1024, 8, 1})
->Args({640, 2048, 1, 1})
->Args({640, 2048, 4, 1})
->Args({640, 2048, 8, 1})
->Args({2048, 2048, 1, 1})
->Args({2048, 2048, 8, 1});
#endif // DOTPROD_BENCHMARKS
| 44.224026 | 80 | 0.560287 | [
"vector"
] |
a36f16f557e0d94750cc97836e2da4b54a35ffab | 4,420 | cpp | C++ | test-suite/handwritten-src/cpp/test_helpers.cpp | lbguilherme/djinni | 644b3092df4c5b9e6b2d369e3a72f9bbbf27d45b | [
"Apache-2.0"
] | 1 | 2015-10-06T02:49:26.000Z | 2015-10-06T02:49:26.000Z | test-suite/handwritten-src/cpp/test_helpers.cpp | mcanthony/djinni | 644b3092df4c5b9e6b2d369e3a72f9bbbf27d45b | [
"Apache-2.0"
] | null | null | null | test-suite/handwritten-src/cpp/test_helpers.cpp | mcanthony/djinni | 644b3092df4c5b9e6b2d369e3a72f9bbbf27d45b | [
"Apache-2.0"
] | 1 | 2019-09-18T07:39:46.000Z | 2019-09-18T07:39:46.000Z | #include "test_helpers.hpp"
#include "client_returned_record.hpp"
#include "client_interface.hpp"
#include "user_token.hpp"
#include <exception>
namespace testsuite {
SetRecord TestHelpers::get_set_record() {
return SetRecord { {
"StringA",
"StringB",
"StringC"
}, std::unordered_set<int32_t>{} };
}
bool TestHelpers::check_set_record(const SetRecord & rec) {
return rec.set == std::unordered_set<std::string>{ "StringA", "StringB", "StringC" };
}
static const PrimitiveList cPrimitiveList { { 1, 2, 3 } };
PrimitiveList TestHelpers::get_primitive_list() {
return cPrimitiveList;
}
bool TestHelpers::check_primitive_list(const PrimitiveList & pl) {
return pl.list == cPrimitiveList.list;
}
static const NestedCollection cNestedCollection { { {u8"String1", u8"String2"},
{u8"StringA", u8"StringB"} } };
NestedCollection TestHelpers::get_nested_collection() {
return cNestedCollection;
}
bool TestHelpers::check_nested_collection(const NestedCollection & nc) {
return nc.set_list == cNestedCollection.set_list;
}
static const std::unordered_map<std::string, int64_t> cMap = {
{ "String1", 1 },
{ "String2", 2 },
{ "String3", 3 },
};
std::unordered_map<std::string, int64_t> TestHelpers::get_map() {
return cMap;
}
bool TestHelpers::check_map(const std::unordered_map<std::string, int64_t> & m) {
return m == cMap;
}
std::unordered_map<std::string, int64_t> TestHelpers::get_empty_map() {
return std::unordered_map<std::string, int64_t>();
}
bool TestHelpers::check_empty_map(const std::unordered_map<std::string,int64_t> & m) {
return m.empty();
}
MapListRecord TestHelpers::get_map_list_record() {
return { { cMap } };
}
bool TestHelpers::check_map_list_record(const MapListRecord & rec) {
return rec.map_list.size() == 1 && rec.map_list[0] == cMap;
}
static const std::string HELLO_WORLD = "Hello World!";
static const std::string NON_ASCII = "Non-ASCII / 非 ASCII 字符";
void TestHelpers::check_client_interface_ascii(const std::shared_ptr<ClientInterface> & i) {
ClientReturnedRecord cReturnedRecord = i->get_record(5, HELLO_WORLD, {});
if (cReturnedRecord.content != HELLO_WORLD) {
std::string error_msg = "Expected String: " + HELLO_WORLD + " Actual: " + cReturnedRecord.content;
throw std::invalid_argument(error_msg);
}
}
void TestHelpers::check_client_interface_nonascii(const std::shared_ptr<ClientInterface> & i) {
ClientReturnedRecord cReturnedRecord = i->get_record(5, NON_ASCII, {});
if (cReturnedRecord.content != NON_ASCII) {
std::string error_msg = "Expected String: " + NON_ASCII + " Actual: " + cReturnedRecord.content;
throw std::invalid_argument(error_msg);
}
}
std::shared_ptr<UserToken> TestHelpers::token_id(const std::shared_ptr<UserToken> & in) {
return in;
}
class CppToken : public UserToken {
std::string whoami() { return "C++"; }
};
std::shared_ptr<UserToken> TestHelpers::create_cpp_token() {
return std::make_shared<CppToken>();
}
void TestHelpers::check_cpp_token(const std::shared_ptr<UserToken> & in) {
// Throws bad_cast if type is wrong
(void)dynamic_cast<CppToken &>(*in);
}
int64_t TestHelpers::cpp_token_id(const std::shared_ptr<UserToken> & in) {
return reinterpret_cast<int64_t>(in.get());
}
void TestHelpers::check_token_type(const std::shared_ptr<UserToken> &t, const std::string & type) {
if (t->whoami() != type) {
throw std::invalid_argument("wrong token type");
}
}
std::experimental::optional<int32_t> TestHelpers::return_none() {
return {};
}
void TestHelpers::check_enum_map(const std::unordered_map<color, std::string> & m) {
std::unordered_map<color, std::string> expected = {
{ color::RED, "red" },
{ color::ORANGE, "orange" },
{ color::YELLOW, "yellow" },
{ color::GREEN, "green" },
{ color::BLUE, "blue" },
{ color::INDIGO, "indigo" },
{ color::VIOLET, "violet" },
};
if (m != expected) {
throw std::invalid_argument("map mismatch");
}
}
void TestHelpers::check_enum(color) {} // stub
AssortedPrimitives TestHelpers::assorted_primitives_id(const AssortedPrimitives & p) {
return p;
}
std::vector<uint8_t> TestHelpers::id_binary(const std::vector<uint8_t> & v) {
return v;
}
} // namespace testsuite
| 29.66443 | 106 | 0.674661 | [
"vector"
] |
a36f6217d9f174820fd064266f5cefc91e070718 | 22,097 | cpp | C++ | src/slg/engines/tilerepository.cpp | bartoszek/LuxCore | 1d90c142f27734ac8035e2b8485d7f4ce946210d | [
"Apache-2.0"
] | null | null | null | src/slg/engines/tilerepository.cpp | bartoszek/LuxCore | 1d90c142f27734ac8035e2b8485d7f4ce946210d | [
"Apache-2.0"
] | null | null | null | src/slg/engines/tilerepository.cpp | bartoszek/LuxCore | 1d90c142f27734ac8035e2b8485d7f4ce946210d | [
"Apache-2.0"
] | null | null | null | /***************************************************************************
* Copyright 1998-2018 by authors (see AUTHORS.txt) *
* *
* This file is part of LuxCoreRender. *
* *
* 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 <boost/format.hpp>
#include "slg/engines/tilerepository.h"
#include "slg/film/imagepipeline/plugins/gammacorrection.h"
#include "slg/film/imagepipeline/plugins/tonemaps/linear.h"
#include "slg/film/imagepipeline/plugins/tonemaps/autolinear.h"
using namespace std;
using namespace luxrays;
using namespace slg;
//------------------------------------------------------------------------------
// Tile
//------------------------------------------------------------------------------
Tile::Tile(TileRepository *repo, const Film &film, const u_int index,
const u_int tileX, const u_int tileY) :
tileRepository(repo), tileIndex(index), pass(0), pendingPasses(0),
error(numeric_limits<float>::infinity()),
done(false), allPassFilm(NULL), evenPassFilm(NULL),
allPassFilmTotalYValue(0.f), hasEnoughWarmUpSample(false) {
const u_int *filmSubRegion = film.GetSubRegion();
coord.x = tileX;
coord.y = tileY;
coord.width = Min(tileX + tileRepository->tileWidth, filmSubRegion[1] + 1) - tileX;
coord.height = Min(tileY + tileRepository->tileHeight, filmSubRegion[3] + 1) - tileY;
allPassFilm = NULL;
evenPassFilm = NULL;
const bool hasVarianceClamping = tileRepository->varianceClamping.hasClamping();
const bool hasConvergenceTest = (tileRepository->enableMultipassRendering && (tileRepository->convergenceTestThreshold > 0.f));
if (hasVarianceClamping || hasConvergenceTest)
InitTileFilm(film, &allPassFilm);
if (hasConvergenceTest)
InitTileFilm(film, &evenPassFilm);
}
Tile::Tile() {
}
Tile::~Tile() {
delete allPassFilm;
delete evenPassFilm;
}
void Tile::InitTileFilm(const Film &film, Film **tileFilm) {
(*tileFilm) = new Film(coord.width, coord.height);
(*tileFilm)->CopyDynamicSettings(film);
// Remove all channels but RADIANCE_PER_PIXEL_NORMALIZED and IMAGEPIPELINE
(*tileFilm)->RemoveChannel(Film::ALPHA);
(*tileFilm)->RemoveChannel(Film::DEPTH);
(*tileFilm)->RemoveChannel(Film::POSITION);
(*tileFilm)->RemoveChannel(Film::GEOMETRY_NORMAL);
(*tileFilm)->RemoveChannel(Film::SHADING_NORMAL);
(*tileFilm)->RemoveChannel(Film::MATERIAL_ID);
(*tileFilm)->RemoveChannel(Film::DIRECT_GLOSSY);
(*tileFilm)->RemoveChannel(Film::EMISSION);
(*tileFilm)->RemoveChannel(Film::INDIRECT_DIFFUSE);
(*tileFilm)->RemoveChannel(Film::INDIRECT_GLOSSY);
(*tileFilm)->RemoveChannel(Film::INDIRECT_SPECULAR);
(*tileFilm)->RemoveChannel(Film::MATERIAL_ID_MASK);
(*tileFilm)->RemoveChannel(Film::DIRECT_SHADOW_MASK);
(*tileFilm)->RemoveChannel(Film::INDIRECT_SHADOW_MASK);
(*tileFilm)->RemoveChannel(Film::UV);
(*tileFilm)->RemoveChannel(Film::RAYCOUNT);
(*tileFilm)->RemoveChannel(Film::BY_MATERIAL_ID);
(*tileFilm)->RemoveChannel(Film::IRRADIANCE);
(*tileFilm)->RemoveChannel(Film::OBJECT_ID);
(*tileFilm)->RemoveChannel(Film::OBJECT_ID_MASK);
(*tileFilm)->RemoveChannel(Film::BY_OBJECT_ID);
(*tileFilm)->RemoveChannel(Film::SAMPLECOUNT);
(*tileFilm)->RemoveChannel(Film::CONVERGENCE);
(*tileFilm)->RemoveChannel(Film::MATERIAL_ID_COLOR);
(*tileFilm)->RemoveChannel(Film::ALBEDO);
// Build an image pipeline with only an auto-linear tone mapping and
// gamma correction.
auto_ptr<ImagePipeline> imagePipeline(new ImagePipeline());
imagePipeline->AddPlugin(new LinearToneMap(1.f));
imagePipeline->AddPlugin(new GammaCorrectionPlugin(2.2f));
(*tileFilm)->SetImagePipelines(imagePipeline.release());
// Disable OpenCL
(*tileFilm)->oclEnable = false;
// Disable denoiser statistics collection
(*tileFilm)->GetDenoiser().SetEnabled(false);
(*tileFilm)->Init();
}
void Tile::Restart(const u_int startPass) {
if (allPassFilm)
allPassFilm->Reset();
if (evenPassFilm)
evenPassFilm->Reset();
pass = startPass;
pendingPasses = 0;
error = numeric_limits<float>::infinity();
hasEnoughWarmUpSample = false;
done = false;
allPassFilmTotalYValue = 0.f;
}
void Tile::VarianceClamp(Film &tileFilm) {
allPassFilm->VarianceClampFilm(tileRepository->varianceClamping, tileFilm);
}
void Tile::AddPass(Film &tileFilm, const u_int passRendered) {
if (tileRepository->varianceClamping.hasClamping()) {
// Apply variance clamping
VarianceClamp(tileFilm);
}
// Increase the pass count
++pass;
// Update the done flag
if (tileRepository->enableMultipassRendering) {
// Check if convergence test is enable
if (tileRepository->convergenceTestThreshold > 0.f) {
// Add the tile to the all pass film
allPassFilm->AddFilm(tileFilm);
if (!hasEnoughWarmUpSample) {
// Update tileRepository->filmTotalYValue and hasEnoughWarmUpSample
UpdateTileStats();
}
if (passRendered % 2 == 1) {
// If it is an odd pass, add also to the even pass film
evenPassFilm->AddFilm(tileFilm);
} else if (hasEnoughWarmUpSample) {
// Update linear tone mapping plugin
// This is the same scale of AutoLinearToneMap::CalcLinearToneMapScale() with gamma set to 1.0
const float scale = AutoLinearToneMap::CalcLinearToneMapScale(*allPassFilm, 0,
tileRepository->filmTotalYValue / (tileRepository->filmRegionWidth * tileRepository->filmRegionHeight));
LinearToneMap *allLT = (LinearToneMap *)allPassFilm->GetImagePipeline(0)->GetPlugin(typeid(LinearToneMap));
allLT->scale = scale;
LinearToneMap *evenLT = (LinearToneMap *)evenPassFilm->GetImagePipeline(0)->GetPlugin(typeid(LinearToneMap));
evenLT->scale = scale;
// If it is an even pass, check convergence status
CheckConvergence();
}
}
if ((tileRepository->maxPassCount > 0) && (pass >= tileRepository->maxPassCount))
done = true;
} else
done = true;
}
void Tile::UpdateTileStats() {
float totalYValue = 0.f;
const size_t channelCount = allPassFilm->GetRadianceGroupCount();
hasEnoughWarmUpSample = true;
for (u_int j = 0; j < channelCount; ++j) {
for (u_int y = 0; y < coord.height; ++y) {
for (u_int x = 0; x < coord.width; ++x) {
const float *pixel = allPassFilm->channel_RADIANCE_PER_PIXEL_NORMALIZEDs[j]->GetPixel(x, y);
if (pixel[3] > 0.f) {
if (pixel[3] < tileRepository->convergenceTestWarmUpSamples)
hasEnoughWarmUpSample = false;
const float w = 1.f / pixel[3];
const float Y = Spectrum(pixel[0] * w, pixel[1] * w, pixel[2] * w).Y();
if ((Y <= 0.f) || isinf(Y))
continue;
totalYValue += Y;
} else
hasEnoughWarmUpSample = false;
}
}
}
// Remove old avg. luminance value and add the new one
tileRepository->filmTotalYValue += totalYValue - allPassFilmTotalYValue;
allPassFilmTotalYValue = totalYValue;
}
void Tile::CheckConvergence() {
float maxError2 = 0.f;
// Get the even pass pixel values
evenPassFilm->ExecuteImagePipeline(0);
const Spectrum *evenPassPixel = (const Spectrum *)evenPassFilm->channel_IMAGEPIPELINEs[0]->GetPixels();
// Get the all pass pixel values
allPassFilm->ExecuteImagePipeline(0);
const Spectrum *allPassPixel = (const Spectrum *)allPassFilm->channel_IMAGEPIPELINEs[0]->GetPixels();
// Compare the pixels result only of even passes with the result
// of all passes
for (u_int y = 0; y < coord.height; ++y) {
for (u_int x = 0; x < coord.width; ++x) {
// This is an variance estimation as defined in:
//
// "Progressive Path Tracing with Lightweight Local Error Estimation" paper
//
// The estimated variance of a pixel V(Pfull) is equal to (Pfull - Peven) ^ 2
// where Pfull is the total pixel value while Peven is the value made
// only of even samples.
for (u_int k = 0; k < COLOR_SAMPLES; ++k) {
// This is an variance estimation as defined in:
//
// "Progressive Path Tracing with Lightweight Local Error Estimation" paper
//
// The estimated variance of a pixel V(Pfull) is equal to (Pfull - Peven)^2
// where Pfull is the total pixel value while Peven is the value made
// only of even samples.
const float diff = Clamp(allPassPixel->c[k], 0.f, 1.f) -
Clamp(evenPassPixel->c[k], 0.f, 1.f);
// I'm using variance^2 to avoid a sqrtf())
//const float variance = diff *diff;
const float variance2 = fabsf(diff);
// Use variance^2 as error estimation
const float error2 = variance2;
maxError2 = Max(error2, maxError2);
}
++evenPassPixel;
++allPassPixel;
}
}
error = maxError2;
done = (maxError2 < tileRepository->convergenceTestThreshold);
}
//------------------------------------------------------------------------------
// TileWork
//------------------------------------------------------------------------------
TileWork::TileWork() : tile(nullptr) {
}
TileWork::TileWork(Tile *t) {
Init(tile);
}
void TileWork::Init(Tile *t) {
tile = t;
tile->pendingPasses++;
multipassIndexToRender = tile->tileRepository->multipassRenderingIndex;
passToRender = tile->pass + tile->pendingPasses;
}
u_int TileWork::GetTileSeed() const {
return tile->tileIndex + (multipassIndexToRender << 16) + 1;
}
void TileWork::AddPass(Film &tileFilm) {
tile->AddPass(tileFilm, passToRender);
if (tile->pendingPasses > 0)
--tile->pendingPasses;
}
//------------------------------------------------------------------------------
// TileRepository
//------------------------------------------------------------------------------
TileRepository::TileRepository(const u_int tileW, const u_int tileH) {
tileWidth = tileW;
tileHeight = tileH;
maxPassCount = 0;
enableMultipassRendering = false;
convergenceTestThreshold = 6.f / 256.f;
convergenceTestThresholdReduction = 0.f;
convergenceTestWarmUpSamples = 32;
enableRenderingDonePrint = true;
done = false;
filmTotalYValue = 0.f;
multipassRenderingIndex = 0;
}
TileRepository::TileRepository() {
}
TileRepository::~TileRepository() {
Clear();
}
void TileRepository::Clear() {
// Free all tiles in the 3 lists
BOOST_FOREACH(Tile *tile, tileList) {
delete tile;
}
tileList.clear();
todoTiles.clear();
pendingTiles.clear();
convergedTiles.clear();
}
void TileRepository::Restart(Film *film, const u_int startPass, const u_int multipassIndex) {
todoTiles.clear();
pendingTiles.clear();
convergedTiles.clear();
BOOST_FOREACH(Tile *tile, tileList) {
tile->Restart(startPass);
todoTiles.push(tile);
}
done = false;
// Reset the film convergence, it may have been set by previous
// rendering (for instance in RTPATHOCL)
film->SetConvergence(0.f);
filmTotalYValue = 0.f;
multipassRenderingIndex = multipassIndex;
}
void TileRepository::GetPendingTiles(deque<const Tile *> &tiles) {
boost::unique_lock<boost::mutex> lock(tileMutex);
tiles.insert(tiles.end(), pendingTiles.begin(), pendingTiles.end());
}
void TileRepository::GetNotConvergedTiles(deque<const Tile *> &tiles) {
boost::unique_lock<boost::mutex> lock(tileMutex);
tiles.insert(tiles.end(), todoTiles.begin(), todoTiles.end());
}
void TileRepository::GetConvergedTiles(deque<const Tile *> &tiles) {
boost::unique_lock<boost::mutex> lock(tileMutex);
tiles.insert(tiles.end(), convergedTiles.begin(), convergedTiles.end());
}
void TileRepository::HilberCurveTiles(
vector<Tile::TileCoord> &coords,
const Film &film,
const u_int n,
const int xo, const int yo,
const int xd, const int yd,
const int xp, const int yp,
const int xEnd, const int yEnd) {
if (n <= 1) {
if((xo < xEnd) && (yo < yEnd))
coords.push_back(Tile::TileCoord(xo, yo, tileWidth, tileHeight));
} else {
const u_int n2 = n >> 1;
HilberCurveTiles(coords, film, n2,
xo,
yo,
xp, yp, xd, yd, xEnd, yEnd);
HilberCurveTiles(coords, film, n2,
xo + xd * static_cast<int>(n2),
yo + yd * static_cast<int>(n2),
xd, yd, xp, yp, xEnd, yEnd);
HilberCurveTiles(coords, film, n2,
xo + (xp + xd) * static_cast<int>(n2),
yo + (yp + yd) * static_cast<int>(n2),
xd, yd, xp, yp, xEnd, yEnd);
HilberCurveTiles(coords, film, n2,
xo + xd * static_cast<int>(n2 - 1) + xp * static_cast<int>(n - 1),
yo + yd * static_cast<int>(n2 - 1) + yp * static_cast<int>(n - 1),
-xp, -yp, -xd, -yd, xEnd, yEnd);
}
}
void TileRepository::InitTiles(const Film &film) {
const double t1 = WallClockTime();
const u_int *filmSubRegion = film.GetSubRegion();
filmRegionWidth = filmSubRegion[1] - filmSubRegion[0] + 1;
filmRegionHeight = filmSubRegion[3] - filmSubRegion[2] + 1;
const u_int n = RoundUp(filmRegionWidth, tileWidth) / tileWidth;
const u_int m = RoundUp(filmRegionHeight, tileHeight) / tileHeight;
vector<Tile::TileCoord> coords;
HilberCurveTiles(coords, film, RoundUpPow2(n * m),
filmSubRegion[0], filmSubRegion[2],
0, tileHeight,
tileWidth, 0,
filmSubRegion[1] + 1, filmSubRegion[3] + 1);
// Initialize the list of tiles
// To speedup the initialization process, work in parallel
const u_int size = coords.size();
tileList.resize(size, NULL);
#pragma omp parallel for
for (
// Visual C++ 2013 supports only OpenMP 2.5
#if _OPENMP >= 200805
unsigned
#endif
int i = 0; i < size; ++i)
tileList[i] = new Tile(this, film, i, coords[i].x, coords[i].y);
// Initialize also the TODO list
BOOST_FOREACH(Tile *tile, tileList)
todoTiles.push(tile);
done = false;
startTime = WallClockTime();
const double elapsedTime = WallClockTime() - t1;
SLG_LOG(boost::format("Tiles initialization time: %.2f secs") % elapsedTime);
}
void TileRepository::SetDone(Film *film) {
// Rendering done
if (!done) {
if (enableRenderingDonePrint) {
const double elapsedTime = WallClockTime() - startTime;
SLG_LOG(boost::format("Rendering time: %.2f secs") % elapsedTime);
}
done = true;
film->SetConvergence(1.f);
}
}
bool TileRepository::GetNewTileWork(TileWork &tileWork) {
// Look for the tile with less passes in pendingTiles
Tile *pendingTile = nullptr;
BOOST_FOREACH(Tile *tile, pendingTiles) {
if ((!tile->done) &&
(!pendingTile ||
(pendingTile->pass + pendingTile->pendingPasses > tile->pass + tile->pendingPasses)))
pendingTile = tile;
}
// Look for the tile with less passes in todoTiles
Tile *toDoTile = (todoTiles.size() > 0) ? todoTiles.top() : nullptr;
if (pendingTile) {
if (toDoTile) {
if (pendingTile->pass + pendingTile->pendingPasses < toDoTile->pass + toDoTile->pendingPasses)
tileWork.Init(pendingTile);
else {
tileWork.Init(toDoTile);
// Remove the tile form todo list
todoTiles.pop();
}
} else
tileWork.Init(pendingTile);
} else {
if (toDoTile) {
tileWork.Init(toDoTile);
// Remove the tile form todo list
todoTiles.pop();
} else {
// This should never happen
SLG_LOG("WARNING: out of tiles to render");
return false;
}
}
// Add the tile to the pending list (so it is counted multiple times
// in case it was pendingTile)
pendingTiles.push_back(tileWork.tile);
return true;
}
bool TileRepository::NextTile(Film *film, boost::mutex *filmMutex,
TileWork &tileWork, Film *tileFilm) {
// Now I have to lock the repository
boost::unique_lock<boost::mutex> lock(tileMutex);
// Check if I have to add the tile to the film
if (tileWork.HasWork()) {
Tile *tile = tileWork.tile;
// Add the pass to the tile
tileWork.AddPass(*tileFilm);
// Remove the first copy of tile from pending list (there can be multiple copy of the same tile)
pendingTiles.erase(find(pendingTiles.begin(), pendingTiles.end(), tile));
if (tile->done) {
// All done for this tile, add to the convergedTiles list, if it is
// not already there
if (find(convergedTiles.begin(), convergedTiles.end(), tile) == convergedTiles.end())
convergedTiles.push_back(tile);
} else {
// Re-add to the todoTiles priority queue, if it is not already there
if (find(todoTiles.begin(), todoTiles.end(), tile) == todoTiles.end())
todoTiles.push(tile);
}
// Add the tile also to the global film
boost::unique_lock<boost::mutex> lock(*filmMutex);
film->AddFilm(*tileFilm,
0, 0,
Min(tileWidth, film->GetWidth() - tile->coord.x),
Min(tileHeight, film->GetHeight() - tile->coord.y),
tile->coord.x, tile->coord.y);
}
// For the support of film halt conditions
if (film->GetConvergence() == 1.f) {
if (pendingTiles.size() == 0) {
// Rendering done
SetDone(film);
}
return false;
}
// For support of TileRepository halt condition and multi-pass rendering
if (todoTiles.size() == 0) {
if (!enableMultipassRendering) {
// Multi-pass rendering disabled
if (pendingTiles.size() == 0) {
// Rendering done
SetDone(film);
}
return false;
} else {
// Multi-pass rendering enabled
// Check the status of pending tiles (one or more of them could be a
// copy of mine and now done)
bool pendingAllDone = true;
BOOST_FOREACH(Tile *tile, pendingTiles) {
if (!tile->done) {
pendingAllDone = false;
break;
}
}
if (pendingAllDone) {
if (convergenceTestThresholdReduction > 0.f) {
// Reduce the target threshold and continue the rendering
if (enableRenderingDonePrint) {
const double elapsedTime = WallClockTime() - startTime;
SLG_LOG(boost::format("Threshold256 %.4f reached: %.2f secs") % (256.f * convergenceTestThreshold) % elapsedTime);
}
convergenceTestThreshold *= convergenceTestThresholdReduction;
// Restart the rendering for all tiles
// I need to save a copy of the current pending tile list because
// it can be not empty. I could just avoid to clear the list but is
// more readable (an safer for the Restart() method) to work in this
// way.
deque<Tile *> currentPendingTiles = pendingTiles;
Restart(film, 0, multipassRenderingIndex + 1);
pendingTiles = currentPendingTiles;
} else {
if (pendingTiles.size() == 0) {
// Rendering done
SetDone(film);
}
return false;
}
}
}
}
// Get the next tile to render
return GetNewTileWork(tileWork);
}
Properties TileRepository::ToProperties(const Properties &cfg) {
Properties props;
// tile.size
const u_int defaultSize = cfg.Get(GetDefaultProps().Get("tile.size")).Get<u_int>();
const Property sizeX = cfg.Get(Property("tile.size.x")(defaultSize));
const Property sizeY = cfg.Get(Property("tile.size.y")(defaultSize));
if (sizeX.Get<u_int>() == sizeY.Get<u_int>())
props << Property("tile.size")(sizeX.Get<u_int>());
else
props << sizeX << sizeY;
// tile.multipass.convergencetest.threshold
if (cfg.IsDefined("tile.multipass.convergencetest.threshold"))
props << cfg.Get(GetDefaultProps().Get("tile.multipass.convergencetest.threshold"));
else {
const float defaultThreshold = GetDefaultProps().Get("tile.multipass.convergencetest.threshold").Get<float>();
props << cfg.Get(Property("tile.multipass.convergencetest.threshold256")(defaultThreshold * 256.f));
}
props <<
cfg.Get(GetDefaultProps().Get("tile.multipass.enable")) <<
cfg.Get(GetDefaultProps().Get("tile.multipass.convergencetest.threshold.reduction")) <<
cfg.Get(GetDefaultProps().Get("tile.multipass.convergencetest.warmup.count"));
return props;
}
TileRepository *TileRepository::FromProperties(const luxrays::Properties &cfg) {
u_int tileWidth = 32;
u_int tileHeight = 32;
if (cfg.IsDefined("tile.size"))
tileWidth = tileHeight = Max(8u, cfg.Get(GetDefaultProps().Get("tile.size")).Get<u_int>());
tileWidth = Max(8u, cfg.Get(Property("tile.size.x")(tileWidth)).Get<u_int>());
tileHeight = Max(8u, cfg.Get(Property("tile.size.y")(tileHeight)).Get<u_int>());
auto_ptr<TileRepository> tileRepository(new TileRepository(tileWidth, tileHeight));
tileRepository->maxPassCount = cfg.Get(Property("batch.haltdebug")(0)).Get<u_int>();
tileRepository->enableMultipassRendering = cfg.Get(GetDefaultProps().Get("tile.multipass.enable")).Get<bool>();
if (cfg.IsDefined("tile.multipass.convergencetest.threshold"))
tileRepository->convergenceTestThreshold = cfg.Get(GetDefaultProps().Get("tile.multipass.convergencetest.threshold")).Get<float>();
else {
const float defaultThreshold256 = 256.f * GetDefaultProps().Get("tile.multipass.convergencetest.threshold").Get<float>();
tileRepository->convergenceTestThreshold = cfg.Get(Property("tile.multipass.convergencetest.threshold256")(defaultThreshold256)).Get<float>() * (1.f / 256.f);
}
tileRepository->convergenceTestThresholdReduction = cfg.Get(GetDefaultProps().Get("tile.multipass.convergencetest.threshold.reduction")).Get<float>();
tileRepository->convergenceTestWarmUpSamples = cfg.Get(GetDefaultProps().Get("tile.multipass.convergencetest.warmup.count")).Get<u_int>();
return tileRepository.release();
}
const Properties &TileRepository::GetDefaultProps() {
static Properties props = Properties() <<
Property("tile.size")(32) <<
Property("tile.multipass.enable")(true) <<
Property("tile.multipass.convergencetest.threshold")(6.f / 256.f) <<
Property("tile.multipass.convergencetest.threshold.reduction")(0.f) <<
Property("tile.multipass.convergencetest.warmup.count")(32);
return props;
}
| 32.980597 | 160 | 0.670272 | [
"render",
"vector"
] |
a373388226b4dc47424953f58fb3c8315b2816aa | 42,411 | cpp | C++ | arch/drisc/ISA.mtsparc.cpp | svp-dev/mgsim | 0abd708f3c48723fc233f6c53f3e638129d070fa | [
"MIT"
] | 7 | 2016-03-01T13:16:59.000Z | 2021-08-20T07:41:43.000Z | arch/drisc/ISA.mtsparc.cpp | svp-dev/mgsim | 0abd708f3c48723fc233f6c53f3e638129d070fa | [
"MIT"
] | null | null | null | arch/drisc/ISA.mtsparc.cpp | svp-dev/mgsim | 0abd708f3c48723fc233f6c53f3e638129d070fa | [
"MIT"
] | 5 | 2015-04-20T14:29:38.000Z | 2018-12-29T11:09:17.000Z | #include "Pipeline.h"
#include "DRISC.h"
#include <arch/FPU.h>
#include <arch/symtable.h>
#include <programs/mgsim.h>
#include <cassert>
#include <cmath>
#include <sstream>
#include <iomanip>
using namespace std;
namespace Simulator
{
namespace drisc
{
static const int RA_SHIFT = 14;
static const int RB_SHIFT = 0;
static const int RC_SHIFT = 25;
static const int REG_MASK = 0x1F;
static const int OP1_SHIFT = 30;
static const int OP1_MASK = 0x3;
static const int OP2_SHIFT = 22;
static const int OP2_MASK = 0x7;
static const int OP3_SHIFT = 19;
static const int OP3_MASK = 0x3F;
static const int COND_SHIFT = 25;
static const int COND_MASK = 0xF;
static const int ASI_SHIFT = 5;
static const int ASI_MASK = 0xFF;
static const int UTASI_SHIFT = 5;
static const int UTASI_MASK = 0xF;
static const int BIT_IMMEDIATE = (1 << 13);
static const int IMM30_SHIFT = 0;
static const int IMM30_SIZE = 30;
static const int IMM30_MASK = (1 << IMM30_SIZE) - 1;
static const int IMM22_SHIFT = 0;
static const int IMM22_SIZE = 22;
static const int IMM22_MASK = (1 << IMM22_SIZE) - 1;
static const int IMM13_SHIFT = 0;
static const int IMM13_SIZE = 13;
static const int IMM13_MASK = (1 << IMM13_SIZE) - 1;
static const int IMM9_SHIFT = 0;
static const int IMM9_SIZE = 9;
static const int IMM9_MASK = (1 << IMM9_SIZE) - 1;
static const int OPF_SHIFT = 5;
static const int OPF_MASK = (1 << 9) - 1;
static const int OPT_SHIFT = 9;
static const int OPT_MASK = (1 << 4) - 1;
// Function for naming local registers according to a standard ABI
const vector<string>& GetDefaultLocalRegisterAliases(RegType type)
{
static const vector<string> intnames = {
"g1", "g2", "g3", "g4", "g5", "g6", "g7",
"o0", "o1", "o2", "o3", "o4", "o5", "sp", "o7",
"l0", "l1", "l2", "l3", "l4", "l5", "l6", "l7",
"i0", "i1", "i2", "i3", "i4", "i5", "fp", "i7", "g0" };
static const vector<string> fltnames = {
"f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7",
"f8", "f9", "f10", "f11", "f12", "f13", "f14", "f15",
"f16", "f17", "f18", "f19", "f20", "f21", "f22", "f23",
"f24", "f25", "f26", "f27", "f28", "f29", "f30", "f31" };
if (type == RT_INTEGER)
return intnames;
else
return fltnames;
}
// Function for getting a register's type and index within that type
unsigned char GetRegisterClass(unsigned char addr, const RegsNo& regs, RegClass* rc, RegType type)
{
assert(regs.globals < 32);
assert(regs.shareds < 32);
assert((type == RT_INTEGER && regs.locals < 32) || regs.locals <= 32);
if (type == RT_INTEGER)
{
// SPARC is strange: integer register 0 is RAZ,
// but FP register 0 is valid.
if (addr == 0)
{
*rc = RC_RAZ;
return addr;
}
addr--;
}
if (addr < regs.locals)
{
*rc = RC_LOCAL;
return addr;
}
addr -= regs.locals;
if (addr < regs.globals)
{
*rc = RC_GLOBAL;
return addr;
}
addr -= regs.globals;
if (addr < regs.shareds)
{
*rc = RC_SHARED;
return addr;
}
addr -= regs.shareds;
if (addr < regs.shareds)
{
*rc = RC_DEPENDENT;
return addr;
}
*rc = RC_RAZ;
return 0;
}
// Sign extend the value, which has the specified size
static int32_t SEXT(uint32_t value, int bits)
{
bits = 32 - bits;
return (int32_t)(value << bits) >> bits;
}
void Pipeline::DecodeStage::DecodeInstruction(const Instruction& instr)
{
m_output.op1 = (uint8_t)((instr >> OP1_SHIFT) & OP1_MASK);
RegIndex Ra = (instr >> RA_SHIFT) & REG_MASK;
RegIndex Rb = (instr >> RB_SHIFT) & REG_MASK;
RegIndex Rc = (instr >> RC_SHIFT) & REG_MASK;
m_output.Ra = INVALID_REG;
m_output.Rb = INVALID_REG;
m_output.Rc = INVALID_REG;
m_output.Rs = INVALID_REG;
m_output.literal = 0;
switch (m_output.op1)
{
case S_OP1_BRANCH:
// SETHI & Branches
m_output.op2 = (uint8_t)((instr >> OP2_SHIFT) & OP2_MASK);
switch (m_output.op2)
{
case S_OP2_SETHI:
// We need to read it first
m_output.literal = (instr >> IMM22_SHIFT) & IMM22_MASK;
m_output.Rc = MAKE_REGADDR(RT_INTEGER, Rc);
break;
default:
// We don't care about the annul bit (not supported; obviously this presents a problem with legacy code later)
m_output.displacement = SEXT((instr >> IMM22_SHIFT) & IMM22_MASK, IMM22_SIZE);
m_output.function = (uint16_t)((instr >> COND_SHIFT) & COND_MASK);
break;
}
break;
case S_OP1_CALL:
m_output.displacement = SEXT((instr >> IMM30_SHIFT) & IMM30_MASK, IMM30_SIZE);
m_output.Rc = MAKE_REGADDR(RT_INTEGER, 15);
break;
case S_OP1_MEMORY:
m_output.op3 = (uint8_t)((instr >> OP3_SHIFT) & OP3_MASK);
m_output.Ra = MAKE_REGADDR(RT_INTEGER, Ra);
if (instr & BIT_IMMEDIATE) {
m_output.literal = SEXT((instr >> IMM13_SHIFT) & IMM13_MASK, IMM13_SIZE);
} else {
m_output.asi = (uint8_t)((instr >> ASI_SHIFT) & ASI_MASK);
m_output.Rb = MAKE_REGADDR(RT_INTEGER, Rb);
}
// Determine operation size
switch (m_output.op3)
{
case S_OP3_STB: case S_OP3_LDUB: case S_OP3_LDSB:
case S_OP3_STBA: case S_OP3_LDSBA: case S_OP3_LDUBA:
case S_OP3_STH: case S_OP3_LDUH: case S_OP3_LDSH:
case S_OP3_STHA: case S_OP3_LDSHA: case S_OP3_LDUHA:
case S_OP3_ST: case S_OP3_LD:
case S_OP3_STF: case S_OP3_LDF:
case S_OP3_STA: case S_OP3_LDA: m_output.RcSize = 4; break;
case S_OP3_STD: case S_OP3_LDD:
case S_OP3_STDF: case S_OP3_LDDF:
case S_OP3_STDA: case S_OP3_LDDA: m_output.RcSize = 8; break;
default:
// We don't support this instruction (yet)
break;
}
// Determine register type
switch (m_output.op3)
{
case S_OP3_STF: case S_OP3_LDF:
case S_OP3_STDF: case S_OP3_LDDF:
// FP load or store
m_output.Rc = MAKE_REGADDR(RT_FLOAT, Rc);
break;
default:
// Integer load or store
m_output.Rc = MAKE_REGADDR(RT_INTEGER, Rc);
break;
}
// Both loads and stores have three operands.
// For stores Rc specifies the value to write to [Ra + Rb].
// For loads we must load Rc to check if we're loading a pending register (which could cause problems).
m_output.Rs = m_output.Rc;
m_output.RsSize = m_output.RcSize;
// However, for stores we don't actually use Rc to write
switch (m_output.op3)
{
case S_OP3_STB: case S_OP3_STBA:
case S_OP3_STH: case S_OP3_STHA:
case S_OP3_ST: case S_OP3_STA:
case S_OP3_STD: case S_OP3_STDA:
case S_OP3_STF: case S_OP3_STDF:
// Stores
m_output.Rc = INVALID_REG;
break;
default:
// Loads
m_output.RaNotPending = true;
break;
}
break;
case S_OP1_OTHER:
m_output.op3 = (uint8_t)((instr >> OP3_SHIFT) & OP3_MASK);
m_output.asi = (uint8_t)((instr >> ASI_SHIFT) & ASI_MASK);
switch (m_output.op3)
{
case S_OP3_FPOP1:
case S_OP3_FPOP2:
// FP operation
m_output.function = (uint16_t)((instr >> OPF_SHIFT) & OPF_MASK);
m_output.Ra = MAKE_REGADDR(RT_FLOAT, Ra);
m_output.Rb = MAKE_REGADDR(RT_FLOAT, Rb);
m_output.Rc = MAKE_REGADDR(RT_FLOAT, Rc);
switch (m_output.function)
{
// Convert Int to FP
case S_OPF_FITOS: m_output.RaSize = m_output.RcSize = 4; break;
case S_OPF_FITOD: m_output.RaSize = m_output.RcSize = 8; break;
case S_OPF_FITOQ: m_output.RaSize = m_output.RcSize = 16; break;
// Convert FP to Int
case S_OPF_FSTOI: m_output.RaSize = m_output.RbSize = 4; break;
case S_OPF_FDTOI: m_output.RaSize = m_output.RbSize = 8; break;
case S_OPF_FQTOI: m_output.RaSize = m_output.RbSize = 16; break;
// Convert FP to FP
case S_OPF_FSTOD: m_output.RaSize = m_output.RbSize = 4; m_output.RcSize = 8; break;
case S_OPF_FSTOQ: m_output.RaSize = m_output.RbSize = 4; m_output.RcSize = 16; break;
case S_OPF_FDTOS: m_output.RaSize = m_output.RbSize = 8; m_output.RcSize = 4; break;
case S_OPF_FDTOQ: m_output.RaSize = m_output.RbSize = 8; m_output.RcSize = 16; break;
case S_OPF_FQTOS: m_output.RaSize = m_output.RbSize = 16; m_output.RcSize = 4; break;
case S_OPF_FQTOD: m_output.RaSize = m_output.RbSize = 16; m_output.RcSize = 8; break;
case S_OPF_FPRINTS: m_output.RaSize = 4; m_output.Rb = MAKE_REGADDR(RT_INTEGER, Rb); break;
case S_OPF_FPRINTD: m_output.RaSize = 8; m_output.Rb = MAKE_REGADDR(RT_INTEGER, Rb); break;
case S_OPF_FPRINTQ: m_output.RaSize = 16; m_output.Rb = MAKE_REGADDR(RT_INTEGER, Rb); break;
// FP Move
case S_OPF_FMOV:
case S_OPF_FNEG:
case S_OPF_FABS: break;
// FP Compare
case S_OPF_FCMPS: case S_OPF_FCMPES: m_output.RcSize = 4; break;
case S_OPF_FCMPD: case S_OPF_FCMPED: m_output.RcSize = 8; break;
case S_OPF_FCMPQ: case S_OPF_FCMPEQ: m_output.RcSize = 16; break;
case S_OPF_FSQRTS: case S_OPF_FADDS: case S_OPF_FSUBS:
case S_OPF_FMULS: case S_OPF_FDIVS: m_output.RaSize = m_output.RbSize = m_output.RcSize = 4; break;
case S_OPF_FSQRTD: case S_OPF_FADDD: case S_OPF_FSUBD:
case S_OPF_FMULD: case S_OPF_FDIVD: m_output.RaSize = m_output.RbSize = m_output.RcSize = 8; break;
case S_OPF_FSQRTQ: case S_OPF_FADDQ: case S_OPF_FSUBQ:
case S_OPF_FMULQ: case S_OPF_FDIVQ: m_output.RaSize = m_output.RbSize = m_output.RcSize = 16; break;
case S_OPF_FSMULD: m_output.RaSize = m_output.RbSize = 4; m_output.RcSize = 8; break;
case S_OPF_FDMULQ: m_output.RaSize = m_output.RbSize = 8; m_output.RcSize = 16; break;
}
break;
case S_OP3_WRASR:
// This instruction needs the Rc specifier, but we can't put it in the literal,
// so we abuse the displacement field so the EX stage can use it
m_output.Ra = MAKE_REGADDR(RT_INTEGER, Ra);
m_output.displacement = Rc;
m_output.function = (uint16_t)((instr >> OPT_SHIFT) & OPT_MASK);
m_output.asi = (instr >> UTASI_SHIFT) & UTASI_MASK;
if (instr & BIT_IMMEDIATE) {
m_output.literal = ((Rc == 0x14/*ASR20*/) || (Rc == 0x13/*ASR19*/))
? SEXT((instr >> IMM9_SHIFT ) & IMM9_MASK , IMM9_SIZE)
: SEXT((instr >> IMM13_SHIFT) & IMM13_MASK, IMM13_SIZE);
} else {
m_output.Rb = MAKE_REGADDR(RT_INTEGER, Rb);
}
if (Rc == 0x14 /*ASR20*/)
{
switch (m_output.function)
{
case S_OPT1_FPUTS:
case S_OPT1_FPUTG:
m_output.Rb = MAKE_REGADDR(RT_FLOAT, Rb);
break;
}
}
break;
case S_OP3_RDASR:
// This instruction needs the Ra specifier, so we put it in the
// displacement just like for WRASR.
m_output.displacement = Ra;
m_output.function = (uint16_t)((instr >> OPT_SHIFT) & OPT_MASK);
m_output.asi = (instr >> UTASI_SHIFT) & UTASI_MASK;
if (instr & BIT_IMMEDIATE) {
m_output.literal = SEXT((instr >> IMM9_SHIFT) & IMM9_MASK, IMM9_SIZE);
} else {
m_output.Rb = MAKE_REGADDR(RT_INTEGER, Rb);
}
m_output.Rc = MAKE_REGADDR(RT_INTEGER, Rc);
if (Ra == 0x13 /*ASR19*/)
{
switch(m_output.function)
{
case S_OPT2_CREBAS:
case S_OPT2_CREBIS:
// Special case, Rc is input as well
m_output.Ra = MAKE_REGADDR(RT_INTEGER, Rc);
break;
}
}
else if (Ra == 0x14 /*ASR20*/)
{
switch (m_output.function)
{
case S_OPT1_ALLOCATE:
case S_OPT1_ALLOCATES:
case S_OPT1_ALLOCATEX:
case S_OPT1_CREATE:
// Special case, Rc is input as well
m_output.Ra = MAKE_REGADDR(RT_INTEGER, Rc);
break;
case S_OPT1_FGETS:
case S_OPT1_FGETG:
// Special case, Rc is really a float
m_output.Rc = MAKE_REGADDR(RT_FLOAT, Rc);
break;
}
}
break;
default:
// Integer operation
m_output.Ra = MAKE_REGADDR(RT_INTEGER, Ra);
m_output.Rc = MAKE_REGADDR(RT_INTEGER, Rc);
if (instr & BIT_IMMEDIATE) {
m_output.literal = SEXT((instr >> IMM13_SHIFT) & IMM13_MASK, IMM13_SIZE);
} else {
m_output.Rb = MAKE_REGADDR(RT_INTEGER, Rb);
}
break;
}
break;
}
}
/*static*/
bool Pipeline::ExecuteStage::BranchTakenInt(int cond, uint32_t psr)
{
const bool n = (psr & PSR_ICC_N) != 0; // Negative
const bool z = (psr & PSR_ICC_Z) != 0; // Zero
const bool v = (psr & PSR_ICC_V) != 0; // Overflow
const bool c = (psr & PSR_ICC_C) != 0; // Carry
bool b;
switch (cond & 7)
{
default:
case 0: b = false; break; // BA, BN
case 1: b = z; break; // BNE, BE
case 2: b = z || (n ^ v); break; // BG, BLE
case 3: b = n ^ v; break; // BGE, BL
case 4: b = c || z; break; // BGU, BLEU
case 5: b = c; break; // BCC, BCS
case 6: b = n; break; // BPOS, BNEG
case 7: b = v; break; // BVC, BVS
}
return (cond & 8) ? !b : b;
}
/*static*/
bool Pipeline::ExecuteStage::BranchTakenFlt(int cond, uint32_t fsr)
{
const bool e = (fsr & FSR_FCC) == FSR_FCC_EQ; // Equal
const bool l = (fsr & FSR_FCC) == FSR_FCC_LT; // Less than
const bool g = (fsr & FSR_FCC) == FSR_FCC_GT; // Greater than
const bool u = (fsr & FSR_FCC) == FSR_FCC_UO; // Unordered
bool b = false;
if (cond & 8) { b |= e; }
cond = (cond & 8) ? ((cond & 7) - 1) : (8 - cond);
if (cond & 4) b |= l;
if (cond & 2) b |= g;
if (cond & 1) b |= u;
return b;
}
uint32_t Pipeline::ExecuteStage::ExecBasicInteger(int opcode, uint32_t Rav, uint32_t Rbv, uint32_t& Y, PSR& psr)
{
uint64_t Rcv = 0;
switch (opcode & 0xF)
{
// Logical operators
case S_OP3_AND: Rcv = Rav & Rbv; break;
case S_OP3_ANDN: Rcv = Rav & ~Rbv; break;
case S_OP3_OR: Rcv = Rav | Rbv; break;
case S_OP3_ORN: Rcv = Rav | ~Rbv; break;
case S_OP3_XOR: Rcv = Rav ^ Rbv; break;
case S_OP3_XNOR: Rcv = Rav ^ ~Rbv; break;
// Addition & Subtraction
case S_OP3_ADD: Rcv = (int64_t)(int32_t)Rav + (int64_t)(int32_t)Rbv; break;
case S_OP3_ADDX: Rcv = (int64_t)(int32_t)Rav + (int64_t)(int32_t)Rbv + (psr & PSR_ICC_C ? 1 : 0); break;
case S_OP3_SUB: Rcv = (int64_t)(int32_t)Rav - (int64_t)(int32_t)Rbv; break;
case S_OP3_SUBX: Rcv = (int64_t)(int32_t)Rav - (int64_t)(int32_t)Rbv - (psr & PSR_ICC_C ? 1 : 0); break;
// Multiplication & Division
case S_OP3_UMUL: Rcv = Rav * Rbv; Y = (uint32_t)(Rcv >> 32); break;
case S_OP3_SMUL: Rcv = (int64_t)(int32_t)Rav * (int64_t)(int32_t)Rbv; Y = (uint32_t)(Rcv >> 32); break;
#define CHECKDIV0(X) if ((X) == 0) ThrowIllegalInstructionException(*this, m_input.pc, "Division by zero")
case S_OP3_UDIV: CHECKDIV0(Rbv); Rcv = (((uint64_t)Y << 32) | Rav) / Rbv; break;
case S_OP3_SDIV: CHECKDIV0((int64_t)(int32_t)Rbv); Rcv = (int64_t)(((uint64_t)Y << 32) | Rav) / (int64_t)(int32_t)Rbv; break;
}
if (opcode & 0x10)
{
// Set icc
const bool A31 = Rav & 0x80000000;
const bool B31 = Rbv & 0x80000000;
const bool C31 = Rcv & 0x80000000;
// Clear the icc flags
psr &= ~PSR_ICC;
switch (opcode & 0xF)
{
case S_OP3_ADD: case S_OP3_ADDX:
// ``Overflow occurs on addition if both operands have the same sign and the sign of the sum is different.''
if (!(A31 ^ B31) && (A31 ^ C31)) psr |= PSR_ICC_V;
if ((A31 && B31) || (!C31 && (A31 || B31))) psr |= PSR_ICC_C;
if (Rcv == 0) psr |= PSR_ICC_Z;
if (C31) psr |= PSR_ICC_N;
break;
case S_OP3_SUB: case S_OP3_SUBX:
// ``Overflow occurs on subtraction if the operands have different signs and the sign of the difference differs from the sign of r[rs1].''
if ((A31 ^ B31) && (A31 ^ C31)) psr |= PSR_ICC_V;
if ((!A31 && B31) || (C31 && (!A31 || B31))) psr |= PSR_ICC_C;
if (Rcv == 0) psr |= PSR_ICC_Z;
if (C31) psr |= PSR_ICC_N;
break;
case S_OP3_AND: case S_OP3_OR: case S_OP3_XOR:
case S_OP3_ANDN: case S_OP3_ORN: case S_OP3_XNOR:
case S_OP3_UMUL: case S_OP3_SMUL:
if (Rcv == 0) psr |= PSR_ICC_Z;
if (C31) psr |= PSR_ICC_N;
break;
case S_OP3_UDIV:
if (Rcv > 0xFFFFFFFFULL) { psr |= PSR_ICC_V; Rcv = 0xFFFFFFFF; }
if (Rcv == 0) psr |= PSR_ICC_Z;
if (C31) psr |= PSR_ICC_N;
break;
case S_OP3_SDIV:
if ((int64_t)Rcv < -0x80000000LL) { psr |= PSR_ICC_V; Rcv = (uint64_t)(int64_t)-0x80000000LL; }
if ((int64_t)Rcv > 0x7FFFFFFFLL) { psr |= PSR_ICC_V; Rcv = (uint64_t)(int64_t) 0x7FFFFFFFLL; }
if (Rcv == 0) psr |= PSR_ICC_Z;
if (C31) psr |= PSR_ICC_N;
break;
}
}
return (uint32_t)Rcv;
}
uint32_t Pipeline::ExecuteStage::ExecOtherInteger(int opcode, uint32_t Rav, uint32_t Rbv, uint32_t& Y, PSR& psr)
{
switch (opcode)
{
case S_OP3_SLL: return Rav << (Rbv & 0x1F);
case S_OP3_SRL: return Rav >> (Rbv & 0x1F);
case S_OP3_SRA: return (int32_t)Rav >> (Rbv & 0x1F);
case S_OP3_MULScc:
{
// Multiply Step, see Sparc v8 manual, B.17
// Step 1 was implicitely done in the Read Stage
// Remember Rav's LSB for step 6
const uint32_t Rav_LSB = (Rav & 1);
// Step 2: Shift Rav, put (N xor V) in MSB gap
const bool N = (psr & PSR_ICC_N) != 0;
const bool V = (psr & PSR_ICC_V) != 0;
Rav = (Rav >> 1) | ((N ^ V) ? 0x80000000 : 0);
// Step 3: Add to multiplier depending on Y's LSB, and
// Step 5: Update icc according to step 3's addition
Rbv = ExecBasicInteger(S_OP3_ADDcc, Rbv, (Y & 1) ? Rav : 0, Y, psr);
// Step 6: Shift Y, put Rav's LSB in MSB gap
Y = (Y >> 1) | (Rav_LSB << 31);
// Step 4: Step 3's result is the result
return Rbv;
}
}
return 0;
}
Pipeline::PipeAction Pipeline::ExecuteStage::ExecReadASR19(uint8_t func)
{
auto& cpu = GetDRISC();
switch (func)
{
case S_OPT2_LDBP:
COMMIT {
// TLS base pointer: base address of TLS
m_output.Rcv.m_integer = cpu.GetTLSAddress(m_input.fid, m_input.tid);
m_output.Rcv.m_state = RST_FULL;
}
break;
case S_OPT2_LDFP:
COMMIT {
/// TLS frame (stack) pointer: top of TLS
const MemAddr tls_base = cpu.GetTLSAddress(m_input.fid, m_input.tid);
const MemAddr tls_size = cpu.GetTLSSize();
m_output.Rcv.m_integer = tls_base + tls_size;
m_output.Rcv.m_state = RST_FULL;
}
break;
case S_OPT2_CREBAS:
case S_OPT2_CREBIS:
{
assert(m_input.Rav.m_size == sizeof(Integer));
assert(m_input.Rbv.m_size == sizeof(Integer));
Integer Rav = m_input.Rav.m_integer.get(m_input.Rav.m_size);
Integer Rbv = m_input.Rbv.m_integer.get(m_input.Rbv.m_size);
return ExecBundle(Rbv, (func == S_OPT2_CREBIS), Rav, m_input.Rc.index);
}
default:
ThrowIllegalInstructionException(*this, m_input.pc, "Invalid read from ASR19: func = %d", (int)func);
break;
}
return PIPE_CONTINUE;
}
Pipeline::PipeAction Pipeline::ExecuteStage::ExecReadASR20(uint8_t func)
{
assert(m_input.Rav.m_size == sizeof(Integer));
assert(m_input.Rbv.m_size == sizeof(Integer));
Integer Rav = m_input.Rav.m_integer.get(m_input.Rav.m_size);
Integer Rbv = m_input.Rbv.m_integer.get(m_input.Rbv.m_size);
auto& cpu = GetDRISC();
switch (func)
{
case S_OPT1_ALLOCATE:
case S_OPT1_ALLOCATES:
case S_OPT1_ALLOCATEX:
{
PlaceID place = cpu.UnpackPlace(Rav);
return ExecAllocate(place, m_input.Rc.index, func != S_OPT1_ALLOCATE, func == S_OPT1_ALLOCATEX, Rbv);
}
case S_OPT1_CREATE:
{
FID fid = cpu.UnpackFID(Rav);
MemAddr addr = Rbv;
return ExecCreate(fid, addr, m_input.Rc.index);
}
case S_OPT1_SYNC:
return ExecSync(cpu.UnpackFID(Rbv));
case S_OPT1_GETTID:
case S_OPT1_GETFID:
case S_OPT1_GETPID:
case S_OPT1_GETCID:
COMMIT {
m_output.Rcv.m_state = RST_FULL;
switch (m_input.function)
{
case S_OPT1_GETFID: m_output.Rcv.m_integer = m_input.fid; break;
case S_OPT1_GETTID: m_output.Rcv.m_integer = m_input.tid; break;
case S_OPT1_GETCID: m_output.Rcv.m_integer = cpu.GetPID(); break;
case S_OPT1_GETPID:
{
PlaceID place;
place.size = m_input.placeSize;
place.pid = cpu.GetPID() & -place.size;
place.capability = 0x1337;
m_output.Rcv.m_integer = cpu.PackPlace(place);
break;
}
}
}
break;
case S_OPT1_GETS:
return ReadFamilyRegister(RRT_LAST_SHARED, RT_INTEGER, cpu.UnpackFID(Rbv), m_input.asi);
case S_OPT1_FGETS:
return ReadFamilyRegister(RRT_LAST_SHARED, RT_FLOAT, cpu.UnpackFID(Rbv), m_input.asi);
case S_OPT1_GETG:
return ReadFamilyRegister(RRT_GLOBAL, RT_INTEGER, cpu.UnpackFID(Rbv), m_input.asi);
case S_OPT1_FGETG:
return ReadFamilyRegister(RRT_GLOBAL, RT_FLOAT, cpu.UnpackFID(Rbv), m_input.asi);
default:
ThrowIllegalInstructionException(*this, m_input.pc, "Invalid read from ASR20: func = %d", (int)func);
break;
}
return PIPE_CONTINUE;
}
Pipeline::PipeAction Pipeline::ExecuteStage::ExecWriteASR19(uint8_t func)
{
assert(m_input.Rav.m_size == sizeof(Integer));
assert(m_input.Rbv.m_size == sizeof(Integer));
Integer Rav = m_input.Rav.m_integer.get(m_input.Rav.m_size);
Integer Rbv = m_input.Rbv.m_integer.get(m_input.Rbv.m_size);
switch (func)
{
case S_OPT2_CREBA:
case S_OPT2_CREBI:
return ExecBundle(Rav, (m_input.function == S_OPT2_CREBI), Rbv, INVALID_REG_INDEX);
case S_OPT2_PRINT:
COMMIT {
ExecDebug(Rav, Rbv);
m_output.Rc = INVALID_REG;
}
break;
default:
ThrowIllegalInstructionException(*this, m_input.pc, "Invalid write to ASR19: func = %d", (int)func);
break;
}
return PIPE_CONTINUE;
}
Pipeline::PipeAction Pipeline::ExecuteStage::ExecWriteASR20(uint8_t func)
{
assert(m_input.Rav.m_size == sizeof(Integer));
assert(m_input.Rbv.m_size == sizeof(Integer));
Integer Rav = m_input.Rav.m_integer.get(m_input.Rav.m_size);
Integer Rbv = m_input.Rbv.m_integer.get(m_input.Rbv.m_size);
auto& cpu = GetDRISC();
switch (func)
{
case S_OPT1_SETSTART:
case S_OPT1_SETLIMIT:
case S_OPT1_SETSTEP:
case S_OPT1_SETBLOCK:
{
FamilyProperty prop;
switch (func)
{
default:
case S_OPT1_SETSTART: prop = FAMPROP_START; break;
case S_OPT1_SETLIMIT: prop = FAMPROP_LIMIT; break;
case S_OPT1_SETSTEP: prop = FAMPROP_STEP; break;
case S_OPT1_SETBLOCK: prop = FAMPROP_BLOCK; break;
}
FID fid = cpu.UnpackFID(Rav);
return SetFamilyProperty(fid, prop, Rbv);
}
case S_OPT1_BREAK:
return ExecBreak();
case S_OPT1_PUTG:
return WriteFamilyRegister(RRT_GLOBAL, RT_INTEGER, cpu.UnpackFID(Rav), m_input.asi);
case S_OPT1_PUTS:
return WriteFamilyRegister(RRT_FIRST_DEPENDENT, RT_INTEGER, cpu.UnpackFID(Rav), m_input.asi);
case S_OPT1_FPUTG:
return WriteFamilyRegister(RRT_GLOBAL, RT_FLOAT, cpu.UnpackFID(Rav), m_input.asi);
case S_OPT1_FPUTS:
return WriteFamilyRegister(RRT_FIRST_DEPENDENT, RT_FLOAT, cpu.UnpackFID(Rav), m_input.asi);
case S_OPT1_DETACH:
return ExecDetach(cpu.UnpackFID(Rav));
default:
ThrowIllegalInstructionException(*this, m_input.pc, "Invalid write to ASR20: func = %d", (int)func);
break;
}
return PIPE_CONTINUE;
}
Pipeline::PipeAction Pipeline::ExecuteStage::ExecuteInstruction()
{
auto& cpu = GetDRISC();
switch (m_input.op1)
{
case S_OP1_CALL:
COMMIT
{
m_output.pc = m_input.pc + m_input.displacement * sizeof(Instruction);
m_output.Rcv.m_integer = m_input.pc;
m_output.Rcv.m_state = RST_FULL;
m_output.Rcv.m_size = sizeof(Integer);
DebugFlowWrite("F%u/T%u(%llu) %s call %s",
(unsigned)m_input.fid, (unsigned)m_input.tid, (unsigned long long)m_input.logical_index, m_input.pc_sym,
cpu.GetSymbolTable()[m_output.pc].c_str());
}
return PIPE_FLUSH;
case S_OP1_BRANCH:
switch (m_input.op2)
{
case S_OP2_SETHI:
COMMIT {
m_output.Rcv.m_integer = m_input.Rbv.m_integer.get(m_input.Rbv.m_size) << 10;
m_output.Rcv.m_size = m_input.Rbv.m_size;
m_output.Rcv.m_state = RST_FULL;
}
break;
case S_OP2_BRANCH_INT: // Bicc
case S_OP2_BRANCH_FLT: // FBfcc
case S_OP2_BRANCH_COP: // CBccc
{
auto& thread = m_threadTable[m_input.tid];
bool taken;
switch (m_input.op2)
{
default:
case S_OP2_BRANCH_COP: taken = false; break; // We don't have a co-processor
case S_OP2_BRANCH_INT: taken = BranchTakenInt(m_input.function, thread.psr); break;
case S_OP2_BRANCH_FLT: taken = BranchTakenFlt(m_input.function, thread.fsr); break;
}
if (taken)
{
// Branch was taken; note that we don't annul
COMMIT {
m_output.pc = m_input.pc + m_input.displacement * sizeof(Instruction);
DebugFlowWrite("F%u/T%u(%llu) %s branch %s",
(unsigned)m_input.fid, (unsigned)m_input.tid, (unsigned long long)m_input.logical_index, m_input.pc_sym,
cpu.GetSymbolTable()[m_output.pc].c_str());
}
return PIPE_FLUSH;
}
break;
}
case S_OP2_UNIMPL:
default:
ThrowIllegalInstructionException(*this, m_input.pc, "Unimplemented branch instruction");
}
break;
case S_OP1_MEMORY:
{
MemAddr address = (MemAddr)(m_input.Rav.m_integer.get(m_input.Rav.m_size) + (int32_t)m_input.Rbv.m_integer.get(m_input.Rbv.m_size));
MemSize size = 0;
bool sign_extend = false;
switch (m_input.op3)
{
case S_OP3_LDSB: size = 1; sign_extend = true; break;
case S_OP3_LDSH: size = 2; sign_extend = true; break;
case S_OP3_STB: case S_OP3_LDUB: size = 1; break;
case S_OP3_STH: case S_OP3_LDUH: size = 2; break;
case S_OP3_LDF: case S_OP3_STF:
case S_OP3_ST: case S_OP3_LD: size = 4; break;
case S_OP3_LDDF: case S_OP3_STDF:
case S_OP3_STD: case S_OP3_LDD: size = 8; break;
// Load/Store Alternate address space.
// These are privileged instructions and we don't support them yet.
case S_OP3_STBA: case S_OP3_STHA: case S_OP3_STA: case S_OP3_STDA:
case S_OP3_LDSBA: case S_OP3_LDSHA: case S_OP3_LDUBA:
case S_OP3_LDUHA: case S_OP3_LDA: case S_OP3_LDDA:
default:
ThrowIllegalInstructionException(*this, m_input.pc, "Unimplemented load/store with ASI");
break;
}
if ((address & (size - 1)) != 0)
{
ThrowIllegalInstructionException(*this, m_input.pc, "Misaligned address for size %u: %#llx",
(unsigned)size, (unsigned long long)address);
}
COMMIT
{
switch (m_input.op3)
{
case S_OP3_STB:
case S_OP3_STH:
case S_OP3_ST:
case S_OP3_STD:
case S_OP3_STF:
case S_OP3_STDF:
m_output.Rcv = m_input.Rsv;
m_output.Ra = m_input.Rs; // for debugging memory only
break;
}
m_output.address = address;
m_output.size = size;
m_output.sign_extend = sign_extend;
}
break;
}
case S_OP1_OTHER:
{
auto& thread = m_threadTable[m_input.tid];
switch (m_input.op3)
{
case S_OP3_FPOP1:
case S_OP3_FPOP2:
{
FPUOperation fpuop = FPU_OP_NONE;
COMMIT {
m_output.Rcv.m_size = m_input.RcSize;
}
switch (m_input.function)
{
// Convert Int to FP
case S_OPF_FITOS:
case S_OPF_FITOD:
case S_OPF_FITOQ:
COMMIT {
m_output.Rcv.m_state = RST_FULL;
m_output.Rcv.m_float.fromfloat(
(double)m_input.Rbv.m_float.toint(m_input.Rbv.m_size),
m_output.Rcv.m_size);
}
break;
// Convert FP to Int
case S_OPF_FSTOI:
case S_OPF_FDTOI:
case S_OPF_FQTOI:
COMMIT {
m_output.Rcv.m_state = RST_FULL;
m_output.Rcv.m_float.fromint(
(uint64_t)m_input.Rbv.m_float.tofloat(m_input.Rbv.m_size),
m_output.Rcv.m_size);
}
break;
// Convert FP to FP
case S_OPF_FSTOD:
case S_OPF_FSTOQ:
case S_OPF_FDTOS:
case S_OPF_FDTOQ:
case S_OPF_FQTOS:
case S_OPF_FQTOD:
COMMIT {
m_output.Rcv.m_state = RST_FULL;
m_output.Rcv.m_float.fromfloat(
m_input.Rbv.m_float.tofloat(m_input.Rbv.m_size),
m_output.Rcv.m_size);
}
break;
case S_OPF_FPRINTS:
case S_OPF_FPRINTD:
case S_OPF_FPRINTQ:
COMMIT {
ExecDebug(m_input.Rav.m_float.tofloat(m_input.Rav.m_size), (Integer)m_input.Rbv.m_integer.get(m_input.Rbv.m_size));
m_output.Rc = INVALID_REG;
}
break;
case S_OPF_FMOV:
COMMIT{
m_output.Rcv.m_float.fromfloat(m_input.Rbv.m_float.tofloat(m_input.Rbv.m_size), m_output.Rcv.m_size);
m_output.Rcv.m_state = RST_FULL;
}
break;
case S_OPF_FNEG:
COMMIT{
m_output.Rcv.m_float.fromfloat(-m_input.Rbv.m_float.tofloat(m_input.Rbv.m_size), m_output.Rcv.m_size);
m_output.Rcv.m_state = RST_FULL;
}
break;
case S_OPF_FABS:
COMMIT{
m_output.Rcv.m_float.fromfloat(abs(m_input.Rbv.m_float.tofloat(m_input.Rbv.m_size)), m_output.Rcv.m_size);
m_output.Rcv.m_state = RST_FULL;
}
break;
// FP Compare
case S_OPF_FCMPS: case S_OPF_FCMPD: case S_OPF_FCMPQ:
case S_OPF_FCMPES: case S_OPF_FCMPED: case S_OPF_FCMPEQ:
COMMIT {
const double Ra = m_input.Rav.m_float.tofloat(m_input.Rav.m_size);
const double Rb = m_input.Rbv.m_float.tofloat(m_input.Rbv.m_size);
thread.fsr = (thread.fsr & ~FSR_FCC) |
isunordered(Ra, Rb) ? +FSR_FCC_UO :
isgreater (Ra, Rb) ? +FSR_FCC_GT :
isless (Ra, Rb) ? +FSR_FCC_LT : +FSR_FCC_EQ;
}
break;
case S_OPF_FSQRTS: case S_OPF_FSQRTD: case S_OPF_FSQRTQ: fpuop = FPU_OP_SQRT; break;
case S_OPF_FADDS: case S_OPF_FADDD: case S_OPF_FADDQ: fpuop = FPU_OP_ADD; break;
case S_OPF_FSUBS: case S_OPF_FSUBD: case S_OPF_FSUBQ: fpuop = FPU_OP_SUB; break;
case S_OPF_FMULS: case S_OPF_FMULD: case S_OPF_FMULQ: fpuop = FPU_OP_MUL; break;
case S_OPF_FDIVS: case S_OPF_FDIVD: case S_OPF_FDIVQ: fpuop = FPU_OP_DIV; break;
case S_OPF_FSMULD: fpuop = FPU_OP_MUL; break;
case S_OPF_FDMULQ: fpuop = FPU_OP_MUL; break;
}
if (fpuop != FPU_OP_NONE)
{
// Absent FPU should trap during decode, not execute.
assert(m_fpu != NULL);
// Dispatch long-latency operation to FPU
if (!m_fpu->QueueOperation(m_fpuSource, fpuop, m_input.RcSize,
m_input.Rav.m_float.tofloat(m_input.Rav.m_size),
m_input.Rbv.m_float.tofloat(m_input.Rbv.m_size), m_input.Rc))
{
DeadlockWrite("F%u/T%u(%llu) %s unable to queue FP operation %u on %s for %s",
(unsigned)m_input.fid, (unsigned)m_input.tid, (unsigned long long)m_input.logical_index, m_input.pc_sym,
(unsigned)fpuop, m_fpu->GetName().c_str(), m_input.Rc.str().c_str());
return PIPE_STALL;
}
COMMIT
{
m_output.Rcv = MAKE_PENDING_PIPEVALUE(m_output.Rcv.m_size);
// We've executed a floating point operation
m_flop++;
}
}
break;
}
case S_OP3_SLL:
case S_OP3_SRL:
case S_OP3_SRA:
case S_OP3_MULScc:
COMMIT {
m_output.Rcv.m_integer = ExecOtherInteger(
m_input.op3,
(uint32_t)m_input.Rav.m_integer.get(m_input.Rav.m_size),
(uint32_t)m_input.Rbv.m_integer.get(m_input.Rbv.m_size),
thread.Y, thread.psr);
m_output.Rcv.m_state = RST_FULL;
}
break;
case S_OP3_RDASR:
// The displacement field holds the original Ra specifier
switch (m_input.displacement)
{
case 0:
// RDY: Read Y Register
COMMIT {
m_output.Rcv.m_integer = thread.Y;
m_output.Rcv.m_state = RST_FULL;
}
break;
case 4:
// RDTICK: read processor cycle counter
COMMIT {
m_output.Rcv.m_integer = cpu.GetCycleNo() & 0xffffffffUL;
m_output.Rcv.m_state = RST_FULL;
}
break;
case 5:
// RDPC: read program counter
COMMIT {
m_output.Rcv.m_integer = m_input.pc;
m_output.Rcv.m_state = RST_FULL;
}
break;
case 15:
// STBAR: Store Barrier
// Rc has to be %g0 (invalid)
if (m_input.Rc.valid()) {
ThrowIllegalInstructionException(*this, m_input.pc, "Store barrier with valid output register %s", m_input.Rc.str().c_str());
}
if (!MemoryWriteBarrier(m_input.tid))
{
// Suspend thread at out PC
COMMIT {
m_output.pc = m_input.pc;
m_output.suspend = SUSPEND_MEMORY_BARRIER;
m_output.swch = true;
m_output.kill = false;
m_output.Rc = INVALID_REG;
}
}
return PIPE_FLUSH;
case 19:
return ExecReadASR19(m_input.function);
case 20:
return ExecReadASR20(m_input.function);
default:
ThrowIllegalInstructionException(*this, m_input.pc, "Unsupported read from ASR%d", (int)m_input.displacement);
break;
}
break;
case S_OP3_WRASR:
switch (m_input.displacement)
{
case 0:
// WRY: Write Y Register
COMMIT {
thread.Y = (uint32_t)(m_input.Rav.m_integer.get(m_input.Rav.m_size) ^ m_input.Rbv.m_integer.get(m_input.Rbv.m_size));
}
break;
case 20:
return ExecWriteASR20(m_input.function);
case 19:
return ExecWriteASR19(m_input.function);
default:
ThrowIllegalInstructionException(*this, m_input.pc, "Unsupported write to ASR%d", (int)m_input.displacement);
break;
}
break;
case S_OP3_SAVE:
case S_OP3_RESTORE:
{
ThrowIllegalInstructionException(*this, m_input.pc, "SAVE/RESTORE not supported on D-RISC");
break;
}
case S_OP3_JMPL:
{
MemAddr target = (MemAddr)(m_input.Rav.m_integer.get(m_input.Rav.m_size) + m_input.Rbv.m_integer.get(m_input.Rbv.m_size));
if ((target & (sizeof(Instruction) - 1)) != 0)
{
ThrowIllegalInstructionException(*this, m_input.pc, "Misaligned jump to %#llx", (unsigned long long)target);
}
COMMIT
{
// Note that we don't annul
m_output.pc = target;
m_output.Rcv.m_integer = m_input.pc;
m_output.Rcv.m_state = RST_FULL;
DebugFlowWrite("F%u/T%u(%llu) %s branch %s",
(unsigned)m_input.fid, (unsigned)m_input.tid, (unsigned long long)m_input.logical_index, m_input.pc_sym,
cpu.GetSymbolTable()[m_output.pc].c_str());
}
return PIPE_FLUSH;
}
case S_OP3_RDPSR:
case S_OP3_RDWIM:
case S_OP3_RDTBR:
case S_OP3_TADDcc:
case S_OP3_TSUBcc:
case S_OP3_TADDccTV:
case S_OP3_TSUBccTV:
case S_OP3_WRPSR:
case S_OP3_WRWIM:
case S_OP3_WRTBR:
case S_OP3_RETT:
case S_OP3_Ticc:
case S_OP3_FLUSH:
case S_OP3_CPOP1:
case S_OP3_CPOP2:
// We don't support these instructions (yet?)
ThrowIllegalInstructionException(*this, m_input.pc, "Unsupported opcode: %#x", (unsigned)m_input.op3);
break;
default:
if (m_input.op3 < 0x20)
{
COMMIT {
m_output.Rcv.m_state = RST_FULL;
m_output.Rcv.m_size = m_input.Rav.m_size;
m_output.Rcv.m_integer = ExecBasicInteger(
m_input.op3,
(uint32_t)m_input.Rav.m_integer.get(m_input.Rav.m_size),
(uint32_t)m_input.Rbv.m_integer.get(m_input.Rbv.m_size),
thread.Y, thread.psr);
}
}
else
{
// Invalid instruction
ThrowIllegalInstructionException(*this, m_input.pc, "Unsupported opcode: %#x", (unsigned)m_input.op3);
}
break;
}
break;
}
}
return PIPE_CONTINUE;
}
}
}
| 36.911227 | 154 | 0.535191 | [
"vector"
] |
a375b6236bdf586364a184257818970d8a944d3a | 4,263 | cc | C++ | Code/Base/accessors/current/dataaccess/IConstDataSource.cc | rtobar/askapsoft | 6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e | [
"BSL-1.0",
"Apache-2.0",
"OpenSSL"
] | 1 | 2020-06-18T08:37:43.000Z | 2020-06-18T08:37:43.000Z | Code/Base/accessors/current/dataaccess/IConstDataSource.cc | ATNF/askapsoft | d839c052d5c62ad8a511e58cd4b6548491a6006f | [
"BSL-1.0",
"Apache-2.0",
"OpenSSL"
] | null | null | null | Code/Base/accessors/current/dataaccess/IConstDataSource.cc | ATNF/askapsoft | d839c052d5c62ad8a511e58cd4b6548491a6006f | [
"BSL-1.0",
"Apache-2.0",
"OpenSSL"
] | null | null | null | /// @file IConstDataSource.cc
/// @brief Access to a source of visibility data
/// @details IConstDataSource allows access to a source of visibility data,
/// probably either a MeasurementSet or a stream.
///
/// @copyright (c) 2007 CSIRO
/// Australia Telescope National Facility (ATNF)
/// Commonwealth Scientific and Industrial Research Organisation (CSIRO)
/// PO Box 76, Epping NSW 1710, Australia
/// atnf-enquiries@csiro.au
///
/// This file is part of the ASKAP software distribution.
///
/// The ASKAP software distribution is free software: you can redistribute it
/// and/or modify it under the terms of the GNU General Public License as
/// published by the Free Software Foundation; either version 2 of the License,
/// or (at your option) any later version.
///
/// This program is distributed in the hope that it will be useful,
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
/// GNU General Public License for more details.
///
/// You should have received a copy of the GNU General Public License
/// along with this program; if not, write to the Free Software
/// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
///
/// @author Max Voronkov <maxim.voronkov@csiro.au>
///
#include <dataaccess/IConstDataSource.h>
namespace askap {
namespace accessors {
// an empty virtual destructor to make the compiler happy
IConstDataSource::~IConstDataSource()
{
}
/// get iterator over a selected part of the dataset represented
/// by this DataSource object. Default data conversion policies
/// will be used, see IDataConverter.h for default values.
/// The default implementation is via the most general
/// createConstIterator(...) call, override it in derived classes,
/// if a (bit) higher performance is required
///
/// @param[in] sel a shared pointer to the selector object defining
/// which subset of the data is used
/// @return a shared pointer to DataIterator object
///
/// The method acts as a factory by creating a new DataIterator.
/// The lifetime of this iterator is the same as the lifetime of
/// the DataSource object. Therefore, it can be reused multiple times,
/// if necessary.
boost::shared_ptr<IConstDataIterator>
IConstDataSource::createConstIterator(const
IDataSelectorConstPtr &sel) const {
// create a new default converter just for this new iterator
return createConstIterator(sel,createConverter());
}
/// get iterator over the whole dataset represented by this DataSource
/// object. Default data conversion policies will be used, see
/// IDataConverter.h for default values. Default implementation is
/// via the most general createConstIterator(...) call, override it in
/// derived classes, if a (bit) higher performance is required
///
/// @return a shared pointer to ConstDataIterator object
///
/// The method acts as a factory by creating a new DataIterator.
/// The lifetime of this iterator is the same as the lifetime of
/// the DataSource object. Therefore, it can be reused multiple times,
/// if necessary.
boost::shared_ptr<IConstDataIterator>
IConstDataSource::createConstIterator() const {
// create new default selector and converter just for this new iterator
return createConstIterator(createSelector(),createConverter());
}
/// get iterator over the whole dataset with explicitly specified
/// conversion policies. Default implementation is via the most
/// general createConstIterator(...) call, override it in the derived
/// classes, if a (bit) higer performance is required
///
/// @param[in] conv a shared pointer to the converter object defining
/// reference frames and units to be used
/// @return a shared pointer to ConstDataIterator object
///
/// The method acts as a factory by creating a new ConstDataIterator.
/// The lifetime of this iterator is the same as the lifetime of
/// the DataSource object. Therefore, it can be reused multiple times,
/// if necessary.
boost::shared_ptr<IConstDataIterator>
IConstDataSource::createConstIterator(const
IDataConverterConstPtr &conv) const {
return createConstIterator(createSelector(),conv);
}
} // end of namespace accessors
} // end of namespace askap
| 40.990385 | 79 | 0.745484 | [
"object"
] |
a3770f750e7079454c2375af5199e5e58cb6a45c | 5,223 | hpp | C++ | include/cppurses/widget/layouts/detail/linear_layout.hpp | thknepper/CPPurses | 4f35ba5284bc5ac563214f73f494bd75fd5bf73b | [
"MIT"
] | 1 | 2020-02-22T21:18:11.000Z | 2020-02-22T21:18:11.000Z | include/cppurses/widget/layouts/detail/linear_layout.hpp | thknepper/CPPurses | 4f35ba5284bc5ac563214f73f494bd75fd5bf73b | [
"MIT"
] | null | null | null | include/cppurses/widget/layouts/detail/linear_layout.hpp | thknepper/CPPurses | 4f35ba5284bc5ac563214f73f494bd75fd5bf73b | [
"MIT"
] | null | null | null | #ifndef CPPURSES_WIDGET_LAYOUTS_DETAIL_LINEAR_LAYOUT_HPP
#define CPPURSES_WIDGET_LAYOUTS_DETAIL_LINEAR_LAYOUT_HPP
#include <cppurses/painter/painter.hpp>
#include <cppurses/system/events/move_event.hpp>
#include <cppurses/system/events/resize_event.hpp>
#include <cppurses/widget/layout.hpp>
#include "shared_space.hpp"
#include "unique_space.hpp"
namespace cppurses::layout::detail {
template <typename Get_policy_t, typename Get_length_t, typename Get_offset_t>
struct Dimension_parameters {
using get_policy = Get_policy_t; // Size_policy const&(Widget const&)
using get_length = Get_length_t; // std::size_t(Widget const&) [w/h]
using get_offset = Get_offset_t; // std::size_t(Widget const&) [global x/y]
};
template <typename Primary_t,
typename Secondary_t,
typename Get_area_t,
typename Get_point_t>
struct Linear_layout_parameters {
using Primary = Primary_t;
using Secondary = Secondary_t;
using get_area = Get_area_t; // Area(size_t primary, size_t secondary)
using get_point = Get_point_t; // Point(size_t primary, size_t secondary)
};
/// Lays out Widgets in 2D, sharing space in a primary dimension.
/** The secondary dimension does not share space among Widgets. */
template <typename Child_t, typename Parameters>
class Linear_layout : public Layout<Child_t> {
protected:
void update_geometry() override
{
auto const primary_lengths = shared_space_.calculate_lengths(*this);
auto const primary_pos =
shared_space_.calculate_positions(primary_lengths);
auto const secondary_lengths = unique_space_.calculate_lengths(*this);
auto const secondary_pos =
unique_space_.calculate_positions(secondary_lengths);
this->send_enable_disable_events(primary_lengths, secondary_lengths);
this->send_resize_events(primary_lengths, secondary_lengths);
this->send_move_events(primary_pos, secondary_pos);
}
/// Return the child Widget offset, the first widget included in the layout.
auto get_offset() const -> std::size_t { return offset_; }
/// Sets the child Widget offset, does not do bounds checking.
auto set_offset(std::size_t index)
{
offset_ = index;
shared_space_.set_offset(index);
unique_space_.set_offset(index);
this->update_geometry();
this->force_repaint_empty_space();
}
private:
using Length_list = std::vector<std::size_t>;
using Position_list = std::vector<std::size_t>;
std::size_t offset_ = 0uL;
Shared_space<Parameters> shared_space_;
Unique_space<Parameters> unique_space_;
private:
// Hack until the paint system is updated and treats layouts accordingly.
void force_repaint_empty_space() { Painter{*this}; }
void send_enable_disable_events(Length_list const& primary,
Length_list const& secondary)
{
auto const children = this->get_children();
for (auto i = 0uL; i < offset_; ++i) {
if (children[i].enabled())
children[i].disable(true, false);
}
for (auto i = 0uL; i < primary.size(); ++i) {
auto& child = children[offset_ + i];
if (is_valid(primary[i], secondary[i])) {
if (not child.enabled())
child.enable(true, false);
}
else {
if (child.enabled())
child.disable(true, false);
}
}
}
void send_resize_events(Length_list const& primary,
Length_list const& secondary)
{
auto const children = this->get_children();
for (auto i = 0uL; i < primary.size(); ++i) {
auto& child = children[offset_ + i];
if (child.enabled()) {
auto const area =
typename Parameters::get_area{}(primary[i], secondary[i]);
System::post_event<Resize_event>(child, area);
}
}
}
void send_move_events(Position_list const& primary,
Position_list const& secondary)
{
auto const children = this->get_children();
auto const primary_offset =
typename Parameters::Primary::get_offset{}(*this);
auto const secondary_offset =
typename Parameters::Secondary::get_offset{}(*this);
for (auto i = 0uL; i < primary.size(); ++i) {
auto& child = children[offset_ + i];
if (child.enabled()) {
auto const point = typename Parameters::get_point{}(
primary[i] + primary_offset,
secondary[i] + secondary_offset);
System::post_event<Move_event>(child, point);
}
}
}
/// Determine whether a widget is valid to display from its lengths
/** A length of zero in any dimension means the Widget will be disabled. */
static auto is_valid(std::size_t primary, std::size_t secondary) -> bool
{
return primary != 0 && secondary != 0;
}
};
} // namespace cppurses::layout::detail
#endif // CPPURSES_WIDGET_LAYOUTS_DETAIL_LINEAR_LAYOUT_HPP
| 37.042553 | 80 | 0.635076 | [
"vector"
] |
a37b3483366be93a6993f5f41e7fbbc2b3931d81 | 8,077 | cpp | C++ | engine/src/cython/engine.cpp | romulo-auccapuclla/blazingsql | c85429479cabc0907212e880d590441f25eb3b59 | [
"Apache-2.0"
] | null | null | null | engine/src/cython/engine.cpp | romulo-auccapuclla/blazingsql | c85429479cabc0907212e880d590441f25eb3b59 | [
"Apache-2.0"
] | null | null | null | engine/src/cython/engine.cpp | romulo-auccapuclla/blazingsql | c85429479cabc0907212e880d590441f25eb3b59 | [
"Apache-2.0"
] | null | null | null | #include "../../include/engine/engine.h"
#include "../CalciteInterpreter.h"
#include "../io/DataLoader.h"
#include "../io/Schema.h"
#include "../io/data_parser/ArgsUtil.h"
#include "../io/data_parser/CSVParser.h"
#include "../io/data_parser/GDFParser.h"
#include "../io/data_parser/JSONParser.h"
#include "../io/data_parser/OrcParser.h"
#include "../io/data_parser/ArrowParser.h"
#include "../io/data_parser/ParquetParser.h"
#include "../io/data_provider/DummyProvider.h"
#include "../io/data_provider/UriDataProvider.h"
#include "../skip_data/SkipDataProcessor.h"
#include "../execution_graph/logic_controllers/LogicalFilter.h"
#include "communication/network/Server.h"
#include <numeric>
std::pair<std::vector<ral::io::data_loader>, std::vector<ral::io::Schema>> get_loaders_and_schemas(
const std::vector<TableSchema> & tableSchemas,
const std::vector<std::vector<std::string>> & tableSchemaCppArgKeys,
const std::vector<std::vector<std::string>> & tableSchemaCppArgValues,
const std::vector<std::vector<std::string>> & filesAll,
const std::vector<int> & fileTypes,
const std::vector<std::vector<std::map<std::string, std::string>>> & uri_values){
std::vector<ral::io::data_loader> input_loaders;
std::vector<ral::io::Schema> schemas;
for(int i = 0; i < tableSchemas.size(); i++) {
auto tableSchema = tableSchemas[i];
auto files = filesAll[i];
auto fileType = fileTypes[i];
auto kwargs = ral::io::to_map(tableSchemaCppArgKeys[i], tableSchemaCppArgValues[i]);
ral::io::ReaderArgs args = ral::io::getReaderArgs((ral::io::DataType) fileType, kwargs);
std::vector<cudf::type_id> types;
for(int col = 0; col < tableSchemas[i].types.size(); col++) {
types.push_back(tableSchemas[i].types[col]);
}
auto schema = ral::io::Schema(tableSchema.names,
tableSchema.calcite_to_file_indices,
types,
tableSchema.in_file,
tableSchema.row_groups_ids);
std::shared_ptr<ral::io::data_parser> parser;
if(fileType == ral::io::DataType::PARQUET) {
parser = std::make_shared<ral::io::parquet_parser>();
} else if(fileType == gdfFileType || fileType == daskFileType) {
parser = std::make_shared<ral::io::gdf_parser>(tableSchema.blazingTableView);
} else if(fileType == ral::io::DataType::ORC) {
parser = std::make_shared<ral::io::orc_parser>(args.orcReaderArg);
} else if(fileType == ral::io::DataType::JSON) {
parser = std::make_shared<ral::io::json_parser>(args.jsonReaderArg);
} else if(fileType == ral::io::DataType::CSV) {
parser = std::make_shared<ral::io::csv_parser>(args.csvReaderArg);
} else if(fileType == ral::io::DataType::ARROW){
parser = std::make_shared<ral::io::arrow_parser>(tableSchema.arrow_table);
}
std::shared_ptr<ral::io::data_provider> provider;
std::vector<Uri> uris;
for(int fileIndex = 0; fileIndex < filesAll[i].size(); fileIndex++) {
uris.push_back(Uri{filesAll[i][fileIndex]});
}
if(fileType == ral::io::DataType::CUDF || fileType == ral::io::DataType::DASK_CUDF) {
// is gdf
provider = std::make_shared<ral::io::dummy_data_provider>();
} else {
// is file (this includes the case where fileType is UNDEFINED too)
provider = std::make_shared<ral::io::uri_data_provider>(uris, uri_values[i]);
}
ral::io::data_loader loader(parser, provider);
input_loaders.push_back(loader);
schemas.push_back(schema);
}
return std::make_pair(std::move(input_loaders), std::move(schemas));
}
std::unique_ptr<ResultSet> runQuery(int32_t masterIndex,
std::vector<NodeMetaDataTCP> tcpMetadata,
std::vector<std::string> tableNames,
std::vector<TableSchema> tableSchemas,
std::vector<std::vector<std::string>> tableSchemaCppArgKeys,
std::vector<std::vector<std::string>> tableSchemaCppArgValues,
std::vector<std::vector<std::string>> filesAll,
std::vector<int> fileTypes,
int32_t ctxToken,
std::string query,
uint64_t accessToken,
std::vector<std::vector<std::map<std::string, std::string>>> uri_values,
bool use_execution_graph) {
std::vector<ral::io::data_loader> input_loaders;
std::vector<ral::io::Schema> schemas;
std::tie(input_loaders, schemas) = get_loaders_and_schemas(tableSchemas, tableSchemaCppArgKeys,
tableSchemaCppArgValues, filesAll, fileTypes, uri_values);
try {
using blazingdb::manager::experimental::Context;
using blazingdb::transport::experimental::Node;
std::vector<Node> contextNodes;
for(auto currentMetadata : tcpMetadata) {
auto address =
blazingdb::transport::experimental::Address::TCP(currentMetadata.ip, currentMetadata.communication_port, 0);
contextNodes.push_back(Node(address));
}
Context queryContext{ctxToken, contextNodes, contextNodes[masterIndex], ""};
ral::communication::network::experimental::Server::getInstance().registerContext(ctxToken);
// Execute query
std::unique_ptr<ral::frame::BlazingTable> frame;
if (use_execution_graph) {
frame = execute_plan(input_loaders, schemas, tableNames, query, accessToken, queryContext);
} else {
frame = evaluate_query(input_loaders, schemas, tableNames, query, accessToken, queryContext);
}
std::unique_ptr<ResultSet> result = std::make_unique<ResultSet>();
result->names = frame->names();
result->cudfTable = frame->releaseCudfTable();
result->skipdata_analysis_fail = false;
return result;
} catch(const std::exception & e) {
std::cerr << e.what() << std::endl;
throw;
}
}
std::unique_ptr<ResultSet> performPartition(int32_t masterIndex,
std::vector<NodeMetaDataTCP> tcpMetadata,
int32_t ctxToken,
const ral::frame::BlazingTableView & table,
std::vector<std::string> column_names) {
try {
std::unique_ptr<ResultSet> result = std::make_unique<ResultSet>();
std::vector<int> columnIndices;
using blazingdb::manager::experimental::Context;
using blazingdb::transport::experimental::Node;
std::vector<Node> contextNodes;
for(auto currentMetadata : tcpMetadata) {
auto address =
blazingdb::transport::experimental::Address::TCP(currentMetadata.ip, currentMetadata.communication_port, 0);
contextNodes.push_back(Node(address));
}
Context queryContext{ctxToken, contextNodes, contextNodes[masterIndex], ""};
ral::communication::network::experimental::Server::getInstance().registerContext(ctxToken);
const std::vector<std::string> & table_col_names = table.names();
for(auto col_name:column_names){
auto it = std::find(table_col_names.begin(), table_col_names.end(), col_name);
if(it != table_col_names.end()){
columnIndices.push_back(std::distance(table_col_names.begin(), it));
}
}
std::unique_ptr<ral::frame::BlazingTable> frame = ral::processor::process_distribution_table(
table, columnIndices, &queryContext);
result->names = frame->names();
result->cudfTable = frame->releaseCudfTable();
result->skipdata_analysis_fail = false;
return result;
} catch(const std::exception & e) {
std::cerr << "**[performPartition]** error partitioning table.\n";
std::cerr << e.what() << std::endl;
throw;
}
}
std::unique_ptr<ResultSet> runSkipData(ral::frame::BlazingTableView metadata,
std::vector<std::string> all_column_names, std::string query) {
try {
std::pair<std::unique_ptr<ral::frame::BlazingTable>, bool> result_pair = ral::skip_data::process_skipdata_for_table(
metadata, all_column_names, query);
std::unique_ptr<ResultSet> result = std::make_unique<ResultSet>();
result->skipdata_analysis_fail = result_pair.second;
if (!result_pair.second){ // if could process skip-data
result->names = result_pair.first->names();
result->cudfTable = result_pair.first->releaseCudfTable();
}
return result;
} catch(const std::exception & e) {
std::cerr << "**[runSkipData]** error parsing metadata.\n";
std::cerr << e.what() << std::endl;
throw;
}
}
TableScanInfo getTableScanInfo(std::string logicalPlan){
std::vector<std::string> relational_algebra_steps, table_names;
std::vector<std::vector<int>> table_columns;
getTableScanInfo(logicalPlan, relational_algebra_steps, table_names, table_columns);
return TableScanInfo{relational_algebra_steps, table_names, table_columns};
}
| 37.221198 | 118 | 0.725888 | [
"vector"
] |
a37db0ff5ac2dcabc9417e5fbae21018db95073a | 913,899 | cpp | C++ | cisco-ios-xr/ydk/models/cisco_ios_xr/fragmented/Cisco_IOS_XR_sysadmin_controllers_ncs5502_2.cpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 17 | 2016-12-02T05:45:49.000Z | 2022-02-10T19:32:54.000Z | cisco-ios-xr/ydk/models/cisco_ios_xr/fragmented/Cisco_IOS_XR_sysadmin_controllers_ncs5502_2.cpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2017-03-27T15:22:38.000Z | 2019-11-05T08:30:16.000Z | cisco-ios-xr/ydk/models/cisco_ios_xr/fragmented/Cisco_IOS_XR_sysadmin_controllers_ncs5502_2.cpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 11 | 2016-12-02T05:45:52.000Z | 2019-11-07T08:28:17.000Z |
#include <sstream>
#include <iostream>
#include <ydk/entity_util.hpp>
#include "bundle_info.hpp"
#include "generated_entity_lookup.hpp"
#include "Cisco_IOS_XR_sysadmin_controllers_ncs5502_2.hpp"
#include "Cisco_IOS_XR_sysadmin_controllers_ncs5502_3.hpp"
using namespace ydk;
namespace cisco_ios_xr {
namespace Cisco_IOS_XR_sysadmin_controllers_ncs5502 {
Controller::Fabric::Oper::Link::Rack::Port::Tx::Detail::Detail()
:
data_idx(this, {"port_data_idx"})
{
yang_name = "detail"; yang_parent_name = "tx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::Detail::~Detail()
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::Detail::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return false;
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::Detail::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Controller::Fabric::Oper::Link::Rack::Port::Tx::Detail::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "detail";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::Rack::Port::Tx::Detail::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::Rack::Port::Tx::Detail::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::Detail::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::Rack::Port::Tx::Detail::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::Detail::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::Detail::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::Detail::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx")
return true;
return false;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::Detail::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "detail"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::Detail::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::Detail::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::Detail::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::Rack::Port::Tx::Detail::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::Rack::Port::Tx::Detail::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::Rack::Port::Tx::Detail::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::Detail::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::Rack::Port::Tx::Detail::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::Detail::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::Detail::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::Detail::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::Detail::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::Detail::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::Detail::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::Detail::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::Rack::Port::Tx::Detail::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::Rack::Port::Tx::Detail::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::Rack::Port::Tx::Detail::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::Rack::Port::Tx::Detail::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::Detail::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::Detail::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::Detail::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::State()
:
up(std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up>())
, down(std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down>())
, mismatch(std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch>())
{
up->parent = this;
down->parent = this;
mismatch->parent = this;
yang_name = "state"; yang_parent_name = "tx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::~State()
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::has_data() const
{
if (is_presence_container) return true;
return (up != nullptr && up->has_data())
|| (down != nullptr && down->has_data())
|| (mismatch != nullptr && mismatch->has_data());
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::has_operation() const
{
return is_set(yfilter)
|| (up != nullptr && up->has_operation())
|| (down != nullptr && down->has_operation())
|| (mismatch != nullptr && mismatch->has_operation());
}
std::string Controller::Fabric::Oper::Link::Rack::Port::Tx::State::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "state";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::Rack::Port::Tx::State::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "up")
{
if(up == nullptr)
{
up = std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up>();
}
return up;
}
if(child_yang_name == "down")
{
if(down == nullptr)
{
down = std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down>();
}
return down;
}
if(child_yang_name == "mismatch")
{
if(mismatch == nullptr)
{
mismatch = std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch>();
}
return mismatch;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(up != nullptr)
{
_children["up"] = up;
}
if(down != nullptr)
{
_children["down"] = down;
}
if(mismatch != nullptr)
{
_children["mismatch"] = mismatch;
}
return _children;
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "up" || name == "down" || name == "mismatch")
return true;
return false;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Up()
:
data_idx(this, {"port_data_idx"})
, brief(std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Brief>())
, detail(std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Detail>())
{
brief->parent = this;
detail->parent = this;
yang_name = "up"; yang_parent_name = "state"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::~Up()
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return (brief != nullptr && brief->has_data())
|| (detail != nullptr && detail->has_data());
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter)
|| (brief != nullptr && brief->has_operation())
|| (detail != nullptr && detail->has_operation());
}
std::string Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "up";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
if(child_yang_name == "brief")
{
if(brief == nullptr)
{
brief = std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Brief>();
}
return brief;
}
if(child_yang_name == "detail")
{
if(detail == nullptr)
{
detail = std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Detail>();
}
return detail;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
if(brief != nullptr)
{
_children["brief"] = brief;
}
if(detail != nullptr)
{
_children["detail"] = detail;
}
return _children;
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx" || name == "brief" || name == "detail")
return true;
return false;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "up"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Brief::Brief()
:
data_idx(this, {"port_data_idx"})
{
yang_name = "brief"; yang_parent_name = "up"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Brief::~Brief()
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Brief::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return false;
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Brief::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Brief::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "brief";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Brief::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Brief::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Brief::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Brief::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Brief::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Brief::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Brief::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx")
return true;
return false;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Brief::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "brief"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Brief::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Brief::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Brief::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Brief::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Brief::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Brief::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Brief::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Brief::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Brief::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Brief::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Brief::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Brief::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Brief::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Brief::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Brief::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Brief::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Brief::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Brief::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Brief::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Brief::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Brief::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Brief::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Detail::Detail()
:
data_idx(this, {"port_data_idx"})
{
yang_name = "detail"; yang_parent_name = "up"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Detail::~Detail()
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Detail::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return false;
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Detail::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Detail::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "detail";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Detail::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Detail::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Detail::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Detail::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Detail::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Detail::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Detail::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx")
return true;
return false;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Detail::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "detail"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Detail::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Detail::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Detail::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Detail::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Detail::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Detail::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Detail::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Detail::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Detail::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Detail::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Detail::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Detail::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Detail::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Detail::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Detail::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Detail::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Detail::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Detail::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Detail::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Detail::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Detail::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Up::Detail::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Down()
:
data_idx(this, {"port_data_idx"})
, brief(std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Brief>())
, detail(std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Detail>())
{
brief->parent = this;
detail->parent = this;
yang_name = "down"; yang_parent_name = "state"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::~Down()
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return (brief != nullptr && brief->has_data())
|| (detail != nullptr && detail->has_data());
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter)
|| (brief != nullptr && brief->has_operation())
|| (detail != nullptr && detail->has_operation());
}
std::string Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "down";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
if(child_yang_name == "brief")
{
if(brief == nullptr)
{
brief = std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Brief>();
}
return brief;
}
if(child_yang_name == "detail")
{
if(detail == nullptr)
{
detail = std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Detail>();
}
return detail;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
if(brief != nullptr)
{
_children["brief"] = brief;
}
if(detail != nullptr)
{
_children["detail"] = detail;
}
return _children;
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx" || name == "brief" || name == "detail")
return true;
return false;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "down"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Brief::Brief()
:
data_idx(this, {"port_data_idx"})
{
yang_name = "brief"; yang_parent_name = "down"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Brief::~Brief()
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Brief::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return false;
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Brief::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Brief::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "brief";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Brief::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Brief::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Brief::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Brief::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Brief::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Brief::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Brief::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx")
return true;
return false;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Brief::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "brief"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Brief::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Brief::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Brief::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Brief::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Brief::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Brief::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Brief::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Brief::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Brief::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Brief::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Brief::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Brief::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Brief::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Brief::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Brief::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Brief::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Brief::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Brief::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Brief::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Brief::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Brief::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Brief::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Detail::Detail()
:
data_idx(this, {"port_data_idx"})
{
yang_name = "detail"; yang_parent_name = "down"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Detail::~Detail()
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Detail::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return false;
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Detail::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Detail::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "detail";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Detail::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Detail::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Detail::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Detail::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Detail::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Detail::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Detail::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx")
return true;
return false;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Detail::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "detail"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Detail::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Detail::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Detail::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Detail::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Detail::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Detail::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Detail::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Detail::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Detail::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Detail::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Detail::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Detail::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Detail::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Detail::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Detail::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Detail::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Detail::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Detail::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Detail::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Detail::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Detail::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Down::Detail::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Mismatch()
:
data_idx(this, {"port_data_idx"})
, brief(std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Brief>())
, detail(std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Detail>())
{
brief->parent = this;
detail->parent = this;
yang_name = "mismatch"; yang_parent_name = "state"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::~Mismatch()
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return (brief != nullptr && brief->has_data())
|| (detail != nullptr && detail->has_data());
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter)
|| (brief != nullptr && brief->has_operation())
|| (detail != nullptr && detail->has_operation());
}
std::string Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "mismatch";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
if(child_yang_name == "brief")
{
if(brief == nullptr)
{
brief = std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Brief>();
}
return brief;
}
if(child_yang_name == "detail")
{
if(detail == nullptr)
{
detail = std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Detail>();
}
return detail;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
if(brief != nullptr)
{
_children["brief"] = brief;
}
if(detail != nullptr)
{
_children["detail"] = detail;
}
return _children;
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx" || name == "brief" || name == "detail")
return true;
return false;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "mismatch"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Brief::Brief()
:
data_idx(this, {"port_data_idx"})
{
yang_name = "brief"; yang_parent_name = "mismatch"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Brief::~Brief()
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Brief::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return false;
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Brief::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Brief::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "brief";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Brief::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Brief::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Brief::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Brief::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Brief::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Brief::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Brief::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx")
return true;
return false;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Brief::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "brief"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Brief::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Brief::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Brief::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Brief::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Brief::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Brief::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Brief::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Brief::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Brief::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Brief::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Brief::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Brief::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Brief::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Brief::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Brief::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Brief::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Brief::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Brief::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Brief::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Brief::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Brief::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Brief::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Detail::Detail()
:
data_idx(this, {"port_data_idx"})
{
yang_name = "detail"; yang_parent_name = "mismatch"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Detail::~Detail()
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Detail::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return false;
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Detail::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Detail::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "detail";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Detail::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Detail::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Detail::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Detail::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Detail::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Detail::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Detail::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx")
return true;
return false;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Detail::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "detail"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Detail::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Detail::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Detail::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Detail::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Detail::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Detail::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Detail::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Detail::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Detail::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Detail::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Detail::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Detail::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Detail::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Detail::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Detail::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Detail::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Detail::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Detail::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Detail::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Detail::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Detail::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::State::Mismatch::Detail::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Statistics()
:
data_idx(this, {"port_data_idx"})
, brief(std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Brief>())
, detail(std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Detail>())
{
brief->parent = this;
detail->parent = this;
yang_name = "statistics"; yang_parent_name = "tx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::~Statistics()
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return (brief != nullptr && brief->has_data())
|| (detail != nullptr && detail->has_data());
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter)
|| (brief != nullptr && brief->has_operation())
|| (detail != nullptr && detail->has_operation());
}
std::string Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "statistics";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
if(child_yang_name == "brief")
{
if(brief == nullptr)
{
brief = std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Brief>();
}
return brief;
}
if(child_yang_name == "detail")
{
if(detail == nullptr)
{
detail = std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Detail>();
}
return detail;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
if(brief != nullptr)
{
_children["brief"] = brief;
}
if(detail != nullptr)
{
_children["detail"] = detail;
}
return _children;
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx" || name == "brief" || name == "detail")
return true;
return false;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
rack_num{YType::str, "rack_num"},
sfe_port{YType::str, "sfe_port"},
tx_control_cells_counter{YType::uint64, "TX_Control_cells_counter"},
tx_data_cell_counter{YType::uint64, "TX_Data_cell_counter"},
tx_data_byte_counter{YType::uint64, "TX_Data_byte_counter"},
rx_crc_errors_counter{YType::uint64, "RX_CRC_errors_counter"},
rx_lfec_fec_correctable_error{YType::uint64, "RX_LFEC_FEC_correctable_error"},
rx_8b_10b_disparity_errors{YType::uint64, "RX_8b_10b_disparity_errors"},
rx_control_cells_counter{YType::uint64, "RX_Control_cells_counter"},
rx_data_cell_counter{YType::uint64, "RX_Data_cell_counter"},
rx_data_byte_counter{YType::uint64, "RX_Data_byte_counter"},
rx_dropped_retransmitted_control{YType::uint64, "RX_dropped_retransmitted_control"},
tx_asyn_fifo_rate{YType::uint64, "TX_Asyn_fifo_rate"},
rx_asyn_fifo_rate{YType::uint64, "RX_Asyn_fifo_rate"},
rx_lfec_fec_uncorrectable_errors{YType::uint64, "RX_LFEC_FEC_uncorrectable_errors"},
rx_8b_10b_code_errors{YType::uint64, "RX_8b_10b_code_errors"},
is_link_error{YType::boolean, "is_link_error"},
link_crc_error{YType::uint32, "link_crc_error"},
link_size_error{YType::uint32, "link_size_error"},
link_mis_align_error{YType::uint32, "link_mis_align_error"},
link_code_group_error{YType::uint32, "link_code_group_error"},
link_no_sig_lock_error{YType::uint32, "link_no_sig_lock_error"},
link_no_sig_accept_error{YType::uint32, "link_no_sig_accept_error"},
link_tokens_error{YType::uint32, "link_tokens_error"},
error_token_count{YType::uint32, "error_token_count"}
{
yang_name = "data_idx"; yang_parent_name = "statistics"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::DataIdx::has_data() const
{
if (is_presence_container) return true;
return port_data_idx.is_set
|| rack_num.is_set
|| sfe_port.is_set
|| tx_control_cells_counter.is_set
|| tx_data_cell_counter.is_set
|| tx_data_byte_counter.is_set
|| rx_crc_errors_counter.is_set
|| rx_lfec_fec_correctable_error.is_set
|| rx_8b_10b_disparity_errors.is_set
|| rx_control_cells_counter.is_set
|| rx_data_cell_counter.is_set
|| rx_data_byte_counter.is_set
|| rx_dropped_retransmitted_control.is_set
|| tx_asyn_fifo_rate.is_set
|| rx_asyn_fifo_rate.is_set
|| rx_lfec_fec_uncorrectable_errors.is_set
|| rx_8b_10b_code_errors.is_set
|| is_link_error.is_set
|| link_crc_error.is_set
|| link_size_error.is_set
|| link_mis_align_error.is_set
|| link_code_group_error.is_set
|| link_no_sig_lock_error.is_set
|| link_no_sig_accept_error.is_set
|| link_tokens_error.is_set
|| error_token_count.is_set;
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::DataIdx::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(rack_num.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(tx_control_cells_counter.yfilter)
|| ydk::is_set(tx_data_cell_counter.yfilter)
|| ydk::is_set(tx_data_byte_counter.yfilter)
|| ydk::is_set(rx_crc_errors_counter.yfilter)
|| ydk::is_set(rx_lfec_fec_correctable_error.yfilter)
|| ydk::is_set(rx_8b_10b_disparity_errors.yfilter)
|| ydk::is_set(rx_control_cells_counter.yfilter)
|| ydk::is_set(rx_data_cell_counter.yfilter)
|| ydk::is_set(rx_data_byte_counter.yfilter)
|| ydk::is_set(rx_dropped_retransmitted_control.yfilter)
|| ydk::is_set(tx_asyn_fifo_rate.yfilter)
|| ydk::is_set(rx_asyn_fifo_rate.yfilter)
|| ydk::is_set(rx_lfec_fec_uncorrectable_errors.yfilter)
|| ydk::is_set(rx_8b_10b_code_errors.yfilter)
|| ydk::is_set(is_link_error.yfilter)
|| ydk::is_set(link_crc_error.yfilter)
|| ydk::is_set(link_size_error.yfilter)
|| ydk::is_set(link_mis_align_error.yfilter)
|| ydk::is_set(link_code_group_error.yfilter)
|| ydk::is_set(link_no_sig_lock_error.yfilter)
|| ydk::is_set(link_no_sig_accept_error.yfilter)
|| ydk::is_set(link_tokens_error.yfilter)
|| ydk::is_set(error_token_count.yfilter);
}
std::string Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (rack_num.is_set || is_set(rack_num.yfilter)) leaf_name_data.push_back(rack_num.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (tx_control_cells_counter.is_set || is_set(tx_control_cells_counter.yfilter)) leaf_name_data.push_back(tx_control_cells_counter.get_name_leafdata());
if (tx_data_cell_counter.is_set || is_set(tx_data_cell_counter.yfilter)) leaf_name_data.push_back(tx_data_cell_counter.get_name_leafdata());
if (tx_data_byte_counter.is_set || is_set(tx_data_byte_counter.yfilter)) leaf_name_data.push_back(tx_data_byte_counter.get_name_leafdata());
if (rx_crc_errors_counter.is_set || is_set(rx_crc_errors_counter.yfilter)) leaf_name_data.push_back(rx_crc_errors_counter.get_name_leafdata());
if (rx_lfec_fec_correctable_error.is_set || is_set(rx_lfec_fec_correctable_error.yfilter)) leaf_name_data.push_back(rx_lfec_fec_correctable_error.get_name_leafdata());
if (rx_8b_10b_disparity_errors.is_set || is_set(rx_8b_10b_disparity_errors.yfilter)) leaf_name_data.push_back(rx_8b_10b_disparity_errors.get_name_leafdata());
if (rx_control_cells_counter.is_set || is_set(rx_control_cells_counter.yfilter)) leaf_name_data.push_back(rx_control_cells_counter.get_name_leafdata());
if (rx_data_cell_counter.is_set || is_set(rx_data_cell_counter.yfilter)) leaf_name_data.push_back(rx_data_cell_counter.get_name_leafdata());
if (rx_data_byte_counter.is_set || is_set(rx_data_byte_counter.yfilter)) leaf_name_data.push_back(rx_data_byte_counter.get_name_leafdata());
if (rx_dropped_retransmitted_control.is_set || is_set(rx_dropped_retransmitted_control.yfilter)) leaf_name_data.push_back(rx_dropped_retransmitted_control.get_name_leafdata());
if (tx_asyn_fifo_rate.is_set || is_set(tx_asyn_fifo_rate.yfilter)) leaf_name_data.push_back(tx_asyn_fifo_rate.get_name_leafdata());
if (rx_asyn_fifo_rate.is_set || is_set(rx_asyn_fifo_rate.yfilter)) leaf_name_data.push_back(rx_asyn_fifo_rate.get_name_leafdata());
if (rx_lfec_fec_uncorrectable_errors.is_set || is_set(rx_lfec_fec_uncorrectable_errors.yfilter)) leaf_name_data.push_back(rx_lfec_fec_uncorrectable_errors.get_name_leafdata());
if (rx_8b_10b_code_errors.is_set || is_set(rx_8b_10b_code_errors.yfilter)) leaf_name_data.push_back(rx_8b_10b_code_errors.get_name_leafdata());
if (is_link_error.is_set || is_set(is_link_error.yfilter)) leaf_name_data.push_back(is_link_error.get_name_leafdata());
if (link_crc_error.is_set || is_set(link_crc_error.yfilter)) leaf_name_data.push_back(link_crc_error.get_name_leafdata());
if (link_size_error.is_set || is_set(link_size_error.yfilter)) leaf_name_data.push_back(link_size_error.get_name_leafdata());
if (link_mis_align_error.is_set || is_set(link_mis_align_error.yfilter)) leaf_name_data.push_back(link_mis_align_error.get_name_leafdata());
if (link_code_group_error.is_set || is_set(link_code_group_error.yfilter)) leaf_name_data.push_back(link_code_group_error.get_name_leafdata());
if (link_no_sig_lock_error.is_set || is_set(link_no_sig_lock_error.yfilter)) leaf_name_data.push_back(link_no_sig_lock_error.get_name_leafdata());
if (link_no_sig_accept_error.is_set || is_set(link_no_sig_accept_error.yfilter)) leaf_name_data.push_back(link_no_sig_accept_error.get_name_leafdata());
if (link_tokens_error.is_set || is_set(link_tokens_error.yfilter)) leaf_name_data.push_back(link_tokens_error.get_name_leafdata());
if (error_token_count.is_set || is_set(error_token_count.yfilter)) leaf_name_data.push_back(error_token_count.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "rack_num")
{
rack_num = value;
rack_num.value_namespace = name_space;
rack_num.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TX_Control_cells_counter")
{
tx_control_cells_counter = value;
tx_control_cells_counter.value_namespace = name_space;
tx_control_cells_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TX_Data_cell_counter")
{
tx_data_cell_counter = value;
tx_data_cell_counter.value_namespace = name_space;
tx_data_cell_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TX_Data_byte_counter")
{
tx_data_byte_counter = value;
tx_data_byte_counter.value_namespace = name_space;
tx_data_byte_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_CRC_errors_counter")
{
rx_crc_errors_counter = value;
rx_crc_errors_counter.value_namespace = name_space;
rx_crc_errors_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_LFEC_FEC_correctable_error")
{
rx_lfec_fec_correctable_error = value;
rx_lfec_fec_correctable_error.value_namespace = name_space;
rx_lfec_fec_correctable_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_8b_10b_disparity_errors")
{
rx_8b_10b_disparity_errors = value;
rx_8b_10b_disparity_errors.value_namespace = name_space;
rx_8b_10b_disparity_errors.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_Control_cells_counter")
{
rx_control_cells_counter = value;
rx_control_cells_counter.value_namespace = name_space;
rx_control_cells_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_Data_cell_counter")
{
rx_data_cell_counter = value;
rx_data_cell_counter.value_namespace = name_space;
rx_data_cell_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_Data_byte_counter")
{
rx_data_byte_counter = value;
rx_data_byte_counter.value_namespace = name_space;
rx_data_byte_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_dropped_retransmitted_control")
{
rx_dropped_retransmitted_control = value;
rx_dropped_retransmitted_control.value_namespace = name_space;
rx_dropped_retransmitted_control.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TX_Asyn_fifo_rate")
{
tx_asyn_fifo_rate = value;
tx_asyn_fifo_rate.value_namespace = name_space;
tx_asyn_fifo_rate.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_Asyn_fifo_rate")
{
rx_asyn_fifo_rate = value;
rx_asyn_fifo_rate.value_namespace = name_space;
rx_asyn_fifo_rate.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_LFEC_FEC_uncorrectable_errors")
{
rx_lfec_fec_uncorrectable_errors = value;
rx_lfec_fec_uncorrectable_errors.value_namespace = name_space;
rx_lfec_fec_uncorrectable_errors.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_8b_10b_code_errors")
{
rx_8b_10b_code_errors = value;
rx_8b_10b_code_errors.value_namespace = name_space;
rx_8b_10b_code_errors.value_namespace_prefix = name_space_prefix;
}
if(value_path == "is_link_error")
{
is_link_error = value;
is_link_error.value_namespace = name_space;
is_link_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_crc_error")
{
link_crc_error = value;
link_crc_error.value_namespace = name_space;
link_crc_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_size_error")
{
link_size_error = value;
link_size_error.value_namespace = name_space;
link_size_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_mis_align_error")
{
link_mis_align_error = value;
link_mis_align_error.value_namespace = name_space;
link_mis_align_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_code_group_error")
{
link_code_group_error = value;
link_code_group_error.value_namespace = name_space;
link_code_group_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_no_sig_lock_error")
{
link_no_sig_lock_error = value;
link_no_sig_lock_error.value_namespace = name_space;
link_no_sig_lock_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_no_sig_accept_error")
{
link_no_sig_accept_error = value;
link_no_sig_accept_error.value_namespace = name_space;
link_no_sig_accept_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_tokens_error")
{
link_tokens_error = value;
link_tokens_error.value_namespace = name_space;
link_tokens_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_token_count")
{
error_token_count = value;
error_token_count.value_namespace = name_space;
error_token_count.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "rack_num")
{
rack_num.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "TX_Control_cells_counter")
{
tx_control_cells_counter.yfilter = yfilter;
}
if(value_path == "TX_Data_cell_counter")
{
tx_data_cell_counter.yfilter = yfilter;
}
if(value_path == "TX_Data_byte_counter")
{
tx_data_byte_counter.yfilter = yfilter;
}
if(value_path == "RX_CRC_errors_counter")
{
rx_crc_errors_counter.yfilter = yfilter;
}
if(value_path == "RX_LFEC_FEC_correctable_error")
{
rx_lfec_fec_correctable_error.yfilter = yfilter;
}
if(value_path == "RX_8b_10b_disparity_errors")
{
rx_8b_10b_disparity_errors.yfilter = yfilter;
}
if(value_path == "RX_Control_cells_counter")
{
rx_control_cells_counter.yfilter = yfilter;
}
if(value_path == "RX_Data_cell_counter")
{
rx_data_cell_counter.yfilter = yfilter;
}
if(value_path == "RX_Data_byte_counter")
{
rx_data_byte_counter.yfilter = yfilter;
}
if(value_path == "RX_dropped_retransmitted_control")
{
rx_dropped_retransmitted_control.yfilter = yfilter;
}
if(value_path == "TX_Asyn_fifo_rate")
{
tx_asyn_fifo_rate.yfilter = yfilter;
}
if(value_path == "RX_Asyn_fifo_rate")
{
rx_asyn_fifo_rate.yfilter = yfilter;
}
if(value_path == "RX_LFEC_FEC_uncorrectable_errors")
{
rx_lfec_fec_uncorrectable_errors.yfilter = yfilter;
}
if(value_path == "RX_8b_10b_code_errors")
{
rx_8b_10b_code_errors.yfilter = yfilter;
}
if(value_path == "is_link_error")
{
is_link_error.yfilter = yfilter;
}
if(value_path == "link_crc_error")
{
link_crc_error.yfilter = yfilter;
}
if(value_path == "link_size_error")
{
link_size_error.yfilter = yfilter;
}
if(value_path == "link_mis_align_error")
{
link_mis_align_error.yfilter = yfilter;
}
if(value_path == "link_code_group_error")
{
link_code_group_error.yfilter = yfilter;
}
if(value_path == "link_no_sig_lock_error")
{
link_no_sig_lock_error.yfilter = yfilter;
}
if(value_path == "link_no_sig_accept_error")
{
link_no_sig_accept_error.yfilter = yfilter;
}
if(value_path == "link_tokens_error")
{
link_tokens_error.yfilter = yfilter;
}
if(value_path == "error_token_count")
{
error_token_count.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "port_data_idx" || name == "rack_num" || name == "sfe_port" || name == "TX_Control_cells_counter" || name == "TX_Data_cell_counter" || name == "TX_Data_byte_counter" || name == "RX_CRC_errors_counter" || name == "RX_LFEC_FEC_correctable_error" || name == "RX_8b_10b_disparity_errors" || name == "RX_Control_cells_counter" || name == "RX_Data_cell_counter" || name == "RX_Data_byte_counter" || name == "RX_dropped_retransmitted_control" || name == "TX_Asyn_fifo_rate" || name == "RX_Asyn_fifo_rate" || name == "RX_LFEC_FEC_uncorrectable_errors" || name == "RX_8b_10b_code_errors" || name == "is_link_error" || name == "link_crc_error" || name == "link_size_error" || name == "link_mis_align_error" || name == "link_code_group_error" || name == "link_no_sig_lock_error" || name == "link_no_sig_accept_error" || name == "link_tokens_error" || name == "error_token_count")
return true;
return false;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Brief::Brief()
:
data_idx(this, {"port_data_idx"})
{
yang_name = "brief"; yang_parent_name = "statistics"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Brief::~Brief()
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Brief::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return false;
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Brief::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Brief::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "brief";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Brief::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Brief::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Brief::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Brief::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Brief::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Brief::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Brief::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx")
return true;
return false;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Brief::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
rack_num{YType::str, "rack_num"},
sfe_port{YType::str, "sfe_port"},
tx_control_cells_counter{YType::uint64, "TX_Control_cells_counter"},
tx_data_cell_counter{YType::uint64, "TX_Data_cell_counter"},
tx_data_byte_counter{YType::uint64, "TX_Data_byte_counter"},
rx_crc_errors_counter{YType::uint64, "RX_CRC_errors_counter"},
rx_lfec_fec_correctable_error{YType::uint64, "RX_LFEC_FEC_correctable_error"},
rx_8b_10b_disparity_errors{YType::uint64, "RX_8b_10b_disparity_errors"},
rx_control_cells_counter{YType::uint64, "RX_Control_cells_counter"},
rx_data_cell_counter{YType::uint64, "RX_Data_cell_counter"},
rx_data_byte_counter{YType::uint64, "RX_Data_byte_counter"},
rx_dropped_retransmitted_control{YType::uint64, "RX_dropped_retransmitted_control"},
tx_asyn_fifo_rate{YType::uint64, "TX_Asyn_fifo_rate"},
rx_asyn_fifo_rate{YType::uint64, "RX_Asyn_fifo_rate"},
rx_lfec_fec_uncorrectable_errors{YType::uint64, "RX_LFEC_FEC_uncorrectable_errors"},
rx_8b_10b_code_errors{YType::uint64, "RX_8b_10b_code_errors"},
is_link_error{YType::boolean, "is_link_error"},
link_crc_error{YType::uint32, "link_crc_error"},
link_size_error{YType::uint32, "link_size_error"},
link_mis_align_error{YType::uint32, "link_mis_align_error"},
link_code_group_error{YType::uint32, "link_code_group_error"},
link_no_sig_lock_error{YType::uint32, "link_no_sig_lock_error"},
link_no_sig_accept_error{YType::uint32, "link_no_sig_accept_error"},
link_tokens_error{YType::uint32, "link_tokens_error"},
error_token_count{YType::uint32, "error_token_count"}
{
yang_name = "data_idx"; yang_parent_name = "brief"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Brief::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Brief::DataIdx::has_data() const
{
if (is_presence_container) return true;
return port_data_idx.is_set
|| rack_num.is_set
|| sfe_port.is_set
|| tx_control_cells_counter.is_set
|| tx_data_cell_counter.is_set
|| tx_data_byte_counter.is_set
|| rx_crc_errors_counter.is_set
|| rx_lfec_fec_correctable_error.is_set
|| rx_8b_10b_disparity_errors.is_set
|| rx_control_cells_counter.is_set
|| rx_data_cell_counter.is_set
|| rx_data_byte_counter.is_set
|| rx_dropped_retransmitted_control.is_set
|| tx_asyn_fifo_rate.is_set
|| rx_asyn_fifo_rate.is_set
|| rx_lfec_fec_uncorrectable_errors.is_set
|| rx_8b_10b_code_errors.is_set
|| is_link_error.is_set
|| link_crc_error.is_set
|| link_size_error.is_set
|| link_mis_align_error.is_set
|| link_code_group_error.is_set
|| link_no_sig_lock_error.is_set
|| link_no_sig_accept_error.is_set
|| link_tokens_error.is_set
|| error_token_count.is_set;
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Brief::DataIdx::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(rack_num.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(tx_control_cells_counter.yfilter)
|| ydk::is_set(tx_data_cell_counter.yfilter)
|| ydk::is_set(tx_data_byte_counter.yfilter)
|| ydk::is_set(rx_crc_errors_counter.yfilter)
|| ydk::is_set(rx_lfec_fec_correctable_error.yfilter)
|| ydk::is_set(rx_8b_10b_disparity_errors.yfilter)
|| ydk::is_set(rx_control_cells_counter.yfilter)
|| ydk::is_set(rx_data_cell_counter.yfilter)
|| ydk::is_set(rx_data_byte_counter.yfilter)
|| ydk::is_set(rx_dropped_retransmitted_control.yfilter)
|| ydk::is_set(tx_asyn_fifo_rate.yfilter)
|| ydk::is_set(rx_asyn_fifo_rate.yfilter)
|| ydk::is_set(rx_lfec_fec_uncorrectable_errors.yfilter)
|| ydk::is_set(rx_8b_10b_code_errors.yfilter)
|| ydk::is_set(is_link_error.yfilter)
|| ydk::is_set(link_crc_error.yfilter)
|| ydk::is_set(link_size_error.yfilter)
|| ydk::is_set(link_mis_align_error.yfilter)
|| ydk::is_set(link_code_group_error.yfilter)
|| ydk::is_set(link_no_sig_lock_error.yfilter)
|| ydk::is_set(link_no_sig_accept_error.yfilter)
|| ydk::is_set(link_tokens_error.yfilter)
|| ydk::is_set(error_token_count.yfilter);
}
std::string Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Brief::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Brief::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (rack_num.is_set || is_set(rack_num.yfilter)) leaf_name_data.push_back(rack_num.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (tx_control_cells_counter.is_set || is_set(tx_control_cells_counter.yfilter)) leaf_name_data.push_back(tx_control_cells_counter.get_name_leafdata());
if (tx_data_cell_counter.is_set || is_set(tx_data_cell_counter.yfilter)) leaf_name_data.push_back(tx_data_cell_counter.get_name_leafdata());
if (tx_data_byte_counter.is_set || is_set(tx_data_byte_counter.yfilter)) leaf_name_data.push_back(tx_data_byte_counter.get_name_leafdata());
if (rx_crc_errors_counter.is_set || is_set(rx_crc_errors_counter.yfilter)) leaf_name_data.push_back(rx_crc_errors_counter.get_name_leafdata());
if (rx_lfec_fec_correctable_error.is_set || is_set(rx_lfec_fec_correctable_error.yfilter)) leaf_name_data.push_back(rx_lfec_fec_correctable_error.get_name_leafdata());
if (rx_8b_10b_disparity_errors.is_set || is_set(rx_8b_10b_disparity_errors.yfilter)) leaf_name_data.push_back(rx_8b_10b_disparity_errors.get_name_leafdata());
if (rx_control_cells_counter.is_set || is_set(rx_control_cells_counter.yfilter)) leaf_name_data.push_back(rx_control_cells_counter.get_name_leafdata());
if (rx_data_cell_counter.is_set || is_set(rx_data_cell_counter.yfilter)) leaf_name_data.push_back(rx_data_cell_counter.get_name_leafdata());
if (rx_data_byte_counter.is_set || is_set(rx_data_byte_counter.yfilter)) leaf_name_data.push_back(rx_data_byte_counter.get_name_leafdata());
if (rx_dropped_retransmitted_control.is_set || is_set(rx_dropped_retransmitted_control.yfilter)) leaf_name_data.push_back(rx_dropped_retransmitted_control.get_name_leafdata());
if (tx_asyn_fifo_rate.is_set || is_set(tx_asyn_fifo_rate.yfilter)) leaf_name_data.push_back(tx_asyn_fifo_rate.get_name_leafdata());
if (rx_asyn_fifo_rate.is_set || is_set(rx_asyn_fifo_rate.yfilter)) leaf_name_data.push_back(rx_asyn_fifo_rate.get_name_leafdata());
if (rx_lfec_fec_uncorrectable_errors.is_set || is_set(rx_lfec_fec_uncorrectable_errors.yfilter)) leaf_name_data.push_back(rx_lfec_fec_uncorrectable_errors.get_name_leafdata());
if (rx_8b_10b_code_errors.is_set || is_set(rx_8b_10b_code_errors.yfilter)) leaf_name_data.push_back(rx_8b_10b_code_errors.get_name_leafdata());
if (is_link_error.is_set || is_set(is_link_error.yfilter)) leaf_name_data.push_back(is_link_error.get_name_leafdata());
if (link_crc_error.is_set || is_set(link_crc_error.yfilter)) leaf_name_data.push_back(link_crc_error.get_name_leafdata());
if (link_size_error.is_set || is_set(link_size_error.yfilter)) leaf_name_data.push_back(link_size_error.get_name_leafdata());
if (link_mis_align_error.is_set || is_set(link_mis_align_error.yfilter)) leaf_name_data.push_back(link_mis_align_error.get_name_leafdata());
if (link_code_group_error.is_set || is_set(link_code_group_error.yfilter)) leaf_name_data.push_back(link_code_group_error.get_name_leafdata());
if (link_no_sig_lock_error.is_set || is_set(link_no_sig_lock_error.yfilter)) leaf_name_data.push_back(link_no_sig_lock_error.get_name_leafdata());
if (link_no_sig_accept_error.is_set || is_set(link_no_sig_accept_error.yfilter)) leaf_name_data.push_back(link_no_sig_accept_error.get_name_leafdata());
if (link_tokens_error.is_set || is_set(link_tokens_error.yfilter)) leaf_name_data.push_back(link_tokens_error.get_name_leafdata());
if (error_token_count.is_set || is_set(error_token_count.yfilter)) leaf_name_data.push_back(error_token_count.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Brief::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Brief::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Brief::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "rack_num")
{
rack_num = value;
rack_num.value_namespace = name_space;
rack_num.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TX_Control_cells_counter")
{
tx_control_cells_counter = value;
tx_control_cells_counter.value_namespace = name_space;
tx_control_cells_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TX_Data_cell_counter")
{
tx_data_cell_counter = value;
tx_data_cell_counter.value_namespace = name_space;
tx_data_cell_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TX_Data_byte_counter")
{
tx_data_byte_counter = value;
tx_data_byte_counter.value_namespace = name_space;
tx_data_byte_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_CRC_errors_counter")
{
rx_crc_errors_counter = value;
rx_crc_errors_counter.value_namespace = name_space;
rx_crc_errors_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_LFEC_FEC_correctable_error")
{
rx_lfec_fec_correctable_error = value;
rx_lfec_fec_correctable_error.value_namespace = name_space;
rx_lfec_fec_correctable_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_8b_10b_disparity_errors")
{
rx_8b_10b_disparity_errors = value;
rx_8b_10b_disparity_errors.value_namespace = name_space;
rx_8b_10b_disparity_errors.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_Control_cells_counter")
{
rx_control_cells_counter = value;
rx_control_cells_counter.value_namespace = name_space;
rx_control_cells_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_Data_cell_counter")
{
rx_data_cell_counter = value;
rx_data_cell_counter.value_namespace = name_space;
rx_data_cell_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_Data_byte_counter")
{
rx_data_byte_counter = value;
rx_data_byte_counter.value_namespace = name_space;
rx_data_byte_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_dropped_retransmitted_control")
{
rx_dropped_retransmitted_control = value;
rx_dropped_retransmitted_control.value_namespace = name_space;
rx_dropped_retransmitted_control.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TX_Asyn_fifo_rate")
{
tx_asyn_fifo_rate = value;
tx_asyn_fifo_rate.value_namespace = name_space;
tx_asyn_fifo_rate.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_Asyn_fifo_rate")
{
rx_asyn_fifo_rate = value;
rx_asyn_fifo_rate.value_namespace = name_space;
rx_asyn_fifo_rate.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_LFEC_FEC_uncorrectable_errors")
{
rx_lfec_fec_uncorrectable_errors = value;
rx_lfec_fec_uncorrectable_errors.value_namespace = name_space;
rx_lfec_fec_uncorrectable_errors.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_8b_10b_code_errors")
{
rx_8b_10b_code_errors = value;
rx_8b_10b_code_errors.value_namespace = name_space;
rx_8b_10b_code_errors.value_namespace_prefix = name_space_prefix;
}
if(value_path == "is_link_error")
{
is_link_error = value;
is_link_error.value_namespace = name_space;
is_link_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_crc_error")
{
link_crc_error = value;
link_crc_error.value_namespace = name_space;
link_crc_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_size_error")
{
link_size_error = value;
link_size_error.value_namespace = name_space;
link_size_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_mis_align_error")
{
link_mis_align_error = value;
link_mis_align_error.value_namespace = name_space;
link_mis_align_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_code_group_error")
{
link_code_group_error = value;
link_code_group_error.value_namespace = name_space;
link_code_group_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_no_sig_lock_error")
{
link_no_sig_lock_error = value;
link_no_sig_lock_error.value_namespace = name_space;
link_no_sig_lock_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_no_sig_accept_error")
{
link_no_sig_accept_error = value;
link_no_sig_accept_error.value_namespace = name_space;
link_no_sig_accept_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_tokens_error")
{
link_tokens_error = value;
link_tokens_error.value_namespace = name_space;
link_tokens_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_token_count")
{
error_token_count = value;
error_token_count.value_namespace = name_space;
error_token_count.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Brief::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "rack_num")
{
rack_num.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "TX_Control_cells_counter")
{
tx_control_cells_counter.yfilter = yfilter;
}
if(value_path == "TX_Data_cell_counter")
{
tx_data_cell_counter.yfilter = yfilter;
}
if(value_path == "TX_Data_byte_counter")
{
tx_data_byte_counter.yfilter = yfilter;
}
if(value_path == "RX_CRC_errors_counter")
{
rx_crc_errors_counter.yfilter = yfilter;
}
if(value_path == "RX_LFEC_FEC_correctable_error")
{
rx_lfec_fec_correctable_error.yfilter = yfilter;
}
if(value_path == "RX_8b_10b_disparity_errors")
{
rx_8b_10b_disparity_errors.yfilter = yfilter;
}
if(value_path == "RX_Control_cells_counter")
{
rx_control_cells_counter.yfilter = yfilter;
}
if(value_path == "RX_Data_cell_counter")
{
rx_data_cell_counter.yfilter = yfilter;
}
if(value_path == "RX_Data_byte_counter")
{
rx_data_byte_counter.yfilter = yfilter;
}
if(value_path == "RX_dropped_retransmitted_control")
{
rx_dropped_retransmitted_control.yfilter = yfilter;
}
if(value_path == "TX_Asyn_fifo_rate")
{
tx_asyn_fifo_rate.yfilter = yfilter;
}
if(value_path == "RX_Asyn_fifo_rate")
{
rx_asyn_fifo_rate.yfilter = yfilter;
}
if(value_path == "RX_LFEC_FEC_uncorrectable_errors")
{
rx_lfec_fec_uncorrectable_errors.yfilter = yfilter;
}
if(value_path == "RX_8b_10b_code_errors")
{
rx_8b_10b_code_errors.yfilter = yfilter;
}
if(value_path == "is_link_error")
{
is_link_error.yfilter = yfilter;
}
if(value_path == "link_crc_error")
{
link_crc_error.yfilter = yfilter;
}
if(value_path == "link_size_error")
{
link_size_error.yfilter = yfilter;
}
if(value_path == "link_mis_align_error")
{
link_mis_align_error.yfilter = yfilter;
}
if(value_path == "link_code_group_error")
{
link_code_group_error.yfilter = yfilter;
}
if(value_path == "link_no_sig_lock_error")
{
link_no_sig_lock_error.yfilter = yfilter;
}
if(value_path == "link_no_sig_accept_error")
{
link_no_sig_accept_error.yfilter = yfilter;
}
if(value_path == "link_tokens_error")
{
link_tokens_error.yfilter = yfilter;
}
if(value_path == "error_token_count")
{
error_token_count.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Brief::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "port_data_idx" || name == "rack_num" || name == "sfe_port" || name == "TX_Control_cells_counter" || name == "TX_Data_cell_counter" || name == "TX_Data_byte_counter" || name == "RX_CRC_errors_counter" || name == "RX_LFEC_FEC_correctable_error" || name == "RX_8b_10b_disparity_errors" || name == "RX_Control_cells_counter" || name == "RX_Data_cell_counter" || name == "RX_Data_byte_counter" || name == "RX_dropped_retransmitted_control" || name == "TX_Asyn_fifo_rate" || name == "RX_Asyn_fifo_rate" || name == "RX_LFEC_FEC_uncorrectable_errors" || name == "RX_8b_10b_code_errors" || name == "is_link_error" || name == "link_crc_error" || name == "link_size_error" || name == "link_mis_align_error" || name == "link_code_group_error" || name == "link_no_sig_lock_error" || name == "link_no_sig_accept_error" || name == "link_tokens_error" || name == "error_token_count")
return true;
return false;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Detail::Detail()
:
data_idx(this, {"port_data_idx"})
{
yang_name = "detail"; yang_parent_name = "statistics"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Detail::~Detail()
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Detail::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return false;
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Detail::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Detail::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "detail";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Detail::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Detail::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Detail::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Detail::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Detail::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Detail::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Detail::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx")
return true;
return false;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Detail::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
rack_num{YType::str, "rack_num"},
sfe_port{YType::str, "sfe_port"},
tx_control_cells_counter{YType::uint64, "TX_Control_cells_counter"},
tx_data_cell_counter{YType::uint64, "TX_Data_cell_counter"},
tx_data_byte_counter{YType::uint64, "TX_Data_byte_counter"},
rx_crc_errors_counter{YType::uint64, "RX_CRC_errors_counter"},
rx_lfec_fec_correctable_error{YType::uint64, "RX_LFEC_FEC_correctable_error"},
rx_8b_10b_disparity_errors{YType::uint64, "RX_8b_10b_disparity_errors"},
rx_control_cells_counter{YType::uint64, "RX_Control_cells_counter"},
rx_data_cell_counter{YType::uint64, "RX_Data_cell_counter"},
rx_data_byte_counter{YType::uint64, "RX_Data_byte_counter"},
rx_dropped_retransmitted_control{YType::uint64, "RX_dropped_retransmitted_control"},
tx_asyn_fifo_rate{YType::uint64, "TX_Asyn_fifo_rate"},
rx_asyn_fifo_rate{YType::uint64, "RX_Asyn_fifo_rate"},
rx_lfec_fec_uncorrectable_errors{YType::uint64, "RX_LFEC_FEC_uncorrectable_errors"},
rx_8b_10b_code_errors{YType::uint64, "RX_8b_10b_code_errors"},
is_link_error{YType::boolean, "is_link_error"},
link_crc_error{YType::uint32, "link_crc_error"},
link_size_error{YType::uint32, "link_size_error"},
link_mis_align_error{YType::uint32, "link_mis_align_error"},
link_code_group_error{YType::uint32, "link_code_group_error"},
link_no_sig_lock_error{YType::uint32, "link_no_sig_lock_error"},
link_no_sig_accept_error{YType::uint32, "link_no_sig_accept_error"},
link_tokens_error{YType::uint32, "link_tokens_error"},
error_token_count{YType::uint32, "error_token_count"}
{
yang_name = "data_idx"; yang_parent_name = "detail"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Detail::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Detail::DataIdx::has_data() const
{
if (is_presence_container) return true;
return port_data_idx.is_set
|| rack_num.is_set
|| sfe_port.is_set
|| tx_control_cells_counter.is_set
|| tx_data_cell_counter.is_set
|| tx_data_byte_counter.is_set
|| rx_crc_errors_counter.is_set
|| rx_lfec_fec_correctable_error.is_set
|| rx_8b_10b_disparity_errors.is_set
|| rx_control_cells_counter.is_set
|| rx_data_cell_counter.is_set
|| rx_data_byte_counter.is_set
|| rx_dropped_retransmitted_control.is_set
|| tx_asyn_fifo_rate.is_set
|| rx_asyn_fifo_rate.is_set
|| rx_lfec_fec_uncorrectable_errors.is_set
|| rx_8b_10b_code_errors.is_set
|| is_link_error.is_set
|| link_crc_error.is_set
|| link_size_error.is_set
|| link_mis_align_error.is_set
|| link_code_group_error.is_set
|| link_no_sig_lock_error.is_set
|| link_no_sig_accept_error.is_set
|| link_tokens_error.is_set
|| error_token_count.is_set;
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Detail::DataIdx::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(rack_num.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(tx_control_cells_counter.yfilter)
|| ydk::is_set(tx_data_cell_counter.yfilter)
|| ydk::is_set(tx_data_byte_counter.yfilter)
|| ydk::is_set(rx_crc_errors_counter.yfilter)
|| ydk::is_set(rx_lfec_fec_correctable_error.yfilter)
|| ydk::is_set(rx_8b_10b_disparity_errors.yfilter)
|| ydk::is_set(rx_control_cells_counter.yfilter)
|| ydk::is_set(rx_data_cell_counter.yfilter)
|| ydk::is_set(rx_data_byte_counter.yfilter)
|| ydk::is_set(rx_dropped_retransmitted_control.yfilter)
|| ydk::is_set(tx_asyn_fifo_rate.yfilter)
|| ydk::is_set(rx_asyn_fifo_rate.yfilter)
|| ydk::is_set(rx_lfec_fec_uncorrectable_errors.yfilter)
|| ydk::is_set(rx_8b_10b_code_errors.yfilter)
|| ydk::is_set(is_link_error.yfilter)
|| ydk::is_set(link_crc_error.yfilter)
|| ydk::is_set(link_size_error.yfilter)
|| ydk::is_set(link_mis_align_error.yfilter)
|| ydk::is_set(link_code_group_error.yfilter)
|| ydk::is_set(link_no_sig_lock_error.yfilter)
|| ydk::is_set(link_no_sig_accept_error.yfilter)
|| ydk::is_set(link_tokens_error.yfilter)
|| ydk::is_set(error_token_count.yfilter);
}
std::string Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Detail::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Detail::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (rack_num.is_set || is_set(rack_num.yfilter)) leaf_name_data.push_back(rack_num.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (tx_control_cells_counter.is_set || is_set(tx_control_cells_counter.yfilter)) leaf_name_data.push_back(tx_control_cells_counter.get_name_leafdata());
if (tx_data_cell_counter.is_set || is_set(tx_data_cell_counter.yfilter)) leaf_name_data.push_back(tx_data_cell_counter.get_name_leafdata());
if (tx_data_byte_counter.is_set || is_set(tx_data_byte_counter.yfilter)) leaf_name_data.push_back(tx_data_byte_counter.get_name_leafdata());
if (rx_crc_errors_counter.is_set || is_set(rx_crc_errors_counter.yfilter)) leaf_name_data.push_back(rx_crc_errors_counter.get_name_leafdata());
if (rx_lfec_fec_correctable_error.is_set || is_set(rx_lfec_fec_correctable_error.yfilter)) leaf_name_data.push_back(rx_lfec_fec_correctable_error.get_name_leafdata());
if (rx_8b_10b_disparity_errors.is_set || is_set(rx_8b_10b_disparity_errors.yfilter)) leaf_name_data.push_back(rx_8b_10b_disparity_errors.get_name_leafdata());
if (rx_control_cells_counter.is_set || is_set(rx_control_cells_counter.yfilter)) leaf_name_data.push_back(rx_control_cells_counter.get_name_leafdata());
if (rx_data_cell_counter.is_set || is_set(rx_data_cell_counter.yfilter)) leaf_name_data.push_back(rx_data_cell_counter.get_name_leafdata());
if (rx_data_byte_counter.is_set || is_set(rx_data_byte_counter.yfilter)) leaf_name_data.push_back(rx_data_byte_counter.get_name_leafdata());
if (rx_dropped_retransmitted_control.is_set || is_set(rx_dropped_retransmitted_control.yfilter)) leaf_name_data.push_back(rx_dropped_retransmitted_control.get_name_leafdata());
if (tx_asyn_fifo_rate.is_set || is_set(tx_asyn_fifo_rate.yfilter)) leaf_name_data.push_back(tx_asyn_fifo_rate.get_name_leafdata());
if (rx_asyn_fifo_rate.is_set || is_set(rx_asyn_fifo_rate.yfilter)) leaf_name_data.push_back(rx_asyn_fifo_rate.get_name_leafdata());
if (rx_lfec_fec_uncorrectable_errors.is_set || is_set(rx_lfec_fec_uncorrectable_errors.yfilter)) leaf_name_data.push_back(rx_lfec_fec_uncorrectable_errors.get_name_leafdata());
if (rx_8b_10b_code_errors.is_set || is_set(rx_8b_10b_code_errors.yfilter)) leaf_name_data.push_back(rx_8b_10b_code_errors.get_name_leafdata());
if (is_link_error.is_set || is_set(is_link_error.yfilter)) leaf_name_data.push_back(is_link_error.get_name_leafdata());
if (link_crc_error.is_set || is_set(link_crc_error.yfilter)) leaf_name_data.push_back(link_crc_error.get_name_leafdata());
if (link_size_error.is_set || is_set(link_size_error.yfilter)) leaf_name_data.push_back(link_size_error.get_name_leafdata());
if (link_mis_align_error.is_set || is_set(link_mis_align_error.yfilter)) leaf_name_data.push_back(link_mis_align_error.get_name_leafdata());
if (link_code_group_error.is_set || is_set(link_code_group_error.yfilter)) leaf_name_data.push_back(link_code_group_error.get_name_leafdata());
if (link_no_sig_lock_error.is_set || is_set(link_no_sig_lock_error.yfilter)) leaf_name_data.push_back(link_no_sig_lock_error.get_name_leafdata());
if (link_no_sig_accept_error.is_set || is_set(link_no_sig_accept_error.yfilter)) leaf_name_data.push_back(link_no_sig_accept_error.get_name_leafdata());
if (link_tokens_error.is_set || is_set(link_tokens_error.yfilter)) leaf_name_data.push_back(link_tokens_error.get_name_leafdata());
if (error_token_count.is_set || is_set(error_token_count.yfilter)) leaf_name_data.push_back(error_token_count.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Detail::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Detail::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Detail::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "rack_num")
{
rack_num = value;
rack_num.value_namespace = name_space;
rack_num.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TX_Control_cells_counter")
{
tx_control_cells_counter = value;
tx_control_cells_counter.value_namespace = name_space;
tx_control_cells_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TX_Data_cell_counter")
{
tx_data_cell_counter = value;
tx_data_cell_counter.value_namespace = name_space;
tx_data_cell_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TX_Data_byte_counter")
{
tx_data_byte_counter = value;
tx_data_byte_counter.value_namespace = name_space;
tx_data_byte_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_CRC_errors_counter")
{
rx_crc_errors_counter = value;
rx_crc_errors_counter.value_namespace = name_space;
rx_crc_errors_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_LFEC_FEC_correctable_error")
{
rx_lfec_fec_correctable_error = value;
rx_lfec_fec_correctable_error.value_namespace = name_space;
rx_lfec_fec_correctable_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_8b_10b_disparity_errors")
{
rx_8b_10b_disparity_errors = value;
rx_8b_10b_disparity_errors.value_namespace = name_space;
rx_8b_10b_disparity_errors.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_Control_cells_counter")
{
rx_control_cells_counter = value;
rx_control_cells_counter.value_namespace = name_space;
rx_control_cells_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_Data_cell_counter")
{
rx_data_cell_counter = value;
rx_data_cell_counter.value_namespace = name_space;
rx_data_cell_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_Data_byte_counter")
{
rx_data_byte_counter = value;
rx_data_byte_counter.value_namespace = name_space;
rx_data_byte_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_dropped_retransmitted_control")
{
rx_dropped_retransmitted_control = value;
rx_dropped_retransmitted_control.value_namespace = name_space;
rx_dropped_retransmitted_control.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TX_Asyn_fifo_rate")
{
tx_asyn_fifo_rate = value;
tx_asyn_fifo_rate.value_namespace = name_space;
tx_asyn_fifo_rate.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_Asyn_fifo_rate")
{
rx_asyn_fifo_rate = value;
rx_asyn_fifo_rate.value_namespace = name_space;
rx_asyn_fifo_rate.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_LFEC_FEC_uncorrectable_errors")
{
rx_lfec_fec_uncorrectable_errors = value;
rx_lfec_fec_uncorrectable_errors.value_namespace = name_space;
rx_lfec_fec_uncorrectable_errors.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_8b_10b_code_errors")
{
rx_8b_10b_code_errors = value;
rx_8b_10b_code_errors.value_namespace = name_space;
rx_8b_10b_code_errors.value_namespace_prefix = name_space_prefix;
}
if(value_path == "is_link_error")
{
is_link_error = value;
is_link_error.value_namespace = name_space;
is_link_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_crc_error")
{
link_crc_error = value;
link_crc_error.value_namespace = name_space;
link_crc_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_size_error")
{
link_size_error = value;
link_size_error.value_namespace = name_space;
link_size_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_mis_align_error")
{
link_mis_align_error = value;
link_mis_align_error.value_namespace = name_space;
link_mis_align_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_code_group_error")
{
link_code_group_error = value;
link_code_group_error.value_namespace = name_space;
link_code_group_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_no_sig_lock_error")
{
link_no_sig_lock_error = value;
link_no_sig_lock_error.value_namespace = name_space;
link_no_sig_lock_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_no_sig_accept_error")
{
link_no_sig_accept_error = value;
link_no_sig_accept_error.value_namespace = name_space;
link_no_sig_accept_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_tokens_error")
{
link_tokens_error = value;
link_tokens_error.value_namespace = name_space;
link_tokens_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_token_count")
{
error_token_count = value;
error_token_count.value_namespace = name_space;
error_token_count.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Detail::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "rack_num")
{
rack_num.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "TX_Control_cells_counter")
{
tx_control_cells_counter.yfilter = yfilter;
}
if(value_path == "TX_Data_cell_counter")
{
tx_data_cell_counter.yfilter = yfilter;
}
if(value_path == "TX_Data_byte_counter")
{
tx_data_byte_counter.yfilter = yfilter;
}
if(value_path == "RX_CRC_errors_counter")
{
rx_crc_errors_counter.yfilter = yfilter;
}
if(value_path == "RX_LFEC_FEC_correctable_error")
{
rx_lfec_fec_correctable_error.yfilter = yfilter;
}
if(value_path == "RX_8b_10b_disparity_errors")
{
rx_8b_10b_disparity_errors.yfilter = yfilter;
}
if(value_path == "RX_Control_cells_counter")
{
rx_control_cells_counter.yfilter = yfilter;
}
if(value_path == "RX_Data_cell_counter")
{
rx_data_cell_counter.yfilter = yfilter;
}
if(value_path == "RX_Data_byte_counter")
{
rx_data_byte_counter.yfilter = yfilter;
}
if(value_path == "RX_dropped_retransmitted_control")
{
rx_dropped_retransmitted_control.yfilter = yfilter;
}
if(value_path == "TX_Asyn_fifo_rate")
{
tx_asyn_fifo_rate.yfilter = yfilter;
}
if(value_path == "RX_Asyn_fifo_rate")
{
rx_asyn_fifo_rate.yfilter = yfilter;
}
if(value_path == "RX_LFEC_FEC_uncorrectable_errors")
{
rx_lfec_fec_uncorrectable_errors.yfilter = yfilter;
}
if(value_path == "RX_8b_10b_code_errors")
{
rx_8b_10b_code_errors.yfilter = yfilter;
}
if(value_path == "is_link_error")
{
is_link_error.yfilter = yfilter;
}
if(value_path == "link_crc_error")
{
link_crc_error.yfilter = yfilter;
}
if(value_path == "link_size_error")
{
link_size_error.yfilter = yfilter;
}
if(value_path == "link_mis_align_error")
{
link_mis_align_error.yfilter = yfilter;
}
if(value_path == "link_code_group_error")
{
link_code_group_error.yfilter = yfilter;
}
if(value_path == "link_no_sig_lock_error")
{
link_no_sig_lock_error.yfilter = yfilter;
}
if(value_path == "link_no_sig_accept_error")
{
link_no_sig_accept_error.yfilter = yfilter;
}
if(value_path == "link_tokens_error")
{
link_tokens_error.yfilter = yfilter;
}
if(value_path == "error_token_count")
{
error_token_count.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::Rack::Port::Tx::Statistics::Detail::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "port_data_idx" || name == "rack_num" || name == "sfe_port" || name == "TX_Control_cells_counter" || name == "TX_Data_cell_counter" || name == "TX_Data_byte_counter" || name == "RX_CRC_errors_counter" || name == "RX_LFEC_FEC_correctable_error" || name == "RX_8b_10b_disparity_errors" || name == "RX_Control_cells_counter" || name == "RX_Data_cell_counter" || name == "RX_Data_byte_counter" || name == "RX_dropped_retransmitted_control" || name == "TX_Asyn_fifo_rate" || name == "RX_Asyn_fifo_rate" || name == "RX_LFEC_FEC_uncorrectable_errors" || name == "RX_8b_10b_code_errors" || name == "is_link_error" || name == "link_crc_error" || name == "link_size_error" || name == "link_mis_align_error" || name == "link_code_group_error" || name == "link_no_sig_lock_error" || name == "link_no_sig_accept_error" || name == "link_tokens_error" || name == "error_token_count")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::NodeLocation()
:
node_str{YType::str, "node_str"}
,
port(this, {"portname"})
{
yang_name = "node_location"; yang_parent_name = "link"; is_top_level_class = false; has_list_ancestor = false;
}
Controller::Fabric::Oper::Link::NodeLocation::~NodeLocation()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<port.len(); index++)
{
if(port[index]->has_data())
return true;
}
return node_str.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::has_operation() const
{
for (std::size_t index=0; index<port.len(); index++)
{
if(port[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(node_str.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-sysadmin-controllers-ncs5502:controller/fabric/oper/link/" << get_segment_path();
return path_buffer.str();
}
std::string Controller::Fabric::Oper::Link::NodeLocation::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "node_location";
ADD_KEY_TOKEN(node_str, "node_str");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (node_str.is_set || is_set(node_str.yfilter)) leaf_name_data.push_back(node_str.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "port")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port>();
ent_->parent = this;
port.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : port.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "node_str")
{
node_str = value;
node_str.value_namespace = name_space;
node_str.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "node_str")
{
node_str.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "port" || name == "node_str")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Port()
:
portname{YType::str, "portname"},
description{YType::str, "description"}
,
location(this, {"loc_str"})
, rx(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx>())
, tx(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Tx>())
{
rx->parent = this;
tx->parent = this;
yang_name = "port"; yang_parent_name = "node_location"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::~Port()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<location.len(); index++)
{
if(location[index]->has_data())
return true;
}
return portname.is_set
|| description.is_set
|| (rx != nullptr && rx->has_data())
|| (tx != nullptr && tx->has_data());
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::has_operation() const
{
for (std::size_t index=0; index<location.len(); index++)
{
if(location[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(portname.yfilter)
|| ydk::is_set(description.yfilter)
|| (rx != nullptr && rx->has_operation())
|| (tx != nullptr && tx->has_operation());
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "port";
ADD_KEY_TOKEN(portname, "portname");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (portname.is_set || is_set(portname.yfilter)) leaf_name_data.push_back(portname.get_name_leafdata());
if (description.is_set || is_set(description.yfilter)) leaf_name_data.push_back(description.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "location")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location>();
ent_->parent = this;
location.append(ent_);
return ent_;
}
if(child_yang_name == "rx")
{
if(rx == nullptr)
{
rx = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx>();
}
return rx;
}
if(child_yang_name == "tx")
{
if(tx == nullptr)
{
tx = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Tx>();
}
return tx;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : location.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
if(rx != nullptr)
{
_children["rx"] = rx;
}
if(tx != nullptr)
{
_children["tx"] = tx;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "portname")
{
portname = value;
portname.value_namespace = name_space;
portname.value_namespace_prefix = name_space_prefix;
}
if(value_path == "description")
{
description = value;
description.value_namespace = name_space;
description.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "portname")
{
portname.yfilter = yfilter;
}
if(value_path == "description")
{
description.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "location" || name == "rx" || name == "tx" || name == "portname" || name == "description")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Location()
:
loc_str{YType::str, "loc_str"}
,
rx(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx>())
, tx(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx>())
{
rx->parent = this;
tx->parent = this;
yang_name = "location"; yang_parent_name = "port"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::~Location()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::has_data() const
{
if (is_presence_container) return true;
return loc_str.is_set
|| (rx != nullptr && rx->has_data())
|| (tx != nullptr && tx->has_data());
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(loc_str.yfilter)
|| (rx != nullptr && rx->has_operation())
|| (tx != nullptr && tx->has_operation());
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "location";
ADD_KEY_TOKEN(loc_str, "loc_str");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (loc_str.is_set || is_set(loc_str.yfilter)) leaf_name_data.push_back(loc_str.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "rx")
{
if(rx == nullptr)
{
rx = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx>();
}
return rx;
}
if(child_yang_name == "tx")
{
if(tx == nullptr)
{
tx = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx>();
}
return tx;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(rx != nullptr)
{
_children["rx"] = rx;
}
if(tx != nullptr)
{
_children["tx"] = tx;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "loc_str")
{
loc_str = value;
loc_str.value_namespace = name_space;
loc_str.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "loc_str")
{
loc_str.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "rx" || name == "tx" || name == "loc_str")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Rx()
:
data_idx(this, {"port_data_idx"})
, brief(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Brief>())
, detail(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Detail>())
, state(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State>())
, statistics(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics>())
{
brief->parent = this;
detail->parent = this;
state->parent = this;
statistics->parent = this;
yang_name = "rx"; yang_parent_name = "location"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::~Rx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return (brief != nullptr && brief->has_data())
|| (detail != nullptr && detail->has_data())
|| (state != nullptr && state->has_data())
|| (statistics != nullptr && statistics->has_data());
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter)
|| (brief != nullptr && brief->has_operation())
|| (detail != nullptr && detail->has_operation())
|| (state != nullptr && state->has_operation())
|| (statistics != nullptr && statistics->has_operation());
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "rx";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
if(child_yang_name == "brief")
{
if(brief == nullptr)
{
brief = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Brief>();
}
return brief;
}
if(child_yang_name == "detail")
{
if(detail == nullptr)
{
detail = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Detail>();
}
return detail;
}
if(child_yang_name == "state")
{
if(state == nullptr)
{
state = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State>();
}
return state;
}
if(child_yang_name == "statistics")
{
if(statistics == nullptr)
{
statistics = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics>();
}
return statistics;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
if(brief != nullptr)
{
_children["brief"] = brief;
}
if(detail != nullptr)
{
_children["detail"] = detail;
}
if(state != nullptr)
{
_children["state"] = state;
}
if(statistics != nullptr)
{
_children["statistics"] = statistics;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx" || name == "brief" || name == "detail" || name == "state" || name == "statistics")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "rx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Brief::Brief()
:
data_idx(this, {"port_data_idx"})
{
yang_name = "brief"; yang_parent_name = "rx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Brief::~Brief()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Brief::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return false;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Brief::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Brief::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "brief";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Brief::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Brief::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Brief::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Brief::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Brief::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Brief::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Brief::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Brief::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "brief"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Brief::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Brief::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Brief::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Brief::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Brief::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Brief::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Brief::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Brief::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Brief::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Brief::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Brief::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Brief::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Brief::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Brief::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Brief::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Brief::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Brief::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Brief::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Brief::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Brief::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Brief::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Brief::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Detail::Detail()
:
data_idx(this, {"port_data_idx"})
{
yang_name = "detail"; yang_parent_name = "rx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Detail::~Detail()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Detail::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return false;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Detail::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Detail::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "detail";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Detail::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Detail::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Detail::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Detail::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Detail::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Detail::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Detail::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Detail::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "detail"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Detail::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Detail::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Detail::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Detail::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Detail::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Detail::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Detail::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Detail::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Detail::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Detail::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Detail::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Detail::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Detail::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Detail::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Detail::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Detail::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Detail::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Detail::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Detail::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Detail::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Detail::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Detail::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::State()
:
up(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up>())
, down(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down>())
, mismatch(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch>())
{
up->parent = this;
down->parent = this;
mismatch->parent = this;
yang_name = "state"; yang_parent_name = "rx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::~State()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::has_data() const
{
if (is_presence_container) return true;
return (up != nullptr && up->has_data())
|| (down != nullptr && down->has_data())
|| (mismatch != nullptr && mismatch->has_data());
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::has_operation() const
{
return is_set(yfilter)
|| (up != nullptr && up->has_operation())
|| (down != nullptr && down->has_operation())
|| (mismatch != nullptr && mismatch->has_operation());
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "state";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "up")
{
if(up == nullptr)
{
up = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up>();
}
return up;
}
if(child_yang_name == "down")
{
if(down == nullptr)
{
down = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down>();
}
return down;
}
if(child_yang_name == "mismatch")
{
if(mismatch == nullptr)
{
mismatch = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch>();
}
return mismatch;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(up != nullptr)
{
_children["up"] = up;
}
if(down != nullptr)
{
_children["down"] = down;
}
if(mismatch != nullptr)
{
_children["mismatch"] = mismatch;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "up" || name == "down" || name == "mismatch")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Up()
:
data_idx(this, {"port_data_idx"})
, brief(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Brief>())
, detail(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Detail>())
{
brief->parent = this;
detail->parent = this;
yang_name = "up"; yang_parent_name = "state"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::~Up()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return (brief != nullptr && brief->has_data())
|| (detail != nullptr && detail->has_data());
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter)
|| (brief != nullptr && brief->has_operation())
|| (detail != nullptr && detail->has_operation());
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "up";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
if(child_yang_name == "brief")
{
if(brief == nullptr)
{
brief = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Brief>();
}
return brief;
}
if(child_yang_name == "detail")
{
if(detail == nullptr)
{
detail = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Detail>();
}
return detail;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
if(brief != nullptr)
{
_children["brief"] = brief;
}
if(detail != nullptr)
{
_children["detail"] = detail;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx" || name == "brief" || name == "detail")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "up"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Brief::Brief()
:
data_idx(this, {"port_data_idx"})
{
yang_name = "brief"; yang_parent_name = "up"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Brief::~Brief()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Brief::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return false;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Brief::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Brief::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "brief";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Brief::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Brief::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Brief::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Brief::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Brief::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Brief::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Brief::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Brief::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "brief"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Brief::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Brief::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Brief::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Brief::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Brief::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Brief::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Brief::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Brief::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Brief::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Brief::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Brief::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Brief::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Brief::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Brief::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Brief::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Brief::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Brief::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Brief::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Brief::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Brief::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Brief::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Brief::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Detail::Detail()
:
data_idx(this, {"port_data_idx"})
{
yang_name = "detail"; yang_parent_name = "up"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Detail::~Detail()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Detail::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return false;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Detail::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Detail::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "detail";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Detail::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Detail::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Detail::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Detail::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Detail::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Detail::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Detail::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Detail::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "detail"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Detail::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Detail::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Detail::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Detail::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Detail::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Detail::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Detail::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Detail::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Detail::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Detail::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Detail::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Detail::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Detail::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Detail::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Detail::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Detail::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Detail::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Detail::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Detail::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Detail::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Detail::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Up::Detail::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Down()
:
data_idx(this, {"port_data_idx"})
, brief(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Brief>())
, detail(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Detail>())
{
brief->parent = this;
detail->parent = this;
yang_name = "down"; yang_parent_name = "state"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::~Down()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return (brief != nullptr && brief->has_data())
|| (detail != nullptr && detail->has_data());
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter)
|| (brief != nullptr && brief->has_operation())
|| (detail != nullptr && detail->has_operation());
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "down";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
if(child_yang_name == "brief")
{
if(brief == nullptr)
{
brief = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Brief>();
}
return brief;
}
if(child_yang_name == "detail")
{
if(detail == nullptr)
{
detail = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Detail>();
}
return detail;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
if(brief != nullptr)
{
_children["brief"] = brief;
}
if(detail != nullptr)
{
_children["detail"] = detail;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx" || name == "brief" || name == "detail")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "down"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Brief::Brief()
:
data_idx(this, {"port_data_idx"})
{
yang_name = "brief"; yang_parent_name = "down"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Brief::~Brief()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Brief::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return false;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Brief::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Brief::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "brief";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Brief::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Brief::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Brief::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Brief::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Brief::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Brief::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Brief::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Brief::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "brief"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Brief::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Brief::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Brief::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Brief::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Brief::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Brief::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Brief::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Brief::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Brief::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Brief::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Brief::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Brief::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Brief::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Brief::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Brief::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Brief::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Brief::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Brief::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Brief::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Brief::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Brief::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Brief::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Detail::Detail()
:
data_idx(this, {"port_data_idx"})
{
yang_name = "detail"; yang_parent_name = "down"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Detail::~Detail()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Detail::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return false;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Detail::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Detail::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "detail";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Detail::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Detail::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Detail::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Detail::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Detail::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Detail::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Detail::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Detail::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "detail"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Detail::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Detail::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Detail::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Detail::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Detail::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Detail::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Detail::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Detail::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Detail::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Detail::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Detail::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Detail::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Detail::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Detail::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Detail::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Detail::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Detail::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Detail::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Detail::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Detail::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Detail::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Down::Detail::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Mismatch()
:
data_idx(this, {"port_data_idx"})
, brief(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Brief>())
, detail(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Detail>())
{
brief->parent = this;
detail->parent = this;
yang_name = "mismatch"; yang_parent_name = "state"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::~Mismatch()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return (brief != nullptr && brief->has_data())
|| (detail != nullptr && detail->has_data());
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter)
|| (brief != nullptr && brief->has_operation())
|| (detail != nullptr && detail->has_operation());
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "mismatch";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
if(child_yang_name == "brief")
{
if(brief == nullptr)
{
brief = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Brief>();
}
return brief;
}
if(child_yang_name == "detail")
{
if(detail == nullptr)
{
detail = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Detail>();
}
return detail;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
if(brief != nullptr)
{
_children["brief"] = brief;
}
if(detail != nullptr)
{
_children["detail"] = detail;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx" || name == "brief" || name == "detail")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "mismatch"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Brief::Brief()
:
data_idx(this, {"port_data_idx"})
{
yang_name = "brief"; yang_parent_name = "mismatch"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Brief::~Brief()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Brief::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return false;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Brief::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Brief::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "brief";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Brief::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Brief::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Brief::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Brief::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Brief::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Brief::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Brief::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Brief::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "brief"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Brief::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Brief::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Brief::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Brief::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Brief::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Brief::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Brief::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Brief::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Brief::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Brief::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Brief::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Brief::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Brief::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Brief::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Brief::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Brief::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Brief::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Brief::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Brief::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Brief::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Brief::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Brief::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Detail::Detail()
:
data_idx(this, {"port_data_idx"})
{
yang_name = "detail"; yang_parent_name = "mismatch"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Detail::~Detail()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Detail::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return false;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Detail::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Detail::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "detail";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Detail::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Detail::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Detail::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Detail::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Detail::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Detail::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Detail::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Detail::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "detail"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Detail::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Detail::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Detail::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Detail::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Detail::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Detail::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Detail::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Detail::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Detail::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Detail::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Detail::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Detail::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Detail::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Detail::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Detail::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Detail::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Detail::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Detail::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Detail::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Detail::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Detail::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::State::Mismatch::Detail::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Statistics()
:
data_idx(this, {"port_data_idx"})
, brief(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Brief>())
, detail(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Detail>())
{
brief->parent = this;
detail->parent = this;
yang_name = "statistics"; yang_parent_name = "rx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::~Statistics()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return (brief != nullptr && brief->has_data())
|| (detail != nullptr && detail->has_data());
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter)
|| (brief != nullptr && brief->has_operation())
|| (detail != nullptr && detail->has_operation());
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "statistics";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
if(child_yang_name == "brief")
{
if(brief == nullptr)
{
brief = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Brief>();
}
return brief;
}
if(child_yang_name == "detail")
{
if(detail == nullptr)
{
detail = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Detail>();
}
return detail;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
if(brief != nullptr)
{
_children["brief"] = brief;
}
if(detail != nullptr)
{
_children["detail"] = detail;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx" || name == "brief" || name == "detail")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
rack_num{YType::str, "rack_num"},
sfe_port{YType::str, "sfe_port"},
tx_control_cells_counter{YType::uint64, "TX_Control_cells_counter"},
tx_data_cell_counter{YType::uint64, "TX_Data_cell_counter"},
tx_data_byte_counter{YType::uint64, "TX_Data_byte_counter"},
rx_crc_errors_counter{YType::uint64, "RX_CRC_errors_counter"},
rx_lfec_fec_correctable_error{YType::uint64, "RX_LFEC_FEC_correctable_error"},
rx_8b_10b_disparity_errors{YType::uint64, "RX_8b_10b_disparity_errors"},
rx_control_cells_counter{YType::uint64, "RX_Control_cells_counter"},
rx_data_cell_counter{YType::uint64, "RX_Data_cell_counter"},
rx_data_byte_counter{YType::uint64, "RX_Data_byte_counter"},
rx_dropped_retransmitted_control{YType::uint64, "RX_dropped_retransmitted_control"},
tx_asyn_fifo_rate{YType::uint64, "TX_Asyn_fifo_rate"},
rx_asyn_fifo_rate{YType::uint64, "RX_Asyn_fifo_rate"},
rx_lfec_fec_uncorrectable_errors{YType::uint64, "RX_LFEC_FEC_uncorrectable_errors"},
rx_8b_10b_code_errors{YType::uint64, "RX_8b_10b_code_errors"},
is_link_error{YType::boolean, "is_link_error"},
link_crc_error{YType::uint32, "link_crc_error"},
link_size_error{YType::uint32, "link_size_error"},
link_mis_align_error{YType::uint32, "link_mis_align_error"},
link_code_group_error{YType::uint32, "link_code_group_error"},
link_no_sig_lock_error{YType::uint32, "link_no_sig_lock_error"},
link_no_sig_accept_error{YType::uint32, "link_no_sig_accept_error"},
link_tokens_error{YType::uint32, "link_tokens_error"},
error_token_count{YType::uint32, "error_token_count"}
{
yang_name = "data_idx"; yang_parent_name = "statistics"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::DataIdx::has_data() const
{
if (is_presence_container) return true;
return port_data_idx.is_set
|| rack_num.is_set
|| sfe_port.is_set
|| tx_control_cells_counter.is_set
|| tx_data_cell_counter.is_set
|| tx_data_byte_counter.is_set
|| rx_crc_errors_counter.is_set
|| rx_lfec_fec_correctable_error.is_set
|| rx_8b_10b_disparity_errors.is_set
|| rx_control_cells_counter.is_set
|| rx_data_cell_counter.is_set
|| rx_data_byte_counter.is_set
|| rx_dropped_retransmitted_control.is_set
|| tx_asyn_fifo_rate.is_set
|| rx_asyn_fifo_rate.is_set
|| rx_lfec_fec_uncorrectable_errors.is_set
|| rx_8b_10b_code_errors.is_set
|| is_link_error.is_set
|| link_crc_error.is_set
|| link_size_error.is_set
|| link_mis_align_error.is_set
|| link_code_group_error.is_set
|| link_no_sig_lock_error.is_set
|| link_no_sig_accept_error.is_set
|| link_tokens_error.is_set
|| error_token_count.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::DataIdx::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(rack_num.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(tx_control_cells_counter.yfilter)
|| ydk::is_set(tx_data_cell_counter.yfilter)
|| ydk::is_set(tx_data_byte_counter.yfilter)
|| ydk::is_set(rx_crc_errors_counter.yfilter)
|| ydk::is_set(rx_lfec_fec_correctable_error.yfilter)
|| ydk::is_set(rx_8b_10b_disparity_errors.yfilter)
|| ydk::is_set(rx_control_cells_counter.yfilter)
|| ydk::is_set(rx_data_cell_counter.yfilter)
|| ydk::is_set(rx_data_byte_counter.yfilter)
|| ydk::is_set(rx_dropped_retransmitted_control.yfilter)
|| ydk::is_set(tx_asyn_fifo_rate.yfilter)
|| ydk::is_set(rx_asyn_fifo_rate.yfilter)
|| ydk::is_set(rx_lfec_fec_uncorrectable_errors.yfilter)
|| ydk::is_set(rx_8b_10b_code_errors.yfilter)
|| ydk::is_set(is_link_error.yfilter)
|| ydk::is_set(link_crc_error.yfilter)
|| ydk::is_set(link_size_error.yfilter)
|| ydk::is_set(link_mis_align_error.yfilter)
|| ydk::is_set(link_code_group_error.yfilter)
|| ydk::is_set(link_no_sig_lock_error.yfilter)
|| ydk::is_set(link_no_sig_accept_error.yfilter)
|| ydk::is_set(link_tokens_error.yfilter)
|| ydk::is_set(error_token_count.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (rack_num.is_set || is_set(rack_num.yfilter)) leaf_name_data.push_back(rack_num.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (tx_control_cells_counter.is_set || is_set(tx_control_cells_counter.yfilter)) leaf_name_data.push_back(tx_control_cells_counter.get_name_leafdata());
if (tx_data_cell_counter.is_set || is_set(tx_data_cell_counter.yfilter)) leaf_name_data.push_back(tx_data_cell_counter.get_name_leafdata());
if (tx_data_byte_counter.is_set || is_set(tx_data_byte_counter.yfilter)) leaf_name_data.push_back(tx_data_byte_counter.get_name_leafdata());
if (rx_crc_errors_counter.is_set || is_set(rx_crc_errors_counter.yfilter)) leaf_name_data.push_back(rx_crc_errors_counter.get_name_leafdata());
if (rx_lfec_fec_correctable_error.is_set || is_set(rx_lfec_fec_correctable_error.yfilter)) leaf_name_data.push_back(rx_lfec_fec_correctable_error.get_name_leafdata());
if (rx_8b_10b_disparity_errors.is_set || is_set(rx_8b_10b_disparity_errors.yfilter)) leaf_name_data.push_back(rx_8b_10b_disparity_errors.get_name_leafdata());
if (rx_control_cells_counter.is_set || is_set(rx_control_cells_counter.yfilter)) leaf_name_data.push_back(rx_control_cells_counter.get_name_leafdata());
if (rx_data_cell_counter.is_set || is_set(rx_data_cell_counter.yfilter)) leaf_name_data.push_back(rx_data_cell_counter.get_name_leafdata());
if (rx_data_byte_counter.is_set || is_set(rx_data_byte_counter.yfilter)) leaf_name_data.push_back(rx_data_byte_counter.get_name_leafdata());
if (rx_dropped_retransmitted_control.is_set || is_set(rx_dropped_retransmitted_control.yfilter)) leaf_name_data.push_back(rx_dropped_retransmitted_control.get_name_leafdata());
if (tx_asyn_fifo_rate.is_set || is_set(tx_asyn_fifo_rate.yfilter)) leaf_name_data.push_back(tx_asyn_fifo_rate.get_name_leafdata());
if (rx_asyn_fifo_rate.is_set || is_set(rx_asyn_fifo_rate.yfilter)) leaf_name_data.push_back(rx_asyn_fifo_rate.get_name_leafdata());
if (rx_lfec_fec_uncorrectable_errors.is_set || is_set(rx_lfec_fec_uncorrectable_errors.yfilter)) leaf_name_data.push_back(rx_lfec_fec_uncorrectable_errors.get_name_leafdata());
if (rx_8b_10b_code_errors.is_set || is_set(rx_8b_10b_code_errors.yfilter)) leaf_name_data.push_back(rx_8b_10b_code_errors.get_name_leafdata());
if (is_link_error.is_set || is_set(is_link_error.yfilter)) leaf_name_data.push_back(is_link_error.get_name_leafdata());
if (link_crc_error.is_set || is_set(link_crc_error.yfilter)) leaf_name_data.push_back(link_crc_error.get_name_leafdata());
if (link_size_error.is_set || is_set(link_size_error.yfilter)) leaf_name_data.push_back(link_size_error.get_name_leafdata());
if (link_mis_align_error.is_set || is_set(link_mis_align_error.yfilter)) leaf_name_data.push_back(link_mis_align_error.get_name_leafdata());
if (link_code_group_error.is_set || is_set(link_code_group_error.yfilter)) leaf_name_data.push_back(link_code_group_error.get_name_leafdata());
if (link_no_sig_lock_error.is_set || is_set(link_no_sig_lock_error.yfilter)) leaf_name_data.push_back(link_no_sig_lock_error.get_name_leafdata());
if (link_no_sig_accept_error.is_set || is_set(link_no_sig_accept_error.yfilter)) leaf_name_data.push_back(link_no_sig_accept_error.get_name_leafdata());
if (link_tokens_error.is_set || is_set(link_tokens_error.yfilter)) leaf_name_data.push_back(link_tokens_error.get_name_leafdata());
if (error_token_count.is_set || is_set(error_token_count.yfilter)) leaf_name_data.push_back(error_token_count.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "rack_num")
{
rack_num = value;
rack_num.value_namespace = name_space;
rack_num.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TX_Control_cells_counter")
{
tx_control_cells_counter = value;
tx_control_cells_counter.value_namespace = name_space;
tx_control_cells_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TX_Data_cell_counter")
{
tx_data_cell_counter = value;
tx_data_cell_counter.value_namespace = name_space;
tx_data_cell_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TX_Data_byte_counter")
{
tx_data_byte_counter = value;
tx_data_byte_counter.value_namespace = name_space;
tx_data_byte_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_CRC_errors_counter")
{
rx_crc_errors_counter = value;
rx_crc_errors_counter.value_namespace = name_space;
rx_crc_errors_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_LFEC_FEC_correctable_error")
{
rx_lfec_fec_correctable_error = value;
rx_lfec_fec_correctable_error.value_namespace = name_space;
rx_lfec_fec_correctable_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_8b_10b_disparity_errors")
{
rx_8b_10b_disparity_errors = value;
rx_8b_10b_disparity_errors.value_namespace = name_space;
rx_8b_10b_disparity_errors.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_Control_cells_counter")
{
rx_control_cells_counter = value;
rx_control_cells_counter.value_namespace = name_space;
rx_control_cells_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_Data_cell_counter")
{
rx_data_cell_counter = value;
rx_data_cell_counter.value_namespace = name_space;
rx_data_cell_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_Data_byte_counter")
{
rx_data_byte_counter = value;
rx_data_byte_counter.value_namespace = name_space;
rx_data_byte_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_dropped_retransmitted_control")
{
rx_dropped_retransmitted_control = value;
rx_dropped_retransmitted_control.value_namespace = name_space;
rx_dropped_retransmitted_control.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TX_Asyn_fifo_rate")
{
tx_asyn_fifo_rate = value;
tx_asyn_fifo_rate.value_namespace = name_space;
tx_asyn_fifo_rate.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_Asyn_fifo_rate")
{
rx_asyn_fifo_rate = value;
rx_asyn_fifo_rate.value_namespace = name_space;
rx_asyn_fifo_rate.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_LFEC_FEC_uncorrectable_errors")
{
rx_lfec_fec_uncorrectable_errors = value;
rx_lfec_fec_uncorrectable_errors.value_namespace = name_space;
rx_lfec_fec_uncorrectable_errors.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_8b_10b_code_errors")
{
rx_8b_10b_code_errors = value;
rx_8b_10b_code_errors.value_namespace = name_space;
rx_8b_10b_code_errors.value_namespace_prefix = name_space_prefix;
}
if(value_path == "is_link_error")
{
is_link_error = value;
is_link_error.value_namespace = name_space;
is_link_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_crc_error")
{
link_crc_error = value;
link_crc_error.value_namespace = name_space;
link_crc_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_size_error")
{
link_size_error = value;
link_size_error.value_namespace = name_space;
link_size_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_mis_align_error")
{
link_mis_align_error = value;
link_mis_align_error.value_namespace = name_space;
link_mis_align_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_code_group_error")
{
link_code_group_error = value;
link_code_group_error.value_namespace = name_space;
link_code_group_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_no_sig_lock_error")
{
link_no_sig_lock_error = value;
link_no_sig_lock_error.value_namespace = name_space;
link_no_sig_lock_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_no_sig_accept_error")
{
link_no_sig_accept_error = value;
link_no_sig_accept_error.value_namespace = name_space;
link_no_sig_accept_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_tokens_error")
{
link_tokens_error = value;
link_tokens_error.value_namespace = name_space;
link_tokens_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_token_count")
{
error_token_count = value;
error_token_count.value_namespace = name_space;
error_token_count.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "rack_num")
{
rack_num.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "TX_Control_cells_counter")
{
tx_control_cells_counter.yfilter = yfilter;
}
if(value_path == "TX_Data_cell_counter")
{
tx_data_cell_counter.yfilter = yfilter;
}
if(value_path == "TX_Data_byte_counter")
{
tx_data_byte_counter.yfilter = yfilter;
}
if(value_path == "RX_CRC_errors_counter")
{
rx_crc_errors_counter.yfilter = yfilter;
}
if(value_path == "RX_LFEC_FEC_correctable_error")
{
rx_lfec_fec_correctable_error.yfilter = yfilter;
}
if(value_path == "RX_8b_10b_disparity_errors")
{
rx_8b_10b_disparity_errors.yfilter = yfilter;
}
if(value_path == "RX_Control_cells_counter")
{
rx_control_cells_counter.yfilter = yfilter;
}
if(value_path == "RX_Data_cell_counter")
{
rx_data_cell_counter.yfilter = yfilter;
}
if(value_path == "RX_Data_byte_counter")
{
rx_data_byte_counter.yfilter = yfilter;
}
if(value_path == "RX_dropped_retransmitted_control")
{
rx_dropped_retransmitted_control.yfilter = yfilter;
}
if(value_path == "TX_Asyn_fifo_rate")
{
tx_asyn_fifo_rate.yfilter = yfilter;
}
if(value_path == "RX_Asyn_fifo_rate")
{
rx_asyn_fifo_rate.yfilter = yfilter;
}
if(value_path == "RX_LFEC_FEC_uncorrectable_errors")
{
rx_lfec_fec_uncorrectable_errors.yfilter = yfilter;
}
if(value_path == "RX_8b_10b_code_errors")
{
rx_8b_10b_code_errors.yfilter = yfilter;
}
if(value_path == "is_link_error")
{
is_link_error.yfilter = yfilter;
}
if(value_path == "link_crc_error")
{
link_crc_error.yfilter = yfilter;
}
if(value_path == "link_size_error")
{
link_size_error.yfilter = yfilter;
}
if(value_path == "link_mis_align_error")
{
link_mis_align_error.yfilter = yfilter;
}
if(value_path == "link_code_group_error")
{
link_code_group_error.yfilter = yfilter;
}
if(value_path == "link_no_sig_lock_error")
{
link_no_sig_lock_error.yfilter = yfilter;
}
if(value_path == "link_no_sig_accept_error")
{
link_no_sig_accept_error.yfilter = yfilter;
}
if(value_path == "link_tokens_error")
{
link_tokens_error.yfilter = yfilter;
}
if(value_path == "error_token_count")
{
error_token_count.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "port_data_idx" || name == "rack_num" || name == "sfe_port" || name == "TX_Control_cells_counter" || name == "TX_Data_cell_counter" || name == "TX_Data_byte_counter" || name == "RX_CRC_errors_counter" || name == "RX_LFEC_FEC_correctable_error" || name == "RX_8b_10b_disparity_errors" || name == "RX_Control_cells_counter" || name == "RX_Data_cell_counter" || name == "RX_Data_byte_counter" || name == "RX_dropped_retransmitted_control" || name == "TX_Asyn_fifo_rate" || name == "RX_Asyn_fifo_rate" || name == "RX_LFEC_FEC_uncorrectable_errors" || name == "RX_8b_10b_code_errors" || name == "is_link_error" || name == "link_crc_error" || name == "link_size_error" || name == "link_mis_align_error" || name == "link_code_group_error" || name == "link_no_sig_lock_error" || name == "link_no_sig_accept_error" || name == "link_tokens_error" || name == "error_token_count")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Brief::Brief()
:
data_idx(this, {"port_data_idx"})
{
yang_name = "brief"; yang_parent_name = "statistics"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Brief::~Brief()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Brief::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return false;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Brief::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Brief::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "brief";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Brief::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Brief::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Brief::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Brief::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Brief::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Brief::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Brief::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Brief::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
rack_num{YType::str, "rack_num"},
sfe_port{YType::str, "sfe_port"},
tx_control_cells_counter{YType::uint64, "TX_Control_cells_counter"},
tx_data_cell_counter{YType::uint64, "TX_Data_cell_counter"},
tx_data_byte_counter{YType::uint64, "TX_Data_byte_counter"},
rx_crc_errors_counter{YType::uint64, "RX_CRC_errors_counter"},
rx_lfec_fec_correctable_error{YType::uint64, "RX_LFEC_FEC_correctable_error"},
rx_8b_10b_disparity_errors{YType::uint64, "RX_8b_10b_disparity_errors"},
rx_control_cells_counter{YType::uint64, "RX_Control_cells_counter"},
rx_data_cell_counter{YType::uint64, "RX_Data_cell_counter"},
rx_data_byte_counter{YType::uint64, "RX_Data_byte_counter"},
rx_dropped_retransmitted_control{YType::uint64, "RX_dropped_retransmitted_control"},
tx_asyn_fifo_rate{YType::uint64, "TX_Asyn_fifo_rate"},
rx_asyn_fifo_rate{YType::uint64, "RX_Asyn_fifo_rate"},
rx_lfec_fec_uncorrectable_errors{YType::uint64, "RX_LFEC_FEC_uncorrectable_errors"},
rx_8b_10b_code_errors{YType::uint64, "RX_8b_10b_code_errors"},
is_link_error{YType::boolean, "is_link_error"},
link_crc_error{YType::uint32, "link_crc_error"},
link_size_error{YType::uint32, "link_size_error"},
link_mis_align_error{YType::uint32, "link_mis_align_error"},
link_code_group_error{YType::uint32, "link_code_group_error"},
link_no_sig_lock_error{YType::uint32, "link_no_sig_lock_error"},
link_no_sig_accept_error{YType::uint32, "link_no_sig_accept_error"},
link_tokens_error{YType::uint32, "link_tokens_error"},
error_token_count{YType::uint32, "error_token_count"}
{
yang_name = "data_idx"; yang_parent_name = "brief"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Brief::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Brief::DataIdx::has_data() const
{
if (is_presence_container) return true;
return port_data_idx.is_set
|| rack_num.is_set
|| sfe_port.is_set
|| tx_control_cells_counter.is_set
|| tx_data_cell_counter.is_set
|| tx_data_byte_counter.is_set
|| rx_crc_errors_counter.is_set
|| rx_lfec_fec_correctable_error.is_set
|| rx_8b_10b_disparity_errors.is_set
|| rx_control_cells_counter.is_set
|| rx_data_cell_counter.is_set
|| rx_data_byte_counter.is_set
|| rx_dropped_retransmitted_control.is_set
|| tx_asyn_fifo_rate.is_set
|| rx_asyn_fifo_rate.is_set
|| rx_lfec_fec_uncorrectable_errors.is_set
|| rx_8b_10b_code_errors.is_set
|| is_link_error.is_set
|| link_crc_error.is_set
|| link_size_error.is_set
|| link_mis_align_error.is_set
|| link_code_group_error.is_set
|| link_no_sig_lock_error.is_set
|| link_no_sig_accept_error.is_set
|| link_tokens_error.is_set
|| error_token_count.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Brief::DataIdx::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(rack_num.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(tx_control_cells_counter.yfilter)
|| ydk::is_set(tx_data_cell_counter.yfilter)
|| ydk::is_set(tx_data_byte_counter.yfilter)
|| ydk::is_set(rx_crc_errors_counter.yfilter)
|| ydk::is_set(rx_lfec_fec_correctable_error.yfilter)
|| ydk::is_set(rx_8b_10b_disparity_errors.yfilter)
|| ydk::is_set(rx_control_cells_counter.yfilter)
|| ydk::is_set(rx_data_cell_counter.yfilter)
|| ydk::is_set(rx_data_byte_counter.yfilter)
|| ydk::is_set(rx_dropped_retransmitted_control.yfilter)
|| ydk::is_set(tx_asyn_fifo_rate.yfilter)
|| ydk::is_set(rx_asyn_fifo_rate.yfilter)
|| ydk::is_set(rx_lfec_fec_uncorrectable_errors.yfilter)
|| ydk::is_set(rx_8b_10b_code_errors.yfilter)
|| ydk::is_set(is_link_error.yfilter)
|| ydk::is_set(link_crc_error.yfilter)
|| ydk::is_set(link_size_error.yfilter)
|| ydk::is_set(link_mis_align_error.yfilter)
|| ydk::is_set(link_code_group_error.yfilter)
|| ydk::is_set(link_no_sig_lock_error.yfilter)
|| ydk::is_set(link_no_sig_accept_error.yfilter)
|| ydk::is_set(link_tokens_error.yfilter)
|| ydk::is_set(error_token_count.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Brief::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Brief::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (rack_num.is_set || is_set(rack_num.yfilter)) leaf_name_data.push_back(rack_num.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (tx_control_cells_counter.is_set || is_set(tx_control_cells_counter.yfilter)) leaf_name_data.push_back(tx_control_cells_counter.get_name_leafdata());
if (tx_data_cell_counter.is_set || is_set(tx_data_cell_counter.yfilter)) leaf_name_data.push_back(tx_data_cell_counter.get_name_leafdata());
if (tx_data_byte_counter.is_set || is_set(tx_data_byte_counter.yfilter)) leaf_name_data.push_back(tx_data_byte_counter.get_name_leafdata());
if (rx_crc_errors_counter.is_set || is_set(rx_crc_errors_counter.yfilter)) leaf_name_data.push_back(rx_crc_errors_counter.get_name_leafdata());
if (rx_lfec_fec_correctable_error.is_set || is_set(rx_lfec_fec_correctable_error.yfilter)) leaf_name_data.push_back(rx_lfec_fec_correctable_error.get_name_leafdata());
if (rx_8b_10b_disparity_errors.is_set || is_set(rx_8b_10b_disparity_errors.yfilter)) leaf_name_data.push_back(rx_8b_10b_disparity_errors.get_name_leafdata());
if (rx_control_cells_counter.is_set || is_set(rx_control_cells_counter.yfilter)) leaf_name_data.push_back(rx_control_cells_counter.get_name_leafdata());
if (rx_data_cell_counter.is_set || is_set(rx_data_cell_counter.yfilter)) leaf_name_data.push_back(rx_data_cell_counter.get_name_leafdata());
if (rx_data_byte_counter.is_set || is_set(rx_data_byte_counter.yfilter)) leaf_name_data.push_back(rx_data_byte_counter.get_name_leafdata());
if (rx_dropped_retransmitted_control.is_set || is_set(rx_dropped_retransmitted_control.yfilter)) leaf_name_data.push_back(rx_dropped_retransmitted_control.get_name_leafdata());
if (tx_asyn_fifo_rate.is_set || is_set(tx_asyn_fifo_rate.yfilter)) leaf_name_data.push_back(tx_asyn_fifo_rate.get_name_leafdata());
if (rx_asyn_fifo_rate.is_set || is_set(rx_asyn_fifo_rate.yfilter)) leaf_name_data.push_back(rx_asyn_fifo_rate.get_name_leafdata());
if (rx_lfec_fec_uncorrectable_errors.is_set || is_set(rx_lfec_fec_uncorrectable_errors.yfilter)) leaf_name_data.push_back(rx_lfec_fec_uncorrectable_errors.get_name_leafdata());
if (rx_8b_10b_code_errors.is_set || is_set(rx_8b_10b_code_errors.yfilter)) leaf_name_data.push_back(rx_8b_10b_code_errors.get_name_leafdata());
if (is_link_error.is_set || is_set(is_link_error.yfilter)) leaf_name_data.push_back(is_link_error.get_name_leafdata());
if (link_crc_error.is_set || is_set(link_crc_error.yfilter)) leaf_name_data.push_back(link_crc_error.get_name_leafdata());
if (link_size_error.is_set || is_set(link_size_error.yfilter)) leaf_name_data.push_back(link_size_error.get_name_leafdata());
if (link_mis_align_error.is_set || is_set(link_mis_align_error.yfilter)) leaf_name_data.push_back(link_mis_align_error.get_name_leafdata());
if (link_code_group_error.is_set || is_set(link_code_group_error.yfilter)) leaf_name_data.push_back(link_code_group_error.get_name_leafdata());
if (link_no_sig_lock_error.is_set || is_set(link_no_sig_lock_error.yfilter)) leaf_name_data.push_back(link_no_sig_lock_error.get_name_leafdata());
if (link_no_sig_accept_error.is_set || is_set(link_no_sig_accept_error.yfilter)) leaf_name_data.push_back(link_no_sig_accept_error.get_name_leafdata());
if (link_tokens_error.is_set || is_set(link_tokens_error.yfilter)) leaf_name_data.push_back(link_tokens_error.get_name_leafdata());
if (error_token_count.is_set || is_set(error_token_count.yfilter)) leaf_name_data.push_back(error_token_count.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Brief::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Brief::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Brief::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "rack_num")
{
rack_num = value;
rack_num.value_namespace = name_space;
rack_num.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TX_Control_cells_counter")
{
tx_control_cells_counter = value;
tx_control_cells_counter.value_namespace = name_space;
tx_control_cells_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TX_Data_cell_counter")
{
tx_data_cell_counter = value;
tx_data_cell_counter.value_namespace = name_space;
tx_data_cell_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TX_Data_byte_counter")
{
tx_data_byte_counter = value;
tx_data_byte_counter.value_namespace = name_space;
tx_data_byte_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_CRC_errors_counter")
{
rx_crc_errors_counter = value;
rx_crc_errors_counter.value_namespace = name_space;
rx_crc_errors_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_LFEC_FEC_correctable_error")
{
rx_lfec_fec_correctable_error = value;
rx_lfec_fec_correctable_error.value_namespace = name_space;
rx_lfec_fec_correctable_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_8b_10b_disparity_errors")
{
rx_8b_10b_disparity_errors = value;
rx_8b_10b_disparity_errors.value_namespace = name_space;
rx_8b_10b_disparity_errors.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_Control_cells_counter")
{
rx_control_cells_counter = value;
rx_control_cells_counter.value_namespace = name_space;
rx_control_cells_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_Data_cell_counter")
{
rx_data_cell_counter = value;
rx_data_cell_counter.value_namespace = name_space;
rx_data_cell_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_Data_byte_counter")
{
rx_data_byte_counter = value;
rx_data_byte_counter.value_namespace = name_space;
rx_data_byte_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_dropped_retransmitted_control")
{
rx_dropped_retransmitted_control = value;
rx_dropped_retransmitted_control.value_namespace = name_space;
rx_dropped_retransmitted_control.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TX_Asyn_fifo_rate")
{
tx_asyn_fifo_rate = value;
tx_asyn_fifo_rate.value_namespace = name_space;
tx_asyn_fifo_rate.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_Asyn_fifo_rate")
{
rx_asyn_fifo_rate = value;
rx_asyn_fifo_rate.value_namespace = name_space;
rx_asyn_fifo_rate.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_LFEC_FEC_uncorrectable_errors")
{
rx_lfec_fec_uncorrectable_errors = value;
rx_lfec_fec_uncorrectable_errors.value_namespace = name_space;
rx_lfec_fec_uncorrectable_errors.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_8b_10b_code_errors")
{
rx_8b_10b_code_errors = value;
rx_8b_10b_code_errors.value_namespace = name_space;
rx_8b_10b_code_errors.value_namespace_prefix = name_space_prefix;
}
if(value_path == "is_link_error")
{
is_link_error = value;
is_link_error.value_namespace = name_space;
is_link_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_crc_error")
{
link_crc_error = value;
link_crc_error.value_namespace = name_space;
link_crc_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_size_error")
{
link_size_error = value;
link_size_error.value_namespace = name_space;
link_size_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_mis_align_error")
{
link_mis_align_error = value;
link_mis_align_error.value_namespace = name_space;
link_mis_align_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_code_group_error")
{
link_code_group_error = value;
link_code_group_error.value_namespace = name_space;
link_code_group_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_no_sig_lock_error")
{
link_no_sig_lock_error = value;
link_no_sig_lock_error.value_namespace = name_space;
link_no_sig_lock_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_no_sig_accept_error")
{
link_no_sig_accept_error = value;
link_no_sig_accept_error.value_namespace = name_space;
link_no_sig_accept_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_tokens_error")
{
link_tokens_error = value;
link_tokens_error.value_namespace = name_space;
link_tokens_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_token_count")
{
error_token_count = value;
error_token_count.value_namespace = name_space;
error_token_count.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Brief::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "rack_num")
{
rack_num.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "TX_Control_cells_counter")
{
tx_control_cells_counter.yfilter = yfilter;
}
if(value_path == "TX_Data_cell_counter")
{
tx_data_cell_counter.yfilter = yfilter;
}
if(value_path == "TX_Data_byte_counter")
{
tx_data_byte_counter.yfilter = yfilter;
}
if(value_path == "RX_CRC_errors_counter")
{
rx_crc_errors_counter.yfilter = yfilter;
}
if(value_path == "RX_LFEC_FEC_correctable_error")
{
rx_lfec_fec_correctable_error.yfilter = yfilter;
}
if(value_path == "RX_8b_10b_disparity_errors")
{
rx_8b_10b_disparity_errors.yfilter = yfilter;
}
if(value_path == "RX_Control_cells_counter")
{
rx_control_cells_counter.yfilter = yfilter;
}
if(value_path == "RX_Data_cell_counter")
{
rx_data_cell_counter.yfilter = yfilter;
}
if(value_path == "RX_Data_byte_counter")
{
rx_data_byte_counter.yfilter = yfilter;
}
if(value_path == "RX_dropped_retransmitted_control")
{
rx_dropped_retransmitted_control.yfilter = yfilter;
}
if(value_path == "TX_Asyn_fifo_rate")
{
tx_asyn_fifo_rate.yfilter = yfilter;
}
if(value_path == "RX_Asyn_fifo_rate")
{
rx_asyn_fifo_rate.yfilter = yfilter;
}
if(value_path == "RX_LFEC_FEC_uncorrectable_errors")
{
rx_lfec_fec_uncorrectable_errors.yfilter = yfilter;
}
if(value_path == "RX_8b_10b_code_errors")
{
rx_8b_10b_code_errors.yfilter = yfilter;
}
if(value_path == "is_link_error")
{
is_link_error.yfilter = yfilter;
}
if(value_path == "link_crc_error")
{
link_crc_error.yfilter = yfilter;
}
if(value_path == "link_size_error")
{
link_size_error.yfilter = yfilter;
}
if(value_path == "link_mis_align_error")
{
link_mis_align_error.yfilter = yfilter;
}
if(value_path == "link_code_group_error")
{
link_code_group_error.yfilter = yfilter;
}
if(value_path == "link_no_sig_lock_error")
{
link_no_sig_lock_error.yfilter = yfilter;
}
if(value_path == "link_no_sig_accept_error")
{
link_no_sig_accept_error.yfilter = yfilter;
}
if(value_path == "link_tokens_error")
{
link_tokens_error.yfilter = yfilter;
}
if(value_path == "error_token_count")
{
error_token_count.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Brief::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "port_data_idx" || name == "rack_num" || name == "sfe_port" || name == "TX_Control_cells_counter" || name == "TX_Data_cell_counter" || name == "TX_Data_byte_counter" || name == "RX_CRC_errors_counter" || name == "RX_LFEC_FEC_correctable_error" || name == "RX_8b_10b_disparity_errors" || name == "RX_Control_cells_counter" || name == "RX_Data_cell_counter" || name == "RX_Data_byte_counter" || name == "RX_dropped_retransmitted_control" || name == "TX_Asyn_fifo_rate" || name == "RX_Asyn_fifo_rate" || name == "RX_LFEC_FEC_uncorrectable_errors" || name == "RX_8b_10b_code_errors" || name == "is_link_error" || name == "link_crc_error" || name == "link_size_error" || name == "link_mis_align_error" || name == "link_code_group_error" || name == "link_no_sig_lock_error" || name == "link_no_sig_accept_error" || name == "link_tokens_error" || name == "error_token_count")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Detail::Detail()
:
data_idx(this, {"port_data_idx"})
{
yang_name = "detail"; yang_parent_name = "statistics"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Detail::~Detail()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Detail::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return false;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Detail::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Detail::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "detail";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Detail::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Detail::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Detail::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Detail::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Detail::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Detail::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Detail::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Detail::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
rack_num{YType::str, "rack_num"},
sfe_port{YType::str, "sfe_port"},
tx_control_cells_counter{YType::uint64, "TX_Control_cells_counter"},
tx_data_cell_counter{YType::uint64, "TX_Data_cell_counter"},
tx_data_byte_counter{YType::uint64, "TX_Data_byte_counter"},
rx_crc_errors_counter{YType::uint64, "RX_CRC_errors_counter"},
rx_lfec_fec_correctable_error{YType::uint64, "RX_LFEC_FEC_correctable_error"},
rx_8b_10b_disparity_errors{YType::uint64, "RX_8b_10b_disparity_errors"},
rx_control_cells_counter{YType::uint64, "RX_Control_cells_counter"},
rx_data_cell_counter{YType::uint64, "RX_Data_cell_counter"},
rx_data_byte_counter{YType::uint64, "RX_Data_byte_counter"},
rx_dropped_retransmitted_control{YType::uint64, "RX_dropped_retransmitted_control"},
tx_asyn_fifo_rate{YType::uint64, "TX_Asyn_fifo_rate"},
rx_asyn_fifo_rate{YType::uint64, "RX_Asyn_fifo_rate"},
rx_lfec_fec_uncorrectable_errors{YType::uint64, "RX_LFEC_FEC_uncorrectable_errors"},
rx_8b_10b_code_errors{YType::uint64, "RX_8b_10b_code_errors"},
is_link_error{YType::boolean, "is_link_error"},
link_crc_error{YType::uint32, "link_crc_error"},
link_size_error{YType::uint32, "link_size_error"},
link_mis_align_error{YType::uint32, "link_mis_align_error"},
link_code_group_error{YType::uint32, "link_code_group_error"},
link_no_sig_lock_error{YType::uint32, "link_no_sig_lock_error"},
link_no_sig_accept_error{YType::uint32, "link_no_sig_accept_error"},
link_tokens_error{YType::uint32, "link_tokens_error"},
error_token_count{YType::uint32, "error_token_count"}
{
yang_name = "data_idx"; yang_parent_name = "detail"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Detail::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Detail::DataIdx::has_data() const
{
if (is_presence_container) return true;
return port_data_idx.is_set
|| rack_num.is_set
|| sfe_port.is_set
|| tx_control_cells_counter.is_set
|| tx_data_cell_counter.is_set
|| tx_data_byte_counter.is_set
|| rx_crc_errors_counter.is_set
|| rx_lfec_fec_correctable_error.is_set
|| rx_8b_10b_disparity_errors.is_set
|| rx_control_cells_counter.is_set
|| rx_data_cell_counter.is_set
|| rx_data_byte_counter.is_set
|| rx_dropped_retransmitted_control.is_set
|| tx_asyn_fifo_rate.is_set
|| rx_asyn_fifo_rate.is_set
|| rx_lfec_fec_uncorrectable_errors.is_set
|| rx_8b_10b_code_errors.is_set
|| is_link_error.is_set
|| link_crc_error.is_set
|| link_size_error.is_set
|| link_mis_align_error.is_set
|| link_code_group_error.is_set
|| link_no_sig_lock_error.is_set
|| link_no_sig_accept_error.is_set
|| link_tokens_error.is_set
|| error_token_count.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Detail::DataIdx::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(rack_num.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(tx_control_cells_counter.yfilter)
|| ydk::is_set(tx_data_cell_counter.yfilter)
|| ydk::is_set(tx_data_byte_counter.yfilter)
|| ydk::is_set(rx_crc_errors_counter.yfilter)
|| ydk::is_set(rx_lfec_fec_correctable_error.yfilter)
|| ydk::is_set(rx_8b_10b_disparity_errors.yfilter)
|| ydk::is_set(rx_control_cells_counter.yfilter)
|| ydk::is_set(rx_data_cell_counter.yfilter)
|| ydk::is_set(rx_data_byte_counter.yfilter)
|| ydk::is_set(rx_dropped_retransmitted_control.yfilter)
|| ydk::is_set(tx_asyn_fifo_rate.yfilter)
|| ydk::is_set(rx_asyn_fifo_rate.yfilter)
|| ydk::is_set(rx_lfec_fec_uncorrectable_errors.yfilter)
|| ydk::is_set(rx_8b_10b_code_errors.yfilter)
|| ydk::is_set(is_link_error.yfilter)
|| ydk::is_set(link_crc_error.yfilter)
|| ydk::is_set(link_size_error.yfilter)
|| ydk::is_set(link_mis_align_error.yfilter)
|| ydk::is_set(link_code_group_error.yfilter)
|| ydk::is_set(link_no_sig_lock_error.yfilter)
|| ydk::is_set(link_no_sig_accept_error.yfilter)
|| ydk::is_set(link_tokens_error.yfilter)
|| ydk::is_set(error_token_count.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Detail::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Detail::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (rack_num.is_set || is_set(rack_num.yfilter)) leaf_name_data.push_back(rack_num.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (tx_control_cells_counter.is_set || is_set(tx_control_cells_counter.yfilter)) leaf_name_data.push_back(tx_control_cells_counter.get_name_leafdata());
if (tx_data_cell_counter.is_set || is_set(tx_data_cell_counter.yfilter)) leaf_name_data.push_back(tx_data_cell_counter.get_name_leafdata());
if (tx_data_byte_counter.is_set || is_set(tx_data_byte_counter.yfilter)) leaf_name_data.push_back(tx_data_byte_counter.get_name_leafdata());
if (rx_crc_errors_counter.is_set || is_set(rx_crc_errors_counter.yfilter)) leaf_name_data.push_back(rx_crc_errors_counter.get_name_leafdata());
if (rx_lfec_fec_correctable_error.is_set || is_set(rx_lfec_fec_correctable_error.yfilter)) leaf_name_data.push_back(rx_lfec_fec_correctable_error.get_name_leafdata());
if (rx_8b_10b_disparity_errors.is_set || is_set(rx_8b_10b_disparity_errors.yfilter)) leaf_name_data.push_back(rx_8b_10b_disparity_errors.get_name_leafdata());
if (rx_control_cells_counter.is_set || is_set(rx_control_cells_counter.yfilter)) leaf_name_data.push_back(rx_control_cells_counter.get_name_leafdata());
if (rx_data_cell_counter.is_set || is_set(rx_data_cell_counter.yfilter)) leaf_name_data.push_back(rx_data_cell_counter.get_name_leafdata());
if (rx_data_byte_counter.is_set || is_set(rx_data_byte_counter.yfilter)) leaf_name_data.push_back(rx_data_byte_counter.get_name_leafdata());
if (rx_dropped_retransmitted_control.is_set || is_set(rx_dropped_retransmitted_control.yfilter)) leaf_name_data.push_back(rx_dropped_retransmitted_control.get_name_leafdata());
if (tx_asyn_fifo_rate.is_set || is_set(tx_asyn_fifo_rate.yfilter)) leaf_name_data.push_back(tx_asyn_fifo_rate.get_name_leafdata());
if (rx_asyn_fifo_rate.is_set || is_set(rx_asyn_fifo_rate.yfilter)) leaf_name_data.push_back(rx_asyn_fifo_rate.get_name_leafdata());
if (rx_lfec_fec_uncorrectable_errors.is_set || is_set(rx_lfec_fec_uncorrectable_errors.yfilter)) leaf_name_data.push_back(rx_lfec_fec_uncorrectable_errors.get_name_leafdata());
if (rx_8b_10b_code_errors.is_set || is_set(rx_8b_10b_code_errors.yfilter)) leaf_name_data.push_back(rx_8b_10b_code_errors.get_name_leafdata());
if (is_link_error.is_set || is_set(is_link_error.yfilter)) leaf_name_data.push_back(is_link_error.get_name_leafdata());
if (link_crc_error.is_set || is_set(link_crc_error.yfilter)) leaf_name_data.push_back(link_crc_error.get_name_leafdata());
if (link_size_error.is_set || is_set(link_size_error.yfilter)) leaf_name_data.push_back(link_size_error.get_name_leafdata());
if (link_mis_align_error.is_set || is_set(link_mis_align_error.yfilter)) leaf_name_data.push_back(link_mis_align_error.get_name_leafdata());
if (link_code_group_error.is_set || is_set(link_code_group_error.yfilter)) leaf_name_data.push_back(link_code_group_error.get_name_leafdata());
if (link_no_sig_lock_error.is_set || is_set(link_no_sig_lock_error.yfilter)) leaf_name_data.push_back(link_no_sig_lock_error.get_name_leafdata());
if (link_no_sig_accept_error.is_set || is_set(link_no_sig_accept_error.yfilter)) leaf_name_data.push_back(link_no_sig_accept_error.get_name_leafdata());
if (link_tokens_error.is_set || is_set(link_tokens_error.yfilter)) leaf_name_data.push_back(link_tokens_error.get_name_leafdata());
if (error_token_count.is_set || is_set(error_token_count.yfilter)) leaf_name_data.push_back(error_token_count.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Detail::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Detail::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Detail::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "rack_num")
{
rack_num = value;
rack_num.value_namespace = name_space;
rack_num.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TX_Control_cells_counter")
{
tx_control_cells_counter = value;
tx_control_cells_counter.value_namespace = name_space;
tx_control_cells_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TX_Data_cell_counter")
{
tx_data_cell_counter = value;
tx_data_cell_counter.value_namespace = name_space;
tx_data_cell_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TX_Data_byte_counter")
{
tx_data_byte_counter = value;
tx_data_byte_counter.value_namespace = name_space;
tx_data_byte_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_CRC_errors_counter")
{
rx_crc_errors_counter = value;
rx_crc_errors_counter.value_namespace = name_space;
rx_crc_errors_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_LFEC_FEC_correctable_error")
{
rx_lfec_fec_correctable_error = value;
rx_lfec_fec_correctable_error.value_namespace = name_space;
rx_lfec_fec_correctable_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_8b_10b_disparity_errors")
{
rx_8b_10b_disparity_errors = value;
rx_8b_10b_disparity_errors.value_namespace = name_space;
rx_8b_10b_disparity_errors.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_Control_cells_counter")
{
rx_control_cells_counter = value;
rx_control_cells_counter.value_namespace = name_space;
rx_control_cells_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_Data_cell_counter")
{
rx_data_cell_counter = value;
rx_data_cell_counter.value_namespace = name_space;
rx_data_cell_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_Data_byte_counter")
{
rx_data_byte_counter = value;
rx_data_byte_counter.value_namespace = name_space;
rx_data_byte_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_dropped_retransmitted_control")
{
rx_dropped_retransmitted_control = value;
rx_dropped_retransmitted_control.value_namespace = name_space;
rx_dropped_retransmitted_control.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TX_Asyn_fifo_rate")
{
tx_asyn_fifo_rate = value;
tx_asyn_fifo_rate.value_namespace = name_space;
tx_asyn_fifo_rate.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_Asyn_fifo_rate")
{
rx_asyn_fifo_rate = value;
rx_asyn_fifo_rate.value_namespace = name_space;
rx_asyn_fifo_rate.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_LFEC_FEC_uncorrectable_errors")
{
rx_lfec_fec_uncorrectable_errors = value;
rx_lfec_fec_uncorrectable_errors.value_namespace = name_space;
rx_lfec_fec_uncorrectable_errors.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_8b_10b_code_errors")
{
rx_8b_10b_code_errors = value;
rx_8b_10b_code_errors.value_namespace = name_space;
rx_8b_10b_code_errors.value_namespace_prefix = name_space_prefix;
}
if(value_path == "is_link_error")
{
is_link_error = value;
is_link_error.value_namespace = name_space;
is_link_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_crc_error")
{
link_crc_error = value;
link_crc_error.value_namespace = name_space;
link_crc_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_size_error")
{
link_size_error = value;
link_size_error.value_namespace = name_space;
link_size_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_mis_align_error")
{
link_mis_align_error = value;
link_mis_align_error.value_namespace = name_space;
link_mis_align_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_code_group_error")
{
link_code_group_error = value;
link_code_group_error.value_namespace = name_space;
link_code_group_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_no_sig_lock_error")
{
link_no_sig_lock_error = value;
link_no_sig_lock_error.value_namespace = name_space;
link_no_sig_lock_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_no_sig_accept_error")
{
link_no_sig_accept_error = value;
link_no_sig_accept_error.value_namespace = name_space;
link_no_sig_accept_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_tokens_error")
{
link_tokens_error = value;
link_tokens_error.value_namespace = name_space;
link_tokens_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_token_count")
{
error_token_count = value;
error_token_count.value_namespace = name_space;
error_token_count.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Detail::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "rack_num")
{
rack_num.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "TX_Control_cells_counter")
{
tx_control_cells_counter.yfilter = yfilter;
}
if(value_path == "TX_Data_cell_counter")
{
tx_data_cell_counter.yfilter = yfilter;
}
if(value_path == "TX_Data_byte_counter")
{
tx_data_byte_counter.yfilter = yfilter;
}
if(value_path == "RX_CRC_errors_counter")
{
rx_crc_errors_counter.yfilter = yfilter;
}
if(value_path == "RX_LFEC_FEC_correctable_error")
{
rx_lfec_fec_correctable_error.yfilter = yfilter;
}
if(value_path == "RX_8b_10b_disparity_errors")
{
rx_8b_10b_disparity_errors.yfilter = yfilter;
}
if(value_path == "RX_Control_cells_counter")
{
rx_control_cells_counter.yfilter = yfilter;
}
if(value_path == "RX_Data_cell_counter")
{
rx_data_cell_counter.yfilter = yfilter;
}
if(value_path == "RX_Data_byte_counter")
{
rx_data_byte_counter.yfilter = yfilter;
}
if(value_path == "RX_dropped_retransmitted_control")
{
rx_dropped_retransmitted_control.yfilter = yfilter;
}
if(value_path == "TX_Asyn_fifo_rate")
{
tx_asyn_fifo_rate.yfilter = yfilter;
}
if(value_path == "RX_Asyn_fifo_rate")
{
rx_asyn_fifo_rate.yfilter = yfilter;
}
if(value_path == "RX_LFEC_FEC_uncorrectable_errors")
{
rx_lfec_fec_uncorrectable_errors.yfilter = yfilter;
}
if(value_path == "RX_8b_10b_code_errors")
{
rx_8b_10b_code_errors.yfilter = yfilter;
}
if(value_path == "is_link_error")
{
is_link_error.yfilter = yfilter;
}
if(value_path == "link_crc_error")
{
link_crc_error.yfilter = yfilter;
}
if(value_path == "link_size_error")
{
link_size_error.yfilter = yfilter;
}
if(value_path == "link_mis_align_error")
{
link_mis_align_error.yfilter = yfilter;
}
if(value_path == "link_code_group_error")
{
link_code_group_error.yfilter = yfilter;
}
if(value_path == "link_no_sig_lock_error")
{
link_no_sig_lock_error.yfilter = yfilter;
}
if(value_path == "link_no_sig_accept_error")
{
link_no_sig_accept_error.yfilter = yfilter;
}
if(value_path == "link_tokens_error")
{
link_tokens_error.yfilter = yfilter;
}
if(value_path == "error_token_count")
{
error_token_count.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Rx::Statistics::Detail::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "port_data_idx" || name == "rack_num" || name == "sfe_port" || name == "TX_Control_cells_counter" || name == "TX_Data_cell_counter" || name == "TX_Data_byte_counter" || name == "RX_CRC_errors_counter" || name == "RX_LFEC_FEC_correctable_error" || name == "RX_8b_10b_disparity_errors" || name == "RX_Control_cells_counter" || name == "RX_Data_cell_counter" || name == "RX_Data_byte_counter" || name == "RX_dropped_retransmitted_control" || name == "TX_Asyn_fifo_rate" || name == "RX_Asyn_fifo_rate" || name == "RX_LFEC_FEC_uncorrectable_errors" || name == "RX_8b_10b_code_errors" || name == "is_link_error" || name == "link_crc_error" || name == "link_size_error" || name == "link_mis_align_error" || name == "link_code_group_error" || name == "link_no_sig_lock_error" || name == "link_no_sig_accept_error" || name == "link_tokens_error" || name == "error_token_count")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Tx()
:
data_idx(this, {"port_data_idx"})
, brief(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Brief>())
, detail(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Detail>())
, state(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State>())
, statistics(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics>())
{
brief->parent = this;
detail->parent = this;
state->parent = this;
statistics->parent = this;
yang_name = "tx"; yang_parent_name = "location"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::~Tx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return (brief != nullptr && brief->has_data())
|| (detail != nullptr && detail->has_data())
|| (state != nullptr && state->has_data())
|| (statistics != nullptr && statistics->has_data());
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter)
|| (brief != nullptr && brief->has_operation())
|| (detail != nullptr && detail->has_operation())
|| (state != nullptr && state->has_operation())
|| (statistics != nullptr && statistics->has_operation());
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "tx";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
if(child_yang_name == "brief")
{
if(brief == nullptr)
{
brief = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Brief>();
}
return brief;
}
if(child_yang_name == "detail")
{
if(detail == nullptr)
{
detail = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Detail>();
}
return detail;
}
if(child_yang_name == "state")
{
if(state == nullptr)
{
state = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State>();
}
return state;
}
if(child_yang_name == "statistics")
{
if(statistics == nullptr)
{
statistics = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics>();
}
return statistics;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
if(brief != nullptr)
{
_children["brief"] = brief;
}
if(detail != nullptr)
{
_children["detail"] = detail;
}
if(state != nullptr)
{
_children["state"] = state;
}
if(statistics != nullptr)
{
_children["statistics"] = statistics;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx" || name == "brief" || name == "detail" || name == "state" || name == "statistics")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "tx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Brief::Brief()
:
data_idx(this, {"port_data_idx"})
{
yang_name = "brief"; yang_parent_name = "tx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Brief::~Brief()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Brief::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return false;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Brief::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Brief::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "brief";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Brief::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Brief::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Brief::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Brief::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Brief::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Brief::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Brief::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Brief::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "brief"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Brief::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Brief::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Brief::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Brief::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Brief::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Brief::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Brief::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Brief::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Brief::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Brief::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Brief::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Brief::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Brief::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Brief::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Brief::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Brief::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Brief::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Brief::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Brief::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Brief::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Brief::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Brief::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Detail::Detail()
:
data_idx(this, {"port_data_idx"})
{
yang_name = "detail"; yang_parent_name = "tx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Detail::~Detail()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Detail::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return false;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Detail::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Detail::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "detail";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Detail::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Detail::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Detail::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Detail::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Detail::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Detail::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Detail::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Detail::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "detail"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Detail::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Detail::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Detail::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Detail::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Detail::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Detail::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Detail::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Detail::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Detail::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Detail::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Detail::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Detail::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Detail::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Detail::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Detail::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Detail::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Detail::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Detail::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Detail::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Detail::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Detail::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Detail::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::State()
:
up(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up>())
, down(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down>())
, mismatch(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch>())
{
up->parent = this;
down->parent = this;
mismatch->parent = this;
yang_name = "state"; yang_parent_name = "tx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::~State()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::has_data() const
{
if (is_presence_container) return true;
return (up != nullptr && up->has_data())
|| (down != nullptr && down->has_data())
|| (mismatch != nullptr && mismatch->has_data());
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::has_operation() const
{
return is_set(yfilter)
|| (up != nullptr && up->has_operation())
|| (down != nullptr && down->has_operation())
|| (mismatch != nullptr && mismatch->has_operation());
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "state";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "up")
{
if(up == nullptr)
{
up = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up>();
}
return up;
}
if(child_yang_name == "down")
{
if(down == nullptr)
{
down = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down>();
}
return down;
}
if(child_yang_name == "mismatch")
{
if(mismatch == nullptr)
{
mismatch = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch>();
}
return mismatch;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(up != nullptr)
{
_children["up"] = up;
}
if(down != nullptr)
{
_children["down"] = down;
}
if(mismatch != nullptr)
{
_children["mismatch"] = mismatch;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "up" || name == "down" || name == "mismatch")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Up()
:
data_idx(this, {"port_data_idx"})
, brief(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Brief>())
, detail(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Detail>())
{
brief->parent = this;
detail->parent = this;
yang_name = "up"; yang_parent_name = "state"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::~Up()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return (brief != nullptr && brief->has_data())
|| (detail != nullptr && detail->has_data());
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter)
|| (brief != nullptr && brief->has_operation())
|| (detail != nullptr && detail->has_operation());
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "up";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
if(child_yang_name == "brief")
{
if(brief == nullptr)
{
brief = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Brief>();
}
return brief;
}
if(child_yang_name == "detail")
{
if(detail == nullptr)
{
detail = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Detail>();
}
return detail;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
if(brief != nullptr)
{
_children["brief"] = brief;
}
if(detail != nullptr)
{
_children["detail"] = detail;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx" || name == "brief" || name == "detail")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "up"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Brief::Brief()
:
data_idx(this, {"port_data_idx"})
{
yang_name = "brief"; yang_parent_name = "up"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Brief::~Brief()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Brief::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return false;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Brief::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Brief::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "brief";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Brief::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Brief::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Brief::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Brief::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Brief::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Brief::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Brief::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Brief::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "brief"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Brief::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Brief::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Brief::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Brief::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Brief::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Brief::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Brief::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Brief::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Brief::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Brief::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Brief::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Brief::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Brief::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Brief::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Brief::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Brief::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Brief::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Brief::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Brief::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Brief::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Brief::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Brief::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Detail::Detail()
:
data_idx(this, {"port_data_idx"})
{
yang_name = "detail"; yang_parent_name = "up"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Detail::~Detail()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Detail::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return false;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Detail::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Detail::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "detail";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Detail::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Detail::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Detail::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Detail::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Detail::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Detail::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Detail::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Detail::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "detail"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Detail::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Detail::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Detail::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Detail::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Detail::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Detail::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Detail::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Detail::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Detail::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Detail::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Detail::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Detail::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Detail::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Detail::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Detail::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Detail::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Detail::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Detail::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Detail::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Detail::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Detail::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Up::Detail::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Down()
:
data_idx(this, {"port_data_idx"})
, brief(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Brief>())
, detail(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Detail>())
{
brief->parent = this;
detail->parent = this;
yang_name = "down"; yang_parent_name = "state"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::~Down()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return (brief != nullptr && brief->has_data())
|| (detail != nullptr && detail->has_data());
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter)
|| (brief != nullptr && brief->has_operation())
|| (detail != nullptr && detail->has_operation());
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "down";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
if(child_yang_name == "brief")
{
if(brief == nullptr)
{
brief = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Brief>();
}
return brief;
}
if(child_yang_name == "detail")
{
if(detail == nullptr)
{
detail = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Detail>();
}
return detail;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
if(brief != nullptr)
{
_children["brief"] = brief;
}
if(detail != nullptr)
{
_children["detail"] = detail;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx" || name == "brief" || name == "detail")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "down"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Brief::Brief()
:
data_idx(this, {"port_data_idx"})
{
yang_name = "brief"; yang_parent_name = "down"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Brief::~Brief()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Brief::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return false;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Brief::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Brief::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "brief";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Brief::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Brief::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Brief::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Brief::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Brief::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Brief::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Brief::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Brief::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "brief"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Brief::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Brief::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Brief::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Brief::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Brief::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Brief::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Brief::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Brief::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Brief::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Brief::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Brief::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Brief::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Brief::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Brief::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Brief::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Brief::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Brief::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Brief::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Brief::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Brief::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Brief::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Brief::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Detail::Detail()
:
data_idx(this, {"port_data_idx"})
{
yang_name = "detail"; yang_parent_name = "down"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Detail::~Detail()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Detail::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return false;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Detail::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Detail::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "detail";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Detail::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Detail::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Detail::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Detail::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Detail::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Detail::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Detail::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Detail::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "detail"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Detail::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Detail::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Detail::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Detail::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Detail::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Detail::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Detail::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Detail::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Detail::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Detail::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Detail::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Detail::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Detail::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Detail::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Detail::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Detail::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Detail::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Detail::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Detail::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Detail::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Detail::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Down::Detail::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Mismatch()
:
data_idx(this, {"port_data_idx"})
, brief(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Brief>())
, detail(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Detail>())
{
brief->parent = this;
detail->parent = this;
yang_name = "mismatch"; yang_parent_name = "state"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::~Mismatch()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return (brief != nullptr && brief->has_data())
|| (detail != nullptr && detail->has_data());
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter)
|| (brief != nullptr && brief->has_operation())
|| (detail != nullptr && detail->has_operation());
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "mismatch";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
if(child_yang_name == "brief")
{
if(brief == nullptr)
{
brief = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Brief>();
}
return brief;
}
if(child_yang_name == "detail")
{
if(detail == nullptr)
{
detail = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Detail>();
}
return detail;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
if(brief != nullptr)
{
_children["brief"] = brief;
}
if(detail != nullptr)
{
_children["detail"] = detail;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx" || name == "brief" || name == "detail")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "mismatch"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Brief::Brief()
:
data_idx(this, {"port_data_idx"})
{
yang_name = "brief"; yang_parent_name = "mismatch"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Brief::~Brief()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Brief::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return false;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Brief::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Brief::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "brief";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Brief::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Brief::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Brief::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Brief::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Brief::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Brief::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Brief::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Brief::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "brief"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Brief::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Brief::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Brief::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Brief::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Brief::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Brief::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Brief::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Brief::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Brief::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Brief::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Brief::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Brief::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Brief::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Brief::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Brief::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Brief::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Brief::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Brief::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Brief::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Brief::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Brief::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Brief::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Detail::Detail()
:
data_idx(this, {"port_data_idx"})
{
yang_name = "detail"; yang_parent_name = "mismatch"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Detail::~Detail()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Detail::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return false;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Detail::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Detail::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "detail";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Detail::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Detail::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Detail::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Detail::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Detail::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Detail::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Detail::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Detail::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "detail"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Detail::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Detail::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Detail::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Detail::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Detail::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Detail::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Detail::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Detail::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Detail::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Detail::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Detail::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Detail::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Detail::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Detail::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Detail::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Detail::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Detail::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Detail::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Detail::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Detail::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Detail::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::State::Mismatch::Detail::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Statistics()
:
data_idx(this, {"port_data_idx"})
, brief(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Brief>())
, detail(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Detail>())
{
brief->parent = this;
detail->parent = this;
yang_name = "statistics"; yang_parent_name = "tx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::~Statistics()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return (brief != nullptr && brief->has_data())
|| (detail != nullptr && detail->has_data());
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter)
|| (brief != nullptr && brief->has_operation())
|| (detail != nullptr && detail->has_operation());
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "statistics";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
if(child_yang_name == "brief")
{
if(brief == nullptr)
{
brief = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Brief>();
}
return brief;
}
if(child_yang_name == "detail")
{
if(detail == nullptr)
{
detail = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Detail>();
}
return detail;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
if(brief != nullptr)
{
_children["brief"] = brief;
}
if(detail != nullptr)
{
_children["detail"] = detail;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx" || name == "brief" || name == "detail")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
rack_num{YType::str, "rack_num"},
sfe_port{YType::str, "sfe_port"},
tx_control_cells_counter{YType::uint64, "TX_Control_cells_counter"},
tx_data_cell_counter{YType::uint64, "TX_Data_cell_counter"},
tx_data_byte_counter{YType::uint64, "TX_Data_byte_counter"},
rx_crc_errors_counter{YType::uint64, "RX_CRC_errors_counter"},
rx_lfec_fec_correctable_error{YType::uint64, "RX_LFEC_FEC_correctable_error"},
rx_8b_10b_disparity_errors{YType::uint64, "RX_8b_10b_disparity_errors"},
rx_control_cells_counter{YType::uint64, "RX_Control_cells_counter"},
rx_data_cell_counter{YType::uint64, "RX_Data_cell_counter"},
rx_data_byte_counter{YType::uint64, "RX_Data_byte_counter"},
rx_dropped_retransmitted_control{YType::uint64, "RX_dropped_retransmitted_control"},
tx_asyn_fifo_rate{YType::uint64, "TX_Asyn_fifo_rate"},
rx_asyn_fifo_rate{YType::uint64, "RX_Asyn_fifo_rate"},
rx_lfec_fec_uncorrectable_errors{YType::uint64, "RX_LFEC_FEC_uncorrectable_errors"},
rx_8b_10b_code_errors{YType::uint64, "RX_8b_10b_code_errors"},
is_link_error{YType::boolean, "is_link_error"},
link_crc_error{YType::uint32, "link_crc_error"},
link_size_error{YType::uint32, "link_size_error"},
link_mis_align_error{YType::uint32, "link_mis_align_error"},
link_code_group_error{YType::uint32, "link_code_group_error"},
link_no_sig_lock_error{YType::uint32, "link_no_sig_lock_error"},
link_no_sig_accept_error{YType::uint32, "link_no_sig_accept_error"},
link_tokens_error{YType::uint32, "link_tokens_error"},
error_token_count{YType::uint32, "error_token_count"}
{
yang_name = "data_idx"; yang_parent_name = "statistics"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::DataIdx::has_data() const
{
if (is_presence_container) return true;
return port_data_idx.is_set
|| rack_num.is_set
|| sfe_port.is_set
|| tx_control_cells_counter.is_set
|| tx_data_cell_counter.is_set
|| tx_data_byte_counter.is_set
|| rx_crc_errors_counter.is_set
|| rx_lfec_fec_correctable_error.is_set
|| rx_8b_10b_disparity_errors.is_set
|| rx_control_cells_counter.is_set
|| rx_data_cell_counter.is_set
|| rx_data_byte_counter.is_set
|| rx_dropped_retransmitted_control.is_set
|| tx_asyn_fifo_rate.is_set
|| rx_asyn_fifo_rate.is_set
|| rx_lfec_fec_uncorrectable_errors.is_set
|| rx_8b_10b_code_errors.is_set
|| is_link_error.is_set
|| link_crc_error.is_set
|| link_size_error.is_set
|| link_mis_align_error.is_set
|| link_code_group_error.is_set
|| link_no_sig_lock_error.is_set
|| link_no_sig_accept_error.is_set
|| link_tokens_error.is_set
|| error_token_count.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::DataIdx::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(rack_num.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(tx_control_cells_counter.yfilter)
|| ydk::is_set(tx_data_cell_counter.yfilter)
|| ydk::is_set(tx_data_byte_counter.yfilter)
|| ydk::is_set(rx_crc_errors_counter.yfilter)
|| ydk::is_set(rx_lfec_fec_correctable_error.yfilter)
|| ydk::is_set(rx_8b_10b_disparity_errors.yfilter)
|| ydk::is_set(rx_control_cells_counter.yfilter)
|| ydk::is_set(rx_data_cell_counter.yfilter)
|| ydk::is_set(rx_data_byte_counter.yfilter)
|| ydk::is_set(rx_dropped_retransmitted_control.yfilter)
|| ydk::is_set(tx_asyn_fifo_rate.yfilter)
|| ydk::is_set(rx_asyn_fifo_rate.yfilter)
|| ydk::is_set(rx_lfec_fec_uncorrectable_errors.yfilter)
|| ydk::is_set(rx_8b_10b_code_errors.yfilter)
|| ydk::is_set(is_link_error.yfilter)
|| ydk::is_set(link_crc_error.yfilter)
|| ydk::is_set(link_size_error.yfilter)
|| ydk::is_set(link_mis_align_error.yfilter)
|| ydk::is_set(link_code_group_error.yfilter)
|| ydk::is_set(link_no_sig_lock_error.yfilter)
|| ydk::is_set(link_no_sig_accept_error.yfilter)
|| ydk::is_set(link_tokens_error.yfilter)
|| ydk::is_set(error_token_count.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (rack_num.is_set || is_set(rack_num.yfilter)) leaf_name_data.push_back(rack_num.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (tx_control_cells_counter.is_set || is_set(tx_control_cells_counter.yfilter)) leaf_name_data.push_back(tx_control_cells_counter.get_name_leafdata());
if (tx_data_cell_counter.is_set || is_set(tx_data_cell_counter.yfilter)) leaf_name_data.push_back(tx_data_cell_counter.get_name_leafdata());
if (tx_data_byte_counter.is_set || is_set(tx_data_byte_counter.yfilter)) leaf_name_data.push_back(tx_data_byte_counter.get_name_leafdata());
if (rx_crc_errors_counter.is_set || is_set(rx_crc_errors_counter.yfilter)) leaf_name_data.push_back(rx_crc_errors_counter.get_name_leafdata());
if (rx_lfec_fec_correctable_error.is_set || is_set(rx_lfec_fec_correctable_error.yfilter)) leaf_name_data.push_back(rx_lfec_fec_correctable_error.get_name_leafdata());
if (rx_8b_10b_disparity_errors.is_set || is_set(rx_8b_10b_disparity_errors.yfilter)) leaf_name_data.push_back(rx_8b_10b_disparity_errors.get_name_leafdata());
if (rx_control_cells_counter.is_set || is_set(rx_control_cells_counter.yfilter)) leaf_name_data.push_back(rx_control_cells_counter.get_name_leafdata());
if (rx_data_cell_counter.is_set || is_set(rx_data_cell_counter.yfilter)) leaf_name_data.push_back(rx_data_cell_counter.get_name_leafdata());
if (rx_data_byte_counter.is_set || is_set(rx_data_byte_counter.yfilter)) leaf_name_data.push_back(rx_data_byte_counter.get_name_leafdata());
if (rx_dropped_retransmitted_control.is_set || is_set(rx_dropped_retransmitted_control.yfilter)) leaf_name_data.push_back(rx_dropped_retransmitted_control.get_name_leafdata());
if (tx_asyn_fifo_rate.is_set || is_set(tx_asyn_fifo_rate.yfilter)) leaf_name_data.push_back(tx_asyn_fifo_rate.get_name_leafdata());
if (rx_asyn_fifo_rate.is_set || is_set(rx_asyn_fifo_rate.yfilter)) leaf_name_data.push_back(rx_asyn_fifo_rate.get_name_leafdata());
if (rx_lfec_fec_uncorrectable_errors.is_set || is_set(rx_lfec_fec_uncorrectable_errors.yfilter)) leaf_name_data.push_back(rx_lfec_fec_uncorrectable_errors.get_name_leafdata());
if (rx_8b_10b_code_errors.is_set || is_set(rx_8b_10b_code_errors.yfilter)) leaf_name_data.push_back(rx_8b_10b_code_errors.get_name_leafdata());
if (is_link_error.is_set || is_set(is_link_error.yfilter)) leaf_name_data.push_back(is_link_error.get_name_leafdata());
if (link_crc_error.is_set || is_set(link_crc_error.yfilter)) leaf_name_data.push_back(link_crc_error.get_name_leafdata());
if (link_size_error.is_set || is_set(link_size_error.yfilter)) leaf_name_data.push_back(link_size_error.get_name_leafdata());
if (link_mis_align_error.is_set || is_set(link_mis_align_error.yfilter)) leaf_name_data.push_back(link_mis_align_error.get_name_leafdata());
if (link_code_group_error.is_set || is_set(link_code_group_error.yfilter)) leaf_name_data.push_back(link_code_group_error.get_name_leafdata());
if (link_no_sig_lock_error.is_set || is_set(link_no_sig_lock_error.yfilter)) leaf_name_data.push_back(link_no_sig_lock_error.get_name_leafdata());
if (link_no_sig_accept_error.is_set || is_set(link_no_sig_accept_error.yfilter)) leaf_name_data.push_back(link_no_sig_accept_error.get_name_leafdata());
if (link_tokens_error.is_set || is_set(link_tokens_error.yfilter)) leaf_name_data.push_back(link_tokens_error.get_name_leafdata());
if (error_token_count.is_set || is_set(error_token_count.yfilter)) leaf_name_data.push_back(error_token_count.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "rack_num")
{
rack_num = value;
rack_num.value_namespace = name_space;
rack_num.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TX_Control_cells_counter")
{
tx_control_cells_counter = value;
tx_control_cells_counter.value_namespace = name_space;
tx_control_cells_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TX_Data_cell_counter")
{
tx_data_cell_counter = value;
tx_data_cell_counter.value_namespace = name_space;
tx_data_cell_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TX_Data_byte_counter")
{
tx_data_byte_counter = value;
tx_data_byte_counter.value_namespace = name_space;
tx_data_byte_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_CRC_errors_counter")
{
rx_crc_errors_counter = value;
rx_crc_errors_counter.value_namespace = name_space;
rx_crc_errors_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_LFEC_FEC_correctable_error")
{
rx_lfec_fec_correctable_error = value;
rx_lfec_fec_correctable_error.value_namespace = name_space;
rx_lfec_fec_correctable_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_8b_10b_disparity_errors")
{
rx_8b_10b_disparity_errors = value;
rx_8b_10b_disparity_errors.value_namespace = name_space;
rx_8b_10b_disparity_errors.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_Control_cells_counter")
{
rx_control_cells_counter = value;
rx_control_cells_counter.value_namespace = name_space;
rx_control_cells_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_Data_cell_counter")
{
rx_data_cell_counter = value;
rx_data_cell_counter.value_namespace = name_space;
rx_data_cell_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_Data_byte_counter")
{
rx_data_byte_counter = value;
rx_data_byte_counter.value_namespace = name_space;
rx_data_byte_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_dropped_retransmitted_control")
{
rx_dropped_retransmitted_control = value;
rx_dropped_retransmitted_control.value_namespace = name_space;
rx_dropped_retransmitted_control.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TX_Asyn_fifo_rate")
{
tx_asyn_fifo_rate = value;
tx_asyn_fifo_rate.value_namespace = name_space;
tx_asyn_fifo_rate.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_Asyn_fifo_rate")
{
rx_asyn_fifo_rate = value;
rx_asyn_fifo_rate.value_namespace = name_space;
rx_asyn_fifo_rate.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_LFEC_FEC_uncorrectable_errors")
{
rx_lfec_fec_uncorrectable_errors = value;
rx_lfec_fec_uncorrectable_errors.value_namespace = name_space;
rx_lfec_fec_uncorrectable_errors.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_8b_10b_code_errors")
{
rx_8b_10b_code_errors = value;
rx_8b_10b_code_errors.value_namespace = name_space;
rx_8b_10b_code_errors.value_namespace_prefix = name_space_prefix;
}
if(value_path == "is_link_error")
{
is_link_error = value;
is_link_error.value_namespace = name_space;
is_link_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_crc_error")
{
link_crc_error = value;
link_crc_error.value_namespace = name_space;
link_crc_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_size_error")
{
link_size_error = value;
link_size_error.value_namespace = name_space;
link_size_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_mis_align_error")
{
link_mis_align_error = value;
link_mis_align_error.value_namespace = name_space;
link_mis_align_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_code_group_error")
{
link_code_group_error = value;
link_code_group_error.value_namespace = name_space;
link_code_group_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_no_sig_lock_error")
{
link_no_sig_lock_error = value;
link_no_sig_lock_error.value_namespace = name_space;
link_no_sig_lock_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_no_sig_accept_error")
{
link_no_sig_accept_error = value;
link_no_sig_accept_error.value_namespace = name_space;
link_no_sig_accept_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_tokens_error")
{
link_tokens_error = value;
link_tokens_error.value_namespace = name_space;
link_tokens_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_token_count")
{
error_token_count = value;
error_token_count.value_namespace = name_space;
error_token_count.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "rack_num")
{
rack_num.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "TX_Control_cells_counter")
{
tx_control_cells_counter.yfilter = yfilter;
}
if(value_path == "TX_Data_cell_counter")
{
tx_data_cell_counter.yfilter = yfilter;
}
if(value_path == "TX_Data_byte_counter")
{
tx_data_byte_counter.yfilter = yfilter;
}
if(value_path == "RX_CRC_errors_counter")
{
rx_crc_errors_counter.yfilter = yfilter;
}
if(value_path == "RX_LFEC_FEC_correctable_error")
{
rx_lfec_fec_correctable_error.yfilter = yfilter;
}
if(value_path == "RX_8b_10b_disparity_errors")
{
rx_8b_10b_disparity_errors.yfilter = yfilter;
}
if(value_path == "RX_Control_cells_counter")
{
rx_control_cells_counter.yfilter = yfilter;
}
if(value_path == "RX_Data_cell_counter")
{
rx_data_cell_counter.yfilter = yfilter;
}
if(value_path == "RX_Data_byte_counter")
{
rx_data_byte_counter.yfilter = yfilter;
}
if(value_path == "RX_dropped_retransmitted_control")
{
rx_dropped_retransmitted_control.yfilter = yfilter;
}
if(value_path == "TX_Asyn_fifo_rate")
{
tx_asyn_fifo_rate.yfilter = yfilter;
}
if(value_path == "RX_Asyn_fifo_rate")
{
rx_asyn_fifo_rate.yfilter = yfilter;
}
if(value_path == "RX_LFEC_FEC_uncorrectable_errors")
{
rx_lfec_fec_uncorrectable_errors.yfilter = yfilter;
}
if(value_path == "RX_8b_10b_code_errors")
{
rx_8b_10b_code_errors.yfilter = yfilter;
}
if(value_path == "is_link_error")
{
is_link_error.yfilter = yfilter;
}
if(value_path == "link_crc_error")
{
link_crc_error.yfilter = yfilter;
}
if(value_path == "link_size_error")
{
link_size_error.yfilter = yfilter;
}
if(value_path == "link_mis_align_error")
{
link_mis_align_error.yfilter = yfilter;
}
if(value_path == "link_code_group_error")
{
link_code_group_error.yfilter = yfilter;
}
if(value_path == "link_no_sig_lock_error")
{
link_no_sig_lock_error.yfilter = yfilter;
}
if(value_path == "link_no_sig_accept_error")
{
link_no_sig_accept_error.yfilter = yfilter;
}
if(value_path == "link_tokens_error")
{
link_tokens_error.yfilter = yfilter;
}
if(value_path == "error_token_count")
{
error_token_count.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "port_data_idx" || name == "rack_num" || name == "sfe_port" || name == "TX_Control_cells_counter" || name == "TX_Data_cell_counter" || name == "TX_Data_byte_counter" || name == "RX_CRC_errors_counter" || name == "RX_LFEC_FEC_correctable_error" || name == "RX_8b_10b_disparity_errors" || name == "RX_Control_cells_counter" || name == "RX_Data_cell_counter" || name == "RX_Data_byte_counter" || name == "RX_dropped_retransmitted_control" || name == "TX_Asyn_fifo_rate" || name == "RX_Asyn_fifo_rate" || name == "RX_LFEC_FEC_uncorrectable_errors" || name == "RX_8b_10b_code_errors" || name == "is_link_error" || name == "link_crc_error" || name == "link_size_error" || name == "link_mis_align_error" || name == "link_code_group_error" || name == "link_no_sig_lock_error" || name == "link_no_sig_accept_error" || name == "link_tokens_error" || name == "error_token_count")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Brief::Brief()
:
data_idx(this, {"port_data_idx"})
{
yang_name = "brief"; yang_parent_name = "statistics"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Brief::~Brief()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Brief::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return false;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Brief::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Brief::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "brief";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Brief::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Brief::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Brief::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Brief::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Brief::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Brief::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Brief::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Brief::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
rack_num{YType::str, "rack_num"},
sfe_port{YType::str, "sfe_port"},
tx_control_cells_counter{YType::uint64, "TX_Control_cells_counter"},
tx_data_cell_counter{YType::uint64, "TX_Data_cell_counter"},
tx_data_byte_counter{YType::uint64, "TX_Data_byte_counter"},
rx_crc_errors_counter{YType::uint64, "RX_CRC_errors_counter"},
rx_lfec_fec_correctable_error{YType::uint64, "RX_LFEC_FEC_correctable_error"},
rx_8b_10b_disparity_errors{YType::uint64, "RX_8b_10b_disparity_errors"},
rx_control_cells_counter{YType::uint64, "RX_Control_cells_counter"},
rx_data_cell_counter{YType::uint64, "RX_Data_cell_counter"},
rx_data_byte_counter{YType::uint64, "RX_Data_byte_counter"},
rx_dropped_retransmitted_control{YType::uint64, "RX_dropped_retransmitted_control"},
tx_asyn_fifo_rate{YType::uint64, "TX_Asyn_fifo_rate"},
rx_asyn_fifo_rate{YType::uint64, "RX_Asyn_fifo_rate"},
rx_lfec_fec_uncorrectable_errors{YType::uint64, "RX_LFEC_FEC_uncorrectable_errors"},
rx_8b_10b_code_errors{YType::uint64, "RX_8b_10b_code_errors"},
is_link_error{YType::boolean, "is_link_error"},
link_crc_error{YType::uint32, "link_crc_error"},
link_size_error{YType::uint32, "link_size_error"},
link_mis_align_error{YType::uint32, "link_mis_align_error"},
link_code_group_error{YType::uint32, "link_code_group_error"},
link_no_sig_lock_error{YType::uint32, "link_no_sig_lock_error"},
link_no_sig_accept_error{YType::uint32, "link_no_sig_accept_error"},
link_tokens_error{YType::uint32, "link_tokens_error"},
error_token_count{YType::uint32, "error_token_count"}
{
yang_name = "data_idx"; yang_parent_name = "brief"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Brief::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Brief::DataIdx::has_data() const
{
if (is_presence_container) return true;
return port_data_idx.is_set
|| rack_num.is_set
|| sfe_port.is_set
|| tx_control_cells_counter.is_set
|| tx_data_cell_counter.is_set
|| tx_data_byte_counter.is_set
|| rx_crc_errors_counter.is_set
|| rx_lfec_fec_correctable_error.is_set
|| rx_8b_10b_disparity_errors.is_set
|| rx_control_cells_counter.is_set
|| rx_data_cell_counter.is_set
|| rx_data_byte_counter.is_set
|| rx_dropped_retransmitted_control.is_set
|| tx_asyn_fifo_rate.is_set
|| rx_asyn_fifo_rate.is_set
|| rx_lfec_fec_uncorrectable_errors.is_set
|| rx_8b_10b_code_errors.is_set
|| is_link_error.is_set
|| link_crc_error.is_set
|| link_size_error.is_set
|| link_mis_align_error.is_set
|| link_code_group_error.is_set
|| link_no_sig_lock_error.is_set
|| link_no_sig_accept_error.is_set
|| link_tokens_error.is_set
|| error_token_count.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Brief::DataIdx::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(rack_num.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(tx_control_cells_counter.yfilter)
|| ydk::is_set(tx_data_cell_counter.yfilter)
|| ydk::is_set(tx_data_byte_counter.yfilter)
|| ydk::is_set(rx_crc_errors_counter.yfilter)
|| ydk::is_set(rx_lfec_fec_correctable_error.yfilter)
|| ydk::is_set(rx_8b_10b_disparity_errors.yfilter)
|| ydk::is_set(rx_control_cells_counter.yfilter)
|| ydk::is_set(rx_data_cell_counter.yfilter)
|| ydk::is_set(rx_data_byte_counter.yfilter)
|| ydk::is_set(rx_dropped_retransmitted_control.yfilter)
|| ydk::is_set(tx_asyn_fifo_rate.yfilter)
|| ydk::is_set(rx_asyn_fifo_rate.yfilter)
|| ydk::is_set(rx_lfec_fec_uncorrectable_errors.yfilter)
|| ydk::is_set(rx_8b_10b_code_errors.yfilter)
|| ydk::is_set(is_link_error.yfilter)
|| ydk::is_set(link_crc_error.yfilter)
|| ydk::is_set(link_size_error.yfilter)
|| ydk::is_set(link_mis_align_error.yfilter)
|| ydk::is_set(link_code_group_error.yfilter)
|| ydk::is_set(link_no_sig_lock_error.yfilter)
|| ydk::is_set(link_no_sig_accept_error.yfilter)
|| ydk::is_set(link_tokens_error.yfilter)
|| ydk::is_set(error_token_count.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Brief::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Brief::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (rack_num.is_set || is_set(rack_num.yfilter)) leaf_name_data.push_back(rack_num.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (tx_control_cells_counter.is_set || is_set(tx_control_cells_counter.yfilter)) leaf_name_data.push_back(tx_control_cells_counter.get_name_leafdata());
if (tx_data_cell_counter.is_set || is_set(tx_data_cell_counter.yfilter)) leaf_name_data.push_back(tx_data_cell_counter.get_name_leafdata());
if (tx_data_byte_counter.is_set || is_set(tx_data_byte_counter.yfilter)) leaf_name_data.push_back(tx_data_byte_counter.get_name_leafdata());
if (rx_crc_errors_counter.is_set || is_set(rx_crc_errors_counter.yfilter)) leaf_name_data.push_back(rx_crc_errors_counter.get_name_leafdata());
if (rx_lfec_fec_correctable_error.is_set || is_set(rx_lfec_fec_correctable_error.yfilter)) leaf_name_data.push_back(rx_lfec_fec_correctable_error.get_name_leafdata());
if (rx_8b_10b_disparity_errors.is_set || is_set(rx_8b_10b_disparity_errors.yfilter)) leaf_name_data.push_back(rx_8b_10b_disparity_errors.get_name_leafdata());
if (rx_control_cells_counter.is_set || is_set(rx_control_cells_counter.yfilter)) leaf_name_data.push_back(rx_control_cells_counter.get_name_leafdata());
if (rx_data_cell_counter.is_set || is_set(rx_data_cell_counter.yfilter)) leaf_name_data.push_back(rx_data_cell_counter.get_name_leafdata());
if (rx_data_byte_counter.is_set || is_set(rx_data_byte_counter.yfilter)) leaf_name_data.push_back(rx_data_byte_counter.get_name_leafdata());
if (rx_dropped_retransmitted_control.is_set || is_set(rx_dropped_retransmitted_control.yfilter)) leaf_name_data.push_back(rx_dropped_retransmitted_control.get_name_leafdata());
if (tx_asyn_fifo_rate.is_set || is_set(tx_asyn_fifo_rate.yfilter)) leaf_name_data.push_back(tx_asyn_fifo_rate.get_name_leafdata());
if (rx_asyn_fifo_rate.is_set || is_set(rx_asyn_fifo_rate.yfilter)) leaf_name_data.push_back(rx_asyn_fifo_rate.get_name_leafdata());
if (rx_lfec_fec_uncorrectable_errors.is_set || is_set(rx_lfec_fec_uncorrectable_errors.yfilter)) leaf_name_data.push_back(rx_lfec_fec_uncorrectable_errors.get_name_leafdata());
if (rx_8b_10b_code_errors.is_set || is_set(rx_8b_10b_code_errors.yfilter)) leaf_name_data.push_back(rx_8b_10b_code_errors.get_name_leafdata());
if (is_link_error.is_set || is_set(is_link_error.yfilter)) leaf_name_data.push_back(is_link_error.get_name_leafdata());
if (link_crc_error.is_set || is_set(link_crc_error.yfilter)) leaf_name_data.push_back(link_crc_error.get_name_leafdata());
if (link_size_error.is_set || is_set(link_size_error.yfilter)) leaf_name_data.push_back(link_size_error.get_name_leafdata());
if (link_mis_align_error.is_set || is_set(link_mis_align_error.yfilter)) leaf_name_data.push_back(link_mis_align_error.get_name_leafdata());
if (link_code_group_error.is_set || is_set(link_code_group_error.yfilter)) leaf_name_data.push_back(link_code_group_error.get_name_leafdata());
if (link_no_sig_lock_error.is_set || is_set(link_no_sig_lock_error.yfilter)) leaf_name_data.push_back(link_no_sig_lock_error.get_name_leafdata());
if (link_no_sig_accept_error.is_set || is_set(link_no_sig_accept_error.yfilter)) leaf_name_data.push_back(link_no_sig_accept_error.get_name_leafdata());
if (link_tokens_error.is_set || is_set(link_tokens_error.yfilter)) leaf_name_data.push_back(link_tokens_error.get_name_leafdata());
if (error_token_count.is_set || is_set(error_token_count.yfilter)) leaf_name_data.push_back(error_token_count.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Brief::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Brief::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Brief::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "rack_num")
{
rack_num = value;
rack_num.value_namespace = name_space;
rack_num.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TX_Control_cells_counter")
{
tx_control_cells_counter = value;
tx_control_cells_counter.value_namespace = name_space;
tx_control_cells_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TX_Data_cell_counter")
{
tx_data_cell_counter = value;
tx_data_cell_counter.value_namespace = name_space;
tx_data_cell_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TX_Data_byte_counter")
{
tx_data_byte_counter = value;
tx_data_byte_counter.value_namespace = name_space;
tx_data_byte_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_CRC_errors_counter")
{
rx_crc_errors_counter = value;
rx_crc_errors_counter.value_namespace = name_space;
rx_crc_errors_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_LFEC_FEC_correctable_error")
{
rx_lfec_fec_correctable_error = value;
rx_lfec_fec_correctable_error.value_namespace = name_space;
rx_lfec_fec_correctable_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_8b_10b_disparity_errors")
{
rx_8b_10b_disparity_errors = value;
rx_8b_10b_disparity_errors.value_namespace = name_space;
rx_8b_10b_disparity_errors.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_Control_cells_counter")
{
rx_control_cells_counter = value;
rx_control_cells_counter.value_namespace = name_space;
rx_control_cells_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_Data_cell_counter")
{
rx_data_cell_counter = value;
rx_data_cell_counter.value_namespace = name_space;
rx_data_cell_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_Data_byte_counter")
{
rx_data_byte_counter = value;
rx_data_byte_counter.value_namespace = name_space;
rx_data_byte_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_dropped_retransmitted_control")
{
rx_dropped_retransmitted_control = value;
rx_dropped_retransmitted_control.value_namespace = name_space;
rx_dropped_retransmitted_control.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TX_Asyn_fifo_rate")
{
tx_asyn_fifo_rate = value;
tx_asyn_fifo_rate.value_namespace = name_space;
tx_asyn_fifo_rate.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_Asyn_fifo_rate")
{
rx_asyn_fifo_rate = value;
rx_asyn_fifo_rate.value_namespace = name_space;
rx_asyn_fifo_rate.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_LFEC_FEC_uncorrectable_errors")
{
rx_lfec_fec_uncorrectable_errors = value;
rx_lfec_fec_uncorrectable_errors.value_namespace = name_space;
rx_lfec_fec_uncorrectable_errors.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_8b_10b_code_errors")
{
rx_8b_10b_code_errors = value;
rx_8b_10b_code_errors.value_namespace = name_space;
rx_8b_10b_code_errors.value_namespace_prefix = name_space_prefix;
}
if(value_path == "is_link_error")
{
is_link_error = value;
is_link_error.value_namespace = name_space;
is_link_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_crc_error")
{
link_crc_error = value;
link_crc_error.value_namespace = name_space;
link_crc_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_size_error")
{
link_size_error = value;
link_size_error.value_namespace = name_space;
link_size_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_mis_align_error")
{
link_mis_align_error = value;
link_mis_align_error.value_namespace = name_space;
link_mis_align_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_code_group_error")
{
link_code_group_error = value;
link_code_group_error.value_namespace = name_space;
link_code_group_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_no_sig_lock_error")
{
link_no_sig_lock_error = value;
link_no_sig_lock_error.value_namespace = name_space;
link_no_sig_lock_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_no_sig_accept_error")
{
link_no_sig_accept_error = value;
link_no_sig_accept_error.value_namespace = name_space;
link_no_sig_accept_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_tokens_error")
{
link_tokens_error = value;
link_tokens_error.value_namespace = name_space;
link_tokens_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_token_count")
{
error_token_count = value;
error_token_count.value_namespace = name_space;
error_token_count.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Brief::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "rack_num")
{
rack_num.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "TX_Control_cells_counter")
{
tx_control_cells_counter.yfilter = yfilter;
}
if(value_path == "TX_Data_cell_counter")
{
tx_data_cell_counter.yfilter = yfilter;
}
if(value_path == "TX_Data_byte_counter")
{
tx_data_byte_counter.yfilter = yfilter;
}
if(value_path == "RX_CRC_errors_counter")
{
rx_crc_errors_counter.yfilter = yfilter;
}
if(value_path == "RX_LFEC_FEC_correctable_error")
{
rx_lfec_fec_correctable_error.yfilter = yfilter;
}
if(value_path == "RX_8b_10b_disparity_errors")
{
rx_8b_10b_disparity_errors.yfilter = yfilter;
}
if(value_path == "RX_Control_cells_counter")
{
rx_control_cells_counter.yfilter = yfilter;
}
if(value_path == "RX_Data_cell_counter")
{
rx_data_cell_counter.yfilter = yfilter;
}
if(value_path == "RX_Data_byte_counter")
{
rx_data_byte_counter.yfilter = yfilter;
}
if(value_path == "RX_dropped_retransmitted_control")
{
rx_dropped_retransmitted_control.yfilter = yfilter;
}
if(value_path == "TX_Asyn_fifo_rate")
{
tx_asyn_fifo_rate.yfilter = yfilter;
}
if(value_path == "RX_Asyn_fifo_rate")
{
rx_asyn_fifo_rate.yfilter = yfilter;
}
if(value_path == "RX_LFEC_FEC_uncorrectable_errors")
{
rx_lfec_fec_uncorrectable_errors.yfilter = yfilter;
}
if(value_path == "RX_8b_10b_code_errors")
{
rx_8b_10b_code_errors.yfilter = yfilter;
}
if(value_path == "is_link_error")
{
is_link_error.yfilter = yfilter;
}
if(value_path == "link_crc_error")
{
link_crc_error.yfilter = yfilter;
}
if(value_path == "link_size_error")
{
link_size_error.yfilter = yfilter;
}
if(value_path == "link_mis_align_error")
{
link_mis_align_error.yfilter = yfilter;
}
if(value_path == "link_code_group_error")
{
link_code_group_error.yfilter = yfilter;
}
if(value_path == "link_no_sig_lock_error")
{
link_no_sig_lock_error.yfilter = yfilter;
}
if(value_path == "link_no_sig_accept_error")
{
link_no_sig_accept_error.yfilter = yfilter;
}
if(value_path == "link_tokens_error")
{
link_tokens_error.yfilter = yfilter;
}
if(value_path == "error_token_count")
{
error_token_count.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Brief::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "port_data_idx" || name == "rack_num" || name == "sfe_port" || name == "TX_Control_cells_counter" || name == "TX_Data_cell_counter" || name == "TX_Data_byte_counter" || name == "RX_CRC_errors_counter" || name == "RX_LFEC_FEC_correctable_error" || name == "RX_8b_10b_disparity_errors" || name == "RX_Control_cells_counter" || name == "RX_Data_cell_counter" || name == "RX_Data_byte_counter" || name == "RX_dropped_retransmitted_control" || name == "TX_Asyn_fifo_rate" || name == "RX_Asyn_fifo_rate" || name == "RX_LFEC_FEC_uncorrectable_errors" || name == "RX_8b_10b_code_errors" || name == "is_link_error" || name == "link_crc_error" || name == "link_size_error" || name == "link_mis_align_error" || name == "link_code_group_error" || name == "link_no_sig_lock_error" || name == "link_no_sig_accept_error" || name == "link_tokens_error" || name == "error_token_count")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Detail::Detail()
:
data_idx(this, {"port_data_idx"})
{
yang_name = "detail"; yang_parent_name = "statistics"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Detail::~Detail()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Detail::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return false;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Detail::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Detail::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "detail";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Detail::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Detail::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Detail::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Detail::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Detail::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Detail::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Detail::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Detail::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
rack_num{YType::str, "rack_num"},
sfe_port{YType::str, "sfe_port"},
tx_control_cells_counter{YType::uint64, "TX_Control_cells_counter"},
tx_data_cell_counter{YType::uint64, "TX_Data_cell_counter"},
tx_data_byte_counter{YType::uint64, "TX_Data_byte_counter"},
rx_crc_errors_counter{YType::uint64, "RX_CRC_errors_counter"},
rx_lfec_fec_correctable_error{YType::uint64, "RX_LFEC_FEC_correctable_error"},
rx_8b_10b_disparity_errors{YType::uint64, "RX_8b_10b_disparity_errors"},
rx_control_cells_counter{YType::uint64, "RX_Control_cells_counter"},
rx_data_cell_counter{YType::uint64, "RX_Data_cell_counter"},
rx_data_byte_counter{YType::uint64, "RX_Data_byte_counter"},
rx_dropped_retransmitted_control{YType::uint64, "RX_dropped_retransmitted_control"},
tx_asyn_fifo_rate{YType::uint64, "TX_Asyn_fifo_rate"},
rx_asyn_fifo_rate{YType::uint64, "RX_Asyn_fifo_rate"},
rx_lfec_fec_uncorrectable_errors{YType::uint64, "RX_LFEC_FEC_uncorrectable_errors"},
rx_8b_10b_code_errors{YType::uint64, "RX_8b_10b_code_errors"},
is_link_error{YType::boolean, "is_link_error"},
link_crc_error{YType::uint32, "link_crc_error"},
link_size_error{YType::uint32, "link_size_error"},
link_mis_align_error{YType::uint32, "link_mis_align_error"},
link_code_group_error{YType::uint32, "link_code_group_error"},
link_no_sig_lock_error{YType::uint32, "link_no_sig_lock_error"},
link_no_sig_accept_error{YType::uint32, "link_no_sig_accept_error"},
link_tokens_error{YType::uint32, "link_tokens_error"},
error_token_count{YType::uint32, "error_token_count"}
{
yang_name = "data_idx"; yang_parent_name = "detail"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Detail::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Detail::DataIdx::has_data() const
{
if (is_presence_container) return true;
return port_data_idx.is_set
|| rack_num.is_set
|| sfe_port.is_set
|| tx_control_cells_counter.is_set
|| tx_data_cell_counter.is_set
|| tx_data_byte_counter.is_set
|| rx_crc_errors_counter.is_set
|| rx_lfec_fec_correctable_error.is_set
|| rx_8b_10b_disparity_errors.is_set
|| rx_control_cells_counter.is_set
|| rx_data_cell_counter.is_set
|| rx_data_byte_counter.is_set
|| rx_dropped_retransmitted_control.is_set
|| tx_asyn_fifo_rate.is_set
|| rx_asyn_fifo_rate.is_set
|| rx_lfec_fec_uncorrectable_errors.is_set
|| rx_8b_10b_code_errors.is_set
|| is_link_error.is_set
|| link_crc_error.is_set
|| link_size_error.is_set
|| link_mis_align_error.is_set
|| link_code_group_error.is_set
|| link_no_sig_lock_error.is_set
|| link_no_sig_accept_error.is_set
|| link_tokens_error.is_set
|| error_token_count.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Detail::DataIdx::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(rack_num.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(tx_control_cells_counter.yfilter)
|| ydk::is_set(tx_data_cell_counter.yfilter)
|| ydk::is_set(tx_data_byte_counter.yfilter)
|| ydk::is_set(rx_crc_errors_counter.yfilter)
|| ydk::is_set(rx_lfec_fec_correctable_error.yfilter)
|| ydk::is_set(rx_8b_10b_disparity_errors.yfilter)
|| ydk::is_set(rx_control_cells_counter.yfilter)
|| ydk::is_set(rx_data_cell_counter.yfilter)
|| ydk::is_set(rx_data_byte_counter.yfilter)
|| ydk::is_set(rx_dropped_retransmitted_control.yfilter)
|| ydk::is_set(tx_asyn_fifo_rate.yfilter)
|| ydk::is_set(rx_asyn_fifo_rate.yfilter)
|| ydk::is_set(rx_lfec_fec_uncorrectable_errors.yfilter)
|| ydk::is_set(rx_8b_10b_code_errors.yfilter)
|| ydk::is_set(is_link_error.yfilter)
|| ydk::is_set(link_crc_error.yfilter)
|| ydk::is_set(link_size_error.yfilter)
|| ydk::is_set(link_mis_align_error.yfilter)
|| ydk::is_set(link_code_group_error.yfilter)
|| ydk::is_set(link_no_sig_lock_error.yfilter)
|| ydk::is_set(link_no_sig_accept_error.yfilter)
|| ydk::is_set(link_tokens_error.yfilter)
|| ydk::is_set(error_token_count.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Detail::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Detail::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (rack_num.is_set || is_set(rack_num.yfilter)) leaf_name_data.push_back(rack_num.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (tx_control_cells_counter.is_set || is_set(tx_control_cells_counter.yfilter)) leaf_name_data.push_back(tx_control_cells_counter.get_name_leafdata());
if (tx_data_cell_counter.is_set || is_set(tx_data_cell_counter.yfilter)) leaf_name_data.push_back(tx_data_cell_counter.get_name_leafdata());
if (tx_data_byte_counter.is_set || is_set(tx_data_byte_counter.yfilter)) leaf_name_data.push_back(tx_data_byte_counter.get_name_leafdata());
if (rx_crc_errors_counter.is_set || is_set(rx_crc_errors_counter.yfilter)) leaf_name_data.push_back(rx_crc_errors_counter.get_name_leafdata());
if (rx_lfec_fec_correctable_error.is_set || is_set(rx_lfec_fec_correctable_error.yfilter)) leaf_name_data.push_back(rx_lfec_fec_correctable_error.get_name_leafdata());
if (rx_8b_10b_disparity_errors.is_set || is_set(rx_8b_10b_disparity_errors.yfilter)) leaf_name_data.push_back(rx_8b_10b_disparity_errors.get_name_leafdata());
if (rx_control_cells_counter.is_set || is_set(rx_control_cells_counter.yfilter)) leaf_name_data.push_back(rx_control_cells_counter.get_name_leafdata());
if (rx_data_cell_counter.is_set || is_set(rx_data_cell_counter.yfilter)) leaf_name_data.push_back(rx_data_cell_counter.get_name_leafdata());
if (rx_data_byte_counter.is_set || is_set(rx_data_byte_counter.yfilter)) leaf_name_data.push_back(rx_data_byte_counter.get_name_leafdata());
if (rx_dropped_retransmitted_control.is_set || is_set(rx_dropped_retransmitted_control.yfilter)) leaf_name_data.push_back(rx_dropped_retransmitted_control.get_name_leafdata());
if (tx_asyn_fifo_rate.is_set || is_set(tx_asyn_fifo_rate.yfilter)) leaf_name_data.push_back(tx_asyn_fifo_rate.get_name_leafdata());
if (rx_asyn_fifo_rate.is_set || is_set(rx_asyn_fifo_rate.yfilter)) leaf_name_data.push_back(rx_asyn_fifo_rate.get_name_leafdata());
if (rx_lfec_fec_uncorrectable_errors.is_set || is_set(rx_lfec_fec_uncorrectable_errors.yfilter)) leaf_name_data.push_back(rx_lfec_fec_uncorrectable_errors.get_name_leafdata());
if (rx_8b_10b_code_errors.is_set || is_set(rx_8b_10b_code_errors.yfilter)) leaf_name_data.push_back(rx_8b_10b_code_errors.get_name_leafdata());
if (is_link_error.is_set || is_set(is_link_error.yfilter)) leaf_name_data.push_back(is_link_error.get_name_leafdata());
if (link_crc_error.is_set || is_set(link_crc_error.yfilter)) leaf_name_data.push_back(link_crc_error.get_name_leafdata());
if (link_size_error.is_set || is_set(link_size_error.yfilter)) leaf_name_data.push_back(link_size_error.get_name_leafdata());
if (link_mis_align_error.is_set || is_set(link_mis_align_error.yfilter)) leaf_name_data.push_back(link_mis_align_error.get_name_leafdata());
if (link_code_group_error.is_set || is_set(link_code_group_error.yfilter)) leaf_name_data.push_back(link_code_group_error.get_name_leafdata());
if (link_no_sig_lock_error.is_set || is_set(link_no_sig_lock_error.yfilter)) leaf_name_data.push_back(link_no_sig_lock_error.get_name_leafdata());
if (link_no_sig_accept_error.is_set || is_set(link_no_sig_accept_error.yfilter)) leaf_name_data.push_back(link_no_sig_accept_error.get_name_leafdata());
if (link_tokens_error.is_set || is_set(link_tokens_error.yfilter)) leaf_name_data.push_back(link_tokens_error.get_name_leafdata());
if (error_token_count.is_set || is_set(error_token_count.yfilter)) leaf_name_data.push_back(error_token_count.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Detail::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Detail::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Detail::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "rack_num")
{
rack_num = value;
rack_num.value_namespace = name_space;
rack_num.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TX_Control_cells_counter")
{
tx_control_cells_counter = value;
tx_control_cells_counter.value_namespace = name_space;
tx_control_cells_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TX_Data_cell_counter")
{
tx_data_cell_counter = value;
tx_data_cell_counter.value_namespace = name_space;
tx_data_cell_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TX_Data_byte_counter")
{
tx_data_byte_counter = value;
tx_data_byte_counter.value_namespace = name_space;
tx_data_byte_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_CRC_errors_counter")
{
rx_crc_errors_counter = value;
rx_crc_errors_counter.value_namespace = name_space;
rx_crc_errors_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_LFEC_FEC_correctable_error")
{
rx_lfec_fec_correctable_error = value;
rx_lfec_fec_correctable_error.value_namespace = name_space;
rx_lfec_fec_correctable_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_8b_10b_disparity_errors")
{
rx_8b_10b_disparity_errors = value;
rx_8b_10b_disparity_errors.value_namespace = name_space;
rx_8b_10b_disparity_errors.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_Control_cells_counter")
{
rx_control_cells_counter = value;
rx_control_cells_counter.value_namespace = name_space;
rx_control_cells_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_Data_cell_counter")
{
rx_data_cell_counter = value;
rx_data_cell_counter.value_namespace = name_space;
rx_data_cell_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_Data_byte_counter")
{
rx_data_byte_counter = value;
rx_data_byte_counter.value_namespace = name_space;
rx_data_byte_counter.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_dropped_retransmitted_control")
{
rx_dropped_retransmitted_control = value;
rx_dropped_retransmitted_control.value_namespace = name_space;
rx_dropped_retransmitted_control.value_namespace_prefix = name_space_prefix;
}
if(value_path == "TX_Asyn_fifo_rate")
{
tx_asyn_fifo_rate = value;
tx_asyn_fifo_rate.value_namespace = name_space;
tx_asyn_fifo_rate.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_Asyn_fifo_rate")
{
rx_asyn_fifo_rate = value;
rx_asyn_fifo_rate.value_namespace = name_space;
rx_asyn_fifo_rate.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_LFEC_FEC_uncorrectable_errors")
{
rx_lfec_fec_uncorrectable_errors = value;
rx_lfec_fec_uncorrectable_errors.value_namespace = name_space;
rx_lfec_fec_uncorrectable_errors.value_namespace_prefix = name_space_prefix;
}
if(value_path == "RX_8b_10b_code_errors")
{
rx_8b_10b_code_errors = value;
rx_8b_10b_code_errors.value_namespace = name_space;
rx_8b_10b_code_errors.value_namespace_prefix = name_space_prefix;
}
if(value_path == "is_link_error")
{
is_link_error = value;
is_link_error.value_namespace = name_space;
is_link_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_crc_error")
{
link_crc_error = value;
link_crc_error.value_namespace = name_space;
link_crc_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_size_error")
{
link_size_error = value;
link_size_error.value_namespace = name_space;
link_size_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_mis_align_error")
{
link_mis_align_error = value;
link_mis_align_error.value_namespace = name_space;
link_mis_align_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_code_group_error")
{
link_code_group_error = value;
link_code_group_error.value_namespace = name_space;
link_code_group_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_no_sig_lock_error")
{
link_no_sig_lock_error = value;
link_no_sig_lock_error.value_namespace = name_space;
link_no_sig_lock_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_no_sig_accept_error")
{
link_no_sig_accept_error = value;
link_no_sig_accept_error.value_namespace = name_space;
link_no_sig_accept_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "link_tokens_error")
{
link_tokens_error = value;
link_tokens_error.value_namespace = name_space;
link_tokens_error.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_token_count")
{
error_token_count = value;
error_token_count.value_namespace = name_space;
error_token_count.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Detail::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "rack_num")
{
rack_num.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "TX_Control_cells_counter")
{
tx_control_cells_counter.yfilter = yfilter;
}
if(value_path == "TX_Data_cell_counter")
{
tx_data_cell_counter.yfilter = yfilter;
}
if(value_path == "TX_Data_byte_counter")
{
tx_data_byte_counter.yfilter = yfilter;
}
if(value_path == "RX_CRC_errors_counter")
{
rx_crc_errors_counter.yfilter = yfilter;
}
if(value_path == "RX_LFEC_FEC_correctable_error")
{
rx_lfec_fec_correctable_error.yfilter = yfilter;
}
if(value_path == "RX_8b_10b_disparity_errors")
{
rx_8b_10b_disparity_errors.yfilter = yfilter;
}
if(value_path == "RX_Control_cells_counter")
{
rx_control_cells_counter.yfilter = yfilter;
}
if(value_path == "RX_Data_cell_counter")
{
rx_data_cell_counter.yfilter = yfilter;
}
if(value_path == "RX_Data_byte_counter")
{
rx_data_byte_counter.yfilter = yfilter;
}
if(value_path == "RX_dropped_retransmitted_control")
{
rx_dropped_retransmitted_control.yfilter = yfilter;
}
if(value_path == "TX_Asyn_fifo_rate")
{
tx_asyn_fifo_rate.yfilter = yfilter;
}
if(value_path == "RX_Asyn_fifo_rate")
{
rx_asyn_fifo_rate.yfilter = yfilter;
}
if(value_path == "RX_LFEC_FEC_uncorrectable_errors")
{
rx_lfec_fec_uncorrectable_errors.yfilter = yfilter;
}
if(value_path == "RX_8b_10b_code_errors")
{
rx_8b_10b_code_errors.yfilter = yfilter;
}
if(value_path == "is_link_error")
{
is_link_error.yfilter = yfilter;
}
if(value_path == "link_crc_error")
{
link_crc_error.yfilter = yfilter;
}
if(value_path == "link_size_error")
{
link_size_error.yfilter = yfilter;
}
if(value_path == "link_mis_align_error")
{
link_mis_align_error.yfilter = yfilter;
}
if(value_path == "link_code_group_error")
{
link_code_group_error.yfilter = yfilter;
}
if(value_path == "link_no_sig_lock_error")
{
link_no_sig_lock_error.yfilter = yfilter;
}
if(value_path == "link_no_sig_accept_error")
{
link_no_sig_accept_error.yfilter = yfilter;
}
if(value_path == "link_tokens_error")
{
link_tokens_error.yfilter = yfilter;
}
if(value_path == "error_token_count")
{
error_token_count.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Location::Tx::Statistics::Detail::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "port_data_idx" || name == "rack_num" || name == "sfe_port" || name == "TX_Control_cells_counter" || name == "TX_Data_cell_counter" || name == "TX_Data_byte_counter" || name == "RX_CRC_errors_counter" || name == "RX_LFEC_FEC_correctable_error" || name == "RX_8b_10b_disparity_errors" || name == "RX_Control_cells_counter" || name == "RX_Data_cell_counter" || name == "RX_Data_byte_counter" || name == "RX_dropped_retransmitted_control" || name == "TX_Asyn_fifo_rate" || name == "RX_Asyn_fifo_rate" || name == "RX_LFEC_FEC_uncorrectable_errors" || name == "RX_8b_10b_code_errors" || name == "is_link_error" || name == "link_crc_error" || name == "link_size_error" || name == "link_mis_align_error" || name == "link_code_group_error" || name == "link_no_sig_lock_error" || name == "link_no_sig_accept_error" || name == "link_tokens_error" || name == "error_token_count")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Rx()
:
data_idx(this, {"port_data_idx"})
, brief(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Brief>())
, detail(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Detail>())
, state(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State>())
, statistics(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Statistics>())
{
brief->parent = this;
detail->parent = this;
state->parent = this;
statistics->parent = this;
yang_name = "rx"; yang_parent_name = "port"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::~Rx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return (brief != nullptr && brief->has_data())
|| (detail != nullptr && detail->has_data())
|| (state != nullptr && state->has_data())
|| (statistics != nullptr && statistics->has_data());
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter)
|| (brief != nullptr && brief->has_operation())
|| (detail != nullptr && detail->has_operation())
|| (state != nullptr && state->has_operation())
|| (statistics != nullptr && statistics->has_operation());
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "rx";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
if(child_yang_name == "brief")
{
if(brief == nullptr)
{
brief = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Brief>();
}
return brief;
}
if(child_yang_name == "detail")
{
if(detail == nullptr)
{
detail = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Detail>();
}
return detail;
}
if(child_yang_name == "state")
{
if(state == nullptr)
{
state = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State>();
}
return state;
}
if(child_yang_name == "statistics")
{
if(statistics == nullptr)
{
statistics = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Statistics>();
}
return statistics;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
if(brief != nullptr)
{
_children["brief"] = brief;
}
if(detail != nullptr)
{
_children["detail"] = detail;
}
if(state != nullptr)
{
_children["state"] = state;
}
if(statistics != nullptr)
{
_children["statistics"] = statistics;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx" || name == "brief" || name == "detail" || name == "state" || name == "statistics")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "rx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Brief::Brief()
:
data_idx(this, {"port_data_idx"})
{
yang_name = "brief"; yang_parent_name = "rx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Brief::~Brief()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Brief::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return false;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Brief::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Brief::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "brief";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Brief::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Brief::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Brief::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Brief::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Brief::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Brief::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Brief::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Brief::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "brief"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Brief::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Brief::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Brief::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Brief::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Brief::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Brief::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Brief::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Brief::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Brief::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Brief::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Brief::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Brief::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Brief::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Brief::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Brief::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Brief::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Brief::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Brief::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Brief::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Brief::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Brief::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Brief::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Detail::Detail()
:
data_idx(this, {"port_data_idx"})
{
yang_name = "detail"; yang_parent_name = "rx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Detail::~Detail()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Detail::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return false;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Detail::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Detail::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "detail";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Detail::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Detail::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Detail::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Detail::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Detail::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Detail::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Detail::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Detail::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "detail"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Detail::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Detail::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Detail::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Detail::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Detail::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Detail::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Detail::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Detail::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Detail::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Detail::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Detail::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Detail::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Detail::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Detail::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Detail::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Detail::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Detail::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Detail::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Detail::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Detail::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Detail::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::Detail::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::State()
:
up(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up>())
, down(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down>())
, mismatch(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Mismatch>())
{
up->parent = this;
down->parent = this;
mismatch->parent = this;
yang_name = "state"; yang_parent_name = "rx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::~State()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::has_data() const
{
if (is_presence_container) return true;
return (up != nullptr && up->has_data())
|| (down != nullptr && down->has_data())
|| (mismatch != nullptr && mismatch->has_data());
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::has_operation() const
{
return is_set(yfilter)
|| (up != nullptr && up->has_operation())
|| (down != nullptr && down->has_operation())
|| (mismatch != nullptr && mismatch->has_operation());
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "state";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "up")
{
if(up == nullptr)
{
up = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up>();
}
return up;
}
if(child_yang_name == "down")
{
if(down == nullptr)
{
down = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down>();
}
return down;
}
if(child_yang_name == "mismatch")
{
if(mismatch == nullptr)
{
mismatch = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Mismatch>();
}
return mismatch;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(up != nullptr)
{
_children["up"] = up;
}
if(down != nullptr)
{
_children["down"] = down;
}
if(mismatch != nullptr)
{
_children["mismatch"] = mismatch;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "up" || name == "down" || name == "mismatch")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Up()
:
data_idx(this, {"port_data_idx"})
, brief(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Brief>())
, detail(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Detail>())
{
brief->parent = this;
detail->parent = this;
yang_name = "up"; yang_parent_name = "state"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::~Up()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return (brief != nullptr && brief->has_data())
|| (detail != nullptr && detail->has_data());
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter)
|| (brief != nullptr && brief->has_operation())
|| (detail != nullptr && detail->has_operation());
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "up";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
if(child_yang_name == "brief")
{
if(brief == nullptr)
{
brief = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Brief>();
}
return brief;
}
if(child_yang_name == "detail")
{
if(detail == nullptr)
{
detail = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Detail>();
}
return detail;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
if(brief != nullptr)
{
_children["brief"] = brief;
}
if(detail != nullptr)
{
_children["detail"] = detail;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx" || name == "brief" || name == "detail")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "up"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Brief::Brief()
:
data_idx(this, {"port_data_idx"})
{
yang_name = "brief"; yang_parent_name = "up"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Brief::~Brief()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Brief::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return false;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Brief::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Brief::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "brief";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Brief::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Brief::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Brief::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Brief::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Brief::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Brief::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Brief::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Brief::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "brief"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Brief::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Brief::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Brief::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Brief::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Brief::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Brief::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Brief::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Brief::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Brief::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Brief::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Brief::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Brief::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Brief::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Brief::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Brief::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Brief::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Brief::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Brief::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Brief::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Brief::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Brief::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Brief::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Detail::Detail()
:
data_idx(this, {"port_data_idx"})
{
yang_name = "detail"; yang_parent_name = "up"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Detail::~Detail()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Detail::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return false;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Detail::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Detail::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "detail";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Detail::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Detail::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Detail::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Detail::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Detail::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Detail::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Detail::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Detail::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "detail"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Detail::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Detail::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Detail::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Detail::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Detail::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Detail::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Detail::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Detail::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Detail::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Detail::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Detail::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Detail::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Detail::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Detail::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Detail::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Detail::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Detail::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Detail::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Detail::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Detail::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Detail::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Up::Detail::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::Down()
:
data_idx(this, {"port_data_idx"})
, brief(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::Brief>())
, detail(std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::Detail>())
{
brief->parent = this;
detail->parent = this;
yang_name = "down"; yang_parent_name = "state"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::~Down()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return (brief != nullptr && brief->has_data())
|| (detail != nullptr && detail->has_data());
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter)
|| (brief != nullptr && brief->has_operation())
|| (detail != nullptr && detail->has_operation());
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "down";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
if(child_yang_name == "brief")
{
if(brief == nullptr)
{
brief = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::Brief>();
}
return brief;
}
if(child_yang_name == "detail")
{
if(detail == nullptr)
{
detail = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::Detail>();
}
return detail;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
if(brief != nullptr)
{
_children["brief"] = brief;
}
if(detail != nullptr)
{
_children["detail"] = detail;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx" || name == "brief" || name == "detail")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "down"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::DataIdx::History::History()
:
history_idx{YType::int32, "history_idx"},
time_stamp{YType::str, "time_stamp"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
error_state{YType::str, "error_state"}
{
yang_name = "history"; yang_parent_name = "data_idx"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::DataIdx::History::~History()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::DataIdx::History::has_data() const
{
if (is_presence_container) return true;
return history_idx.is_set
|| time_stamp.is_set
|| admin_state.is_set
|| oper_state.is_set
|| error_state.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::DataIdx::History::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(history_idx.yfilter)
|| ydk::is_set(time_stamp.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(error_state.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::DataIdx::History::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "history";
ADD_KEY_TOKEN(history_idx, "history_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::DataIdx::History::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (history_idx.is_set || is_set(history_idx.yfilter)) leaf_name_data.push_back(history_idx.get_name_leafdata());
if (time_stamp.is_set || is_set(time_stamp.yfilter)) leaf_name_data.push_back(time_stamp.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (error_state.is_set || is_set(error_state.yfilter)) leaf_name_data.push_back(error_state.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::DataIdx::History::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::DataIdx::History::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::DataIdx::History::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "history_idx")
{
history_idx = value;
history_idx.value_namespace = name_space;
history_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "time_stamp")
{
time_stamp = value;
time_stamp.value_namespace = name_space;
time_stamp.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "error_state")
{
error_state = value;
error_state.value_namespace = name_space;
error_state.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::DataIdx::History::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "history_idx")
{
history_idx.yfilter = yfilter;
}
if(value_path == "time_stamp")
{
time_stamp.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "error_state")
{
error_state.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::DataIdx::History::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history_idx" || name == "time_stamp" || name == "admin-state" || name == "oper_state" || name == "error_state")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::Brief::Brief()
:
data_idx(this, {"port_data_idx"})
{
yang_name = "brief"; yang_parent_name = "down"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::Brief::~Brief()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::Brief::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_data())
return true;
}
return false;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::Brief::has_operation() const
{
for (std::size_t index=0; index<data_idx.len(); index++)
{
if(data_idx[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::Brief::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "brief";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::Brief::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::Brief::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "data_idx")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::Brief::DataIdx>();
ent_->parent = this;
data_idx.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::Brief::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : data_idx.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::Brief::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::Brief::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::Brief::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "data_idx")
return true;
return false;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::Brief::DataIdx::DataIdx()
:
port_data_idx{YType::int64, "port_data_idx"},
sfe_port{YType::str, "sfe_port"},
admin_state{YType::str, "admin-state"},
oper_state{YType::str, "oper_state"},
near_end_cdr_ln{YType::str, "near_end_cdr_ln"},
near_end_cxp_ch{YType::str, "near_end_cxp_ch"},
far_end_cxp_ch{YType::str, "far_end_cxp_ch"},
far_end_cdr_ln{YType::str, "far_end_cdr_ln"},
neighbor_link{YType::str, "neighbor_link"}
,
history(this, {"history_idx"})
{
yang_name = "data_idx"; yang_parent_name = "brief"; is_top_level_class = false; has_list_ancestor = true;
}
Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::Brief::DataIdx::~DataIdx()
{
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::Brief::DataIdx::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_data())
return true;
}
return port_data_idx.is_set
|| sfe_port.is_set
|| admin_state.is_set
|| oper_state.is_set
|| near_end_cdr_ln.is_set
|| near_end_cxp_ch.is_set
|| far_end_cxp_ch.is_set
|| far_end_cdr_ln.is_set
|| neighbor_link.is_set;
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::Brief::DataIdx::has_operation() const
{
for (std::size_t index=0; index<history.len(); index++)
{
if(history[index]->has_operation())
return true;
}
return is_set(yfilter)
|| ydk::is_set(port_data_idx.yfilter)
|| ydk::is_set(sfe_port.yfilter)
|| ydk::is_set(admin_state.yfilter)
|| ydk::is_set(oper_state.yfilter)
|| ydk::is_set(near_end_cdr_ln.yfilter)
|| ydk::is_set(near_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cxp_ch.yfilter)
|| ydk::is_set(far_end_cdr_ln.yfilter)
|| ydk::is_set(neighbor_link.yfilter);
}
std::string Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::Brief::DataIdx::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "data_idx";
ADD_KEY_TOKEN(port_data_idx, "port_data_idx");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::Brief::DataIdx::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (port_data_idx.is_set || is_set(port_data_idx.yfilter)) leaf_name_data.push_back(port_data_idx.get_name_leafdata());
if (sfe_port.is_set || is_set(sfe_port.yfilter)) leaf_name_data.push_back(sfe_port.get_name_leafdata());
if (admin_state.is_set || is_set(admin_state.yfilter)) leaf_name_data.push_back(admin_state.get_name_leafdata());
if (oper_state.is_set || is_set(oper_state.yfilter)) leaf_name_data.push_back(oper_state.get_name_leafdata());
if (near_end_cdr_ln.is_set || is_set(near_end_cdr_ln.yfilter)) leaf_name_data.push_back(near_end_cdr_ln.get_name_leafdata());
if (near_end_cxp_ch.is_set || is_set(near_end_cxp_ch.yfilter)) leaf_name_data.push_back(near_end_cxp_ch.get_name_leafdata());
if (far_end_cxp_ch.is_set || is_set(far_end_cxp_ch.yfilter)) leaf_name_data.push_back(far_end_cxp_ch.get_name_leafdata());
if (far_end_cdr_ln.is_set || is_set(far_end_cdr_ln.yfilter)) leaf_name_data.push_back(far_end_cdr_ln.get_name_leafdata());
if (neighbor_link.is_set || is_set(neighbor_link.yfilter)) leaf_name_data.push_back(neighbor_link.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::Brief::DataIdx::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "history")
{
auto ent_ = std::make_shared<Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::Brief::DataIdx::History>();
ent_->parent = this;
history.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::Brief::DataIdx::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : history.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::Brief::DataIdx::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "port_data_idx")
{
port_data_idx = value;
port_data_idx.value_namespace = name_space;
port_data_idx.value_namespace_prefix = name_space_prefix;
}
if(value_path == "sfe_port")
{
sfe_port = value;
sfe_port.value_namespace = name_space;
sfe_port.value_namespace_prefix = name_space_prefix;
}
if(value_path == "admin-state")
{
admin_state = value;
admin_state.value_namespace = name_space;
admin_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "oper_state")
{
oper_state = value;
oper_state.value_namespace = name_space;
oper_state.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln = value;
near_end_cdr_ln.value_namespace = name_space;
near_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch = value;
near_end_cxp_ch.value_namespace = name_space;
near_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch = value;
far_end_cxp_ch.value_namespace = name_space;
far_end_cxp_ch.value_namespace_prefix = name_space_prefix;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln = value;
far_end_cdr_ln.value_namespace = name_space;
far_end_cdr_ln.value_namespace_prefix = name_space_prefix;
}
if(value_path == "neighbor_link")
{
neighbor_link = value;
neighbor_link.value_namespace = name_space;
neighbor_link.value_namespace_prefix = name_space_prefix;
}
}
void Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::Brief::DataIdx::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "port_data_idx")
{
port_data_idx.yfilter = yfilter;
}
if(value_path == "sfe_port")
{
sfe_port.yfilter = yfilter;
}
if(value_path == "admin-state")
{
admin_state.yfilter = yfilter;
}
if(value_path == "oper_state")
{
oper_state.yfilter = yfilter;
}
if(value_path == "near_end_cdr_ln")
{
near_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "near_end_cxp_ch")
{
near_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cxp_ch")
{
far_end_cxp_ch.yfilter = yfilter;
}
if(value_path == "far_end_cdr_ln")
{
far_end_cdr_ln.yfilter = yfilter;
}
if(value_path == "neighbor_link")
{
neighbor_link.yfilter = yfilter;
}
}
bool Controller::Fabric::Oper::Link::NodeLocation::Port::Rx::State::Down::Brief::DataIdx::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "history" || name == "port_data_idx" || name == "sfe_port" || name == "admin-state" || name == "oper_state" || name == "near_end_cdr_ln" || name == "near_end_cxp_ch" || name == "far_end_cxp_ch" || name == "far_end_cdr_ln" || name == "neighbor_link")
return true;
return false;
}
}
}
| 36.61161 | 883 | 0.690023 | [
"vector"
] |
a380301f98f6ea9329ad73ed7b30420227ae9211 | 3,216 | cpp | C++ | Non_linear_regression/NonLinearRegression.cpp | shorane/cpp_tracking_filtering_estimation | a3cb564ac581f57eed17e014302bad3297c9d647 | [
"MIT"
] | null | null | null | Non_linear_regression/NonLinearRegression.cpp | shorane/cpp_tracking_filtering_estimation | a3cb564ac581f57eed17e014302bad3297c9d647 | [
"MIT"
] | null | null | null | Non_linear_regression/NonLinearRegression.cpp | shorane/cpp_tracking_filtering_estimation | a3cb564ac581f57eed17e014302bad3297c9d647 | [
"MIT"
] | null | null | null | #include<iostream>
#include <math.h>
#include<fstream>
#include<vector>
#include <Eigen/Dense>
#include<string>
#define TOTAL_ITERATIONS 50000
using Eigen::MatrixXd;
using namespace std;
//helper function declaration:
MatrixXd* read_matrix(string filename);
void write_matrix(string filename, MatrixXd m);
void write_vec(string filename, vector<double> m);
// MAIN PROGRAM
int main(){
string casename = "A";
// import the data required from A,B and C files
MatrixXd* data = read_matrix("Data_"+ casename + "_lab_2.csv");
double an,an1,fan,fpan, xi, yi;
int i,j;
an = 0.1; // initial guess of a
vector<double> v;
v.push_back(an);
for (j=0; j<TOTAL_ITERATIONS; j++){
fan=fpan=0.0;
for (i=0; i<(*data).rows(); i++){
// cout<<i<<endl;
xi = (*data)(i,0);
yi = (*data)(i,1);
fan+= (yi - log(an * xi)) * 1/an;
fpan+= (- 1/an) * 1/an - (yi - log(an * xi)) * 1/(an*an);
}
an1=an-fan/fpan;
printf("%lf %lf\n",an,an1);
if (fabs(an-an1) < 0.00000001)
break;
v.push_back(fabs(an-an1));
an=an1;
}
printf("%d iterations\n",j);
// exporting data fit:
MatrixXd XiYi(600,2);
for(int i=0; i<600; i++){
XiYi(i,0) = (i+1)/10; // store the x value
XiYi(i,1) = log(an * ((i+1)/10)); // store the y value
}
if (casename=="A"){
write_vec("iterations_A.txt", v);
write_matrix("A_fit.txt", XiYi);}
else if (casename=="B"){
write_vec("iterations_B.txt", v);
write_matrix("B_fit.txt", XiYi);
}
else if (casename=="C"){
write_vec("iterations_C.txt", v);
write_matrix("C_fit.txt", XiYi);
}
return 0;
}
MatrixXd* read_matrix(string filename){
ifstream myfile;
myfile.open(filename);
if (!myfile.is_open()) throw runtime_error("Could not open file");
string row_item;
vector<vector<double> > rows;
string line;
while(myfile.good()){
vector<double> row;
getline(myfile, line);
// cout<<line<<endl;
stringstream s(line);
while (getline(s,row_item,' ')){
// cout<<row_item<<" ";
row.push_back(stod(row_item));
}
rows.push_back(row);
}
myfile.close();
int nrows,ncols;
nrows = rows.end() - rows.begin();
ncols = rows[0].end() - rows[0].begin();
MatrixXd* m = new MatrixXd(nrows,ncols);
for(int i=0; i<nrows; i++){
for (int j=0; j<ncols; j++){
(*m)(i,j) = rows[i][j];
// cout<<rows[i][j]<<" ";
}
}
// cout<<"The following is a matrix of "<<nrows<<" rows and "<<ncols<<" coloumns: "<<endl<<*m<<endl;
return m;
}
void write_matrix(string filename, MatrixXd m){
ofstream(myfile);
myfile.open(filename);
for(int i=0; i<m.rows(); i++){
for(int j=0; j<m.cols(); j++){
myfile << m(i,j) <<",";
}
myfile << endl;
}
}
void write_vec(string filename, vector<double> m){
ofstream(myfile);
myfile.open(filename);
for(int i=0; i<m.end()-m.begin(); i++){
myfile << m[i] <<endl;
}
} | 26.146341 | 104 | 0.533582 | [
"vector"
] |
a38470e3a3a3d56ca2cec1a338fa24b422ebaf33 | 3,956 | cc | C++ | mindspore/ccsrc/kernel/cpu/mkldnn/mkl_cpu_kernel.cc | wudenggang/mindspore | 95e75c3119909cc5c7c3098232851d1d7bc4ef8c | [
"Apache-2.0"
] | 1 | 2020-06-20T06:22:41.000Z | 2020-06-20T06:22:41.000Z | mindspore/ccsrc/kernel/cpu/mkldnn/mkl_cpu_kernel.cc | shaolei-wang/mindspore | 2d50a43be9d17269f6adb41e51b8f7a540ebc9f1 | [
"Apache-2.0"
] | null | null | null | mindspore/ccsrc/kernel/cpu/mkldnn/mkl_cpu_kernel.cc | shaolei-wang/mindspore | 2d50a43be9d17269f6adb41e51b8f7a540ebc9f1 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2020 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "kernel/cpu/mkldnn/mkl_cpu_kernel.h"
#include <vector>
#include <string>
#include <algorithm>
#include "common/utils.h"
#include "kernel/cpu/mkldnn/mkl_kernel_engine.h"
namespace mindspore {
namespace kernel {
void MKLCPUKernel::GetPadding(const CNodePtr &kernel_node, const std::string &pad_mode,
const std::vector<size_t> &src_shape, int kernel_size, int stride,
std::vector<int> *padding_l, std::vector<int> *padding_r) {
MS_EXCEPTION_IF_NULL(kernel_node);
if (src_shape.size() < 2) {
MS_LOG(EXCEPTION) << "set pad only support src dim >= 2!";
}
std::vector<int> weight_height;
weight_height.emplace_back(src_shape[src_shape.size() - 2]);
weight_height.emplace_back(src_shape[src_shape.size() - 1]);
int rad = kernel_size / 2;
int need_pad = kernel_size - 1;
MS_LOG(INFO) << "pad mode " << pad_mode;
if (pad_mode == PAD_MODE_LOWER_SAME || pad_mode == PAD_MODE_UPPER_SAME) {
for (auto wh : weight_height) {
int re = (wh - 1) % stride;
int pad = std::max(rad - (re / 2), 0);
padding_r->emplace_back(pad);
pad = std::max(need_pad - pad - re, 0);
padding_l->emplace_back(pad);
}
} else if (pad_mode == PAD_MODE_LOWER_VALID || pad_mode == PAD_MODE_UPPER_VALID) {
MS_LOG(INFO) << "pad valid";
padding_l->emplace_back(0);
padding_l->emplace_back(0);
padding_r->emplace_back(0);
padding_r->emplace_back(0);
} else {
std::vector<int> pad = AnfAlgo::GetNodeAttr<std::vector<int>>(kernel_node, PAD);
if (pad.size() != 4) {
MS_LOG(EXCEPTION) << "wrong pad size in max pooling " << pad.size();
}
padding_l->emplace_back(pad[0]);
padding_l->emplace_back(pad[1]);
padding_r->emplace_back(pad[2]);
padding_r->emplace_back(pad[3]);
}
}
dnnl::memory::format_tag MKLCPUKernel::GetDefaultFormatTag(const dnnl::memory::dims &dims) const {
dnnl::memory::format_tag mem_tag;
auto dim_size = dims.size();
if (dim_size == 4) {
mem_tag = dnnl::memory::format_tag::abcd;
} else if (dim_size == 3) {
mem_tag = dnnl::memory::format_tag::abc;
} else if (dim_size == 2) {
mem_tag = dnnl::memory::format_tag::ab;
} else if (dim_size == 1) {
mem_tag = dnnl::memory::format_tag::a;
} else {
MS_LOG(EXCEPTION) << "kernel dims invalid " << dim_size;
}
return mem_tag;
}
dnnl::memory::desc MKLCPUKernel::GetDefaultMemDesc(const std::vector<size_t> &shape) {
dnnl::memory::dims dims;
dims.insert(dims.end(), shape.begin(), shape.end());
dnnl::memory::format_tag mem_tag = GetDefaultFormatTag(dims);
dnnl::memory::desc mem_desc(dims, dnnl::memory::data_type::f32, mem_tag);
return mem_desc;
}
void MKLCPUKernel::AddArgument(int arg_key, const dnnl::memory::desc &mem_desc, bool alloc) {
arguments_[arg_key] = MKLKernelEngine::Get().CreateMemory(mem_desc, alloc);
}
void MKLCPUKernel::SetArgumentHandle(int arg_key, void *ptr) {
auto arg_iter = arguments_.find(arg_key);
if (arg_iter != arguments_.end()) {
arg_iter->second.set_data_handle(ptr);
}
}
void MKLCPUKernel::ExecutePrimitive() { MKLKernelEngine::Get().Execute(primitive_, arguments_); }
void MKLCPUKernel::Reorder(dnnl::memory *src_mem, dnnl::memory *dst_mem) {
MKLKernelEngine::Get().Reorder(src_mem, dst_mem);
}
} // namespace kernel
} // namespace mindspore
| 36.971963 | 98 | 0.683771 | [
"shape",
"vector"
] |
a387032448a6098ba8eff5ca194894f6ab8b5d79 | 2,718 | cpp | C++ | settings/workspace.cpp | Mytherin/Panther | 1eac47074aa33ba747140950f373c9b7dd7f3d67 | [
"Apache-2.0"
] | 5 | 2018-01-25T14:43:20.000Z | 2021-02-28T11:37:55.000Z | settings/workspace.cpp | Mytherin/Panther | 1eac47074aa33ba747140950f373c9b7dd7f3d67 | [
"Apache-2.0"
] | null | null | null | settings/workspace.cpp | Mytherin/Panther | 1eac47074aa33ba747140950f373c9b7dd7f3d67 | [
"Apache-2.0"
] | 3 | 2018-01-28T13:22:49.000Z | 2020-09-23T02:55:04.000Z |
#include "mmap.h"
#include "replaymanager.h"
#include "workspace.h"
#include <fstream>
using namespace nlohmann;
PGWorkspace::PGWorkspace() {
}
void PGWorkspace::LoadWorkspace(std::string filename) {
this->filename = filename;
lng result_size;
PGFileError error;
json j;
char* ptr = (char*)panther::ReadFile(filename, result_size, error);
if (!ptr) {
goto default_workspace;
}
try {
j = json::parse(ptr);
} catch (...) {
goto default_workspace;
}
this->settings = j;
if (j.count("workspace_name") > 0) {
this->workspace_name = j["workspace_name"].get<std::string>();
}
if (j.count("files") > 0 && j["files"].is_array()) {
FileManager::LoadWorkspace(j["files"]);
} else {
goto default_workspace;
}
findtext.LoadWorkspace(j);
if (j.count("windows") > 0 && j["windows"].is_array() && j["windows"].size() > 0) {
for (int index = 0; index < j["windows"].size(); index++) {
auto window = PGCreateWindow(this, std::vector<std::shared_ptr<TextView>>());
if (!window) {
goto default_workspace;
}
PGLoadWorkspace(window, j["windows"][index]);
}
return;
}
default_workspace:
this->settings = j;
this->workspace_name = "Default Workspace";
auto window = PGCreateWindow(this, std::vector<std::shared_ptr<TextView>>());
}
std::string PGWorkspace::WriteWorkspace() {
if (PGGlobalReplayManager::running_replay) return "";
std::string errmsg;
if (filename.size() == 0) return "File not found.";
json j = settings;
findtext.WriteWorkspace(j);
j["workspace_name"] = this->workspace_name;
j["files"] = nlohmann::json::array();
FileManager::WriteWorkspace(j["files"]);
j["windows"] = nlohmann::json::array();
int index = 0;
for (auto it = windows.begin(); it != windows.end(); it++) {
j["windows"][index] = nlohmann::json::object();
PGWriteWorkspace(*it, j["windows"][index]);
index++;
}
// we write the workspace to a temporary file first (workspace.json.tmp)
std::string temp_filename = filename + ".tmp";
std::ofstream out(temp_filename);
if (!out) {
return "Could not open file \"" + temp_filename + "\"";
}
if (!(out << std::setw(4) << j)) {
out.close();
goto cleanup;
}
out.close();
{
// after writing to the temporary file, we move it over the old workspace file
auto ret = PGRenameFile(temp_filename, filename);
if (ret == PGIOSuccess) {
return "";
}
}
cleanup:
PGRemoveFile(temp_filename);
return "I/O error.";
}
void PGWorkspace::RemoveWindow(PGWindowHandle window) {
bool close_workspace = windows.size() == 1;
if (close_workspace) {
WriteWorkspace();
}
windows.erase(std::find(windows.begin(), windows.end(), window));
if (close_workspace) {
PGCloseWorkspace(this);
} else {
WriteWorkspace();
}
}
| 24.709091 | 84 | 0.662252 | [
"object",
"vector"
] |
a389108dbafe214ccd101bb2f6fbc0fb513e8ecc | 5,456 | cpp | C++ | glut_demo/main.cpp | silenthell/Spline | f49f405d62fe34bedd4361eae1e32d6c744a8ce8 | [
"MIT"
] | 15 | 2017-11-24T16:01:51.000Z | 2020-05-13T03:26:36.000Z | glut_demo/main.cpp | brainexcerpts/Spline | f49f405d62fe34bedd4361eae1e32d6c744a8ce8 | [
"MIT"
] | 1 | 2020-12-26T15:57:42.000Z | 2020-12-26T15:57:42.000Z | glut_demo/main.cpp | silenthell/Spline | f49f405d62fe34bedd4361eae1e32d6c744a8ce8 | [
"MIT"
] | 13 | 2016-09-25T08:59:55.000Z | 2020-05-21T02:22:48.000Z | #include <GL/glut.h>
#include "vec3.hpp"
#include "splines.hpp"
static int g_win_number;
// Control points parameters
float _width = 5.0f;
int _nb_control_points = 16;
bool _animate = true;
std::vector<Vec3> _control_points;
// Number of line subdivisions to display the spline
int _spline_resolution = 1000;
// Smoothness of the spline (min 2)
int _spline_order = 3;
Spline<Vec3, float> _spline_curve(_spline_order, /*spline::eOPEN_UNIFORM*/spline::eUNIFORM);
// =============================================================================
void key_stroke (unsigned char c, int mouseX, int mouseY) {
static bool wires = false;
switch (c) {
case 27 :
glFinish();
glutDestroyWindow(g_win_number);
exit (0);
break;
case 'a' : _animate = !_animate; break;
case 'w' :
if(!wires) {
glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
glutPostRedisplay();
wires = true;
}else {
glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
glutPostRedisplay();
wires = false;
}
break;
}
}
// -----------------------------------------------------------------------------
void draw_spline(const Spline<Vec3, float>& spline_curve)
{
glLineWidth(4.0f);
glColor3f( 1.0f, 1.0f, 1.0f);
glBegin(GL_LINES);
Vec3 start = spline_curve.eval_f(0.0f);
glVertex3f(start.x, start.y, start.z);
for(int i = 0; i < _spline_resolution; ++i) {
Vec3 p = spline_curve.eval_f( float(i) / float(_spline_resolution-1) );
glVertex3fv((float*)p);
if(i < (_spline_resolution-1) )
glVertex3fv((float*)p);
}
glEnd();
}
// -----------------------------------------------------------------------------
void draw_spline_speed(const Spline<Vec3, float>& spline_curve, float t)
{
glLineWidth(2.0f);
glColor3f( 0.0f, 0.8f, 0.1f);
glBegin(GL_LINES);
Vec3 v = spline_curve.eval_df(t) * 0.1f;
Vec3 mid = spline_curve.eval_f(t);
Vec3 start = mid - v;
Vec3 end = mid + v;
glVertex3f(start.x, start.y, start.z +0.00001f /*put it slightly forward*/);
glVertex3f(end.x , end.y , end.z +0.00001f /*put it slightly forward*/);
glEnd();
glBegin(GL_POINTS);
glColor3f ( 1.0f, 0.0f, 1.0f);
glVertex3f( mid.x, mid.y, mid.z+0.0001f /*put it slightly forward*/ );
glEnd();
}
// -----------------------------------------------------------------------------
void draw_ctrl_points(const std::vector<Vec3>& control_points)
{
glPointSize(6.0f);
glBegin(GL_POINTS);
for(Vec3 v : control_points){
glColor3f ( 1.0f, 0.0f, 0.0f);
glVertex3f( v.x, v.y, v.z+0.00001f /*put it slightly forward*/ );
}
glEnd();
}
// -----------------------------------------------------------------------------
void display(void)
{
glClearColor (0.8, 0.8, 0.8, 0.0);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glViewport(0,0,900,900);
glMatrixMode (GL_PROJECTION);
glLoadIdentity();
gluPerspective(60., 1., 0.5, 100.);
glMatrixMode (GL_MODELVIEW);
glLoadIdentity ();
glTranslatef(0.0, 0.0, -1.0);
float s = 0.2f;
glScalef(s, s, s);
// Animate control points to go up and down
static float sign = -1.0f;
static float y = 0.2f;
if( _animate ){
sign = y < -0.8f ? 1.0f : (y > 0.4f ? -1.0f : sign);
y = y + 0.01f*sign;
for(int i = 1; i < (_nb_control_points/2)-1; ++i) {
Vec3 p = _control_points[i*2];
_control_points[i*2] = Vec3(p.x, y, p.z );
}
}
_spline_curve.set_ctrl_points(_control_points);
draw_spline(_spline_curve);
draw_ctrl_points(_control_points);
{
static float t = 0.0f;
t += 0.001f;
t = t > 1.0f ? 0.0f : t;
draw_spline_speed(_spline_curve, t);
}
glutSwapBuffers();
glFlush ();
glutPostRedisplay();
}
// -----------------------------------------------------------------------------
int main (int argc, char** argv)
{
float h = 0.2f;
float start_x = -_width*0.5f;
float step = _width / float(_nb_control_points-1);
for(int i = 0; i < _nb_control_points; ++i) {
float x = start_x + step * float(i);
float sign = i % 2 ? -1.0f : 1.0f;
_control_points.push_back( Vec3(x, h*sign, 0.0f) );
}
/*
g_control_points.push_back( Vec3(-1.00f, h, 0.0f) );
g_control_points.push_back( Vec3(-0.75f, -h, 0.0f) );
g_control_points.push_back( Vec3(-0.50f, h, 0.0f) );
g_control_points.push_back( Vec3(-0.25f, -h, 0.0f) );
g_control_points.push_back( Vec3( 0.00f, h, 0.0f) );
g_control_points.push_back( Vec3( 0.25f, -h, 0.0f) );
g_control_points.push_back( Vec3( 0.50f, h, 0.0f) );
g_control_points.push_back( Vec3( 0.75f, -h, 0.0f) );
g_control_points.push_back( Vec3( 1.00f, h, 0.0f) );
*/
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize (900, 900);
glutInitWindowPosition (240, 212);
g_win_number = glutCreateWindow (argv[0]);
glEnable(GL_DEPTH_TEST);
glEnable(GL_NORMALIZE);
glEnable(GL_POINT_SMOOTH);
glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);
glEnable(GL_LINE_SMOOTH);
//glEnable(GL_LIGHTING);
//glEnable(GL_LIGHT0);
glutKeyboardFunc(key_stroke);
glutDisplayFunc(display);
glutMainLoop();
return (0);
}
| 28.26943 | 92 | 0.552969 | [
"vector"
] |
a38c454c70e90a2f06f605fcc8a8a37ac584f2c1 | 29,943 | cpp | C++ | tests/unit/prob_test.cpp | chang-liang/HadoopBNEM | dd90a70786271ebf5b0beda2484f8e476ab4a97a | [
"BSD-2-Clause"
] | 48 | 2015-01-19T18:56:28.000Z | 2021-12-30T20:30:50.000Z | tests/unit/prob_test.cpp | chang-liang/HadoopBNEM | dd90a70786271ebf5b0beda2484f8e476ab4a97a | [
"BSD-2-Clause"
] | 2 | 2016-01-18T08:17:38.000Z | 2021-04-28T18:08:38.000Z | tests/unit/prob_test.cpp | chang-liang/HadoopBNEM | dd90a70786271ebf5b0beda2484f8e476ab4a97a | [
"BSD-2-Clause"
] | 29 | 2015-04-07T07:38:25.000Z | 2022-02-01T22:18:58.000Z | /* This file is part of libDAI - http://www.libdai.org/
*
* Copyright (c) 2006-2011, The libDAI authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
*/
#include <dai/util.h>
#include <dai/prob.h>
#include <strstream>
using namespace dai;
const Real tol = 1e-8;
#define BOOST_TEST_MODULE ProbTest
#include <boost/test/unit_test.hpp>
#include <boost/test/floating_point_comparison.hpp>
BOOST_AUTO_TEST_CASE( ConstructorsTest ) {
// check constructors
Prob x1;
BOOST_CHECK_EQUAL( x1.size(), 0U );
BOOST_CHECK( x1.p() == Prob::container_type() );
Prob x2( 3 );
BOOST_CHECK_EQUAL( x2.size(), 3 );
BOOST_CHECK_CLOSE( x2[0], (Real)(1.0 / 3.0), tol );
BOOST_CHECK_CLOSE( x2[1], (Real)(1.0 / 3.0), tol );
BOOST_CHECK_CLOSE( x2[2], (Real)(1.0 / 3.0), tol );
Prob x3( 4, (Real)1.0 );
BOOST_CHECK_EQUAL( x3.size(), 4 );
BOOST_CHECK( x3.p() == Prob::container_type( 4, (Real)1.0 ) );
BOOST_CHECK_EQUAL( x3[0], (Real)1.0 );
BOOST_CHECK_EQUAL( x3[1], (Real)1.0 );
BOOST_CHECK_EQUAL( x3[2], (Real)1.0 );
BOOST_CHECK_EQUAL( x3[3], (Real)1.0 );
x3.set( 0, 0.5 );
x3.set( 1, 1.0 );
x3.set( 2, 2.0 );
x3.set( 3, 4.0 );
std::vector<Real> v;
v.push_back( 0.5 );
v.push_back( 1.0 );
v.push_back( 2.0 );
v.push_back( 4.0 );
Prob x4( v.begin(), v.end(), 0 );
BOOST_CHECK_EQUAL( x4.size(), 4 );
BOOST_CHECK( x4.p() == x3.p() );
BOOST_CHECK( x4 == x3 );
BOOST_CHECK_EQUAL( x4[0], (Real)0.5 );
BOOST_CHECK_EQUAL( x4[1], (Real)1.0 );
BOOST_CHECK_EQUAL( x4[2], (Real)2.0 );
BOOST_CHECK_EQUAL( x4[3], (Real)4.0 );
Prob x5( v.begin(), v.end(), v.size() );
BOOST_CHECK_EQUAL( x5.size(), 4 );
BOOST_CHECK( x5.p() == x3.p() );
BOOST_CHECK( x5 == x3 );
BOOST_CHECK_EQUAL( x5[0], (Real)0.5 );
BOOST_CHECK_EQUAL( x5[1], (Real)1.0 );
BOOST_CHECK_EQUAL( x5[2], (Real)2.0 );
BOOST_CHECK_EQUAL( x5[3], (Real)4.0 );
std::vector<int> y( 3, 2 );
Prob x6( y );
BOOST_CHECK_EQUAL( x6.size(), 3 );
BOOST_CHECK_EQUAL( x6[0], (Real)2.0 );
BOOST_CHECK_EQUAL( x6[1], (Real)2.0 );
BOOST_CHECK_EQUAL( x6[2], (Real)2.0 );
Prob x7( x6 );
BOOST_CHECK( x7 == x6 );
Prob x8 = x6;
BOOST_CHECK( x8 == x6 );
x7.resize( 5 );
BOOST_CHECK_EQUAL( x7.size(), 5 );
BOOST_CHECK_EQUAL( x7[0], (Real)2.0 );
BOOST_CHECK_EQUAL( x7[1], (Real)2.0 );
BOOST_CHECK_EQUAL( x7[2], (Real)2.0 );
BOOST_CHECK_EQUAL( x7[3], (Real)0.0 );
BOOST_CHECK_EQUAL( x7[4], (Real)0.0 );
x8.resize( 1 );
BOOST_CHECK_EQUAL( x8.size(), 1 );
BOOST_CHECK_EQUAL( x8[0], (Real)2.0 );
}
#ifndef DAI_SPARSE
BOOST_AUTO_TEST_CASE( IteratorTest ) {
Prob x( 5, 0.0 );
size_t i;
for( i = 0; i < x.size(); i++ )
x.set( i, (Real)i );
i = 0;
for( Prob::const_iterator cit = x.begin(); cit != x.end(); cit++, i++ )
BOOST_CHECK_EQUAL( *cit, (Real)i );
i = 0;
for( Prob::iterator it = x.begin(); it != x.end(); it++, i++ )
*it = (Real)(4 - i);
i = 0;
for( Prob::const_iterator it = x.begin(); it != x.end(); it++, i++ )
BOOST_CHECK_EQUAL( *it, (Real)(4 - i) );
i = 0;
for( Prob::const_reverse_iterator crit = x.rbegin(); crit != static_cast<Prob::const_reverse_iterator>(x.rend()); crit++, i++ )
BOOST_CHECK_EQUAL( *crit, (Real)i );
i = 0;
for( Prob::reverse_iterator rit = x.rbegin(); rit != x.rend(); rit++, i++ )
*rit = (Real)(2 * i);
i = 0;
for( Prob::const_reverse_iterator crit = x.rbegin(); crit != static_cast<Prob::const_reverse_iterator>(x.rend()); crit++, i++ )
BOOST_CHECK_EQUAL( *crit, (Real)2 * i );
}
#endif
BOOST_AUTO_TEST_CASE( QueriesTest ) {
Prob x( 5, 0.0 );
for( size_t i = 0; i < x.size(); i++ )
x.set( i, 2.0 - i );
// test accumulate, min, max, sum, sumAbs, maxAbs
BOOST_CHECK_CLOSE( x.sum(), (Real)0.0, tol );
BOOST_CHECK_CLOSE( x.accumulateSum( 0.0, fo_id<Real>() ), (Real)0.0, tol );
BOOST_CHECK_CLOSE( x.accumulateSum( 1.0, fo_id<Real>() ), (Real)1.0, tol );
BOOST_CHECK_CLOSE( x.accumulateSum( -1.0, fo_id<Real>() ), (Real)-1.0, tol );
BOOST_CHECK_CLOSE( x.max(), (Real)2.0, tol );
BOOST_CHECK_CLOSE( x.accumulateMax( -INFINITY, fo_id<Real>(), false ), (Real)2.0, tol );
BOOST_CHECK_CLOSE( x.accumulateMax( 3.0, fo_id<Real>(), false ), (Real)3.0, tol );
BOOST_CHECK_CLOSE( x.accumulateMax( -5.0, fo_id<Real>(), false ), (Real)2.0, tol );
BOOST_CHECK_CLOSE( x.min(), (Real)-2.0, tol );
BOOST_CHECK_CLOSE( x.accumulateMax( INFINITY, fo_id<Real>(), true ), (Real)-2.0, tol );
BOOST_CHECK_CLOSE( x.accumulateMax( -3.0, fo_id<Real>(), true ), (Real)-3.0, tol );
BOOST_CHECK_CLOSE( x.accumulateMax( 5.0, fo_id<Real>(), true ), (Real)-2.0, tol );
BOOST_CHECK_CLOSE( x.sumAbs(), (Real)6.0, tol );
BOOST_CHECK_CLOSE( x.accumulateSum( 0.0, fo_abs<Real>() ), (Real)6.0, tol );
BOOST_CHECK_CLOSE( x.accumulateSum( 1.0, fo_abs<Real>() ), (Real)7.0, tol );
BOOST_CHECK_CLOSE( x.accumulateSum( -1.0, fo_abs<Real>() ), (Real)7.0, tol );
BOOST_CHECK_CLOSE( x.maxAbs(), (Real)2.0, tol );
BOOST_CHECK_CLOSE( x.accumulateMax( 0.0, fo_abs<Real>(), false ), (Real)2.0, tol );
BOOST_CHECK_CLOSE( x.accumulateMax( 1.0, fo_abs<Real>(), false ), (Real)2.0, tol );
BOOST_CHECK_CLOSE( x.accumulateMax( -1.0, fo_abs<Real>(), false ), (Real)2.0, tol );
BOOST_CHECK_CLOSE( x.accumulateMax( 3.0, fo_abs<Real>(), false ), (Real)3.0, tol );
BOOST_CHECK_CLOSE( x.accumulateMax( -3.0, fo_abs<Real>(), false ), (Real)3.0, tol );
x.set( 1, 1.0 );
BOOST_CHECK_CLOSE( x.maxAbs(), (Real)2.0, tol );
BOOST_CHECK_CLOSE( x.accumulateMax( 0.0, fo_abs<Real>(), false ), (Real)2.0, tol );
BOOST_CHECK_CLOSE( x.accumulateMax( 1.0, fo_abs<Real>(), false ), (Real)2.0, tol );
BOOST_CHECK_CLOSE( x.accumulateMax( -1.0, fo_abs<Real>(), false ), (Real)2.0, tol );
BOOST_CHECK_CLOSE( x.accumulateMax( 3.0, fo_abs<Real>(), false ), (Real)3.0, tol );
BOOST_CHECK_CLOSE( x.accumulateMax( -3.0, fo_abs<Real>(), false ), (Real)3.0, tol );
for( size_t i = 0; i < x.size(); i++ )
x.set( i, i ? (1.0 / i) : 0.0 );
BOOST_CHECK_CLOSE( x.accumulateSum( 0.0, fo_inv0<Real>() ), (Real)10.0, tol );
x /= x.sum();
// test entropy
BOOST_CHECK( x.entropy() < Prob(5).entropy() );
for( size_t i = 1; i < 100; i++ )
BOOST_CHECK_CLOSE( Prob(i).entropy(), dai::log((Real)i), tol );
// test hasNaNs and hasNegatives
BOOST_CHECK( !Prob( 3, 0.0 ).hasNaNs() );
Real c = 0.0;
BOOST_CHECK( Prob( 3, c / c ).hasNaNs() );
BOOST_CHECK( !Prob( 3, 0.0 ).hasNegatives() );
BOOST_CHECK( !Prob( 3, 1.0 ).hasNegatives() );
BOOST_CHECK( Prob( 3, -1.0 ).hasNegatives() );
x.set( 0, 0.0 ); x.set( 1, 0.0 ); x.set( 2, -1.0 ); x.set( 3, 1.0 ); x.set( 4, 100.0 );
BOOST_CHECK( x.hasNegatives() );
x.set( 2, -INFINITY );
BOOST_CHECK( x.hasNegatives() );
x.set( 2, INFINITY );
BOOST_CHECK( !x.hasNegatives() );
x.set( 2, -1.0 );
// test argmax
BOOST_CHECK( x.argmax() == std::make_pair( (size_t)4, (Real)100.0 ) );
x.set( 4, 0.5 );
BOOST_CHECK( x.argmax() == std::make_pair( (size_t)3, (Real)1.0 ) );
x.set( 3, -2.0 );
BOOST_CHECK( x.argmax() == std::make_pair( (size_t)4, (Real)0.5 ) );
x.set( 4, -1.0 );
BOOST_CHECK( x.argmax() == std::make_pair( (size_t)0, (Real)0.0 ) );
x.set( 0, -2.0 );
BOOST_CHECK( x.argmax() == std::make_pair( (size_t)1, (Real)0.0 ) );
x.set( 1, -3.0 );
BOOST_CHECK( x.argmax() == std::make_pair( (size_t)2, (Real)-1.0 ) );
x.set( 2, -2.0 );
BOOST_CHECK( x.argmax() == std::make_pair( (size_t)4, (Real)-1.0 ) );
// test draw
for( size_t i = 0; i < x.size(); i++ )
x.set( i, i ? (1.0 / i) : 0.0 );
for( size_t repeat = 0; repeat < 10000; repeat++ ) {
BOOST_CHECK( x.draw() < x.size() );
BOOST_CHECK( x.draw() != 0 );
}
x.set( 2, 0.0 );
for( size_t repeat = 0; repeat < 10000; repeat++ ) {
BOOST_CHECK( x.draw() < x.size() );
BOOST_CHECK( x.draw() != 0 );
BOOST_CHECK( x.draw() != 2 );
}
x.set( 4, 0.0 );
for( size_t repeat = 0; repeat < 10000; repeat++ ) {
BOOST_CHECK( x.draw() < x.size() );
BOOST_CHECK( x.draw() != 0 );
BOOST_CHECK( x.draw() != 2 );
BOOST_CHECK( x.draw() != 4 );
}
x.set( 1, 0.0 );
for( size_t repeat = 0; repeat < 10000; repeat++ )
BOOST_CHECK( x.draw() == 3 );
// test <, ==
Prob a(3, 1.0), b(3, 1.0);
BOOST_CHECK( !(a < b) );
BOOST_CHECK( !(b < a) );
BOOST_CHECK( a == b );
a.set( 0, 0.0 );
BOOST_CHECK( a < b );
BOOST_CHECK( !(b < a) );
BOOST_CHECK( !(a == b) );
b.set( 2, 0.0 );
BOOST_CHECK( a < b );
BOOST_CHECK( !(b < a) );
BOOST_CHECK( !(a == b) );
b.set( 0, 0.0 );
BOOST_CHECK( !(a < b) );
BOOST_CHECK( b < a );
BOOST_CHECK( !(a == b) );
a.set( 1, 0.0 );
BOOST_CHECK( a < b );
BOOST_CHECK( !(b < a) );
BOOST_CHECK( !(a == b) );
b.set( 1, 0.0 );
BOOST_CHECK( !(a < b) );
BOOST_CHECK( b < a );
BOOST_CHECK( !(a == b) );
a.set( 2, 0.0 );
BOOST_CHECK( !(a < b) );
BOOST_CHECK( !(b < a) );
BOOST_CHECK( a == b );
}
BOOST_AUTO_TEST_CASE( UnaryTransformationsTest ) {
Prob x( 3 );
x.set( 0, -2.0 );
x.set( 1, 0.0 );
x.set( 2, 2.0 );
Prob y = -x;
Prob z = x.pwUnaryTr( std::negate<Real>() );
BOOST_CHECK_CLOSE( y[0], (Real)2.0, tol );
BOOST_CHECK_CLOSE( y[1], (Real)0.0, tol );
BOOST_CHECK_CLOSE( y[2], (Real)-2.0, tol );
BOOST_CHECK( y == z );
y = x.abs();
z = x.pwUnaryTr( fo_abs<Real>() );
BOOST_CHECK_CLOSE( y[0], (Real)2.0, tol );
BOOST_CHECK_CLOSE( y[1], (Real)0.0, tol );
BOOST_CHECK_CLOSE( y[2], (Real)2.0, tol );
BOOST_CHECK( y == z );
y = x.exp();
z = x.pwUnaryTr( fo_exp<Real>() );
BOOST_CHECK_CLOSE( y[0], dai::exp((Real)-2.0), tol );
BOOST_CHECK_CLOSE( y[1], (Real)1.0, tol );
BOOST_CHECK_CLOSE( y[2], (Real)1.0 / y[0], tol );
BOOST_CHECK( y == z );
y = x.log(false);
z = x.pwUnaryTr( fo_log<Real>() );
BOOST_CHECK( dai::isnan( y[0] ) );
BOOST_CHECK_EQUAL( y[1], -INFINITY );
BOOST_CHECK_CLOSE( y[2], dai::log((Real)2.0), tol );
BOOST_CHECK( !(y == z) );
y.set( 0, 0.0 );
z.set( 0, 0.0 );
BOOST_CHECK( y == z );
y = x.log(true);
z = x.pwUnaryTr( fo_log0<Real>() );
BOOST_CHECK( dai::isnan( y[0] ) );
BOOST_CHECK_CLOSE( y[1], (Real)0.0, tol );
BOOST_CHECK_CLOSE( y[2], dai::log((Real)2.0), tol );
BOOST_CHECK( !(y == z) );
y.set( 0, 0.0 );
z.set( 0, 0.0 );
BOOST_CHECK( y == z );
y = x.inverse(false);
z = x.pwUnaryTr( fo_inv<Real>() );
BOOST_CHECK_CLOSE( y[0], (Real)-0.5, tol );
BOOST_CHECK_EQUAL( y[1], INFINITY );
BOOST_CHECK_CLOSE( y[2], (Real)0.5, tol );
BOOST_CHECK( y == z );
y = x.inverse(true);
z = x.pwUnaryTr( fo_inv0<Real>() );
BOOST_CHECK_CLOSE( y[0], (Real)-0.5, tol );
BOOST_CHECK_CLOSE( y[1], (Real)0.0, tol );
BOOST_CHECK_CLOSE( y[2], (Real)0.5, tol );
BOOST_CHECK( y == z );
x.set( 0, 2.0 );
y = x.normalized();
BOOST_CHECK_CLOSE( y[0], (Real)0.5, tol );
BOOST_CHECK_CLOSE( y[1], (Real)0.0, tol );
BOOST_CHECK_CLOSE( y[2], (Real)0.5, tol );
y = x.normalized( NORMPROB );
BOOST_CHECK_CLOSE( y[0], (Real)0.5, tol );
BOOST_CHECK_CLOSE( y[1], (Real)0.0, tol );
BOOST_CHECK_CLOSE( y[2], (Real)0.5, tol );
x.set( 0, -2.0 );
y = x.normalized( NORMLINF );
BOOST_CHECK_CLOSE( y[0], (Real)-1.0, tol );
BOOST_CHECK_CLOSE( y[1], (Real)0.0, tol );
BOOST_CHECK_CLOSE( y[2], (Real)1.0, tol );
}
BOOST_AUTO_TEST_CASE( UnaryOperationsTest ) {
Prob xorg(3);
xorg.set( 0, 2.0 );
xorg.set( 1, 0.0 );
xorg.set( 2, 1.0 );
Prob y(3);
Prob x = xorg;
BOOST_CHECK( x.setUniform() == Prob(3) );
BOOST_CHECK( x == Prob(3) );
y.set( 0, dai::exp(2.0) );
y.set( 1, 1.0 );
y.set( 2, dai::exp(1.0) );
x = xorg;
BOOST_CHECK_SMALL( dist( x.takeExp(), y, DISTL1 ), tol );
BOOST_CHECK_SMALL( dist( x, y, DISTL1 ), tol );
x = xorg;
BOOST_CHECK_SMALL( dist( x.pwUnaryOp( fo_exp<Real>() ), y, DISTL1 ), tol );
BOOST_CHECK_SMALL( dist( x, y, DISTL1 ), tol );
y.set( 0, dai::log(2.0) );
y.set( 1, -INFINITY );
y.set( 2, 0.0 );
x = xorg;
Prob z = x.takeLog();
BOOST_CHECK_CLOSE( z[0], y[0], tol );
// BOOST_CHECK_CLOSE( z[1], y[1], tol );
BOOST_CHECK_CLOSE( z[2], y[2], tol );
BOOST_CHECK( x == z );
x = xorg;
z = x.takeLog(false);
BOOST_CHECK_CLOSE( z[0], y[0], tol );
// BOOST_CHECK_CLOSE( z[1], y[1], tol );
BOOST_CHECK_CLOSE( z[2], y[2], tol );
BOOST_CHECK( x == z );
x = xorg;
z = x.pwUnaryOp( fo_log<Real>() );
BOOST_CHECK_CLOSE( z[0], y[0], tol );
// BOOST_CHECK_CLOSE( z[1], y[1], tol );
BOOST_CHECK_CLOSE( z[2], y[2], tol );
BOOST_CHECK( x == z );
y.set( 1, 0.0 );
x = xorg;
BOOST_CHECK_SMALL( dist( x.takeLog(true), y, DISTL1 ), tol );
BOOST_CHECK_SMALL( dist( x, y, DISTL1 ), tol );
x = xorg;
BOOST_CHECK_SMALL( dist( x.pwUnaryOp( fo_log0<Real>() ), y, DISTL1 ), tol );
BOOST_CHECK_SMALL( dist( x, y, DISTL1 ), tol );
y.set( 0, 2.0 / 3.0 );
y.set( 1, 0.0 / 3.0 );
y.set( 2, 1.0 / 3.0 );
x = xorg;
BOOST_CHECK_CLOSE( x.normalize(), (Real)3.0, tol );
BOOST_CHECK_SMALL( dist( x, y, DISTL1 ), tol );
x = xorg;
BOOST_CHECK_CLOSE( x.normalize( NORMPROB ), (Real)3.0, tol );
BOOST_CHECK_SMALL( dist( x, y, DISTL1 ), tol );
y.set( 0, 2.0 / 2.0 );
y.set( 1, 0.0 / 2.0 );
y.set( 2, 1.0 / 2.0 );
x = xorg;
BOOST_CHECK_CLOSE( x.normalize( NORMLINF ), (Real)2.0, tol );
BOOST_CHECK_SMALL( dist( x, y, DISTL1 ), tol );
xorg.set( 0, -2.0 );
y.set( 0, 2.0 );
y.set( 1, 0.0 );
y.set( 2, 1.0 );
x = xorg;
BOOST_CHECK( x.takeAbs() == y );
BOOST_CHECK( x == y );
for( size_t repeat = 0; repeat < 10000; repeat++ ) {
x.randomize();
for( size_t i = 0; i < x.size(); i++ ) {
BOOST_CHECK( x[i] < (Real)1.0 );
BOOST_CHECK( x[i] >= (Real)0.0 );
}
}
}
BOOST_AUTO_TEST_CASE( ScalarTransformationsTest ) {
Prob x(3);
x.set( 0, 2.0 );
x.set( 1, 0.0 );
x.set( 2, 1.0 );
Prob y(3);
y.set( 0, 3.0 ); y.set( 1, 1.0 ); y.set( 2, 2.0 );
BOOST_CHECK_SMALL( dist( (x + 1.0), y, DISTL1 ), tol );
y.set( 0, 0.0 ); y.set( 1, -2.0 ); y.set( 2, -1.0 );
BOOST_CHECK_SMALL( dist( (x + (-2.0)), y, DISTL1 ), tol );
y.set( 0, 1.0 ); y.set( 1, -1.0 ); y.set( 2, 0.0 );
BOOST_CHECK_SMALL( dist( (x - 1.0), y, DISTL1 ), tol );
y.set( 0, 4.0 ); y.set( 1, 2.0 ); y.set( 2, 3.0 );
BOOST_CHECK_SMALL( dist( (x - (-2.0)), y, DISTL1 ), tol );
BOOST_CHECK_SMALL( dist( (x * 1.0), x, DISTL1 ), tol );
y.set( 0, 4.0 ); y.set( 1, 0.0 ); y.set( 2, 2.0 );
BOOST_CHECK_SMALL( dist( (x * 2.0), y, DISTL1 ), tol );
y.set( 0, -1.0 ); y.set( 1, 0.0 ); y.set( 2, -0.5 );
BOOST_CHECK_SMALL( dist( (x * -0.5), y, DISTL1 ), tol );
BOOST_CHECK_SMALL( dist( (x / 1.0), x, DISTL1 ), tol );
y.set( 0, 1.0 ); y.set( 1, 0.0 ); y.set( 2, 0.5 );
BOOST_CHECK_SMALL( dist( (x / 2.0), y, DISTL1 ), tol );
y.set( 0, -4.0 ); y.set( 1, 0.0 ); y.set( 2, -2.0 );
BOOST_CHECK_SMALL( dist( (x / -0.5), y, DISTL1 ), tol );
BOOST_CHECK( (x / 0.0) == Prob(3, 0.0) );
BOOST_CHECK( (x ^ 1.0) == x );
BOOST_CHECK( (x ^ 0.0) == Prob(3, 1.0) );
y.set( 0, 4.0 ); y.set( 1, 0.0 ); y.set( 2, 1.0 );
BOOST_CHECK_SMALL( dist( (x ^ 2.0), y, DISTL1 ), tol );
y.set( 0, std::sqrt(2.0) ); y.set( 1, 0.0 ); y.set( 2, 1.0 );
BOOST_CHECK_SMALL( dist( (x ^ 0.5), y, DISTL1 ), tol );
}
BOOST_AUTO_TEST_CASE( ScalarOperationsTest ) {
Prob xorg(3), x(3);
xorg.set( 0, 2.0 );
xorg.set( 1, 0.0 );
xorg.set( 2, 1.0 );
Prob y(3);
x = xorg;
BOOST_CHECK( x.fill( 1.0 ) == Prob(3, 1.0) );
BOOST_CHECK( x == Prob(3, 1.0) );
BOOST_CHECK( x.fill( 2.0 ) == Prob(3, 2.0) );
BOOST_CHECK( x == Prob(3, 2.0) );
BOOST_CHECK( x.fill( 0.0 ) == Prob(3, 0.0) );
BOOST_CHECK( x == Prob(3, 0.0) );
x = xorg;
y.set( 0, 3.0 ); y.set( 1, 1.0 ); y.set( 2, 2.0 );
BOOST_CHECK_SMALL( dist( (x += 1.0), y, DISTL1 ), tol );
BOOST_CHECK_SMALL( dist( x, y, DISTL1 ), tol );
y.set( 0, 1.0 ); y.set( 1, -1.0 ); y.set( 2, 0.0 );
BOOST_CHECK_SMALL( dist( (x += -2.0), y, DISTL1 ), tol );
BOOST_CHECK_SMALL( dist( x, y, DISTL1 ), tol );
x = xorg;
y.set( 0, 1.0 ); y.set( 1, -1.0 ); y.set( 2, 0.0 );
BOOST_CHECK_SMALL( dist( (x -= 1.0), y, DISTL1 ), tol );
BOOST_CHECK_SMALL( dist( x, y, DISTL1 ), tol );
y.set( 0, 3.0 ); y.set( 1, 1.0 ); y.set( 2, 2.0 );
BOOST_CHECK_SMALL( dist( (x -= -2.0), y, DISTL1 ), tol );
BOOST_CHECK_SMALL( dist( x, y, DISTL1 ), tol );
x = xorg;
BOOST_CHECK_SMALL( dist( (x *= 1.0), x, DISTL1 ), tol );
BOOST_CHECK_SMALL( dist( x, x, DISTL1 ), tol );
y.set( 0, 4.0 ); y.set( 1, 0.0 ); y.set( 2, 2.0 );
BOOST_CHECK_SMALL( dist( (x *= 2.0), y, DISTL1 ), tol );
BOOST_CHECK_SMALL( dist( x, y, DISTL1 ), tol );
y.set( 0, -1.0 ); y.set( 1, 0.0 ); y.set( 2, -0.5 );
BOOST_CHECK_SMALL( dist( (x *= -0.25), y, DISTL1 ), tol );
BOOST_CHECK_SMALL( dist( x, y, DISTL1 ), tol );
x = xorg;
BOOST_CHECK_SMALL( dist( (x /= 1.0), x, DISTL1 ), tol );
BOOST_CHECK_SMALL( dist( x, x, DISTL1 ), tol );
y.set( 0, 1.0 ); y.set( 1, 0.0 ); y.set( 2, 0.5 );
BOOST_CHECK_SMALL( dist( (x /= 2.0), y, DISTL1 ), tol );
BOOST_CHECK_SMALL( dist( x, y, DISTL1 ), tol );
y.set( 0, -4.0 ); y.set( 1, 0.0 ); y.set( 2, -2.0 );
BOOST_CHECK_SMALL( dist( (x /= -0.25), y, DISTL1 ), tol );
BOOST_CHECK_SMALL( dist( x, y, DISTL1 ), tol );
BOOST_CHECK( (x /= 0.0) == Prob(3, 0.0) );
BOOST_CHECK( x == Prob(3, 0.0) );
x = xorg;
BOOST_CHECK( (x ^= 1.0) == x );
BOOST_CHECK( x == x );
BOOST_CHECK( (x ^= 0.0) == Prob(3, 1.0) );
BOOST_CHECK( x == Prob(3, 1.0) );
x = xorg;
y.set( 0, 4.0 ); y.set( 1, 0.0 ); y.set( 2, 1.0 );
BOOST_CHECK_SMALL( dist( (x ^= 2.0), y, DISTL1 ), tol );
BOOST_CHECK_SMALL( dist( x, y, DISTL1 ), tol );
y.set( 0, 2.0 ); y.set( 1, 0.0 ); y.set( 2, 1.0 );
BOOST_CHECK_SMALL( dist( (x ^= 0.5), y, DISTL1 ), tol );
BOOST_CHECK_SMALL( dist( x, y, DISTL1 ), tol );
}
BOOST_AUTO_TEST_CASE( VectorOperationsTest ) {
size_t N = 6;
Prob xorg(N), x(N);
xorg.set( 0, 2.0 ); xorg.set( 1, 0.0 ); xorg.set( 2, 1.0 ); xorg.set( 3, 0.0 ); xorg.set( 4, 2.0 ); xorg.set( 5, 3.0 );
Prob y(N);
y.set( 0, 0.5 ); y.set( 1, 1.0 ); y.set( 2, 0.0 ); y.set( 3, 0.0 ); y.set( 4, -2.0 ); y.set( 5, 3.0 );
Prob z(N), r(N);
z.set( 0, 2.5 ); z.set( 1, 1.0 ); z.set( 2, 1.0 ); z.set( 3, 0.0 ); z.set( 4, 0.0 ); z.set( 5, 6.0 );
x = xorg;
r = (x += y);
for( size_t i = 0; i < N; i++ )
BOOST_CHECK_CLOSE( r[i], z[i], tol );
BOOST_CHECK_SMALL( dist( x, z, DISTL1 ), tol );
x = xorg;
BOOST_CHECK( x.pwBinaryOp( y, std::plus<Real>() ) == r );
BOOST_CHECK( x == r );
z.set( 0, 1.5 ); z.set( 1, -1.0 ); z.set( 2, 1.0 ); z.set( 3, 0.0 ); z.set( 4, 4.0 ); z.set( 5, 0.0 );
x = xorg;
r = (x -= y);
for( size_t i = 0; i < N; i++ )
BOOST_CHECK_CLOSE( r[i], z[i], tol );
BOOST_CHECK_SMALL( dist( x, z, DISTL1 ), tol );
x = xorg;
BOOST_CHECK( x.pwBinaryOp( y, std::minus<Real>() ) == r );
BOOST_CHECK( x == r );
z.set( 0, 1.0 ); z.set( 1, 0.0 ); z.set( 2, 0.0 ); z.set( 3, 0.0 ); z.set( 4, -4.0 ); z.set( 5, 9.0 );
x = xorg;
r = (x *= y);
for( size_t i = 0; i < N; i++ )
BOOST_CHECK_CLOSE( r[i], z[i], tol );
BOOST_CHECK_SMALL( dist( x, z, DISTL1 ), tol );
x = xorg;
BOOST_CHECK( x.pwBinaryOp( y, std::multiplies<Real>() ) == r );
BOOST_CHECK( x == r );
z.set( 0, 4.0 ); z.set( 1, 0.0 ); z.set( 2, 0.0 ); z.set( 3, 0.0 ); z.set( 4, -1.0 ); z.set( 5, 1.0 );
x = xorg;
r = (x /= y);
for( size_t i = 0; i < N; i++ )
BOOST_CHECK_CLOSE( r[i], z[i], tol );
BOOST_CHECK_SMALL( dist( x, z, DISTL1 ), tol );
x = xorg;
BOOST_CHECK( x.pwBinaryOp( y, fo_divides0<Real>() ) == r );
BOOST_CHECK( x == r );
z.set( 0, 4.0 ); z.set( 1, 0.0 ); z.set( 2, INFINITY ); /*z.set( 3, INFINITY );*/ z.set( 4, -1.0 ); z.set( 5, 1.0 );
x = xorg;
r = (x.divide( y ));
BOOST_CHECK_CLOSE( r[0], z[0], tol );
BOOST_CHECK_CLOSE( r[1], z[1], tol );
BOOST_CHECK_EQUAL( r[2], z[2] );
BOOST_CHECK( dai::isnan(r[3]) );
BOOST_CHECK_CLOSE( r[4], z[4], tol );
BOOST_CHECK_CLOSE( r[5], z[5], tol );
x.set( 3, 0.0 ); r.set( 3, 0.0 );
BOOST_CHECK( x == r );
x = xorg;
r = x.pwBinaryOp( y, std::divides<Real>() );
BOOST_CHECK_CLOSE( r[0], z[0], tol );
BOOST_CHECK_CLOSE( r[1], z[1], tol );
BOOST_CHECK_EQUAL( r[2], z[2] );
BOOST_CHECK( dai::isnan(r[3]) );
BOOST_CHECK_CLOSE( r[4], z[4], tol );
BOOST_CHECK_CLOSE( r[5], z[5], tol );
x.set( 3, 0.0 ); r.set( 3, 0.0 );
BOOST_CHECK( x == r );
z.set( 0, std::sqrt(2.0) ); z.set( 1, 0.0 ); z.set( 2, 1.0 ); z.set( 3, 1.0 ); z.set( 4, 0.25 ); z.set( 5, 27.0 );
x = xorg;
r = (x ^= y);
for( size_t i = 0; i < 6; i++ )
BOOST_CHECK_CLOSE( r[i], z[i], tol );
BOOST_CHECK( x == r );
x = xorg;
r = x.pwBinaryOp( y, fo_pow<Real>() );
for( size_t i = 0; i < 6; i++ )
BOOST_CHECK_CLOSE( r[i], z[i], tol );
BOOST_CHECK( x == r );
}
BOOST_AUTO_TEST_CASE( VectorTransformationsTest ) {
size_t N = 6;
Prob x(N);
x.set( 0, 2.0 ); x.set( 1, 0.0 ); x.set( 2, 1.0 ); x.set( 3, 0.0 ); x.set( 4, 2.0 ); x.set( 5, 3.0 );
Prob y(N);
y.set( 0, 0.5 ); y.set( 1, 1.0 ); y.set( 2, 0.0 ); y.set( 3, 0.0 ); y.set( 4, -2.0 ); y.set( 5, 3.0 );
Prob z(N), r(N);
z.set( 0, 2.5 ); z.set( 1, 1.0 ); z.set( 2, 1.0 ); z.set( 3, 0.0 ); z.set( 4, 0.0 ); z.set( 5, 6.0 );
r = x + y;
for( size_t i = 0; i < N; i++ )
BOOST_CHECK_CLOSE( r[i], z[i], tol );
z = x.pwBinaryTr( y, std::plus<Real>() );
BOOST_CHECK( r == z );
z.set( 0, 1.5 ); z.set( 1, -1.0 ); z.set( 2, 1.0 ); z.set( 3, 0.0 ); z.set( 4, 4.0 ); z.set( 5, 0.0 );
r = x - y;
for( size_t i = 0; i < N; i++ )
BOOST_CHECK_CLOSE( r[i], z[i], tol );
z = x.pwBinaryTr( y, std::minus<Real>() );
BOOST_CHECK( r == z );
z.set( 0, 1.0 ); z.set( 1, 0.0 ); z.set( 2, 0.0 ); z.set( 3, 0.0 ); z.set( 4, -4.0 ); z.set( 5, 9.0 );
r = x * y;
for( size_t i = 0; i < N; i++ )
BOOST_CHECK_CLOSE( r[i], z[i], tol );
z = x.pwBinaryTr( y, std::multiplies<Real>() );
BOOST_CHECK( r == z );
z.set( 0, 4.0 ); z.set( 1, 0.0 ); z.set( 2, 0.0 ); z.set( 3, 0.0 ); z.set( 4, -1.0 ); z.set( 5, 1.0 );
r = x / y;
for( size_t i = 0; i < N; i++ )
BOOST_CHECK_CLOSE( r[i], z[i], tol );
z = x.pwBinaryTr( y, fo_divides0<Real>() );
BOOST_CHECK( r == z );
z.set( 0, 4.0 ); z.set( 1, 0.0 ); z.set( 2, INFINITY ); /*z.set( 3, INFINITY );*/ z.set( 4, -1.0 ); z.set( 5, 1.0 );
r = x.divided_by( y );
BOOST_CHECK_CLOSE( r[0], z[0], tol );
BOOST_CHECK_CLOSE( r[1], z[1], tol );
BOOST_CHECK_EQUAL( r[2], z[2] );
BOOST_CHECK( dai::isnan(r[3]) );
BOOST_CHECK_CLOSE( r[4], z[4], tol );
BOOST_CHECK_CLOSE( r[5], z[5], tol );
z = x.pwBinaryTr( y, std::divides<Real>() );
BOOST_CHECK_CLOSE( r[0], z[0], tol );
BOOST_CHECK_CLOSE( r[1], z[1], tol );
BOOST_CHECK_EQUAL( r[2], z[2] );
BOOST_CHECK( dai::isnan(r[3]) );
BOOST_CHECK_CLOSE( r[4], z[4], tol );
BOOST_CHECK_CLOSE( r[5], z[5], tol );
z.set( 0, std::sqrt(2.0) ); z.set( 1, 0.0 ); z.set( 2, 1.0 ); z.set( 3, 1.0 ); z.set( 4, 0.25 ); z.set( 5, 27.0 );
r = x ^ y;
BOOST_CHECK_CLOSE( r[0], z[0], tol );
BOOST_CHECK_CLOSE( r[1], z[1], tol );
BOOST_CHECK_CLOSE( r[2], z[2], tol );
BOOST_CHECK_CLOSE( r[3], z[3], tol );
BOOST_CHECK_CLOSE( r[4], z[4], tol );
BOOST_CHECK_CLOSE( r[5], z[5], tol );
z = x.pwBinaryTr( y, fo_pow<Real>() );
BOOST_CHECK( r == z );
}
BOOST_AUTO_TEST_CASE( RelatedFunctionsTest ) {
Prob x(3), y(3), z(3);
x.set( 0, 0.2 );
x.set( 1, 0.8 );
x.set( 2, 0.0 );
y.set( 0, 0.0 );
y.set( 1, 0.6 );
y.set( 2, 0.4 );
z = min( x, y );
BOOST_CHECK_EQUAL( z[0], (Real)0.0 );
BOOST_CHECK_EQUAL( z[1], (Real)0.6 );
BOOST_CHECK_EQUAL( z[2], (Real)0.0 );
z = max( x, y );
BOOST_CHECK_EQUAL( z[0], (Real)0.2 );
BOOST_CHECK_EQUAL( z[1], (Real)0.8 );
BOOST_CHECK_EQUAL( z[2], (Real)0.4 );
BOOST_CHECK_CLOSE( dist( x, x, DISTL1 ), (Real)0.0, tol );
BOOST_CHECK_CLOSE( dist( y, y, DISTL1 ), (Real)0.0, tol );
BOOST_CHECK_CLOSE( dist( x, y, DISTL1 ), (Real)(0.2 + 0.2 + 0.4), tol );
BOOST_CHECK_CLOSE( dist( y, x, DISTL1 ), (Real)(0.2 + 0.2 + 0.4), tol );
BOOST_CHECK_CLOSE( dist( x, y, DISTL1 ), x.innerProduct( y, 0.0, std::plus<Real>(), fo_absdiff<Real>() ), tol );
BOOST_CHECK_CLOSE( dist( y, x, DISTL1 ), y.innerProduct( x, 0.0, std::plus<Real>(), fo_absdiff<Real>() ), tol );
BOOST_CHECK_CLOSE( dist( x, x, DISTLINF ), (Real)0.0, tol );
BOOST_CHECK_CLOSE( dist( y, y, DISTLINF ), (Real)0.0, tol );
BOOST_CHECK_CLOSE( dist( x, y, DISTLINF ), (Real)0.4, tol );
BOOST_CHECK_CLOSE( dist( y, x, DISTLINF ), (Real)0.4, tol );
BOOST_CHECK_CLOSE( dist( x, y, DISTLINF ), x.innerProduct( y, 0.0, fo_max<Real>(), fo_absdiff<Real>() ), tol );
BOOST_CHECK_CLOSE( dist( y, x, DISTLINF ), y.innerProduct( x, 0.0, fo_max<Real>(), fo_absdiff<Real>() ), tol );
BOOST_CHECK_CLOSE( dist( x, x, DISTTV ), (Real)0.0, tol );
BOOST_CHECK_CLOSE( dist( y, y, DISTTV ), (Real)0.0, tol );
BOOST_CHECK_CLOSE( dist( x, y, DISTTV ), (Real)(0.5 * (0.2 + 0.2 + 0.4)), tol );
BOOST_CHECK_CLOSE( dist( y, x, DISTTV ), (Real)(0.5 * (0.2 + 0.2 + 0.4)), tol );
BOOST_CHECK_CLOSE( dist( x, y, DISTTV ), x.innerProduct( y, 0.0, std::plus<Real>(), fo_absdiff<Real>() ) / 2.0, tol );
BOOST_CHECK_CLOSE( dist( y, x, DISTTV ), y.innerProduct( x, 0.0, std::plus<Real>(), fo_absdiff<Real>() ) / 2.0, tol );
BOOST_CHECK_CLOSE( dist( x, x, DISTKL ), (Real)0.0, tol );
BOOST_CHECK_CLOSE( dist( y, y, DISTKL ), (Real)0.0, tol );
BOOST_CHECK_EQUAL( dist( x, y, DISTKL ), INFINITY );
BOOST_CHECK_EQUAL( dist( y, x, DISTKL ), INFINITY );
BOOST_CHECK_EQUAL( dist( x, y, DISTKL ), x.innerProduct( y, 0.0, std::plus<Real>(), fo_KL<Real>() ) );
BOOST_CHECK_EQUAL( dist( y, x, DISTKL ), y.innerProduct( x, 0.0, std::plus<Real>(), fo_KL<Real>() ) );
BOOST_CHECK_CLOSE( dist( x, x, DISTHEL ), (Real)0.0, tol );
BOOST_CHECK_CLOSE( dist( y, y, DISTHEL ), (Real)0.0, tol );
BOOST_CHECK_CLOSE( dist( x, y, DISTHEL ), (Real)(0.5 * (0.2 + dai::pow(std::sqrt(0.8) - std::sqrt(0.6), 2.0) + 0.4)), tol );
BOOST_CHECK_CLOSE( dist( y, x, DISTHEL ), (Real)(0.5 * (0.2 + dai::pow(std::sqrt(0.8) - std::sqrt(0.6), 2.0) + 0.4)), tol );
BOOST_CHECK_CLOSE( dist( x, y, DISTHEL ), x.innerProduct( y, 0.0, std::plus<Real>(), fo_Hellinger<Real>() ) / 2.0, tol );
BOOST_CHECK_CLOSE( dist( y, x, DISTHEL ), y.innerProduct( x, 0.0, std::plus<Real>(), fo_Hellinger<Real>() ) / 2.0, tol );
x.set( 1, 0.7 ); x.set( 2, 0.1 );
y.set( 0, 0.1 ); y.set( 1, 0.5 );
BOOST_CHECK_CLOSE( dist( x, y, DISTKL ), (Real)(0.2 * dai::log(0.2 / 0.1) + 0.7 * dai::log(0.7 / 0.5) + 0.1 * dai::log(0.1 / 0.4)), tol );
BOOST_CHECK_CLOSE( dist( y, x, DISTKL ), (Real)(0.1 * dai::log(0.1 / 0.2) + 0.5 * dai::log(0.5 / 0.7) + 0.4 * dai::log(0.4 / 0.1)), tol );
BOOST_CHECK_CLOSE( dist( x, y, DISTKL ), x.innerProduct( y, 0.0, std::plus<Real>(), fo_KL<Real>() ), tol );
BOOST_CHECK_CLOSE( dist( y, x, DISTKL ), y.innerProduct( x, 0.0, std::plus<Real>(), fo_KL<Real>() ), tol );
Prob xx(4), yy(4);
for( size_t i = 0; i < 3; i++ ) {
xx.set( i, x[i] );
yy.set( i, y[i] );
}
std::stringstream ss;
ss << xx;
std::string s;
std::getline( ss, s );
#ifdef DAI_SPARSE
BOOST_CHECK_EQUAL( s, std::string("(size:4, def:0.25, 0:0.2, 1:0.7, 2:0.1)") );
#else
BOOST_CHECK_EQUAL( s, std::string("(0.2, 0.7, 0.1, 0.25)") );
#endif
std::stringstream ss2;
ss2 << yy;
std::getline( ss2, s );
#ifdef DAI_SPARSE
BOOST_CHECK_EQUAL( s, std::string("(size:4, def:0.25, 0:0.1, 1:0.5, 2:0.4)") );
#else
BOOST_CHECK_EQUAL( s, std::string("(0.1, 0.5, 0.4, 0.25)") );
#endif
z = min( x, y );
BOOST_CHECK_EQUAL( z[0], (Real)0.1 );
BOOST_CHECK_EQUAL( z[1], (Real)0.5 );
BOOST_CHECK_EQUAL( z[2], (Real)0.1 );
z = max( x, y );
BOOST_CHECK_EQUAL( z[0], (Real)0.2 );
BOOST_CHECK_EQUAL( z[1], (Real)0.7 );
BOOST_CHECK_EQUAL( z[2], (Real)0.4 );
BOOST_CHECK_CLOSE( x.innerProduct( y, 0.0, std::plus<Real>(), std::multiplies<Real>() ), (Real)(0.2*0.1 + 0.7*0.5 + 0.1*0.4), tol );
BOOST_CHECK_CLOSE( y.innerProduct( x, 0.0, std::plus<Real>(), std::multiplies<Real>() ), (Real)(0.2*0.1 + 0.7*0.5 + 0.1*0.4), tol );
BOOST_CHECK_CLOSE( x.innerProduct( y, 1.0, std::plus<Real>(), std::multiplies<Real>() ), (Real)(1.0 + 0.2*0.1 + 0.7*0.5 + 0.1*0.4), tol );
BOOST_CHECK_CLOSE( y.innerProduct( x, 1.0, std::plus<Real>(), std::multiplies<Real>() ), (Real)(1.0 + 0.2*0.1 + 0.7*0.5 + 0.1*0.4), tol );
BOOST_CHECK_CLOSE( x.innerProduct( y, -1.0, std::plus<Real>(), std::multiplies<Real>() ), (Real)(-1.0 + 0.2*0.1 + 0.7*0.5 + 0.1*0.4), tol );
BOOST_CHECK_CLOSE( y.innerProduct( x, -1.0, std::plus<Real>(), std::multiplies<Real>() ), (Real)(-1.0 + 0.2*0.1 + 0.7*0.5 + 0.1*0.4), tol );
}
| 38.241379 | 144 | 0.531577 | [
"vector"
] |
a38fc34791ad2f25d32633868bd1b7498c99dac7 | 7,801 | cc | C++ | components/visitedlink/browser/visitedlink_event_listener.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | components/visitedlink/browser/visitedlink_event_listener.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | components/visitedlink/browser/visitedlink_event_listener.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/visitedlink/browser/visitedlink_event_listener.h"
#include "base/bind.h"
#include "components/visitedlink/browser/visitedlink_delegate.h"
#include "components/visitedlink/common/visitedlink.mojom.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_types.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_widget_host.h"
#include "services/service_manager/public/cpp/interface_provider.h"
using base::Time;
using base::TimeDelta;
using content::RenderWidgetHost;
namespace {
// The amount of time we wait to accumulate visited link additions.
constexpr int kCommitIntervalMs = 100;
// Size of the buffer after which individual link updates deemed not warranted
// and the overall update should be used instead.
const unsigned kVisitedLinkBufferThreshold = 50;
} // namespace
namespace visitedlink {
// This class manages buffering and sending visited link hashes (fingerprints)
// to renderer based on widget visibility.
// As opposed to the VisitedLinkEventListener, which coalesces to
// reduce the rate of messages being sent to render processes, this class
// ensures that the updates occur only when explicitly requested. This is
// used for RenderProcessHostImpl to only send Add/Reset link events to the
// renderers when their tabs are visible and the corresponding RenderViews are
// created.
class VisitedLinkUpdater {
public:
explicit VisitedLinkUpdater(int render_process_id)
: reset_needed_(false),
invalidate_hashes_(false),
render_process_id_(render_process_id) {
BindInterface(content::RenderProcessHost::FromID(render_process_id),
&sink_);
}
// Informs the renderer about a new visited link table.
void SendVisitedLinkTable(base::ReadOnlySharedMemoryRegion* region) {
if (region->IsValid())
sink_->UpdateVisitedLinks(region->Duplicate());
}
// Buffers |links| to update, but doesn't actually relay them.
void AddLinks(const VisitedLinkCommon::Fingerprints& links) {
if (reset_needed_)
return;
if (pending_.size() + links.size() > kVisitedLinkBufferThreshold) {
// Once the threshold is reached, there's no need to store pending visited
// link updates -- we opt for resetting the state for all links.
AddReset(false);
return;
}
pending_.insert(pending_.end(), links.begin(), links.end());
}
// Tells the updater that sending individual link updates is no longer
// necessary and the visited state for all links should be reset. If
// |invalidateHashes| is true all cached visited links hashes should be
// dropped.
void AddReset(bool invalidate_hashes) {
reset_needed_ = true;
// Do not set to false. If tab is invisible the reset message will not be
// sent until tab became visible.
if (invalidate_hashes)
invalidate_hashes_ = true;
pending_.clear();
}
// Sends visited link update messages: a list of links whose visited state
// changed or reset of visited state for all links.
void Update() {
content::RenderProcessHost* process =
content::RenderProcessHost::FromID(render_process_id_);
if (!process)
return; // Happens in tests
if (!process->VisibleClientCount())
return;
if (reset_needed_) {
sink_->ResetVisitedLinks(invalidate_hashes_);
reset_needed_ = false;
invalidate_hashes_ = false;
return;
}
if (pending_.empty())
return;
sink_->AddVisitedLinks(pending_);
pending_.clear();
}
private:
bool reset_needed_;
bool invalidate_hashes_;
int render_process_id_;
mojom::VisitedLinkNotificationSinkPtr sink_;
VisitedLinkCommon::Fingerprints pending_;
};
VisitedLinkEventListener::VisitedLinkEventListener(
content::BrowserContext* browser_context)
: coalesce_timer_(&default_coalesce_timer_),
browser_context_(browser_context) {
registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_CREATED,
content::NotificationService::AllBrowserContextsAndSources());
registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_TERMINATED,
content::NotificationService::AllBrowserContextsAndSources());
registrar_.Add(this, content::NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
content::NotificationService::AllBrowserContextsAndSources());
}
VisitedLinkEventListener::~VisitedLinkEventListener() {
if (!pending_visited_links_.empty())
pending_visited_links_.clear();
}
void VisitedLinkEventListener::NewTable(
base::ReadOnlySharedMemoryRegion* table_region) {
DCHECK(table_region && table_region->IsValid());
table_region_ = table_region->Duplicate();
if (!table_region_.IsValid())
return;
// Send to all RenderProcessHosts.
for (Updaters::iterator i = updaters_.begin(); i != updaters_.end(); ++i) {
// Make sure to not send to incognito renderers.
content::RenderProcessHost* process =
content::RenderProcessHost::FromID(i->first);
if (!process)
continue;
i->second->SendVisitedLinkTable(&table_region_);
}
}
void VisitedLinkEventListener::Add(VisitedLinkMaster::Fingerprint fingerprint) {
pending_visited_links_.push_back(fingerprint);
if (!coalesce_timer_->IsRunning()) {
coalesce_timer_->Start(
FROM_HERE, TimeDelta::FromMilliseconds(kCommitIntervalMs),
base::Bind(&VisitedLinkEventListener::CommitVisitedLinks,
base::Unretained(this)));
}
}
void VisitedLinkEventListener::Reset(bool invalidate_hashes) {
pending_visited_links_.clear();
coalesce_timer_->Stop();
for (Updaters::iterator i = updaters_.begin(); i != updaters_.end(); ++i) {
i->second->AddReset(invalidate_hashes);
i->second->Update();
}
}
void VisitedLinkEventListener::SetCoalesceTimerForTest(
base::Timer* coalesce_timer_override) {
coalesce_timer_ = coalesce_timer_override;
}
void VisitedLinkEventListener::CommitVisitedLinks() {
// Send to all RenderProcessHosts.
for (Updaters::iterator i = updaters_.begin(); i != updaters_.end(); ++i) {
i->second->AddLinks(pending_visited_links_);
i->second->Update();
}
pending_visited_links_.clear();
}
void VisitedLinkEventListener::Observe(
int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
switch (type) {
case content::NOTIFICATION_RENDERER_PROCESS_CREATED: {
content::RenderProcessHost* process =
content::Source<content::RenderProcessHost>(source).ptr();
if (browser_context_ != process->GetBrowserContext())
return;
// Happens on browser start up.
if (!table_region_.IsValid())
return;
updaters_[process->GetID()].reset(
new VisitedLinkUpdater(process->GetID()));
updaters_[process->GetID()]->SendVisitedLinkTable(&table_region_);
break;
}
case content::NOTIFICATION_RENDERER_PROCESS_TERMINATED: {
content::RenderProcessHost* process =
content::Source<content::RenderProcessHost>(source).ptr();
if (updaters_.count(process->GetID())) {
updaters_.erase(process->GetID());
}
break;
}
case content::NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED: {
RenderWidgetHost* widget =
content::Source<RenderWidgetHost>(source).ptr();
int child_id = widget->GetProcess()->GetID();
if (updaters_.count(child_id))
updaters_[child_id]->Update();
break;
}
default:
NOTREACHED();
break;
}
}
} // namespace visitedlink
| 33.337607 | 80 | 0.720036 | [
"render"
] |
a39319ba3ffccc01ebdc126510a51b00d45c80e2 | 9,159 | cpp | C++ | tools/redis_to_kedis/src_redis_conn.cpp | jianqingdu/kedis | 97ac63d8d96c5cda69c878ef20f04eb8efb4b396 | [
"MIT"
] | 94 | 2017-11-30T03:17:58.000Z | 2022-03-29T13:43:07.000Z | tools/redis_to_kedis/src_redis_conn.cpp | flike/kedis | 97ac63d8d96c5cda69c878ef20f04eb8efb4b396 | [
"MIT"
] | 9 | 2017-12-11T03:12:31.000Z | 2020-04-20T13:04:00.000Z | tools/redis_to_kedis/src_redis_conn.cpp | jianqingdu/kedis | 97ac63d8d96c5cda69c878ef20f04eb8efb4b396 | [
"MIT"
] | 19 | 2017-12-01T17:22:15.000Z | 2022-01-10T01:39:39.000Z | //
// src_redis_conn.cpp
// kedis
//
// Created by ziteng on 17-11-20.
// Copyright (c) 2017年 mgj. All rights reserved.
//
#include "src_redis_conn.h"
#include "redis_parser.h"
#include "cmd_line_parser.h"
#include "sync_task.h"
#include "simple_log.h"
#include <ctype.h>
#include <algorithm>
using namespace std;
void SrcRedisConn::OnConfirm()
{
log_message(kLogLevelInfo, "connect to redis %s:%d success\n", m_peer_ip.c_str(), m_peer_port);
BaseConn::OnConfirm();
if (!g_config.src_redis_password.empty()) {
vector<string> cmd_vec = {"AUTH", g_config.src_redis_password};
string request;
build_request(cmd_vec, request);
Send((void*)request.data(), (int)request.size());
conn_state_ = CONN_STATE_AUTH;
} else {
vector<string> cmd_vec = {"SYNC"};
string request;
build_request(cmd_vec, request);
Send((void*)request.data(), (int)request.size());
conn_state_ = CONN_STATE_READ_RDB_LEN;
}
}
void SrcRedisConn::OnRead()
{
int write_offset = m_in_buf.GetWriteOffset();
_RecvData();
int recv_bytes = m_in_buf.GetWriteOffset() - write_offset;
// 处理redis协议需要按C语言以'\0'结尾的字符串处理,接收buf预留了至少1个字节来放'\0'
uchar_t* write_pos = m_in_buf.GetWriteBuffer();
write_pos[0] = 0;
if (conn_state_ == CONN_STATE_AUTH) {
_HandleAuth();
}
if (conn_state_ == CONN_STATE_READ_RDB_LEN) {
_ReadRdbLength();
}
if (conn_state_ == CONN_STATE_READ_RDB_DATA) {
_ReadRdbData();
_LimitRDBReceiveSpeed(recv_bytes);
}
if (conn_state_ == CONN_STATE_SYNC_CMD) {
_SyncWriteCommand();
}
m_in_buf.ResetOffset();
}
void SrcRedisConn::OnClose()
{
if (m_open) {
log_message(kLogLevelInfo, "connection to redis %s:%d broken\n", m_peer_ip.c_str(), m_peer_port);
} else {
log_message(kLogLevelInfo, "connect to redis %s:%d failed\n", m_peer_ip.c_str(), m_peer_port);
}
BaseConn::Close();
}
void SrcRedisConn::OnTimer(uint64_t curr_tick)
{
// if RDB sync finished wihout any more redis command, AOF sync task need to be triggered here
if (g_sync_rdb_finished) {
_CommitAofTask();
}
}
void SrcRedisConn::_LimitRDBReceiveSpeed(int recv_bytes)
{
uint64_t current_tick = get_tick_count();
if (current_tick >= start_tick_ + 1000) {
start_tick_ = current_tick;
recv_bytes_ = recv_bytes;
} else {
recv_bytes_ += recv_bytes;
if (recv_bytes_ > g_config.network_limit) {
uint32_t sleep_time = (uint32_t)(current_tick - start_tick_) * 1000;
log_message(kLogLevelInfo, "receive too fast, sleep %d microsecond\n", sleep_time);
usleep(sleep_time);
}
}
}
void SrcRedisConn::_HandleAuth()
{
RedisReply reply;
int ret = parse_redis_response((char*)m_in_buf.GetReadBuffer(), m_in_buf.GetReadableLen(), reply);
if (ret > 0) {
if ((reply.GetType() == REDIS_TYPE_STATUS) && (reply.GetStrValue() == "OK")) {
log_message(kLogLevelInfo, "Auth OK, continue\n");
m_in_buf.Read(NULL, ret);
vector<string> cmd_vec = {"SYNC"};
string request;
build_request(cmd_vec, request);
Send((void*)request.data(), (int)request.size());
conn_state_ = CONN_STATE_READ_RDB_LEN;
} else {
log_message(kLogLevelError, "Auth failed, exit\n");
exit(1);
}
} else if (ret < 0) {
log_message(kLogLevelError, "redis parse failed, exit\n");
exit(1);
}
}
void SrcRedisConn::_ReadRdbLength()
{
// SYNC command return format: $len\r\n rdb_data(len bytes)
char* redis_cmd = (char*)m_in_buf.GetReadBuffer();
int redis_len = m_in_buf.GetReadableLen();
if (redis_len < 3) {
return;
}
char* new_line = strstr(redis_cmd, "\r\n");
if (!new_line) {
return;
}
// Redis-Server may send multiple '\n' befor send $len\r\n
int dollar_pos = 0;
while ((redis_cmd[dollar_pos] != '$') && (redis_cmd + dollar_pos != new_line)) {
dollar_pos++;
}
if (redis_cmd[dollar_pos] != '$') {
log_message(kLogLevelError, "SYNC response without a $ exit: %s\n", redis_cmd);
exit(1);
}
long rdb_total_len = atol(redis_cmd + dollar_pos + 1);
int rdb_start_pos = (int)(new_line - redis_cmd) + 2;
m_in_buf.Read(NULL, rdb_start_pos);
log_message(kLogLevelInfo, "rdb_len=%ld\n", rdb_total_len);
rdb_remain_len_ = rdb_total_len;
conn_state_ = CONN_STATE_READ_RDB_DATA;
recv_bytes_ = 0;
start_tick_ = get_tick_count();
// write to file cause rdb file may be too large that can not reside in memory
rdb_file_ = fopen(g_config.rdb_file.c_str(), "wb");
if (!rdb_file_) {
log_message(kLogLevelError, "open file %s for write failed, exit\n", g_config.rdb_file.c_str());
exit(1);
}
}
void SrcRedisConn::_ReadRdbData()
{
char* rdb_data = (char*)m_in_buf.GetReadBuffer();
long rdb_len = m_in_buf.GetReadableLen();
if (rdb_len > rdb_remain_len_) {
rdb_len = rdb_remain_len_;
}
if (fwrite(rdb_data, 1, rdb_len, rdb_file_) != (size_t)rdb_len) {
log_message(kLogLevelError, "fwrite failed, exit\n");
exit(1);
}
rdb_remain_len_ -= rdb_len;
m_in_buf.Read(NULL, (uint32_t)rdb_len);
if (rdb_remain_len_ == 0) {
conn_state_ = CONN_STATE_SYNC_CMD;
fclose(rdb_file_);
rdb_file_ = NULL;
log_message(kLogLevelInfo, "read all rdb data\n");
SyncRdbTask* task = new SyncRdbTask;
g_thread_pool.AddTask(task);
}
}
void SrcRedisConn::_SyncWriteCommand()
{
while (true) {
vector<string> cmd_vec;
string err_msg;
int ret = parse_redis_request((char*)m_in_buf.GetReadBuffer(), m_in_buf.GetReadableLen(), cmd_vec, err_msg);
if (ret > 0) {
if (!cmd_vec.empty()) {
string& cmd = cmd_vec[0];
transform(cmd.begin(), cmd.end(), cmd.begin(), ::toupper);
req_buf = (char*)m_in_buf.GetReadBuffer();
req_len = ret;
_HandleRedisCommand(cmd_vec);
}
m_in_buf.Read(NULL, ret);
} else if (ret < 0) {
log_message(kLogLevelError, "parse redis failed: %s", err_msg.c_str());
OnClose();
break;
} else {
// not yet receive a whole command
break;
}
}
}
void SrcRedisConn::_RemoveKeyPrefix(string& key)
{
size_t pos = key.find(g_config.prefix);
if (pos != string::npos) {
key = key.substr(pos + g_config.prefix.size());
}
}
void SrcRedisConn::_CommitAofTask()
{
if (aof_file_) {
int cmd_len = 0;
fwrite(&cmd_len, 4, 1, aof_file_);
fclose(aof_file_);
aof_file_ = NULL;
SyncAofTask* task = new SyncAofTask;
g_thread_pool.AddTask(task);
}
}
void SrcRedisConn::_HandleRedisCommand(vector<string>& cmd_vec)
{
const string& cmd = cmd_vec[0];
if (cmd == "PING") {
;
} else if (cmd == "SELECT") {
cur_db_num_ = atoi(cmd_vec[1].c_str());
} else {
if ((g_config.src_redis_db == -1) || (g_config.src_redis_db == cur_db_num_)) {
string raw_cmd;
if (g_config.prefix.empty()) {
// do not need delete key prefix
raw_cmd.append(req_buf, req_len);
} else {
// delete key prefix
if ((cmd == "DEL") || (cmd == "MGET") || (cmd == "PFCOUNT")) {
int cmd_cnt = (int)cmd_vec.size();
for (int i = 1; i < cmd_cnt; ++i) {
_RemoveKeyPrefix(cmd_vec[i]);
}
} else if (cmd == "MSET") {
int cmd_cnt = (int)cmd_vec.size();
for (int i = 1; i < cmd_cnt; i += 2) {
_RemoveKeyPrefix(cmd_vec[i]);
}
} else {
_RemoveKeyPrefix(cmd_vec[1]);
}
build_request(cmd_vec, raw_cmd);
}
if (!g_sync_rdb_finished) {
if (!aof_file_) {
aof_file_ = fopen(g_config.aof_file.c_str(), "wb");
if (!aof_file_) {
log_message(kLogLevelError, "fopen aof file %s for write failed\n", g_config.aof_file.c_str());
exit(1);
}
}
int cmd_len = (int)raw_cmd.size();
fwrite(&cmd_len, 4, 1, aof_file_);
fwrite(raw_cmd.data(), 1, raw_cmd.size(), aof_file_);
} else {
_CommitAofTask();
SyncCmdTask* task = new SyncCmdTask(raw_cmd);
g_thread_pool.AddTask(task);
}
}
}
}
| 30.227723 | 119 | 0.559341 | [
"vector",
"transform"
] |
a395726bb428188e9f1f01c017ff8daf398c5f9a | 8,796 | cpp | C++ | liboh/plugins/js/JSVisibleData.cpp | sirikata/sirikata | 3a0d54a8c4778ad6e25ef031d461b2bc3e264860 | [
"BSD-3-Clause"
] | 31 | 2015-01-28T17:01:10.000Z | 2021-11-04T08:30:37.000Z | liboh/plugins/js/JSVisibleData.cpp | sirikata/sirikata | 3a0d54a8c4778ad6e25ef031d461b2bc3e264860 | [
"BSD-3-Clause"
] | null | null | null | liboh/plugins/js/JSVisibleData.cpp | sirikata/sirikata | 3a0d54a8c4778ad6e25ef031d461b2bc3e264860 | [
"BSD-3-Clause"
] | 9 | 2015-08-02T18:39:49.000Z | 2019-10-11T10:32:30.000Z | // Copyright (c) 2011 Sirikata Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can
// be found in the LICENSE file.
#include "JSVisibleData.hpp"
namespace Sirikata {
namespace JS {
JSVisibleData::~JSVisibleData()
{
}
void JSVisibleData::clearFromParent() {
// We're guaranteed by shared_ptrs and our reference counting that
// this destructor is only called once there are no more
// ProxyObjectPtrs and no v8 visibles referring to this data,
// allowing us to clear this out of the JSVisibleManager.
if (mParent) mParent->removeVisibleData(this);
}
void JSVisibleData::disable() {
mParent = NULL;
}
// JSProxyVisibleData
JSProxyVisibleData::JSProxyVisibleData(JSVisibleDataListener* parent, ProxyObjectPtr from)
: JSVisibleData(parent),
proxy(from)
{
proxy->PositionProvider::addListener(this);
proxy->MeshProvider::addListener(this);
}
JSProxyVisibleData::~JSProxyVisibleData() {
if (proxy) {
proxy->PositionProvider::removeListener(this);
proxy->MeshProvider::removeListener(this);
}
clearFromParent();
}
const SpaceObjectReference& JSProxyVisibleData::id() {
return proxy->getObjectReference();
}
const SpaceObjectReference& JSProxyVisibleData::observer() {
return proxy->getOwnerPresenceID();
}
void JSProxyVisibleData::disable() {
if (proxy) {
proxy->PositionProvider::removeListener(this);
proxy->MeshProvider::removeListener(this);
proxy.reset();
}
JSVisibleData::disable();
}
// PositionListener Interface
void JSProxyVisibleData::updateLocation(ProxyObjectPtr obj,
const TimedMotionVector3f &newLocation, const TimedMotionQuaternion& newOrient,
const AggregateBoundingInfo& newBounds, const SpaceObjectReference& sporef)
{
// FIXME this interface doesn't let us tell exactly what's updated, so we
// have to send notifications for everything
notify(&JSVisibleDataEventListener::visiblePositionChanged, this);
notify(&JSVisibleDataEventListener::visibleVelocityChanged, this);
notify(&JSVisibleDataEventListener::visibleOrientationChanged, this);
notify(&JSVisibleDataEventListener::visibleOrientationVelChanged, this);
// scale handled by MeshListener interface
}
// MeshListener Interface
void JSProxyVisibleData::onSetMesh(ProxyObjectPtr proxy, Transfer::URI const& newMesh, const SpaceObjectReference& sporef) {
notify(&JSVisibleDataEventListener::visibleMeshChanged, this);
}
void JSProxyVisibleData::onSetScale(ProxyObjectPtr proxy, float32 newScale,const SpaceObjectReference& sporef ) {
notify(&JSVisibleDataEventListener::visibleScaleChanged, this);
}
void JSProxyVisibleData::onSetPhysics(ProxyObjectPtr proxy, const String& phy,const SpaceObjectReference& sporef ) {
notify(&JSVisibleDataEventListener::visiblePhysicsChanged, this);
}
void JSProxyVisibleData::onSetIsAggregate(ProxyObjectPtr proxy, bool isAggregate, const SpaceObjectReference& sporef ) {
// Not exposed to VisibleDataEventListeners
}
// JSRestoredVisibleData
JSRestoredVisibleData::JSRestoredVisibleData(JSVisibleDataListener* parent, const SpaceObjectReference& from, JSVisibleDataPtr fromData)
: JSVisibleData(parent),
sporefToListenTo(from)
{
if (fromData) {
assert(from == fromData->id());
updateFrom(*fromData);
}
}
JSRestoredVisibleData::JSRestoredVisibleData(JSVisibleDataListener* parent, const SpaceObjectReference& from, const IPresencePropertiesRead& orig)
: JSVisibleData(parent),
sporefToListenTo(from)
{
updateFrom(orig);
}
JSRestoredVisibleData::~JSRestoredVisibleData() {
clearFromParent();
}
const SpaceObjectReference& JSRestoredVisibleData::id() {
return sporefToListenTo;
}
const SpaceObjectReference& JSRestoredVisibleData::observer() {
// No observer...
static SpaceObjectReference n = SpaceObjectReference::null();
return n;
}
void JSRestoredVisibleData::updateFrom(const IPresencePropertiesRead& orig) {
setLocation(orig.location());
setOrientation(orig.orientation());
setBounds(orig.bounds());
setMesh(orig.mesh());
setPhysics(orig.physics());
}
// JSAggregateVisibleData
JSAggregateVisibleData::JSAggregateVisibleData(JSVisibleDataListener* parent, const SpaceObjectReference& vis)
: JSVisibleData(parent),
refcount(0),
selfPtr(),
mBest(SpaceObjectReference::null())
{
// Note NULL so we don't get notifications since they'd only happen on
// destruction since we hold strong refs currently.
// We use null index to indicate no associated presence
mChildren[SpaceObjectReference::null()] =
JSVisibleDataPtr(new JSRestoredVisibleData(NULL, vis) );
}
JSAggregateVisibleData::~JSAggregateVisibleData() {
clearFromParent();
}
const SpaceObjectReference& JSAggregateVisibleData::id() {
return getBestChild()->id();
}
const SpaceObjectReference& JSAggregateVisibleData::observer() {
// Can't specify one observer...
static SpaceObjectReference n = SpaceObjectReference::null();
return n;
}
// IPresencePropertiesRead Interface
TimedMotionVector3f JSAggregateVisibleData::location() const{
return getBestChild()->location();
}
TimedMotionQuaternion JSAggregateVisibleData::orientation() const{
return getBestChild()->orientation();
}
AggregateBoundingInfo JSAggregateVisibleData::bounds() const{
return getBestChild()->bounds();
}
Transfer::URI JSAggregateVisibleData::mesh() const{
return getBestChild()->mesh();
}
String JSAggregateVisibleData::physics() const{
return getBestChild()->physics();
}
bool JSAggregateVisibleData::isAggregate() const{
return getBestChild()->isAggregate();
}
ObjectReference JSAggregateVisibleData::parent() const{
return getBestChild()->parent();
}
void JSAggregateVisibleData::removeVisibleData(JSVisibleData* data) {
Mutex::scoped_lock locker (childMutex);
mChildren.erase(data->observer());
}
void JSAggregateVisibleData::updateFrom(ProxyObjectPtr proxy) {
Mutex::scoped_lock locker (childMutex);
if (mChildren.find(proxy->getObjectReference()) == mChildren.end()) {
// Note that we currently pass in NULL so we don't get
// notifications. We'd only get them upon clearing our children list in
// the destructor anyway.
JSVisibleDataPtr jsvisdata(new JSProxyVisibleData(NULL, proxy));
jsvisdata->addListener(this); // JSVisibleDataEventListener
mChildren[proxy->getObjectReference()] = jsvisdata;
}
mBest = proxy->getObjectReference();
}
void JSAggregateVisibleData::updateFrom(const IPresencePropertiesRead& props) {
Mutex::scoped_lock locker (childMutex);
if (mChildren.find(SpaceObjectReference::null()) != mChildren.end()) {
std::tr1::dynamic_pointer_cast<JSRestoredVisibleData>(mChildren[SpaceObjectReference::null()])->updateFrom(props);
}
// We don't update mBest because either it's already this, or we have a
// Proxy, which is preferable.
}
JSVisibleDataPtr JSAggregateVisibleData::getBestChild() const{
Mutex::scoped_lock locker (const_cast<Mutex&>(childMutex));
assert(!mChildren.empty());
assert(mChildren.find(mBest) != mChildren.end());
return mChildren.find(mBest)->second;
}
void JSAggregateVisibleData::incref(JSVisibleDataPtr self) {
selfPtr = self;
refcount++;
}
void JSAggregateVisibleData::decref() {
assert(refcount > 0);
refcount--;
if (refcount == 0) selfPtr.reset();
}
bool JSAggregateVisibleData::visibleToPresence() const {
return refcount > 0;
}
void JSAggregateVisibleData::disable() {
Mutex::scoped_lock locker (childMutex);
mChildren.clear();
JSVisibleData::disable();
}
void JSAggregateVisibleData::visiblePositionChanged(JSVisibleData* data) {
notify(&JSVisibleDataEventListener::visiblePositionChanged, this);
}
void JSAggregateVisibleData::visibleVelocityChanged(JSVisibleData* data) {
notify(&JSVisibleDataEventListener::visibleVelocityChanged, this);
}
void JSAggregateVisibleData::visibleOrientationChanged(JSVisibleData* data) {
notify(&JSVisibleDataEventListener::visibleOrientationChanged, this);
}
void JSAggregateVisibleData::visibleOrientationVelChanged(JSVisibleData* data) {
notify(&JSVisibleDataEventListener::visibleOrientationVelChanged, this);
}
void JSAggregateVisibleData::visibleScaleChanged(JSVisibleData* data) {
notify(&JSVisibleDataEventListener::visibleScaleChanged, this);
}
void JSAggregateVisibleData::visibleMeshChanged(JSVisibleData* data) {
notify(&JSVisibleDataEventListener::visibleMeshChanged, this);
}
void JSAggregateVisibleData::visiblePhysicsChanged(JSVisibleData* data) {
notify(&JSVisibleDataEventListener::visiblePhysicsChanged, this);
}
} // namespace JS
} // namespace Sirikata
| 31.869565 | 146 | 0.754206 | [
"mesh"
] |
a395ad12dc2f4f027de0848da07ec57710594ad7 | 1,853 | hpp | C++ | src/mlpack/methods/ann/visitor/load_output_parameter_visitor_impl.hpp | abinezer/mlpack | 8002e49150742acea4e76deef8161653b8350936 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2019-11-07T14:34:37.000Z | 2019-11-07T14:34:37.000Z | src/mlpack/methods/ann/visitor/load_output_parameter_visitor_impl.hpp | 876arham/mlpack | 1379831e578037c9d0ed3a1683ce76e3d1c8247e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2020-04-10T17:39:50.000Z | 2020-04-11T14:56:25.000Z | src/mlpack/methods/ann/visitor/load_output_parameter_visitor_impl.hpp | 876arham/mlpack | 1379831e578037c9d0ed3a1683ce76e3d1c8247e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | /**
* @file load_output_parameter_visitor_impl.hpp
* @author Marcus Edel
*
* Implementation of the OutputParameter() function layer abstraction.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_METHODS_ANN_VISITOR_LOAD_OUTPUT_PARAMETER_VISITOR_IMPL_HPP
#define MLPACK_METHODS_ANN_VISITOR_LOAD_OUTPUT_PARAMETER_VISITOR_IMPL_HPP
// In case it hasn't been included yet.
#include "load_output_parameter_visitor.hpp"
namespace mlpack {
namespace ann {
//! LoadOutputParameterVisitor visitor class.
inline LoadOutputParameterVisitor::LoadOutputParameterVisitor(
std::vector<arma::mat>& parameter) : parameter(parameter)
{
/* Nothing to do here. */
}
template<typename LayerType>
inline void LoadOutputParameterVisitor::operator()(LayerType* layer) const
{
OutputParameter(layer);
}
inline void LoadOutputParameterVisitor::operator()(MoreTypes layer) const
{
layer.apply_visitor(*this);
}
template<typename T>
inline typename std::enable_if<
!HasModelCheck<T>::value, void>::type
LoadOutputParameterVisitor::OutputParameter(T* layer) const
{
layer->OutputParameter() = parameter.back();
parameter.pop_back();
}
template<typename T>
inline typename std::enable_if<
HasModelCheck<T>::value, void>::type
LoadOutputParameterVisitor::OutputParameter(T* layer) const
{
for (size_t i = 0; i < layer->Model().size(); ++i)
{
boost::apply_visitor(LoadOutputParameterVisitor(parameter),
layer->Model()[layer->Model().size() - i - 1]);
}
layer->OutputParameter() = parameter.back();
parameter.pop_back();
}
} // namespace ann
} // namespace mlpack
#endif
| 27.656716 | 78 | 0.752833 | [
"vector",
"model"
] |
a39663d4cbaacebcce1d4f0c0d9d7c8dc09e61d8 | 11,734 | cpp | C++ | geometrictools/libgeometrictools.cpp | eth-sri/transformation-smoothing | 12a653e881a6d61c5c63a3e16d58292435486cbd | [
"Apache-2.0"
] | 3 | 2020-11-07T18:12:50.000Z | 2021-06-11T22:56:09.000Z | geometrictools/libgeometrictools.cpp | eth-sri/transformation-smoothing | 12a653e881a6d61c5c63a3e16d58292435486cbd | [
"Apache-2.0"
] | null | null | null | geometrictools/libgeometrictools.cpp | eth-sri/transformation-smoothing | 12a653e881a6d61c5c63a3e16d58292435486cbd | [
"Apache-2.0"
] | null | null | null | #include "libgeometrictools.h"
#include "gpu/gpu.h"
void initGeometricTools() {
initGPU();
}
bool calc(const arg_t& args,
const Image& img,
const HyperBox& gamma,
const float *filter,
vector<float>& out_epsilons) {
assert(gamma.it[0].sup - gamma.it[0].inf > Constants::EPS);
const size_t batch_size = (img.isGPU()) ? args.batch_size : 1;
size_t dims = 0;
if (args.transform == Transform::rotation) dims = 1;
else if (args.transform == Transform::translation) dims = 2;
else assert(false);
Image imgGamma;
Image imgOrig;
bool isEmpty = false;
const size_t M = args.betas[0].size();
//compute inverse
if (args.inv) {
if (args.debug) cout << "start inverse" << endl << flush;
if (args.transform == Transform::rotation) {
imgOrig = img.inverseRotation(gamma.it[0], isEmpty, args.refinements, args.doInt, args.doInt);
}
else if (args.transform == Transform::translation) {
imgOrig = img.inverseTranslation(gamma.it[0], gamma.it[1], isEmpty, args.refinements, args.doInt, args.doInt);
}
imgGamma = img;
if (args.debug) cout << "done inverse; empty: " << isEmpty << endl << flush;
if (isEmpty) {
for(size_t k = 0; k < M; ++k) {
out_epsilons.push_back(0);
}
return true;
}
} else {
imgOrig = img;
if (args.transform == Transform::rotation) {
assert(img.img);
assert(imgOrig.img);
imgGamma = imgOrig.rotate(gamma.it[0], args.doInt);
}
else if (args.transform == Transform::translation)
imgGamma = imgOrig.translate(gamma.it[0], gamma.it[1], args.doInt);
}
const size_t nChannels = img.nChannels();
const size_t N = ceil(((double)M) / batch_size); // number of loop passes
for (size_t k = 0; k < N; ++k) {
vector<vector<float>> beta_batch(dims);
vector<vector<Interval>> beta_gamma_batch(dims);
vector<float> epsilon_batch;
for(size_t j = 0; j < batch_size; ++j) {
const size_t m = k + j * N;
if (m < M) {
for(size_t dim = 0; dim < dims; ++dim) {
beta_batch[dim].push_back(args.betas[dim][m]);
beta_gamma_batch[dim].push_back(gamma.it[dim] + args.betas[dim][m]);
}
}
}
const size_t B = beta_batch[0].size();
if (args.debug) cout << "start transform" << endl << flush;
Image transformed_gamma_transformed_beta_processed, transformed_gamma_beta_processed;
if (args.transform == Transform::rotation) {
transformed_gamma_transformed_beta_processed = imgGamma.rotate(beta_batch[0], args.doInt);
transformed_gamma_beta_processed = imgOrig.rotate(beta_gamma_batch[0], args.doInt);
}
else if (args.transform == Transform::translation) {
transformed_gamma_transformed_beta_processed = imgGamma.translate(beta_batch[0], beta_batch[1], args.doInt);
transformed_gamma_transformed_beta_processed = transformed_gamma_transformed_beta_processed.rect_vignetting((int)args.radiusDecrease);
transformed_gamma_beta_processed = imgOrig.translate(beta_gamma_batch[0], beta_gamma_batch[1], args.doInt);
transformed_gamma_beta_processed = transformed_gamma_beta_processed.rect_vignetting((int)args.radiusDecrease);
}
if (args.debug) cout << "done transform" << endl << flush;
assert(transformed_gamma_transformed_beta_processed.nChannels() == nChannels * B);
assert(transformed_gamma_beta_processed.nChannels() == nChannels * B);
if (args.resize_postTransform > 0 || args.center_crop_postTranform > 0) {
if (args.debug) cout << "start post" << endl << flush;
transformed_gamma_transformed_beta_processed = transformed_gamma_transformed_beta_processed.resize(args.resize_postTransform, args.doInt, args.center_crop_postTranform);
transformed_gamma_beta_processed = transformed_gamma_beta_processed.resize(args.resize_postTransform, args.doInt, args.center_crop_postTranform);
if (args.debug) cout << "done post" << endl << flush;
}
assert(transformed_gamma_transformed_beta_processed.nChannels() == nChannels * B);
assert(transformed_gamma_beta_processed.nChannels() == nChannels * B);
if (args.debug) {
transformed_gamma_transformed_beta_processed.to_cpu().channels(0, nChannels).saveBMP("transformed_gamma_transformed_beta_post_resize_inf.bmp", true);
transformed_gamma_transformed_beta_processed.to_cpu().channels(0, nChannels).saveBMP("transformed_gamma_transformed_beta_post_resize_sup.bmp", false);
}
if (args.debug) cout << "start norm 123" << endl << flush;
epsilon_batch = transformed_gamma_transformed_beta_processed.filterVignettingL2diffC(transformed_gamma_beta_processed,
filter,
args.filter_size,
(args.transform == Transform::rotation) ? args.radiusDecrease : -1,
nChannels);
out_epsilons.insert(out_epsilons.end(),epsilon_batch.begin(),epsilon_batch.end());
if (args.debug) cout << "done norm" << endl << flush;
}
assert(out_epsilons.size() == M);
return false;
}
void process_initial_split(const arg_t& args,
split_t& split_,
Image& image,
Statistics& stats,
vector<split_t>& out_subsplits) {
out_subsplits.push_back(split_);
}
void process_split(const arg_t& args,
split_t& split_,
Image& image,
float* filter,
Statistics& stats,
vector<split_t>& out_subsplits) {
const float prevMaxErr = get<0>(split_);
vector<float> prevErr = get<1>(split_);
HyperBox split = get<2>(split_);
if (args.debug) cout << "Split " << split << " came from interval with error " << prevMaxErr;
bool atRefinementLimit = false;
// if the split is smaller than the minimum size (this can happen after refining at the borders)
// make it large enough (but only once -- in order to avoid infinite refinements)
if (split.anyDimBelow(Constants::EPS)) {
if (args.debug) cout << " as it is currently smaller than the minimum it is reshaped into ";
for(size_t d = 0; d < split.dim; ++d) {
Interval it = split.it[d];
float upper = it.sup;
float k = 0.25f;
while(upper - it.inf <= Constants::EPS) {upper = it.sup + k * Constants::EPS; k*=2;}
split.it[d] = Interval(it.inf, upper);
atRefinementLimit = true;
}
if (args.debug) cout << split << " ";
}
// now all dimensions of the split are eat least the minimum size
assert(!split.anyDimBelow(Constants::EPS));
// compute error
vector<float> epsilons;
bool isEmpty = calc(args, image, split, filter, epsilons);
// update statistics and add new splits
if (isEmpty) {
stats.add_area(split.area());
} else {
float maxErr = *max_element(epsilons.begin(), epsilons.end());
if (args.debug) cout << " has err " << maxErr;
if (maxErr <= stats.get_targetErr() || atRefinementLimit ) { // no further refinement
if (args.debug) cout << "-> done" << endl << flush;
stats.add_area(split.area());
stats.update_maxParam(split);
stats.update_err(epsilons);
if (atRefinementLimit) stats.update_targetErr(maxErr);
} else { // refinement
if (args.debug) cout << "and will be refined into: ";
float current = split.maxDim();
float next = (current + Constants::EPS) / 4.0f;
size_t s = ceilf(current/next);
vector<HyperBox>subsplits = split.split(s);
for(HyperBox b : subsplits) out_subsplits.push_back({maxErr, epsilons, b});
}
}
}
tuple<vector<float>,
vector<float>> getE(const arg_t& args) {
// check input
size_t dims = 0;
switch(args.transform) {
case Transform::rotation: dims = 1; break;
case Transform::translation: dims = 2; break;
default: assert(false);
}
assert(args.betas.size() == dims); // we have dims x n args.betas
assert(args.betas.size() > 0);
size_t n = args.betas[0].size();
for(auto b : args.betas) assert(b.size() == n);
// create images and filters for each thread
vector<Image> images(args.threads);
vector<float*> filters(args.threads);
int numGPUs = 0;
if (args.gpu) {
cudaGetDeviceCount(&numGPUs);
}
for(size_t k = 0; k < args.threads; ++k) {
if (args.gpu) {
images[k] = args.img.to_gpu(k % numGPUs);
} else {
images[k] = args.img;
}
if (args.filter_sigma > 0) {
filters[k] = images[k].getFilter(args.filter_sigma, args.filter_size);
} else {
filters[k] = 0;
}
}
if(args.debug) cout.precision(22);
Statistics stats(args);
auto comp = [] (split_t &a, split_t &b) -> bool {
const float errA = get<0>(a);
const float errB = get<0>(b);
return errA < errB; //return True if a < b
};
priority_queue<split_t,
vector<split_t>,
decltype(comp)> splits(comp);
vector<HyperBox> initialSplits_ = args.params.split(args.initialSplits);
//assert(initialSplits_.size() == args.initialSplits); args.initialSplits^nDims
vector<split_t> initialSplits;
for(HyperBox s : initialSplits_) initialSplits.push_back({numeric_limits<float>::infinity(), {}, s});
mutex mtx_splits;
// define worker threads
auto worker = [&](const size_t tid) {
split_t split;
while(stats.running()){
bool hasWork = false;
mtx_splits.lock();
if (stats.is_initial()) {
hasWork = !initialSplits.empty();
if (hasWork) {
split = initialSplits.back();
initialSplits.pop_back();
}
}
else {
hasWork = !splits.empty();
if (hasWork) {
split = splits.top();
splits.pop();
}
}
mtx_splits.unlock();
if (hasWork) {
vector<split_t> subsplits;
if (stats.is_initial()){
process_initial_split(args, split, images[tid], stats, subsplits);
stats.initial_split_done();
} else {
process_split(args, split, images[tid], filters[tid], stats, subsplits);
stats.split_done();
}
// add subsplits
mtx_splits.lock();
for (auto b : subsplits) splits.push(b);
mtx_splits.unlock();
stats.add_split_count(subsplits.size());
stats.update_status();
} else {
this_thread::sleep_for(chrono::milliseconds(200));
}
}
};
// start worker thread
vector<thread> workers(args.threads);
for (size_t k = 0; k < args.threads; ++k){
workers[k] = thread(worker, k);
}
// monitor threads
while(stats.running()) {
this_thread::sleep_for(chrono::milliseconds(200));
const float maxSplitErr = get<0>(splits.top());
stats.update_status(); // by also calling this here we make sure that the timeout is enforced
if (!args.debug) stats.update_progressbar(maxSplitErr);
}
stats.update_progressbar(0);
for (size_t k = 0; k < args.threads; ++k){
workers[k].join();
}
vector<float> err = stats.get_err();
vector<float> maxParam = stats.get_maxParam();
while(!splits.empty()) {
vector<float> splitErr = get<1>(splits.top());
splits.pop();
for(size_t u = 0; u < err.size(); ++u) {
err[u] = max(err[u], splitErr[u]);
}
}
return {err, maxParam};
}
| 36.783699 | 175 | 0.614454 | [
"vector",
"transform"
] |
a39ae1e8b32813badde3e26c6886315854eba138 | 12,155 | cpp | C++ | modules/sksg/samples/SampleSVGPong.cpp | marxin/skia | 5da7327358e3b8d0c14c2bd2c9ec44072da79e1a | [
"BSD-3-Clause"
] | null | null | null | modules/sksg/samples/SampleSVGPong.cpp | marxin/skia | 5da7327358e3b8d0c14c2bd2c9ec44072da79e1a | [
"BSD-3-Clause"
] | null | null | null | modules/sksg/samples/SampleSVGPong.cpp | marxin/skia | 5da7327358e3b8d0c14c2bd2c9ec44072da79e1a | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "include/core/SkCanvas.h"
#include "include/core/SkPathBuilder.h"
#include "include/core/SkRRect.h"
#include "include/utils/SkRandom.h"
#include "samplecode/Sample.h"
#include "tools/timer/TimeUtils.h"
#include "modules/sksg/include/SkSGDraw.h"
#include "modules/sksg/include/SkSGGroup.h"
#include "modules/sksg/include/SkSGInvalidationController.h"
#include "modules/sksg/include/SkSGPaint.h"
#include "modules/sksg/include/SkSGPath.h"
#include "modules/sksg/include/SkSGRect.h"
#include "modules/sksg/include/SkSGScene.h"
#include "modules/sksg/include/SkSGTransform.h"
namespace {
static const SkRect kBounds = SkRect::MakeLTRB(0.1f, 0.1f, 0.9f, 0.9f);
static const SkSize kPaddleSize = SkSize::Make(0.03f, 0.1f);
static const SkScalar kBallSize = 0.04f;
static const SkScalar kShadowOpacity = 0.40f;
static const SkScalar kShadowParallax = 0.04f;
static const SkScalar kBackgroundStroke = 0.01f;
static const uint32_t kBackgroundDashCount = 20;
static const SkScalar kBallSpeedMax = 0.0020f;
static const SkScalar kBallSpeedMin = 0.0005f;
static const SkScalar kBallSpeedFuzz = 0.0002f;
static const SkScalar kTimeScaleMin = 0.0f;
static const SkScalar kTimeScaleMax = 5.0f;
// Box the value within [min, max), by applying infinite reflection on the interval endpoints.
SkScalar box_reflect(SkScalar v, SkScalar min, SkScalar max) {
const SkScalar intervalLen = max - min;
SkASSERT(intervalLen > 0);
// f(v) is periodic in 2 * intervalLen: one normal progression + one reflection
const SkScalar P = intervalLen * 2;
// relative to P origin
const SkScalar vP = v - min;
// map to [0, P)
const SkScalar vMod = (vP < 0) ? P - SkScalarMod(-vP, P) : SkScalarMod(vP, P);
// reflect if needed, to map to [0, intervalLen)
const SkScalar vInterval = vMod < intervalLen ? vMod : P - vMod;
// finally, reposition relative to min
return vInterval + min;
}
// Compute <t, y> for the trajectory intersection with the next vertical edge.
std::tuple<SkScalar, SkScalar> find_yintercept(const SkPoint& pos, const SkVector& spd,
const SkRect& box) {
const SkScalar edge = spd.fX > 0 ? box.fRight : box.fLeft;
const SkScalar t = (edge - pos.fX) / spd.fX;
SkASSERT(t >= 0);
const SkScalar dY = t * spd.fY;
return std::make_tuple(t, box_reflect(pos.fY + dY, box.fTop, box.fBottom));
}
void update_pos(const sk_sp<sksg::RRect>& rr, const SkPoint& pos) {
// TODO: position setters on RRect?
const auto r = rr->getRRect().rect();
const auto offsetX = pos.x() - r.x(),
offsetY = pos.y() - r.y();
rr->setRRect(rr->getRRect().makeOffset(offsetX, offsetY));
}
} // namespace
class PongView final : public Sample {
public:
PongView() = default;
protected:
void onOnceBeforeDraw() override {
const SkRect fieldBounds = kBounds.makeOutset(kBallSize / 2, kBallSize / 2);
const SkRRect ball = SkRRect::MakeOval(SkRect::MakeWH(kBallSize, kBallSize));
const SkRRect paddle = SkRRect::MakeRectXY(SkRect::MakeWH(kPaddleSize.width(),
kPaddleSize.height()),
kPaddleSize.width() / 2,
kPaddleSize.width() / 2);
fBall.initialize(ball,
SkPoint::Make(kBounds.centerX(), kBounds.centerY()),
SkVector::Make(fRand.nextRangeScalar(kBallSpeedMin, kBallSpeedMax),
fRand.nextRangeScalar(kBallSpeedMin, kBallSpeedMax)));
fPaddle0.initialize(paddle,
SkPoint::Make(fieldBounds.left() - kPaddleSize.width() / 2,
fieldBounds.centerY()),
SkVector::Make(0, 0));
fPaddle1.initialize(paddle,
SkPoint::Make(fieldBounds.right() + kPaddleSize.width() / 2,
fieldBounds.centerY()),
SkVector::Make(0, 0));
// Background decoration.
SkPathBuilder bgPath;
bgPath.moveTo(kBounds.left() , fieldBounds.top())
.lineTo(kBounds.right(), fieldBounds.top())
.moveTo(kBounds.left() , fieldBounds.bottom())
.lineTo(kBounds.right(), fieldBounds.bottom());
// TODO: stroke-dash support would come in handy right about now.
for (uint32_t i = 0; i < kBackgroundDashCount; ++i) {
bgPath.moveTo(kBounds.centerX(),
kBounds.top() + (i + 0.25f) * kBounds.height() / kBackgroundDashCount)
.lineTo(kBounds.centerX(),
kBounds.top() + (i + 0.75f) * kBounds.height() / kBackgroundDashCount);
}
auto bg_path = sksg::Path::Make(bgPath.detach());
auto bg_paint = sksg::Color::Make(SK_ColorBLACK);
bg_paint->setStyle(SkPaint::kStroke_Style);
bg_paint->setStrokeWidth(kBackgroundStroke);
auto ball_paint = sksg::Color::Make(SK_ColorGREEN),
paddle0_paint = sksg::Color::Make(SK_ColorBLUE),
paddle1_paint = sksg::Color::Make(SK_ColorRED),
shadow_paint = sksg::Color::Make(SK_ColorBLACK);
ball_paint->setAntiAlias(true);
paddle0_paint->setAntiAlias(true);
paddle1_paint->setAntiAlias(true);
shadow_paint->setAntiAlias(true);
shadow_paint->setOpacity(kShadowOpacity);
// Build the scene graph.
auto group = sksg::Group::Make();
group->addChild(sksg::Draw::Make(std::move(bg_path), std::move(bg_paint)));
group->addChild(sksg::Draw::Make(fPaddle0.shadowNode, shadow_paint));
group->addChild(sksg::Draw::Make(fPaddle1.shadowNode, shadow_paint));
group->addChild(sksg::Draw::Make(fBall.shadowNode, shadow_paint));
group->addChild(sksg::Draw::Make(fPaddle0.objectNode, paddle0_paint));
group->addChild(sksg::Draw::Make(fPaddle1.objectNode, paddle1_paint));
group->addChild(sksg::Draw::Make(fBall.objectNode, ball_paint));
// Handle everything in a normalized 1x1 space.
fContentMatrix = sksg::Matrix<SkMatrix>::Make(
SkMatrix::MakeRectToRect(SkRect::MakeWH(1, 1),
SkRect::MakeIWH(this->width(), this->height()),
SkMatrix::kFill_ScaleToFit));
auto root = sksg::TransformEffect::Make(std::move(group), fContentMatrix);
fScene = sksg::Scene::Make(std::move(root));
// Off we go.
this->updatePaddleStrategy();
}
SkString name() override { return SkString("SGPong"); }
bool onChar(SkUnichar uni) override {
switch (uni) {
case '[':
fTimeScale = SkTPin(fTimeScale - 0.1f, kTimeScaleMin, kTimeScaleMax);
return true;
case ']':
fTimeScale = SkTPin(fTimeScale + 0.1f, kTimeScaleMin, kTimeScaleMax);
return true;
case 'I':
fShowInval = !fShowInval;
return true;
default:
break;
}
return false;
}
void onSizeChange() override {
if (fContentMatrix) {
fContentMatrix->setMatrix(SkMatrix::MakeRectToRect(SkRect::MakeWH(1, 1),
SkRect::MakeIWH(this->width(),
this->height()),
SkMatrix::kFill_ScaleToFit));
}
this->INHERITED::onSizeChange();
}
void onDrawContent(SkCanvas* canvas) override {
sksg::InvalidationController ic;
fScene->render(canvas);
if (fShowInval) {
SkPaint fill, stroke;
fill.setAntiAlias(true);
fill.setColor(0x40ff0000);
stroke.setAntiAlias(true);
stroke.setColor(0xffff0000);
stroke.setStyle(SkPaint::kStroke_Style);
for (const auto& r : ic) {
canvas->drawRect(r, fill);
canvas->drawRect(r, stroke);
}
}
}
bool onAnimate(double nanos) override {
// onAnimate may fire before the first draw.
if (fScene) {
SkScalar dt = (TimeUtils::NanosToMSec(nanos) - fLastTick) * fTimeScale;
fLastTick = TimeUtils::NanosToMSec(nanos);
fPaddle0.posTick(dt);
fPaddle1.posTick(dt);
fBall.posTick(dt);
this->enforceConstraints();
fPaddle0.updateDom();
fPaddle1.updateDom();
fBall.updateDom();
}
return true;
}
private:
struct Object {
void initialize(const SkRRect& rrect, const SkPoint& p, const SkVector& s) {
objectNode = sksg::RRect::Make(rrect);
shadowNode = sksg::RRect::Make(rrect);
pos = p;
spd = s;
size = SkSize::Make(rrect.width(), rrect.height());
}
void posTick(SkScalar dt) {
pos += spd * dt;
}
void updateDom() {
const SkPoint corner = pos - SkPoint::Make(size.width() / 2, size.height() / 2);
update_pos(objectNode, corner);
// Simulate parallax shadow for a centered light source.
SkPoint shadowOffset = pos - SkPoint::Make(kBounds.centerX(), kBounds.centerY());
shadowOffset.scale(kShadowParallax);
const SkPoint shadowCorner = corner + shadowOffset;
update_pos(shadowNode, shadowCorner);
}
sk_sp<sksg::RRect> objectNode,
shadowNode;
SkPoint pos;
SkVector spd;
SkSize size;
};
void enforceConstraints() {
// Perfect vertical reflection.
if (fBall.pos.fY < kBounds.fTop || fBall.pos.fY >= kBounds.fBottom) {
fBall.spd.fY = -fBall.spd.fY;
fBall.pos.fY = box_reflect(fBall.pos.fY, kBounds.fTop, kBounds.fBottom);
}
// Horizontal bounce - introduces a speed fuzz.
if (fBall.pos.fX < kBounds.fLeft || fBall.pos.fX >= kBounds.fRight) {
fBall.spd.fX = this->fuzzBallSpeed(-fBall.spd.fX);
fBall.spd.fY = this->fuzzBallSpeed(fBall.spd.fY);
fBall.pos.fX = box_reflect(fBall.pos.fX, kBounds.fLeft, kBounds.fRight);
this->updatePaddleStrategy();
}
}
SkScalar fuzzBallSpeed(SkScalar spd) {
// The speed limits are absolute values.
const SkScalar sign = spd >= 0 ? 1.0f : -1.0f;
const SkScalar fuzzed = fabs(spd) + fRand.nextRangeScalar(-kBallSpeedFuzz, kBallSpeedFuzz);
return sign * SkTPin(fuzzed, kBallSpeedMin, kBallSpeedMax);
}
void updatePaddleStrategy() {
Object* pitcher = fBall.spd.fX > 0 ? &fPaddle0 : &fPaddle1;
Object* catcher = fBall.spd.fX > 0 ? &fPaddle1 : &fPaddle0;
SkScalar t, yIntercept;
std::tie(t, yIntercept) = find_yintercept(fBall.pos, fBall.spd, kBounds);
// The pitcher aims for a neutral/centered position.
pitcher->spd.fY = (kBounds.centerY() - pitcher->pos.fY) / t;
// The catcher goes for the ball. Duh.
catcher->spd.fY = (yIntercept - catcher->pos.fY) / t;
}
std::unique_ptr<sksg::Scene> fScene;
sk_sp<sksg::Matrix<SkMatrix>> fContentMatrix;
Object fPaddle0, fPaddle1, fBall;
SkRandom fRand;
SkMSec fLastTick = 0;
SkScalar fTimeScale = 1.0f;
bool fShowInval = false;
typedef Sample INHERITED;
};
DEF_SAMPLE( return new PongView(); )
| 39.33657 | 99 | 0.57573 | [
"render",
"object"
] |
a39b797b74190672bf3b4fc1f3f798ea09654967 | 2,337 | hpp | C++ | src/core/g_maps.hpp | dmlerner/win-vind | f5c25bc0e082b9600ef19c02ba4f565bc3b14cfe | [
"MIT"
] | null | null | null | src/core/g_maps.hpp | dmlerner/win-vind | f5c25bc0e082b9600ef19c02ba4f565bc3b14cfe | [
"MIT"
] | null | null | null | src/core/g_maps.hpp | dmlerner/win-vind | f5c25bc0e082b9600ef19c02ba4f565bc3b14cfe | [
"MIT"
] | null | null | null | #ifndef _G_MAPS_HPP
#define _G_MAPS_HPP
#include "defs.hpp"
#include "mode.hpp"
#include <memory>
namespace vind
{
namespace core
{
enum class MapType : unsigned char {
UNDEFINED = 0b0000'0000,
MAP = 0b0001'0000,
NOREMAP = 0b0010'0000,
NOREMAP_FUNCTION = 0b0010'0001,
} ;
class MapCell {
private:
struct Impl ;
std::shared_ptr<Impl> pimpl ;
public:
MapCell() ;
explicit MapCell(
const std::string& in,
const std::string& out,
MapType expect_type,
bool check_if_func=false) ;
bool is_noremap() const noexcept ;
bool is_noremap_function() const noexcept ;
bool is_map() const noexcept ;
const Command& trigger_command() const noexcept ;
const std::string& trigger_command_string() const noexcept ;
const Command& target_command() const ;
const std::string& target_command_string() const noexcept ;
bool empty() const noexcept ;
std::size_t in_hash() const ;
std::size_t out_hash() const ;
static std::size_t compute_hash(const std::string& strcmd) ;
static std::size_t compute_hash(const Command& cmd) ;
bool operator==(MapCell&& rhs) const ;
bool operator==(const MapCell& rhs) const ;
bool operator!=(MapCell&& rhs) const ;
bool operator!=(const MapCell& rhs) const ;
} ;
void initialize_maps() ;
void reset_all_maps() ;
void do_map(
const std::string& incmd,
const std::string& outcmd,
Mode mode) ;
void do_noremap(
const std::string& incmd,
const std::string& outcmd,
Mode mode) ;
void do_unmap(
const std::string& incmd,
Mode mode) ;
void do_mapclear(Mode mode) ;
MapCell get_map(
const std::string& cmd,
Mode mode) ;
void get_maps(
Mode mode,
std::vector<MapCell>& returns) ;
}
}
#endif
| 26.862069 | 72 | 0.507488 | [
"vector"
] |
a39e7bc1d166df006e777cb4432ac205af377e68 | 11,936 | cpp | C++ | crogine/src/ecs/components/Transform.cpp | fallahn/crogine | f6cf3ade1f4e5de610d52e562bf43e852344bca0 | [
"FTL",
"Zlib"
] | 41 | 2017-08-29T12:14:36.000Z | 2022-02-04T23:49:48.000Z | crogine/src/ecs/components/Transform.cpp | fallahn/crogine | f6cf3ade1f4e5de610d52e562bf43e852344bca0 | [
"FTL",
"Zlib"
] | 11 | 2017-09-02T15:32:45.000Z | 2021-12-27T13:34:56.000Z | crogine/src/ecs/components/Transform.cpp | fallahn/crogine | f6cf3ade1f4e5de610d52e562bf43e852344bca0 | [
"FTL",
"Zlib"
] | 5 | 2020-01-25T17:51:45.000Z | 2022-03-01T05:20:30.000Z | /*-----------------------------------------------------------------------
Matt Marchant 2017 - 2020
http://trederia.blogspot.com
crogine - Zlib license.
This software is provided 'as-is', without any express or
implied warranty.In no event will the authors be held
liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute
it freely, subject to the following restrictions :
1. The origin of this software must not be misrepresented;
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but
is not required.
2. Altered source versions must be plainly marked as such,
and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any
source distribution.
-----------------------------------------------------------------------*/
#include <crogine/ecs/components/Transform.hpp>
#include <crogine/detail/glm/gtx/euler_angles.hpp>
#include <crogine/detail/glm/gtx/quaternion.hpp>
#include <crogine/detail/glm/gtx/matrix_decompose.hpp>
#include <crogine/detail/glm/gtc/matrix_transform.hpp>
#include <crogine/detail/glm/gtc/matrix_access.hpp>
using namespace cro;
Transform::Transform()
: m_origin (0.f, 0.f, 0.f),
m_position (0.f, 0.f, 0.f),
m_scale (1.f, 1.f, 1.f),
m_rotation (1.f, 0.f, 0.f, 0.f),
m_transform (1.f),
m_parent (nullptr),
m_depth (0),
m_dirtyFlags (0)
{
}
Transform::Transform(Transform&& other) noexcept
: m_origin (0.f, 0.f, 0.f),
m_position (0.f, 0.f, 0.f),
m_scale (1.f, 1.f, 1.f),
m_rotation (1.f, 0.f, 0.f, 0.f),
m_transform (1.f),
m_parent (nullptr),
m_depth (0),
m_dirtyFlags (0)
{
CRO_ASSERT(other.m_parent != this, "Invalid assignment");
if (other.m_parent != this)
{
//orphan any children
for (auto c : m_children)
{
c->m_parent = nullptr;
while (c->m_depth > 0)
{
c->decreaseDepth();
}
}
//and adopt new
m_parent = other.m_parent;
m_depth = other.m_depth;
other.m_parent = nullptr;
//swap ourself into siblings list
if (m_parent)
{
auto& siblings = m_parent->m_children;
for (auto i = 0u; i < siblings.size(); ++i)
{
if (siblings[i] == &other)
{
siblings[i] = this;
break;
}
}
}
m_children = std::move(other.m_children);
//update the children's new parent
for (auto* c : m_children)
{
CRO_ASSERT(c != this, "we already exist in the child list!");
c->m_parent = this;
//should already be at the correct depth if
//we're taking on theexisting depth..?
while (c->m_depth > m_depth + 1)
{
c->decreaseDepth();
}
while (c->m_depth <= m_depth)
{
c->increaseDepth();
}
}
//actually take on the other transform
setPosition(other.getPosition());
setRotation(other.getRotation());
setScale(other.getScale());
setOrigin(other.getOrigin());
m_dirtyFlags = Flags::Tx;
other.reset();
}
}
Transform& Transform::operator=(Transform&& other) noexcept
{
CRO_ASSERT(&other != this && other.m_parent != this, "Invalid assignment");
if (&other != this && other.m_parent != this)
{
//orphan any children
for (auto c : m_children)
{
c->m_parent = nullptr;
while (c->m_depth > 0)
{
c->decreaseDepth();
}
}
m_parent = other.m_parent;
m_depth = other.m_depth;
other.m_parent = nullptr;
//swap ourself into siblings list
if (m_parent)
{
auto& siblings = m_parent->m_children;
for (auto i = 0u; i < siblings.size(); ++i)
{
if (siblings[i] == &other)
{
siblings[i] = this;
break;
}
}
}
m_children = std::move(other.m_children);
//update the children's new parent
for (auto c : m_children)
{
CRO_ASSERT(c != this, "we already exist in the child list!");
c->m_parent = this;
while (c->m_depth > m_depth + 1)
{
c->decreaseDepth();
}
while (c->m_depth <= m_depth)
{
c->increaseDepth();
}
}
//actually take on the other transform
setPosition(other.getPosition());
setRotation(other.getRotation());
setScale(other.getScale());
setOrigin(other.getOrigin());
m_dirtyFlags = Flags::Tx;
other.reset();
}
return *this;
}
Transform::~Transform()
{
//remove this transform from its parent
if (m_parent)
{
m_parent->removeChild(*this);
}
//orphan any children
for (auto c : m_children)
{
c->m_parent = nullptr;
while (c->m_depth > 0)
{
c->decreaseDepth();
}
}
}
//public
void Transform::setOrigin(glm::vec3 o)
{
m_origin = o;
m_dirtyFlags |= Tx;
}
void Transform::setOrigin(glm::vec2 o)
{
setOrigin(glm::vec3(o.x, o.y, 0.f));
}
void Transform::setPosition(glm::vec3 position)
{
m_position = position;
m_dirtyFlags |= Tx;
}
void Transform::setPosition(glm::vec2 position)
{
m_position.x = position.x;
m_position.y = position.t;
m_dirtyFlags |= Tx;
}
void Transform::setRotation(glm::vec3 axis, float angle)
{
glm::quat q = glm::quat(1.f, 0.f, 0.f, 0.f);
m_rotation = glm::rotate(q, angle, axis);
m_dirtyFlags |= Tx;
}
void Transform::setRotation(float radians)
{
setRotation(Z_AXIS, radians);
}
void Transform::setRotation(glm::quat rotation)
{
m_rotation = rotation;
m_dirtyFlags |= Tx;
}
void Transform::setRotation(glm::mat4 rotation)
{
m_rotation = glm::quat_cast(rotation);
m_dirtyFlags |= Tx;
}
void Transform::setScale(glm::vec3 scale)
{
m_scale = scale;
m_dirtyFlags |= Tx;
}
void Transform::setScale(glm::vec2 scale)
{
setScale(glm::vec3(scale.x, scale.y, 1.f));
}
void Transform::move(glm::vec3 distance)
{
m_position += distance;
m_dirtyFlags |= Tx;
}
void Transform::move(glm::vec2 distance)
{
move(glm::vec3(distance.x, distance.y, 0.f));
}
void Transform::rotate(glm::vec3 axis, float rotation)
{
m_rotation = glm::rotate(m_rotation, rotation, glm::normalize(axis));
m_dirtyFlags |= Tx;
}
void Transform::rotate(float amount)
{
rotate(Z_AXIS, amount);
}
void Transform::rotate(glm::quat rotation)
{
m_rotation = rotation * m_rotation;
m_dirtyFlags |= Tx;
}
void Transform::rotate(glm::mat4 rotation)
{
m_rotation = glm::quat_cast(rotation) * m_rotation;
}
void Transform::scale(glm::vec3 scale)
{
m_scale *= scale;
m_dirtyFlags |= Tx;
}
void Transform::scale(glm::vec2 amount)
{
scale(glm::vec3(amount.x, amount.y, 0.f));
}
glm::vec3 Transform::getOrigin() const
{
return m_origin;
}
glm::vec3 Transform::getPosition() const
{
return m_position;// +(m_origin * m_scale);
}
glm::vec3 Transform::getWorldPosition() const
{
return glm::vec3(getWorldTransform()[3]) - ((m_origin * m_scale) * m_rotation);
}
glm::quat Transform::getRotation() const
{
return m_rotation;
}
glm::vec3 Transform::getScale() const
{
return m_scale;
}
const glm::mat4& Transform::getLocalTransform() const
{
if (m_dirtyFlags & Tx)
{
m_transform = glm::translate(glm::mat4(1.f), m_position);
m_transform *= glm::toMat4(m_rotation);
m_transform = glm::scale(m_transform, m_scale);
m_transform = glm::translate(m_transform, -m_origin);
m_dirtyFlags &= ~Tx;
}
return m_transform;
}
void Transform::setLocalTransform(glm::mat4 transform)
{
m_position = transform[3];
m_rotation = glm::quat_cast(transform);
//not simple when rotations involved. Based
//on glm::matrix_decompose()
std::array<glm::vec3, 3u> row = {};
for (auto i = 0u; i < 3u; ++i)
{
for (auto j = 0u; j < 3u; ++j)
{
row[i][j] = transform[i][j] / transform[3][3];
}
}
m_scale.x = glm::length(row[0]);
m_scale.y = glm::length(row[1]);
m_scale.z = glm::length(row[2]);
auto t = glm::cross(row[1], row[2]);
if (glm::dot(row[0], t) < 0)
{
for (auto i = 0u; i < 3; ++i)
{
m_scale[i] *= -1.f;
}
}
//m_dirtyFlags |= Tx;
m_transform = glm::translate(transform, -m_origin);
m_dirtyFlags &= ~Tx;
}
glm::mat4 Transform::getWorldTransform() const
{
if (m_parent)
{
return m_parent->getWorldTransform() * getLocalTransform();
}
return getLocalTransform();
}
glm::vec3 Transform::getForwardVector() const
{
const auto& tx = getWorldTransform();
return -glm::column(tx, 2);
}
glm::vec3 Transform::getUpVector() const
{
const auto& tx = getWorldTransform();
return glm::column(tx, 1);
}
glm::vec3 Transform::getRightVector() const
{
const auto& tx = getWorldTransform();
return glm::column(tx, 0);
}
bool Transform::addChild(Transform& child)
{
CRO_ASSERT(&child != this, "can't parent to ourselves");
//don't really remember why there's a limit
if (m_children.size() < MaxChildren)
{
//remove any existing parent
if (child.m_parent)
{
if (child.m_parent == this)
{
return true; //already added!
}
auto& otherSiblings = child.m_parent->m_children;
otherSiblings.erase(std::remove_if(otherSiblings.begin(), otherSiblings.end(),
[&child](const Transform* ptr)
{
return ptr == &child;
}), otherSiblings.end());
}
child.m_parent = this;
//correct the depth
while (child.m_depth < (m_depth + 1))
{
child.increaseDepth();
}
while (child.m_depth > (m_depth + 1))
{
child.decreaseDepth();
}
m_children.push_back(&child);
return true;
}
Logger::log("Could not add child transform, max children has been reached");
return false;
}
void Transform::removeChild(Transform& tx)
{
if (tx.m_parent != this) return;
tx.m_parent = nullptr;
while (tx.m_depth > 0)
{
tx.decreaseDepth();
}
m_children.erase(std::remove_if(m_children.begin(), m_children.end(),
[&tx](const Transform* ptr)
{
return ptr == &tx;
}), m_children.end());
}
//private
void Transform::reset()
{
m_origin = glm::vec3(0.f, 0.f, 0.f);
m_position = glm::vec3(0.f, 0.f, 0.f);
m_scale = glm::vec3(1.f, 1.f, 1.f);
m_rotation = glm::quat(1.f, 0.f, 0.f, 0.f);
m_transform = glm::mat4(1.f);
m_parent = nullptr;
m_dirtyFlags = 0;
m_depth = 0;
m_children.clear();
}
void Transform::increaseDepth()
{
m_depth++;
for (auto& c : m_children)
{
c->increaseDepth();
}
}
void Transform::decreaseDepth()
{
if(m_depth > 0) m_depth--; //this is a hack, we should never call this if we're at 0 already
for (auto& c : m_children)
{
c->decreaseDepth();
}
} | 23.358121 | 96 | 0.560573 | [
"transform"
] |
a3a065b1eb93d23d0857fc629d9241b95c532e5c | 4,299 | cpp | C++ | source/test/range-test.cpp | CaptainCrowbar/rs-format | ef9cf9fcfe1ad74aba9e4eefd48f83b8d0d1f57c | [
"BSL-1.0"
] | null | null | null | source/test/range-test.cpp | CaptainCrowbar/rs-format | ef9cf9fcfe1ad74aba9e4eefd48f83b8d0d1f57c | [
"BSL-1.0"
] | null | null | null | source/test/range-test.cpp | CaptainCrowbar/rs-format | ef9cf9fcfe1ad74aba9e4eefd48f83b8d0d1f57c | [
"BSL-1.0"
] | null | null | null | #include "rs-format/range.hpp"
#include "rs-format/formatter.hpp"
#include "rs-unit-test.hpp"
#include <map>
#include <string>
#include <vector>
using namespace RS::Format;
void test_rs_format_string() {
TEST_EQUAL(format_string("", ""), "");
TEST_EQUAL(format_string("", "s"), "");
TEST_EQUAL(format_string("", "s5"), "");
TEST_EQUAL(format_string("", "q"), "\"\"");
TEST_EQUAL(format_string("", "q5"), "\"\"");
TEST_EQUAL(format_string("", "x"), "");
TEST_EQUAL(format_string("", "x5"), "");
TEST_EQUAL(format_string("", "X"), "");
TEST_EQUAL(format_string("Hello world", ""), "Hello world");
TEST_EQUAL(format_string("Hello world", "s"), "Hello world");
TEST_EQUAL(format_string("Hello world", "s5"), "Hello...");
TEST_EQUAL(format_string("Hello world", "q"), "\"Hello world\"");
TEST_EQUAL(format_string("Hello world", "q5"), "\"Hello...\"");
TEST_EQUAL(format_string("Hello world", "x"), "48 65 6c 6c 6f 20 77 6f 72 6c 64");
TEST_EQUAL(format_string("Hello world", "x5"), "48 65 6c 6c 6f...");
TEST_EQUAL(format_string("Hello world", "X"), "48 65 6C 6C 6F 20 77 6F 72 6C 64");
TEST_EQUAL(format_string("Hello world", "xz"), "48656c6c6f20776f726c64");
TEST_EQUAL(format_string("Hello world", "xz5"), "48656c6c6f...");
TEST_EQUAL(format_string("Hello world", "Xz"), "48656C6C6F20776F726C64");
TEST_EQUAL(format_string("αβγδε", ""), "αβγδε");
TEST_EQUAL(format_string("αβγδε", "q"), "\"αβγδε\"");
TEST_EQUAL(format_string("αβγδε", "x"), "ce b1 ce b2 ce b3 ce b4 ce b5");
TEST_EQUAL(format_string("αβγδε", "xz"), "ceb1ceb2ceb3ceb4ceb5");
TEST_EQUAL(format_string(u"αβγδε", ""), "αβγδε");
TEST_EQUAL(format_string(u"αβγδε", "q"), "\"αβγδε\"");
TEST_EQUAL(format_string(u"αβγδε", "x"), "ce b1 ce b2 ce b3 ce b4 ce b5");
TEST_EQUAL(format_string(u"αβγδε", "xz"), "ceb1ceb2ceb3ceb4ceb5");
TEST_EQUAL(format_string(U"αβγδε", ""), "αβγδε");
TEST_EQUAL(format_string(U"αβγδε", "q"), "\"αβγδε\"");
TEST_EQUAL(format_string(U"αβγδε", "x"), "ce b1 ce b2 ce b3 ce b4 ce b5");
TEST_EQUAL(format_string(U"αβγδε", "xz"), "ceb1ceb2ceb3ceb4ceb5");
TEST_EQUAL(format_string(L"αβγδε", ""), "αβγδε");
TEST_EQUAL(format_string(L"αβγδε", "q"), "\"αβγδε\"");
TEST_EQUAL(format_string(L"αβγδε", "x"), "ce b1 ce b2 ce b3 ce b4 ce b5");
TEST_EQUAL(format_string(L"αβγδε", "xz"), "ceb1ceb2ceb3ceb4ceb5");
}
void test_rs_format_ranges() {
std::vector<int> v;
v = {}; TEST_EQUAL(format_object(v), "[]"); TEST_EQUAL(format_object(v, "x4"), "[]");
v = {32}; TEST_EQUAL(format_object(v), "[32]"); TEST_EQUAL(format_object(v, "x4"), "[0020]");
v = {32,64}; TEST_EQUAL(format_object(v), "[32,64]"); TEST_EQUAL(format_object(v, "x4"), "[0020,0040]");
v = {32,64,128}; TEST_EQUAL(format_object(v), "[32,64,128]"); TEST_EQUAL(format_object(v, "x4"), "[0020,0040,0080]");
v = {32,64,128,256}; TEST_EQUAL(format_object(v), "[32,64,128,256]"); TEST_EQUAL(format_object(v, "x4"), "[0020,0040,0080,0100]");
std::map<int, std::string> m;
m = {}; TEST_EQUAL(format_object(m), "{}"); TEST_EQUAL(format_object(m, "n2"), "{}");
m = {{1,"abc"}}; TEST_EQUAL(format_object(m), "{1:abc}"); TEST_EQUAL(format_object(m, "n2"), "{01:abc}");
m = {{1,"abc"},{2,"def"}}; TEST_EQUAL(format_object(m), "{1:abc,2:def}"); TEST_EQUAL(format_object(m, "n2"), "{01:abc,02:def}");
m = {{1,"abc"},{2,"def"},{3,"ghi"}}; TEST_EQUAL(format_object(m), "{1:abc,2:def,3:ghi}"); TEST_EQUAL(format_object(m, "n2"), "{01:abc,02:def,03:ghi}");
m = {{1,"abc"},{2,"def"},{3,"ghi"},{4,"jkl"}}; TEST_EQUAL(format_object(m), "{1:abc,2:def,3:ghi,4:jkl}"); TEST_EQUAL(format_object(m, "n2"), "{01:abc,02:def,03:ghi,04:jkl}");
}
| 62.304348 | 180 | 0.542917 | [
"vector"
] |
a3a22d409e279acc40b7c7fa68524f1e23ffb513 | 2,313 | cpp | C++ | code/tests/PriorityQueueTests.cpp | noSTALKER/nxtcore | 4fdd225417f1b8b6d70d824d3c889588b387e1b8 | [
"MIT"
] | 1 | 2019-06-18T09:53:39.000Z | 2019-06-18T09:53:39.000Z | code/tests/PriorityQueueTests.cpp | noSTALKER/nxtcore | 4fdd225417f1b8b6d70d824d3c889588b387e1b8 | [
"MIT"
] | null | null | null | code/tests/PriorityQueueTests.cpp | noSTALKER/nxtcore | 4fdd225417f1b8b6d70d824d3c889588b387e1b8 | [
"MIT"
] | null | null | null | #include "catch.hpp"
#include "../include/Container/PriorityQueue.h"
#include "../include/Container/Vector.h"
TEST_CASE("PriorityQueue Tests", "[priority_queue]") {
SECTION("Priority Queue Push and Pop Tests") {
nxt::core::Vector values = {5, 1, 2, 4, 6, 7, 8, 5, 2};
nxt::core::PriorityQueue queue(values.begin(), values.end());
REQUIRE(values.size() == queue.size());
REQUIRE(queue.top() == 8);
REQUIRE(queue.popAndExtract() == 8);
REQUIRE(queue.size() == 8);
REQUIRE(queue.top() == 7);
REQUIRE(queue.popAndExtract() == 7);
REQUIRE(queue.size() == 7);
REQUIRE(queue.top() == 6);
REQUIRE(queue.popAndExtract() == 6);
REQUIRE(queue.size() == 6);
REQUIRE(queue.top() == 5);
REQUIRE(queue.popAndExtract() == 5);
REQUIRE(queue.size() == 5);
REQUIRE(queue.top() == 5);
queue.push(0);
REQUIRE(queue.size() == 6);
REQUIRE(queue.top() == 5);
queue.push(1);
REQUIRE(queue.size() == 7);
REQUIRE(queue.top() == 5);
queue.push(5);
REQUIRE(queue.size() == 8);
REQUIRE(queue.top() == 5);
queue.emplace(6);
REQUIRE(queue.size() == 9);
REQUIRE(queue.top() == 6);
REQUIRE(queue.popAndExtract() == 6);
REQUIRE(queue.size() == 8);
REQUIRE(queue.top() == 5);
REQUIRE(queue.popAndExtract() == 5);
REQUIRE(queue.size() == 7);
REQUIRE(queue.top() == 5);
REQUIRE(queue.popAndExtract() == 5);
REQUIRE(queue.size() == 6);
REQUIRE(queue.top() == 4);
REQUIRE(queue.popAndExtract() == 4);
REQUIRE(queue.size() == 5);
REQUIRE(queue.top() == 2);
REQUIRE(queue.popAndExtract() == 2);
REQUIRE(queue.size() == 4);
REQUIRE(queue.top() == 2);
REQUIRE(queue.popAndExtract() == 2);
REQUIRE(queue.size() == 3);
REQUIRE(queue.top() == 1);
REQUIRE(queue.popAndExtract() == 1);
REQUIRE(queue.size() == 2);
REQUIRE(queue.top() == 1);
REQUIRE(queue.popAndExtract() == 1);
REQUIRE(queue.size() == 1);
REQUIRE(queue.top() == 0);
REQUIRE(queue.popAndExtract() == 0);
REQUIRE(queue.size() == 0);
}
} | 28.207317 | 69 | 0.518374 | [
"vector"
] |
a3a3222daeaede969ff8e6125217e283013aa5c4 | 10,973 | cpp | C++ | src/mongo/client/embedded/embedded_transport_layer.cpp | qconner/mongo | 4a77fa59b402710054345ec51000bf540847dd8e | [
"Apache-2.0"
] | null | null | null | src/mongo/client/embedded/embedded_transport_layer.cpp | qconner/mongo | 4a77fa59b402710054345ec51000bf540847dd8e | [
"Apache-2.0"
] | null | null | null | src/mongo/client/embedded/embedded_transport_layer.cpp | qconner/mongo | 4a77fa59b402710054345ec51000bf540847dd8e | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2017 MongoDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects
* for all of the code used other than as permitted herein. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you do not
* wish to do so, delete this exception statement from your version. If you
* delete this exception statement from all source files in the program,
* then also delete it in the license file.
*/
#include "mongo/client/embedded/embedded_transport_layer.h"
#include <cstdlib>
#include <deque>
#include <iostream>
#include <iterator>
#include <memory>
#include <string>
#include "mongo/base/data_range.h"
#include "mongo/base/data_range_cursor.h"
#include "mongo/client/embedded/libmongodbcapi.h"
#include "mongo/util/assert_util.h"
#include "mongo/util/shared_buffer.h"
enum RPCState { WaitingForMessageLength, WaitingForMessageContent, HaveOutput };
struct FreeDeleter {
void operator()(void* x) {
free(x);
}
};
struct mongoc_stream_embedded_t : mongoc_stream_t {
libmongodbcapi_client* clientHandle;
mongo::DataRangeCursor inputBuf = mongo::DataRangeCursor(nullptr, nullptr);
std::unique_ptr<char, FreeDeleter> hiddenBuf;
mongo::ConstDataRangeCursor outputBuf = mongo::ConstDataRangeCursor(nullptr, nullptr);
void* libmongo_output;
size_t libmongo_output_size;
// If this is 0, we have recieved a full message and expect another header
u_long input_length_to_go;
RPCState state;
};
namespace {
struct FreeAndDestroy {
void operator()(mongoc_stream_t* x) {
auto stream = static_cast<mongoc_stream_embedded_t*>(x);
libmongodbcapi_db_client_destroy(stream->clientHandle);
stream->~mongoc_stream_embedded_t();
free(stream);
}
};
extern "C" void mongoc_stream_embedded_destroy(mongoc_stream_t* s) try {
std::unique_ptr<mongoc_stream_t, FreeAndDestroy> stream(s);
} catch (...) {
errno = EBADMSG;
}
extern "C" ssize_t mongoc_stream_embedded_writev(mongoc_stream_t* s,
mongoc_iovec_t* iov,
size_t iovcnt,
int32_t timeout_msec) try {
auto stream = static_cast<mongoc_stream_embedded_t*>(s);
invariant(stream->state == RPCState::WaitingForMessageContent ||
stream->state == RPCState::WaitingForMessageLength);
u_long already_read = 0;
for (size_t i = 0; i < iovcnt; i++) {
char* current_loc = static_cast<char*>(iov[i].iov_base);
u_long remaining_iov = iov[i].iov_len;
// do we need a new message?
if (stream->state == RPCState::WaitingForMessageLength) {
invariant(remaining_iov >= 4);
// message length is the first four bytes
// Should use dataview from mongo server
stream->input_length_to_go =
mongo::ConstDataView(current_loc).read<mongo::LittleEndian<int32_t>>();
// stream->hiddenBuf = (char*)malloc(stream->input_length_to_go);
stream->hiddenBuf =
std::unique_ptr<char, FreeDeleter>((char*)malloc(stream->input_length_to_go));
stream->inputBuf = mongo::DataRangeCursor(
stream->hiddenBuf.get(), stream->hiddenBuf.get() + stream->input_length_to_go);
auto writeOK =
stream->inputBuf.writeAndAdvance(mongo::DataRange(current_loc, current_loc + 4));
invariant(writeOK.isOK());
current_loc += 4;
remaining_iov -= 4;
stream->input_length_to_go -= 4;
already_read += 4;
stream->state = RPCState::WaitingForMessageContent;
}
// if there is no more message after reading length, we're done
if (remaining_iov <= 0)
continue;
// copy message length into buffer
// pipelining is not allowed, so remaining_iov must be less than input_length_to_go
invariant(stream->input_length_to_go >= remaining_iov);
auto writeOK = stream->inputBuf.writeAndAdvance(
mongo::DataRange(current_loc, current_loc + remaining_iov));
invariant(writeOK.isOK());
// cleanup number values to reflect the copy
stream->input_length_to_go -= remaining_iov;
already_read += remaining_iov;
remaining_iov = 0;
// if we found a complete message, send it
if (stream->input_length_to_go == 0) {
auto input_len = (size_t)(stream->inputBuf.data() - stream->hiddenBuf.get());
int retVal =
libmongodbcapi_db_client_wire_protocol_rpc(stream->clientHandle,
stream->hiddenBuf.get(),
input_len,
&(stream->libmongo_output),
&(stream->libmongo_output_size));
if (retVal != LIBMONGODB_CAPI_SUCCESS) {
return -1;
}
// We will allocate a new one when we read in the next message length
stream->hiddenBuf.reset();
// and then write the output to our output buffer
auto start = static_cast<char*>(stream->libmongo_output);
auto end = (static_cast<char*>(stream->libmongo_output)) + stream->libmongo_output_size;
stream->outputBuf = mongo::ConstDataRangeCursor(start, end);
stream->state = RPCState::HaveOutput;
}
}
return already_read;
} catch (...) {
errno = EBADMSG;
return 0; // not guarenteeing anything was written
}
extern "C" ssize_t mongoc_stream_embedded_readv(mongoc_stream_t* s,
mongoc_iovec_t* iov,
size_t iovcnt,
size_t min_bytes,
int32_t timeout_msec) try {
size_t bytes_read = 0;
auto stream = static_cast<mongoc_stream_embedded_t*>(s);
invariant(stream->state == RPCState::HaveOutput);
for (size_t i = 0; i < iovcnt && stream->outputBuf.length() > 0; i++) {
// for each vector, fill the vector if we are able
size_t bytes_to_copy = std::min(iov[i].iov_len, stream->outputBuf.length());
memcpy(iov[i].iov_base, stream->outputBuf.data(), bytes_to_copy);
auto x = stream->outputBuf.advance(bytes_to_copy);
invariant(x.isOK());
bytes_read += bytes_to_copy;
}
stream->state =
stream->outputBuf.length() == 0 ? RPCState::WaitingForMessageLength : RPCState::HaveOutput;
return bytes_read;
} catch (...) {
errno = EBADMSG;
return 0; // not guarenteeing anything was read
}
extern "C" int mongoc_stream_embedded_close(mongoc_stream_t* s) {
return 0;
}
extern "C" ssize_t mongoc_stream_embedded_poll(mongoc_stream_poll_t* s,
size_t array_length,
int32_t timeout_msec) try {
for (size_t i = 0; i < array_length; i++) {
s[i].revents = s[i].events & (POLLIN | POLLOUT);
}
return array_length;
} catch (...) {
errno = EBADMSG;
return -1;
}
extern "C" bool mongoc_stream_embedded_check_closed(mongoc_stream_t* s) noexcept {
return false;
}
extern "C" mongoc_stream_t* embedded_stream_initiator(const mongoc_uri_t* uri,
const mongoc_host_list_t* host,
void* user_data,
bson_error_t* error) try {
std::unique_ptr<unsigned char, FreeDeleter> stream_buf(
static_cast<unsigned char*>(bson_malloc0(sizeof(mongoc_stream_embedded_t))));
if (!stream_buf) {
errno = ENOMEM;
return nullptr;
}
// Create the stream
std::unique_ptr<mongoc_stream_embedded_t, FreeAndDestroy> stream(
new (stream_buf.get()) mongoc_stream_embedded_t());
stream_buf.release(); // This must be here so we don't have double ownership
stream->state = RPCState::WaitingForMessageLength;
// Set up connections to database
stream->clientHandle = libmongodbcapi_db_client_new((libmongodbcapi_db*)user_data);
// Connect the functions to the stream
// type is not relevant for us. Has to be set for the C Driver, but it has to do with picking
// how to communicate over the networ
stream->type = 1000;
stream->poll = mongoc_stream_embedded_poll;
stream->close = mongoc_stream_embedded_close;
stream->readv = mongoc_stream_embedded_readv;
stream->writev = mongoc_stream_embedded_writev;
stream->destroy = mongoc_stream_embedded_destroy;
stream->check_closed = mongoc_stream_embedded_check_closed;
return stream.release();
} catch (...) {
errno = EBADMSG;
return nullptr;
}
} // namespace
struct ClientDeleter {
void operator()(mongoc_client_t* x) {
mongoc_client_destroy(x);
}
};
extern "C" mongoc_client_t* embedded_mongoc_client_new(libmongodbcapi_db* db) try {
if (!db) {
errno = EINVAL;
return nullptr;
}
std::unique_ptr<mongoc_client_t, ClientDeleter> client(mongoc_client_new(NULL));
mongoc_client_set_stream_initiator(client.get(), embedded_stream_initiator, db);
return client.release();
} catch (const std::out_of_range& c) {
errno = EACCES;
return nullptr;
} catch (const std::overflow_error& c) {
errno = EOVERFLOW;
return nullptr;
} catch (const std::underflow_error& c) {
errno = ERANGE;
return nullptr;
} catch (const std::invalid_argument& c) {
errno = EINVAL;
return nullptr;
} catch (...) {
errno = EBADMSG;
return nullptr;
}
| 40.047445 | 100 | 0.62909 | [
"vector"
] |
a3a3d0eed3e64f538f327b552ed76066b2a01546 | 786 | cpp | C++ | CDR-docker_main_file/deepstream-yolov5/nvdsinfer_custom_impl_Yolo/layers/implicit_layer.cpp | zengming995/cv-detect-robot | 9b6cf38008bd404e9ae15c82479453e7ed124f93 | [
"Apache-2.0"
] | 2 | 2022-02-25T07:51:12.000Z | 2022-02-28T05:51:50.000Z | CDR-docker_main_file/deepstream-yolov5/nvdsinfer_custom_impl_Yolo/layers/implicit_layer.cpp | zengming995/cv-detect-robot | 9b6cf38008bd404e9ae15c82479453e7ed124f93 | [
"Apache-2.0"
] | null | null | null | CDR-docker_main_file/deepstream-yolov5/nvdsinfer_custom_impl_Yolo/layers/implicit_layer.cpp | zengming995/cv-detect-robot | 9b6cf38008bd404e9ae15c82479453e7ed124f93 | [
"Apache-2.0"
] | 1 | 2022-02-28T05:51:42.000Z | 2022-02-28T05:51:42.000Z | /*
* Created by Marcos Luciano
* https://www.github.com/marcoslucianops
*/
#include <math.h>
#include "implicit_layer.h"
nvinfer1::ILayer* implicitLayer(
int channels,
std::vector<float>& weights,
std::vector<nvinfer1::Weights>& trtWeights,
int& weightPtr,
nvinfer1::INetworkDefinition* network)
{
nvinfer1::Weights convWt{nvinfer1::DataType::kFLOAT, nullptr, channels};
float* val = new float[channels];
for (int i = 0; i < channels; ++i)
{
val[i] = weights[weightPtr];
weightPtr++;
}
convWt.values = val;
trtWeights.push_back(convWt);
nvinfer1::IConstantLayer* implicit = network->addConstant(nvinfer1::Dims3{static_cast<int>(channels), 1, 1}, convWt);
assert(implicit != nullptr);
return implicit;
} | 25.354839 | 121 | 0.66285 | [
"vector"
] |
a3a6c835c37c6b4663d5b5b195111a859ba2ddb3 | 3,583 | cpp | C++ | dev/Gems/LandscapeCanvas/Code/Source/Editor/Nodes/BaseNode.cpp | brianherrera/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | [
"AML"
] | 1,738 | 2017-09-21T10:59:12.000Z | 2022-03-31T21:05:46.000Z | dev/Gems/LandscapeCanvas/Code/Source/Editor/Nodes/BaseNode.cpp | ArchitectureStudios/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | [
"AML"
] | 427 | 2017-09-29T22:54:36.000Z | 2022-02-15T19:26:50.000Z | dev/Gems/LandscapeCanvas/Code/Source/Editor/Nodes/BaseNode.cpp | ArchitectureStudios/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | [
"AML"
] | 671 | 2017-09-21T08:04:01.000Z | 2022-03-29T14:30:07.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// AZ
#include <AzCore/Component/ComponentApplicationBus.h>
#include <AzCore/Serialization/SerializeContext.h>
#include <AzToolsFramework/Entity/EditorEntityInfoBus.h>
// Qt
#include <QString>
// Graph Model
#include <GraphModel/Model/Slot.h>
// Landscape Canvas
#include "BaseNode.h"
#include <Editor/Core/Core.h>
#include <Editor/Core/GraphContext.h>
namespace LandscapeCanvas
{
void BaseNode::Reflect(AZ::ReflectContext* context)
{
AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context);
if (serializeContext)
{
serializeContext->Class<BaseNode, GraphModel::Node>()
->Version(0)
->Field("m_vegetationEntityId", &BaseNode::m_vegetationEntityId)
->Field("m_componentId", &BaseNode::m_componentId)
;
}
}
BaseNode::BaseNode(GraphModel::GraphPtr graph)
: Node(graph)
{
}
void BaseNode::CreateEntityNameSlot()
{
// Property field to show the name of the corresponding Vegetation Entity
GraphModel::DataTypePtr stringDataType = GraphContext::GetInstance()->GetDataType(LandscapeCanvasDataTypeEnum::String);
RegisterSlot(GraphModel::SlotDefinition::CreateProperty(
ENTITY_NAME_SLOT_ID,
ENTITY_NAME_SLOT_LABEL.toUtf8().constData(),
stringDataType,
stringDataType->GetDefaultValue(),
ENTITY_NAME_SLOT_DESCRIPTION.toUtf8().constData()));
}
void BaseNode::SetVegetationEntityId(const AZ::EntityId& entityId)
{
m_vegetationEntityId = entityId;
// Update the Entity Name (if we have the property slot)
GraphModel::SlotPtr slot = GetSlot(ENTITY_NAME_SLOT_ID);
if (slot)
{
AZStd::string name;
AzToolsFramework::EditorEntityInfoRequestBus::EventResult(name, entityId, &AzToolsFramework::EditorEntityInfoRequestBus::Events::GetName);
slot->SetValue(AZStd::any(name));
}
}
void BaseNode::SetComponentId(const AZ::ComponentId& componentId)
{
m_componentId = componentId;
}
AZ::Component* BaseNode::GetComponent() const
{
AZ::Entity* gradientEntity = nullptr;
AZ::ComponentApplicationBus::BroadcastResult(gradientEntity, &AZ::ComponentApplicationRequests::FindEntity, GetVegetationEntityId());
if (!gradientEntity)
{
return nullptr;
}
AZ::Component* component = gradientEntity->FindComponent(GetComponentId());
if (component)
{
return component;
}
return nullptr;
}
bool BaseNode::IsAreaExtender() const
{
BaseNodeType baseNodeType = GetBaseNodeType();
return baseNodeType == LandscapeCanvas::BaseNode::VegetationAreaModifier
|| baseNodeType == LandscapeCanvas::BaseNode::VegetationAreaFilter
|| baseNodeType == LandscapeCanvas::BaseNode::VegetationAreaSelector
;
}
} // namespace LandscapeCanvas
| 33.485981 | 150 | 0.66983 | [
"model"
] |
a3b221c17820248bf11fe23f29596d50012b9020 | 7,674 | hpp | C++ | ThirdParty-mod/java2cpp/java/security/cert/CertPathValidator.hpp | kakashidinho/HQEngine | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | [
"MIT"
] | 1 | 2019-04-03T01:53:28.000Z | 2019-04-03T01:53:28.000Z | ThirdParty-mod/java2cpp/java/security/cert/CertPathValidator.hpp | kakashidinho/HQEngine | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | [
"MIT"
] | null | null | null | ThirdParty-mod/java2cpp/java/security/cert/CertPathValidator.hpp | kakashidinho/HQEngine | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | [
"MIT"
] | null | null | null | /*================================================================================
code generated by: java2cpp
author: Zoran Angelov, mailto://baldzar@gmail.com
class: java.security.cert.CertPathValidator
================================================================================*/
#ifndef J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_JAVA_SECURITY_CERT_CERTPATHVALIDATOR_HPP_DECL
#define J2CPP_JAVA_SECURITY_CERT_CERTPATHVALIDATOR_HPP_DECL
namespace j2cpp { namespace java { namespace lang { class Object; } } }
namespace j2cpp { namespace java { namespace lang { class String; } } }
namespace j2cpp { namespace java { namespace security { class Provider; } } }
namespace j2cpp { namespace java { namespace security { namespace cert { class CertPath; } } } }
namespace j2cpp { namespace java { namespace security { namespace cert { class CertPathValidatorResult; } } } }
namespace j2cpp { namespace java { namespace security { namespace cert { class CertPathParameters; } } } }
#include <java/lang/Object.hpp>
#include <java/lang/String.hpp>
#include <java/security/Provider.hpp>
#include <java/security/cert/CertPath.hpp>
#include <java/security/cert/CertPathParameters.hpp>
#include <java/security/cert/CertPathValidatorResult.hpp>
namespace j2cpp {
namespace java { namespace security { namespace cert {
class CertPathValidator;
class CertPathValidator
: public object<CertPathValidator>
{
public:
J2CPP_DECLARE_CLASS
J2CPP_DECLARE_METHOD(0)
J2CPP_DECLARE_METHOD(1)
J2CPP_DECLARE_METHOD(2)
J2CPP_DECLARE_METHOD(3)
J2CPP_DECLARE_METHOD(4)
J2CPP_DECLARE_METHOD(5)
J2CPP_DECLARE_METHOD(6)
J2CPP_DECLARE_METHOD(7)
explicit CertPathValidator(jobject jobj)
: object<CertPathValidator>(jobj)
{
}
operator local_ref<java::lang::Object>() const;
local_ref< java::lang::String > getAlgorithm();
local_ref< java::security::Provider > getProvider();
static local_ref< java::security::cert::CertPathValidator > getInstance(local_ref< java::lang::String > const&);
static local_ref< java::security::cert::CertPathValidator > getInstance(local_ref< java::lang::String > const&, local_ref< java::lang::String > const&);
static local_ref< java::security::cert::CertPathValidator > getInstance(local_ref< java::lang::String > const&, local_ref< java::security::Provider > const&);
local_ref< java::security::cert::CertPathValidatorResult > validate(local_ref< java::security::cert::CertPath > const&, local_ref< java::security::cert::CertPathParameters > const&);
static local_ref< java::lang::String > getDefaultType();
}; //class CertPathValidator
} //namespace cert
} //namespace security
} //namespace java
} //namespace j2cpp
#endif //J2CPP_JAVA_SECURITY_CERT_CERTPATHVALIDATOR_HPP_DECL
#else //J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_JAVA_SECURITY_CERT_CERTPATHVALIDATOR_HPP_IMPL
#define J2CPP_JAVA_SECURITY_CERT_CERTPATHVALIDATOR_HPP_IMPL
namespace j2cpp {
java::security::cert::CertPathValidator::operator local_ref<java::lang::Object>() const
{
return local_ref<java::lang::Object>(get_jobject());
}
local_ref< java::lang::String > java::security::cert::CertPathValidator::getAlgorithm()
{
return call_method<
java::security::cert::CertPathValidator::J2CPP_CLASS_NAME,
java::security::cert::CertPathValidator::J2CPP_METHOD_NAME(1),
java::security::cert::CertPathValidator::J2CPP_METHOD_SIGNATURE(1),
local_ref< java::lang::String >
>(get_jobject());
}
local_ref< java::security::Provider > java::security::cert::CertPathValidator::getProvider()
{
return call_method<
java::security::cert::CertPathValidator::J2CPP_CLASS_NAME,
java::security::cert::CertPathValidator::J2CPP_METHOD_NAME(2),
java::security::cert::CertPathValidator::J2CPP_METHOD_SIGNATURE(2),
local_ref< java::security::Provider >
>(get_jobject());
}
local_ref< java::security::cert::CertPathValidator > java::security::cert::CertPathValidator::getInstance(local_ref< java::lang::String > const &a0)
{
return call_static_method<
java::security::cert::CertPathValidator::J2CPP_CLASS_NAME,
java::security::cert::CertPathValidator::J2CPP_METHOD_NAME(3),
java::security::cert::CertPathValidator::J2CPP_METHOD_SIGNATURE(3),
local_ref< java::security::cert::CertPathValidator >
>(a0);
}
local_ref< java::security::cert::CertPathValidator > java::security::cert::CertPathValidator::getInstance(local_ref< java::lang::String > const &a0, local_ref< java::lang::String > const &a1)
{
return call_static_method<
java::security::cert::CertPathValidator::J2CPP_CLASS_NAME,
java::security::cert::CertPathValidator::J2CPP_METHOD_NAME(4),
java::security::cert::CertPathValidator::J2CPP_METHOD_SIGNATURE(4),
local_ref< java::security::cert::CertPathValidator >
>(a0, a1);
}
local_ref< java::security::cert::CertPathValidator > java::security::cert::CertPathValidator::getInstance(local_ref< java::lang::String > const &a0, local_ref< java::security::Provider > const &a1)
{
return call_static_method<
java::security::cert::CertPathValidator::J2CPP_CLASS_NAME,
java::security::cert::CertPathValidator::J2CPP_METHOD_NAME(5),
java::security::cert::CertPathValidator::J2CPP_METHOD_SIGNATURE(5),
local_ref< java::security::cert::CertPathValidator >
>(a0, a1);
}
local_ref< java::security::cert::CertPathValidatorResult > java::security::cert::CertPathValidator::validate(local_ref< java::security::cert::CertPath > const &a0, local_ref< java::security::cert::CertPathParameters > const &a1)
{
return call_method<
java::security::cert::CertPathValidator::J2CPP_CLASS_NAME,
java::security::cert::CertPathValidator::J2CPP_METHOD_NAME(6),
java::security::cert::CertPathValidator::J2CPP_METHOD_SIGNATURE(6),
local_ref< java::security::cert::CertPathValidatorResult >
>(get_jobject(), a0, a1);
}
local_ref< java::lang::String > java::security::cert::CertPathValidator::getDefaultType()
{
return call_static_method<
java::security::cert::CertPathValidator::J2CPP_CLASS_NAME,
java::security::cert::CertPathValidator::J2CPP_METHOD_NAME(7),
java::security::cert::CertPathValidator::J2CPP_METHOD_SIGNATURE(7),
local_ref< java::lang::String >
>();
}
J2CPP_DEFINE_CLASS(java::security::cert::CertPathValidator,"java/security/cert/CertPathValidator")
J2CPP_DEFINE_METHOD(java::security::cert::CertPathValidator,0,"<init>","(Ljava/security/cert/CertPathValidatorSpi;Ljava/security/Provider;Ljava/lang/String;)V")
J2CPP_DEFINE_METHOD(java::security::cert::CertPathValidator,1,"getAlgorithm","()Ljava/lang/String;")
J2CPP_DEFINE_METHOD(java::security::cert::CertPathValidator,2,"getProvider","()Ljava/security/Provider;")
J2CPP_DEFINE_METHOD(java::security::cert::CertPathValidator,3,"getInstance","(Ljava/lang/String;)Ljava/security/cert/CertPathValidator;")
J2CPP_DEFINE_METHOD(java::security::cert::CertPathValidator,4,"getInstance","(Ljava/lang/String;Ljava/lang/String;)Ljava/security/cert/CertPathValidator;")
J2CPP_DEFINE_METHOD(java::security::cert::CertPathValidator,5,"getInstance","(Ljava/lang/String;Ljava/security/Provider;)Ljava/security/cert/CertPathValidator;")
J2CPP_DEFINE_METHOD(java::security::cert::CertPathValidator,6,"validate","(Ljava/security/cert/CertPath;Ljava/security/cert/CertPathParameters;)Ljava/security/cert/CertPathValidatorResult;")
J2CPP_DEFINE_METHOD(java::security::cert::CertPathValidator,7,"getDefaultType","()Ljava/lang/String;")
} //namespace j2cpp
#endif //J2CPP_JAVA_SECURITY_CERT_CERTPATHVALIDATOR_HPP_IMPL
#endif //J2CPP_INCLUDE_IMPLEMENTATION
| 43.355932 | 229 | 0.742247 | [
"object"
] |
a3b3850decebaab1b035939a28a1e56561f8ebdd | 470 | cpp | C++ | POJ/3980/11792762_AC_375ms_712kB.cpp | BakaErii/ACM_Collection | d368b15c7f1c84472424d5e61e5ebc667f589025 | [
"WTFPL"
] | null | null | null | POJ/3980/11792762_AC_375ms_712kB.cpp | BakaErii/ACM_Collection | d368b15c7f1c84472424d5e61e5ebc667f589025 | [
"WTFPL"
] | null | null | null | POJ/3980/11792762_AC_375ms_712kB.cpp | BakaErii/ACM_Collection | d368b15c7f1c84472424d5e61e5ebc667f589025 | [
"WTFPL"
] | null | null | null | /**
* @authors Moe_Sakiya sakiya@tun.moe
* @date 2017-12-01 16:21:03
*
*/
#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 mod(int a, int b) {
return a % b;
}
int main(void) {
int a, b;
while (~scanf("%d %d", &a, &b))
printf("%d\n", mod(a, b) );
return 0;
} | 14.6875 | 41 | 0.617021 | [
"vector"
] |
a3b6bcba3d3d804507b37cb90507f8952ebc0a6e | 14,670 | cpp | C++ | Proj2/ScrabbleJunior/Main.cpp | marhcouto/FEUP-PROG | e88a37065e02038a97e34072b1a21ff0c75b5bb8 | [
"MIT"
] | null | null | null | Proj2/ScrabbleJunior/Main.cpp | marhcouto/FEUP-PROG | e88a37065e02038a97e34072b1a21ff0c75b5bb8 | [
"MIT"
] | null | null | null | Proj2/ScrabbleJunior/Main.cpp | marhcouto/FEUP-PROG | e88a37065e02038a97e34072b1a21ff0c75b5bb8 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <windows.h>
#include <string>
#include <map>
#include <iterator>
#include "Tile.h"
#include "Pool.h"
#include "Player.h"
#include "Board.h"
void Instructions(void) { //Prints instructions according to the user's decision
bool stop = false;
std::string response;
std::cout << "Do you want to read the game's intructions/rules?('yes' or 'no')\n";
do {
std::cin >> response;
if (response == "yes" || response == "no")
stop = true;
else
std::cout << "Invalid answer. Please type 'yes' or 'no'\n";
} while (!stop);
if (response == "yes")
std::cout << "\n Each player starts the game with 7 tiles. Each tile has a letter on it.\n"
<< "In each turn, the player must play 2 of its tiles on the board.\n"
<< "The tiles have to be played on coordinates that represent the first\n"
<< "available letter in a word. If a player does not have any tile that\n"
<< "fills the requirements on his 'deck', the game will automatically\n"
<< "draw tiles from the pool until the play is possible. Scoring chips\n"
<< "are earned every time the player places the last letter in a word.\n"
<< "Whoever has the most scoring chips when there are no tiles left wins.\n\n";
}
void ChangeColor(unsigned int color) { //Changes color
HANDLE hCon = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hCon, color);
}
void printColored(Board& board, char bigL, char smallL) { //Decides what to print in each coordinate, used in display
unsigned int color = 8;
if (board.boardMap.count({ bigL, smallL })) {
if (board.boardMap[{bigL, smallL}].used) //If the coordinate already has a tile
color = 4;
else if (board.boardMap[{bigL, smallL}].firstLetterH || board.boardMap[{bigL, smallL}].firstLetterV) //If it is a firts letter
color = 10;
ChangeColor(color);
std::cout << board.boardMap[{bigL, smallL}].letter << " ";
ChangeColor(8);
}
else
std::cout << " "; //If there's nothing in the coordinate
ChangeColor(15);
}
void TileRequester(Player& player, Board& board, Pool& pool) { //Requests tiles from the pool to the player's deck
unsigned int goodTiles = 0; //if he has no playable ones
char letter;
for (unsigned int i = 0; i < player.deck.size(); i++) {
letter = player.deck[i];
for (auto it = board.boardMap.begin(); it != board.boardMap.end(); it++) {
if (letter == it->second.letter && (it->second.firstLetterH || it->second.firstLetterV)) //Checking if there are any available
goodTiles++; //tiles in the deck
}
}
if (goodTiles == 0) {
std::cout << "No matching tiles. Withdrawing a tile from the pool.\n";
player.DrawFromPool(pool, 1);
TileRequester(player, board, pool);
}
}
void Display(Board& board, std::vector <Player> playersVector) { //Prints the board and other info
int hight = board.boardSize.first; //Number of lines
int length = board.boardSize.second; //Number of columns
char smallL = 'a';
char bigL = 'A';
system("CLS");
std::cout << " SCRABBLE\n\n";
std::cout << " ";
while (length > 0) {
std::cout << smallL << " ";
smallL = char(int(smallL) + 1);
length--;
}
std::cout << " | ";
unsigned int nPlayers = playersVector.size();
std::cout << "Scoring chips: | ";
for (unsigned int i = 0; i < playersVector.size(); i++) {
ChangeColor(5);
std::cout << playersVector[i].GetName() << ": " << playersVector[i].GetScore();
ChangeColor(15);
std::cout << " | ";
}
std::cout << "\n";
smallL = 'a';
length = board.boardSize.second;
while (hight > 0) {
std::cout << bigL << " ";
while (length > 0) {
printColored(board, bigL, smallL);
length--; //Printing the board
smallL++;
}
bigL++;
smallL = 'a';
length = board.boardSize.second;
hight--;
std::cout << " |";
if (hight == 0) {
ChangeColor(8);
std::cout << " Grey - Normal tile |";
ChangeColor(15);
}
if (hight == 1) {
ChangeColor(9);
std::cout << " Blue - Tile good to play from your pool |"; //Color scheme
ChangeColor(15);
}
if (hight == 2) {
ChangeColor(4);
std::cout << " Red - A tile was already placed in those coordinates |";
ChangeColor(15);
}
if (hight == 3) {
ChangeColor(10);
std::cout << " Green - Available spaces to play on the board |";
ChangeColor(15);
}
std::cout << "\n";
}
std::cout << std::endl;
}
void PlayerMoveSetter(Player& player, Board& board) { //Sets the player's move
std::string playerName = player.GetName();
std::pair<char, char> coordPair;
char tile1, coordinate1, coordinate2;
std::string cinFailMsg = "Input type invalid.";
std::string tileFailMsg = "There are no tiles that correspond with the choosen letter in your deck.";
std::string coordFailMsg = "The coordinate you chose has no letters in the board.";
std::string tileCoordFailMsg = "The letter you chose doesn't correspond to the posicion chosen in the board.";
std::string notFirstLetterFailMsg = "The coordinates you chose to place your tile don't represent the first letter available of any word.";
std::string usedLetterFailMsg = "The coordinates you chose to place your tile already have a tile placed.";
bool tileFail;
bool coordFail;
bool tileCoordFail;
bool stop; //Different types of errors that could come up from input and its messages
bool notFirstLetterFail;
bool usedLetterFail;
if(player.firstTile)
std::cout << "Your turn " << playerName << std::endl;
std::cout << "Your Pool: ";
ChangeColor(8);
for (unsigned int i = 0; i < player.deck.size(); i++) {
for (auto it = board.boardMap.begin(); it != board.boardMap.end(); it++) {
if (player.deck[i] == it->second.letter && (it->second.firstLetterH || it->second.firstLetterV))
ChangeColor(9);
}
std::cout << "-" << player.deck[i] << " ";
ChangeColor(8);
}
ChangeColor(15);
std::cout << std::endl;
do {
if (player.firstTile)
std::cout << "Choose one tile from your tile collection (must be capital letter).\n";
else
std::cout << "Choose another tile from your tile collection (must be capital letter).\n";
std::cin >> tile1;
std::cout << "\nChoose the coordinate corresponding to the line you want the tile placed on (must be capital letter).\n";
std::cin >> coordinate1;
std::cout << "\nChoose the coordinate corresponding to the column you want the tile placed on (must be small letter).\n";
std::cin >> coordinate2;
coordPair = { coordinate1, coordinate2 };
tileFail = !std::count(player.deck.begin(), player.deck.end(), tile1);
coordFail = (board.boardMap.count(coordPair) == 0);
tileCoordFail = board.boardMap[{coordPair}].letter != tile1;
notFirstLetterFail = !(board.boardMap[{coordPair}].firstLetterH || board.boardMap[{coordPair}].firstLetterV);
usedLetterFail = board.boardMap[{coordPair}].used;
if (std::cin.fail()) {
std::cout << cinFailMsg << std::endl;
stop = false;
}
else if (tileFail) {
std::cout << tileFailMsg << std::endl;
stop = false;
}
else if (coordFail) {
std::cout << coordFailMsg << std::endl;
stop = false;
}
else if (tileCoordFail) {
std::cout << tileCoordFailMsg << std::endl;
stop = false;
}
else if (notFirstLetterFail) {
std::cout << notFirstLetterFailMsg << std::endl;
stop = false;
}
else if (usedLetterFail) {
std::cout << usedLetterFailMsg << std::endl;
stop = false;
}
else
stop = true;
} while (!stop);
std::vector <char> move = { coordinate1, coordinate2, tile1 };
player.move = move;
}
void Play(Player& player, Board& board) {
std::vector<char> move = player.move;
std::vector<char> ::iterator iterOfUsedTile = std::find(player.deck.begin(), player.deck.end(), move[2]);
player.deck.erase(iterOfUsedTile);
board.boardMap[{move[0], move[1]}].used = true;
if (board.boardMap[{move[0], move[1]}].horizontal) {
if (board.boardMap[{move[0], move[1]}].lastLetterH)
player.ScoreIncrementer();
if (board.boardMap[{move[0], move[1]}].firstLetterH)
board.boardMap[{move[0], char(int(move[1]) + 1)}].firstLetterH = true;
board.boardMap[{move[0], move[1]}].firstLetterH = false;
}
if (board.boardMap[{move[0], move[1]}].vertical) {
if (board.boardMap[{move[0], move[1]}].lastLetterV)
player.ScoreIncrementer();
if (board.boardMap[{move[0], move[1]}].firstLetterV)
board.boardMap[{char(move[0] + 1), move[1]}].firstLetterV = true;
board.boardMap[{move[0], move[1]}].firstLetterV = false;
}
}
bool GameOver(Board& board) {
unsigned int nonUsedTiles = 0;
for (std::map < std::pair<char, char>, Tile > ::iterator it = board.boardMap.begin(); it != board.boardMap.end(); it++) {
if (!(it->second.used))
nonUsedTiles++;
}
if (nonUsedTiles == 0)
return true;
else
return false;
}
void GameCloser(std::vector <Player> playersVector) {
unsigned int highestScore = 0;
std::vector <Player> winners;
std::string multipleWinners;
for (unsigned int i = 0; i < playersVector.size(); i++) {
if (playersVector[i].GetScore() > highestScore) {
highestScore = playersVector[i].GetScore();
}
}
for (unsigned int i = 0; i < playersVector.size(); i++) {
if (playersVector[i].GetScore() == highestScore)
winners.push_back(playersVector[i]);
}
if (winners.size() == 1)
std::cout << "The winner is " << winners[0].GetName() << " with " << winners[0].GetScore() << "scoring chips.\n";
else {
std::cout << "It's a draw between ";
for (unsigned int i = 0; i < winners.size(); i++) {
multipleWinners = multipleWinners + winners[i].GetName() + " with " + std::to_string(winners[i].GetScore()) + " scoring chips and ";
}
multipleWinners.erase(multipleWinners.end() - 4, multipleWinners.end());
std::cout << multipleWinners;
}
}
void AnotherGo (bool& playAgain) {
std::string response;
std::cout << "Want to play again?('yes' or 'no')\n";
bool stop = false;
do {
std::cin >> response;
if (response == "yes" || response == "no")
stop = true;
else
std::cout << "Invalid answer. Please type 'yes' or 'no'\n";
} while (stop);
if (response == "yes")
playAgain = true;
}
int MissingTiles(Player& player) {
int missingTiles = 7 - player.GetDeck().size();
if (missingTiles <= 0)
return 0;
else
return missingTiles;
}
std::vector <Player> PlayersVectorCreator() {
unsigned int nPlayers;
std::cout << "The game supports 2-4 players, how many would like to play?\n";
do {
std::cin >> nPlayers;
if (!(nPlayers >= 2 and nPlayers <= 4) || std::cin.fail()) {
std::cout << "Invalid number of players, please type a integer between 2 and 4\n";
}
} while (!(nPlayers >= 2 and nPlayers <= 4) || std::cin.fail());
Player player1("Player1");
Player player2("Player2");
std::vector <Player> pVector = { player1, player2 };
if (nPlayers > 2) {
Player player3("Player3");
pVector.push_back(player3);
}
if (nPlayers > 3) {
Player player4("Player4");
pVector.push_back(player4);
}
return pVector;
}
void Game() {
Instructions(); //Asks the user if he wants to read the basic instructions and, if so, prints them on the console
Pool pool;
Board board(pool);
std::vector <Player> playersVector = PlayersVectorCreator(); //Creating a vector with the players
for (unsigned int i = 0; i < playersVector.size(); i++)
playersVector[i].DrawFromPool(pool, 7); //Creating their deck/minipool
while (!GameOver(board)) { //Executes until there are no more tiles
Display(board, playersVector); //Displays the gameboard, scores and a small color scheme
TileRequester(playersVector[Player::turn], board, pool); //Checks if the player has playable tiles and, if not, fetches tiles from the pool
Player::firstTile = true; //Used in PlayerMoveSetter
PlayerMoveSetter(playersVector[Player::turn], board); //Gets the player's move from the user
Play(playersVector[Player::turn], board); //Executes the move
Display(board, playersVector); //Repeating the process for the second tile to be played in a turn
TileRequester(playersVector[Player::turn], board, pool);
Player::firstTile = false;
PlayerMoveSetter(playersVector[Player::turn], board);
Play(playersVector[Player::turn], board);
playersVector[Player::turn].DrawFromPool(pool, MissingTiles(playersVector[Player::turn])); //Draws tiles from the pool according to how many the player is missing
Player::turn = (Player::turn + 1) % playersVector.size(); //Changes the turn
}
GameCloser(playersVector); //Announces the winner
}
int main()
{
bool playAgain;
do {
playAgain = false;
Game(); //Actual game
AnotherGo(playAgain); //Asks the user if it wants to play again and changes the playAgain's value accordingly
} while (playAgain);
} | 38.103896 | 170 | 0.570211 | [
"vector"
] |
a3bad48117dc959547234cc4ccbabc6e6c660b28 | 1,948 | hpp | C++ | tst/test_subject/jni/test/JNITest.hpp | CMakeezer/cppJNI | 730482ffff00e89bb4f0e4a9e4b5a87090a646bf | [
"BSD-3-Clause"
] | 11 | 2017-11-14T22:38:41.000Z | 2021-10-04T14:50:22.000Z | tst/test_subject/jni/test/JNITest.hpp | CMakeezer/cppJNI | 730482ffff00e89bb4f0e4a9e4b5a87090a646bf | [
"BSD-3-Clause"
] | 2 | 2017-11-22T09:21:47.000Z | 2018-01-11T19:35:59.000Z | tst/test_subject/jni/test/JNITest.hpp | CMakeezer/cppJNI | 730482ffff00e89bb4f0e4a9e4b5a87090a646bf | [
"BSD-3-Clause"
] | 5 | 2018-01-11T18:50:26.000Z | 2020-01-14T18:19:09.000Z | #pragma once
#include <cppjni/concepts/string_type.hpp>
#include <cppjni/method_signature.hpp>
#include <cppjni/predefined/java/lang/object.hpp>
#include <cppjni/predefined/java/lang/string.hpp>
#include <cppjni/predefined/java/util/list.hpp>
namespace test
{
namespace cppjni
{
namespace cj = ::cppjni;
namespace java = cj::predefined::java;
template<typename T>
struct JNITest: virtual java::lang::Object<T>
{
using class_path_t = string_type_is("jni/test/JNITest");
MAKE_JAVA_CONSTRUCTOR(cj::types::Object<::test::cppjni::JNITest>(cj::Int, cj::String))
MAKE_JAVA_METHOD(getPrimitiveField, cj::Method<cj::Int()>)
MAKE_JAVA_METHOD(getPrimitiveField2, cj::Method<cj::Int()>)
MAKE_JAVA_METHOD(getObjectField, cj::Method<cj::types::Object<::test::cppjni::JNITest>()>)
MAKE_JAVA_METHOD(getStringField, cj::Method<cj::String()>)
MAKE_JAVA_METHOD(setStringField,
cj::Method<cj::Void(cj::types::Object<java::lang::String>)>,
cj::Method<cj::Void(cj::String)>
)
MAKE_JAVA_METHOD(incrementIntField, cj::Method<cj::Void(cj::Int)>)
MAKE_JAVA_METHOD(staticReturningPrimitive,
cj::StaticMethod<cj::Int()>,
cj::StaticMethod<cj::Long(cj::Int)>
)
MAKE_JAVA_METHOD(staticReturningString, cj::StaticMethod<cj::String(cj::String)>)
MAKE_JAVA_METHOD(staticVoid, cj::StaticMethod<cj::Void()>)
MAKE_JAVA_METHOD(staticFactory,
cj::StaticMethod<cj::types::Object<::test::cppjni::JNITest>()>,
cj::StaticMethod<cj::types::Object<::test::cppjni::JNITest>(cj::Int, cj::String)>
)
MAKE_JAVA_METHOD(throwException, cj::Method<cj::Void()>)
MAKE_JAVA_METHOD(getStringList, cj::StaticMethod<cj::types::Object<java::util::List>()>)
};
}
} | 43.288889 | 106 | 0.626797 | [
"object"
] |
a3bb914efba775e43a2dc9ec665d7339e703d1f6 | 6,193 | cpp | C++ | aws-cpp-sdk-autoscaling/source/model/ScalingActivityStatusCode.cpp | ambasta/aws-sdk-cpp | c81192e00b572b76d175d84dff77185bd17ae1ac | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-autoscaling/source/model/ScalingActivityStatusCode.cpp | ambasta/aws-sdk-cpp | c81192e00b572b76d175d84dff77185bd17ae1ac | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-autoscaling/source/model/ScalingActivityStatusCode.cpp | ambasta/aws-sdk-cpp | c81192e00b572b76d175d84dff77185bd17ae1ac | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/autoscaling/model/ScalingActivityStatusCode.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>
using namespace Aws::Utils;
namespace Aws
{
namespace AutoScaling
{
namespace Model
{
namespace ScalingActivityStatusCodeMapper
{
static const int PendingSpotBidPlacement_HASH = HashingUtils::HashString("PendingSpotBidPlacement");
static const int WaitingForSpotInstanceRequestId_HASH = HashingUtils::HashString("WaitingForSpotInstanceRequestId");
static const int WaitingForSpotInstanceId_HASH = HashingUtils::HashString("WaitingForSpotInstanceId");
static const int WaitingForInstanceId_HASH = HashingUtils::HashString("WaitingForInstanceId");
static const int PreInService_HASH = HashingUtils::HashString("PreInService");
static const int InProgress_HASH = HashingUtils::HashString("InProgress");
static const int WaitingForELBConnectionDraining_HASH = HashingUtils::HashString("WaitingForELBConnectionDraining");
static const int MidLifecycleAction_HASH = HashingUtils::HashString("MidLifecycleAction");
static const int WaitingForInstanceWarmup_HASH = HashingUtils::HashString("WaitingForInstanceWarmup");
static const int Successful_HASH = HashingUtils::HashString("Successful");
static const int Failed_HASH = HashingUtils::HashString("Failed");
static const int Cancelled_HASH = HashingUtils::HashString("Cancelled");
ScalingActivityStatusCode GetScalingActivityStatusCodeForName(const Aws::String& name)
{
int hashCode = HashingUtils::HashString(name.c_str());
if (hashCode == PendingSpotBidPlacement_HASH)
{
return ScalingActivityStatusCode::PendingSpotBidPlacement;
}
else if (hashCode == WaitingForSpotInstanceRequestId_HASH)
{
return ScalingActivityStatusCode::WaitingForSpotInstanceRequestId;
}
else if (hashCode == WaitingForSpotInstanceId_HASH)
{
return ScalingActivityStatusCode::WaitingForSpotInstanceId;
}
else if (hashCode == WaitingForInstanceId_HASH)
{
return ScalingActivityStatusCode::WaitingForInstanceId;
}
else if (hashCode == PreInService_HASH)
{
return ScalingActivityStatusCode::PreInService;
}
else if (hashCode == InProgress_HASH)
{
return ScalingActivityStatusCode::InProgress;
}
else if (hashCode == WaitingForELBConnectionDraining_HASH)
{
return ScalingActivityStatusCode::WaitingForELBConnectionDraining;
}
else if (hashCode == MidLifecycleAction_HASH)
{
return ScalingActivityStatusCode::MidLifecycleAction;
}
else if (hashCode == WaitingForInstanceWarmup_HASH)
{
return ScalingActivityStatusCode::WaitingForInstanceWarmup;
}
else if (hashCode == Successful_HASH)
{
return ScalingActivityStatusCode::Successful;
}
else if (hashCode == Failed_HASH)
{
return ScalingActivityStatusCode::Failed;
}
else if (hashCode == Cancelled_HASH)
{
return ScalingActivityStatusCode::Cancelled;
}
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
overflowContainer->StoreOverflow(hashCode, name);
return static_cast<ScalingActivityStatusCode>(hashCode);
}
return ScalingActivityStatusCode::NOT_SET;
}
Aws::String GetNameForScalingActivityStatusCode(ScalingActivityStatusCode enumValue)
{
switch(enumValue)
{
case ScalingActivityStatusCode::PendingSpotBidPlacement:
return "PendingSpotBidPlacement";
case ScalingActivityStatusCode::WaitingForSpotInstanceRequestId:
return "WaitingForSpotInstanceRequestId";
case ScalingActivityStatusCode::WaitingForSpotInstanceId:
return "WaitingForSpotInstanceId";
case ScalingActivityStatusCode::WaitingForInstanceId:
return "WaitingForInstanceId";
case ScalingActivityStatusCode::PreInService:
return "PreInService";
case ScalingActivityStatusCode::InProgress:
return "InProgress";
case ScalingActivityStatusCode::WaitingForELBConnectionDraining:
return "WaitingForELBConnectionDraining";
case ScalingActivityStatusCode::MidLifecycleAction:
return "MidLifecycleAction";
case ScalingActivityStatusCode::WaitingForInstanceWarmup:
return "WaitingForInstanceWarmup";
case ScalingActivityStatusCode::Successful:
return "Successful";
case ScalingActivityStatusCode::Failed:
return "Failed";
case ScalingActivityStatusCode::Cancelled:
return "Cancelled";
default:
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
}
return "";
}
}
} // namespace ScalingActivityStatusCodeMapper
} // namespace Model
} // namespace AutoScaling
} // namespace Aws
| 41.286667 | 124 | 0.676086 | [
"model"
] |
a3c560e7440bfbd17cdf8d5d3280fa8b71a55275 | 7,391 | cpp | C++ | src/view/view-3d.cpp | pushqrdx/wayfire | f012f82ba3fba861bf23a175941591921e1fdd22 | [
"MIT"
] | 1 | 2020-05-28T22:28:49.000Z | 2020-05-28T22:28:49.000Z | src/view/view-3d.cpp | myfreeweb/wayfire | c56e5a555ed54156270d39dbd5e2ec73d7cf76a7 | [
"MIT"
] | null | null | null | src/view/view-3d.cpp | myfreeweb/wayfire | c56e5a555ed54156270d39dbd5e2ec73d7cf76a7 | [
"MIT"
] | null | null | null | #include "wayfire/view-transform.hpp"
#include "wayfire/opengl.hpp"
#include "wayfire/core.hpp"
#include "wayfire/output.hpp"
#include <algorithm>
#include <cmath>
#include <glm/gtc/matrix_transform.hpp>
#define PI 3.14159265359
wlr_box wf::view_transformer_t::get_bounding_box(wf::geometry_t view, wlr_box region)
{
const auto p1 = transform_point(view, {1.0 * region.x, 1.0 * region.y});
const auto p2 = transform_point(view, {1.0 * region.x + region.width,
1.0 * region.y});
const auto p3 = transform_point(view, {1.0 * region.x,
1.0 * region.y + region.height});
const auto p4 = transform_point(view, {1.0 * region.x + region.width,
1.0 * region.y + region.height});
const int x1 = std::min({p1.x, p2.x, p3.x, p4.x});
const int x2 = std::max({p1.x, p2.x, p3.x, p4.x});
const int y1 = std::min({p1.y, p2.y, p3.y, p4.y});
const int y2 = std::max({p1.y, p2.y, p3.y, p4.y});
return wlr_box{x1, y1, x2 - x1, y2 - y1};
}
wf::region_t wf::view_transformer_t::transform_opaque_region(
wf::geometry_t box, wf::region_t region)
{
return {};
}
void wf::view_transformer_t::render_with_damage(wf::texture_t src_tex,
wlr_box src_box,
const wf::region_t& damage, const wf::framebuffer_t& target_fb)
{
for (const auto& rect : damage)
{
render_box(src_tex, src_box, wlr_box_from_pixman_box(rect), target_fb);
}
}
struct transformable_quad
{
gl_geometry geometry;
float off_x, off_y;
};
static wf::point_t get_center(wf::geometry_t view)
{
return {
view.x + view.width / 2,
view.y + view.height / 2
};
}
static wf::pointf_t get_center_relative_coords(wf::geometry_t view,
wf::pointf_t point)
{
return {
(point.x - view.x) - view.width / 2.0,
view.height / 2.0 - (point.y - view.y)
};
}
static wf::pointf_t get_absolute_coords_from_relative(wf::geometry_t view,
wf::pointf_t point)
{
return {
point.x + view.x + view.width / 2.0,
(view.height / 2.0 - point.y) + view.y
};
}
static transformable_quad center_geometry(wf::geometry_t output_geometry,
wf::geometry_t geometry,
wf::point_t target_center)
{
transformable_quad quad;
geometry.x -= output_geometry.x;
geometry.y -= output_geometry.y;
target_center.x -= output_geometry.x;
target_center.y -= output_geometry.y;
quad.geometry.x1 = -(target_center.x - geometry.x);
quad.geometry.y1 = (target_center.y - geometry.y);
quad.geometry.x2 = quad.geometry.x1 + geometry.width;
quad.geometry.y2 = quad.geometry.y1 - geometry.height;
quad.off_x = (geometry.x - output_geometry.width / 2.0) - quad.geometry.x1;
quad.off_y = (output_geometry.height / 2.0 - geometry.y) - quad.geometry.y1;
return quad;
}
wf::view_2D::view_2D(wayfire_view view)
{
this->view = view;
}
static void rotate_xy(float& x, float& y, float angle)
{
auto v = glm::vec4{x, y, 0, 1};
auto rot = glm::rotate(glm::mat4(1.0), angle, {0, 0, 1});
v = rot * v;
x = v.x;
y = v.y;
}
wf::pointf_t wf::view_2D::transform_point(
wf::geometry_t geometry, wf::pointf_t point)
{
auto p2 = get_center_relative_coords(view->get_wm_geometry(), point);
float x = p2.x, y = p2.y;
x *= scale_x;
y *= scale_y;
rotate_xy(x, y, angle);
x += translation_x;
y -= translation_y;
auto r = get_absolute_coords_from_relative(view->get_wm_geometry(), {x, y});
return r;
}
wf::pointf_t wf::view_2D::untransform_point(
wf::geometry_t geometry, wf::pointf_t point)
{
point = get_center_relative_coords(view->get_wm_geometry(), point);
float x = point.x, y = point.y;
x -= translation_x;
y += translation_y;
rotate_xy(x, y, -angle);
x /= scale_x;
y /= scale_y;
return get_absolute_coords_from_relative(view->get_wm_geometry(), {x, y});
}
void wf::view_2D::render_box(wf::texture_t src_tex, wlr_box src_box,
wlr_box scissor_box, const wf::framebuffer_t& fb)
{
auto quad =
center_geometry(fb.geometry, src_box, get_center(view->get_wm_geometry()));
quad.geometry.x1 *= scale_x;
quad.geometry.x2 *= scale_x;
quad.geometry.y1 *= scale_y;
quad.geometry.y2 *= scale_y;
auto rotate = glm::rotate(glm::mat4(1.0), angle, {0, 0, 1});
auto translate = glm::translate(glm::mat4(1.0),
{quad.off_x + translation_x,
quad.off_y - translation_y, 0});
auto ortho = glm::ortho(-fb.geometry.width / 2.0f, fb.geometry.width / 2.0f,
-fb.geometry.height / 2.0f, fb.geometry.height / 2.0f);
auto transform = fb.transform * ortho * translate * rotate;
OpenGL::render_begin(fb);
fb.logic_scissor(scissor_box);
OpenGL::render_transformed_texture(src_tex, quad.geometry, {},
transform, {1.0f, 1.0f, 1.0f, alpha});
OpenGL::render_end();
}
const float wf::view_3D::fov = PI / 4;
glm::mat4 wf::view_3D::default_view_matrix()
{
return glm::lookAt(
glm::vec3(0., 0., 1.0 / std::tan(fov / 2)),
glm::vec3(0., 0., 0.),
glm::vec3(0., 1., 0.));
}
glm::mat4 wf::view_3D::default_proj_matrix()
{
return glm::perspective(fov, 1.0f, .1f, 100.f);
}
wf::view_3D::view_3D(wayfire_view view)
{
this->view = view;
view_proj = default_proj_matrix() * default_view_matrix();
}
/* TODO: cache total_transform, because it is often unnecessarily recomputed */
glm::mat4 wf::view_3D::calculate_total_transform()
{
auto og = view->get_output()->get_relative_geometry();
glm::mat4 depth_scale =
glm::scale(glm::mat4(1.0), {1, 1, 2.0 / std::min(og.width, og.height)});
return translation * view_proj * depth_scale * rotation * scaling;
}
wf::pointf_t wf::view_3D::transform_point(
wf::geometry_t geometry, wf::pointf_t point)
{
auto p = get_center_relative_coords(geometry, point);
glm::vec4 v(1.0f * p.x, 1.0f * p.y, 0, 1);
v = calculate_total_transform() * v;
if (std::abs(v.w) < 1e-6)
{
/* This should never happen as long as we use well-behaving matrices.
* However if we set transform to the zero matrix we might get
* this case where v.w is zero. In this case we assume the view is
* just a single point at 0,0 */
v.x = v.y = 0;
} else
{
v.x /= v.w;
v.y /= v.w;
}
return get_absolute_coords_from_relative(geometry, {v.x, v.y});
}
/* TODO: is there a way to realiably reverse projective transformations? */
wf::pointf_t wf::view_3D::untransform_point(wf::geometry_t geometry,
wf::pointf_t point)
{
return {wf::compositor_core_t::invalid_coordinate,
wf::compositor_core_t::invalid_coordinate};
}
void wf::view_3D::render_box(wf::texture_t src_tex, wlr_box src_box,
wlr_box scissor_box, const wf::framebuffer_t& fb)
{
auto quad = center_geometry(fb.geometry, src_box, get_center(src_box));
auto transform = calculate_total_transform();
auto translate = glm::translate(glm::mat4(1.0), {quad.off_x, quad.off_y, 0});
auto scale = glm::scale(glm::mat4(1.0), {
2.0 / fb.geometry.width,
2.0 / fb.geometry.height,
1.0
});
transform = fb.transform * scale * translate * transform;
OpenGL::render_begin(fb);
fb.logic_scissor(scissor_box);
OpenGL::render_transformed_texture(src_tex, quad.geometry, {},
transform, color);
OpenGL::render_end();
}
| 28.647287 | 85 | 0.644297 | [
"geometry",
"transform"
] |
a3c59bc83b168c94be4a0b9b93d19dbb157d1125 | 660 | cpp | C++ | source/filter.cpp | MarianFriedrich/3_programmiersprachen-blatt | 0bd4087b29fa628a7e9ff0a0f489402b08685bd1 | [
"MIT"
] | null | null | null | source/filter.cpp | MarianFriedrich/3_programmiersprachen-blatt | 0bd4087b29fa628a7e9ff0a0f489402b08685bd1 | [
"MIT"
] | null | null | null | source/filter.cpp | MarianFriedrich/3_programmiersprachen-blatt | 0bd4087b29fa628a7e9ff0a0f489402b08685bd1 | [
"MIT"
] | null | null | null | #define CATCH_CONFIG_RUNNER
#include <catch.hpp>
#include <vector>
bool is_even(int i);
bool is_odd(int i);
bool is_even(int i){return((i%2)==0);}
bool is_odd(int i){return((i%2)==1);}
// Filter
template <typename container, typename function>
container filter(container cont, function func)
{
cont.erase(std::remove_if(cont.begin(), cont.end(), func),cont.end());
return cont;
}
TEST_CASE("describe_filter","[filter]")
{
std::vector<int> v1{1,2,3,4,5,6};
std::vector<int> alleven = filter(v1, is_odd);
REQUIRE(std::all_of(alleven.begin(),alleven.end(),is_even));
}
int main(int argc, char *argv[])
{
return Catch::Session().run(argc, argv);
}
| 20.625 | 71 | 0.686364 | [
"vector"
] |
a3c683d1537a9d4e9d06806282a21e83d4b8edb9 | 1,929 | cpp | C++ | inference-engine/src/transformations/src/transformations/op_conversions/convert_gelu.cpp | Andruxin52rus/openvino | d824e371fe7dffb90e6d3d58e4e34adecfce4606 | [
"Apache-2.0"
] | 1 | 2022-01-19T15:36:45.000Z | 2022-01-19T15:36:45.000Z | inference-engine/src/transformations/src/transformations/op_conversions/convert_gelu.cpp | Andruxin52rus/openvino | d824e371fe7dffb90e6d3d58e4e34adecfce4606 | [
"Apache-2.0"
] | 22 | 2021-02-03T12:41:51.000Z | 2022-02-21T13:04:48.000Z | inference-engine/src/transformations/src/transformations/op_conversions/convert_gelu.cpp | mmakridi/openvino | 769bb7709597c14debdaa356dd60c5a78bdfa97e | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2018-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "itt.hpp"
#include <memory>
#include <ngraph/opsets/opset2.hpp>
#include <transformations/op_conversions/convert_gelu.hpp>
#include <transformations/utils/utils.hpp>
#include <ngraph/ngraph.hpp>
#include <ngraph/rt_info.hpp>
#include <ngraph/pattern/op/wrap_type.hpp>
NGRAPH_RTTI_DEFINITION(ngraph::pass::ConvertGELU, "ConvertGELU", 0);
ngraph::pass::ConvertGELU::ConvertGELU() {
MATCHER_SCOPE(ConvertGELU);
auto gelu = pattern::wrap_type<ngraph::opset2::Gelu>();
ngraph::matcher_pass_callback callback = [this](pattern::Matcher& m) {
auto gelu = std::dynamic_pointer_cast<ngraph::opset2::Gelu>(m.get_match_root());
if (!gelu || transformation_callback(gelu))
return false;
auto input = gelu->input_value(0);
auto input_type = input.get_element_type();
// f(x) = 0.5 * x * (1.0 + erf( x / sqrt(2.0) )
auto mul = std::make_shared<ngraph::opset1::Multiply>(input, ngraph::opset1::Constant::create(input_type, Shape{}, {0.5}));
auto sq2 = std::make_shared<ngraph::opset1::Sqrt>(ngraph::opset1::Constant::create(input_type, Shape{}, {2.0}));
auto div = register_new_node<ngraph::opset1::Divide>(input, sq2); // can be decomposed
auto erf = std::make_shared<ngraph::opset1::Erf>(div);
auto add = std::make_shared<ngraph::opset1::Add>(erf, ngraph::opset1::Constant::create(input_type, Shape{}, {1.0}));
auto res = std::make_shared<ngraph::opset1::Multiply>(mul, add);
res->set_friendly_name(gelu->get_friendly_name());
ngraph::copy_runtime_info(gelu, {mul, sq2, div, erf, add, res});
ngraph::replace_node(gelu, res);
return true;
};
auto m = std::make_shared<ngraph::pattern::Matcher>(gelu, matcher_name);
register_matcher(m, callback, PassProperty::CHANGE_DYNAMIC_STATE);
}
| 42.866667 | 131 | 0.676516 | [
"shape"
] |
a3cd123305ba675762af80d52568e2b1f50fdfcf | 45,324 | cpp | C++ | emulator/src/devices/bus/isa/trident.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | 1 | 2022-01-15T21:38:38.000Z | 2022-01-15T21:38:38.000Z | emulator/src/devices/bus/isa/trident.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | emulator/src/devices/bus/isa/trident.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | // license:BSD-3-Clause
// copyright-holders:Barry Rodewald
/*
* trident.c
*
* Implementation of Trident VGA GUI accelerators
*
*
*/
#include "emu.h"
#include "trident.h"
#include "debugger.h"
#include "screen.h"
DEFINE_DEVICE_TYPE(TRIDENT_VGA, tgui9860_device, "trident_vga", "Trident TGUI9860")
DEFINE_DEVICE_TYPE(TVGA9000_VGA, tvga9000_device, "tvga9000_vga", "Trident TVGA9000")
#define CRTC_PORT_ADDR ((vga.miscellaneous_output&1)?0x3d0:0x3b0)
#define LOG (1)
#define LOG_ACCEL (1)
trident_vga_device::trident_vga_device(const machine_config &mconfig, device_type type, const char *tag, device_t *owner, uint32_t clock)
: svga_device(mconfig, type, tag, owner, clock)
{
}
tgui9860_device::tgui9860_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: trident_vga_device(mconfig, TRIDENT_VGA, tag, owner, clock)
{
m_version = 0xd3; // 0xd3 identifies at TGUI9660XGi (set to 0xe3 to identify at TGUI9440AGi)
}
tvga9000_device::tvga9000_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: trident_vga_device(mconfig, TVGA9000_VGA, tag, owner, clock)
{
m_version = 0x43;
}
uint8_t trident_vga_device::READPIXEL8(int16_t x, int16_t y)
{
return (vga.memory[((y & 0xfff)*offset() + (x & 0xfff)) % vga.svga_intf.vram_size]);
}
uint16_t trident_vga_device::READPIXEL15(int16_t x, int16_t y)
{
return (vga.memory[((y & 0xfff)*offset() + (x & 0xfff)*2) % vga.svga_intf.vram_size] |
(vga.memory[((y & 0xfff)*offset() + ((x & 0xfff)*2)+1) % vga.svga_intf.vram_size] << 8));
}
uint16_t trident_vga_device::READPIXEL16(int16_t x, int16_t y)
{
return (vga.memory[((y & 0xfff)*offset() + (x & 0xfff)*2) % vga.svga_intf.vram_size] |
(vga.memory[((y & 0xfff)*offset() + ((x & 0xfff)*2)+1) % vga.svga_intf.vram_size] << 8));
}
uint32_t trident_vga_device::READPIXEL32(int16_t x, int16_t y)
{
return (vga.memory[((y & 0xfff)*offset() + (x & 0xfff)*4) % vga.svga_intf.vram_size] |
(vga.memory[((y & 0xfff)*offset() + ((x & 0xfff)*4)+1) % vga.svga_intf.vram_size] << 8) |
(vga.memory[((y & 0xfff)*offset() + ((x & 0xfff)*4)+2) % vga.svga_intf.vram_size] << 16) |
(vga.memory[((y & 0xfff)*offset() + ((x & 0xfff)*4)+3) % vga.svga_intf.vram_size] << 24));
}
void trident_vga_device::WRITEPIXEL8(int16_t x, int16_t y, uint8_t data)
{
if((x & 0xfff)<tri.accel_dest_x_clip && (y & 0xfff)<tri.accel_dest_y_clip)
{
data = handle_rop(data,READPIXEL8(x,y)) & 0xff;
vga.memory[((y & 0xfff)*offset() + (x & 0xfff)) % vga.svga_intf.vram_size] = data;
}
}
void trident_vga_device::WRITEPIXEL15(int16_t x, int16_t y, uint16_t data)
{
if((x & 0xfff)<tri.accel_dest_x_clip && (y & 0xfff)<tri.accel_dest_y_clip)
{
data = handle_rop(data,READPIXEL8(x,y)) & 0x7fff;
vga.memory[((y & 0xfff)*offset() + (x & 0xfff)*2) % vga.svga_intf.vram_size] = data & 0x00ff;
vga.memory[((y & 0xfff)*offset() + ((x & 0xfff)*2)+1) % vga.svga_intf.vram_size] = (data & 0x7f00) >> 8;
}
}
void trident_vga_device::WRITEPIXEL16(int16_t x, int16_t y, uint16_t data)
{
if((x & 0xfff)<tri.accel_dest_x_clip && (y & 0xfff)<tri.accel_dest_y_clip)
{
data = handle_rop(data,READPIXEL8(x,y)) & 0xffff;
vga.memory[((y & 0xfff)*offset() + (x & 0xfff)*2) % vga.svga_intf.vram_size] = data & 0x00ff;
vga.memory[((y & 0xfff)*offset() + ((x & 0xfff)*2)+1) % vga.svga_intf.vram_size] = (data & 0xff00) >> 8;
}
}
void trident_vga_device::WRITEPIXEL32(int16_t x, int16_t y, uint32_t data)
{
if((x & 0xfff)<tri.accel_dest_x_clip && (y & 0xfff)<tri.accel_dest_y_clip)
{
data = handle_rop(data,READPIXEL8(x,y));
vga.memory[((y & 0xfff)*offset() + (x & 0xfff)*4) % vga.svga_intf.vram_size] = data & 0x000000ff;
vga.memory[((y & 0xfff)*offset() + ((x & 0xfff)*4)+1) % vga.svga_intf.vram_size] = (data & 0x0000ff00) >> 8;
vga.memory[((y & 0xfff)*offset() + ((x & 0xfff)*4)+2) % vga.svga_intf.vram_size] = (data & 0x00ff0000) >> 16;
vga.memory[((y & 0xfff)*offset() + ((x & 0xfff)*4)+3) % vga.svga_intf.vram_size] = (data & 0xff000000) >> 24;
}
}
uint32_t trident_vga_device::handle_rop(uint32_t src, uint32_t dst)
{
switch(tri.accel_fmix) // TODO: better understand this register
{
case 0xf0: // PAT
case 0xcc: // SRC
break; // pass data through
case 0x00: // 0
src = 0;
break;
case 0xff: // 1
src = 0xffffffff;
break;
case 0x66: // XOR
case 0x5a: // XOR PAT
src = dst ^ src;
break;
case 0xb8: // PAT xor (SRC and (DST xor PAT)) (correct?)
src = src & (dst ^ src);
break;
}
return src;
}
uint32_t trident_vga_device::READPIXEL(int16_t x,int16_t y)
{
if(svga.rgb8_en)
return READPIXEL8(x,y) & 0xff;
if(svga.rgb15_en)
return READPIXEL15(x,y) & 0x7fff;
if(svga.rgb16_en)
return READPIXEL16(x,y) & 0xffff;
if(svga.rgb32_en)
return READPIXEL32(x,y);
return 0; // should never reach here
}
void trident_vga_device::WRITEPIXEL(int16_t x,int16_t y, uint32_t data)
{
if(svga.rgb8_en)
WRITEPIXEL8(x,y,(((data >> 8) & 0xff) | (data & 0xff))); // XFree86 3.3 sets bits 0-7 to 0 when using mono patterns, does it OR each byte?
if(svga.rgb15_en)
WRITEPIXEL15(x,y,data & 0x7fff);
if(svga.rgb16_en)
WRITEPIXEL16(x,y,data & 0xffff);
if(svga.rgb32_en)
WRITEPIXEL32(x,y,data);
}
void trident_vga_device::device_start()
{
zero();
int i;
for (i = 0; i < 0x100; i++)
set_pen_color(i, 0, 0, 0);
// Avoid an infinite loop when displaying. 0 is not possible anyway.
vga.crtc.maximum_scan_line = 1;
// copy over interfaces
vga.read_dipswitch = read8_delegate(); //read_dipswitch;
vga.svga_intf.vram_size = 0x200000;
vga.memory.resize(vga.svga_intf.vram_size);
memset(&vga.memory[0], 0, vga.svga_intf.vram_size);
save_item(NAME(vga.memory));
save_pointer(vga.crtc.data,"CRTC Registers",0x100);
save_pointer(vga.sequencer.data,"Sequencer Registers",0x100);
save_pointer(vga.attribute.data,"Attribute Registers", 0x15);
save_pointer(tri.accel_pattern,"Pattern Data", 0x80);
save_pointer(tri.lutdac_reg,"LUTDAC registers", 0x100);
m_vblank_timer = machine().scheduler().timer_alloc(timer_expired_delegate(FUNC(vga_device::vblank_timer_cb),this));
vga.svga_intf.seq_regcount = 0x0f;
vga.svga_intf.crtc_regcount = 0x60;
memset(&tri, 0, sizeof(tri));
}
void trident_vga_device::device_reset()
{
svga_device::device_reset();
svga.id = m_version;
tri.revision = 0x01; // revision identifies as TGUI9680
tri.new_mode = false; // start up in old mode
tri.dac_active = false;
tri.linear_active = false;
tri.mmio_active = false;
tri.sr0f = 0x6f;
tri.sr0c = 0x70;
tri.cr2a = 0x03; // set ISA interface?
tri.mem_clock = 0x2c6; // 50MHz default
tri.vid_clock = 0;
tri.port_3c3 = true;
tri.accel_busy = false;
tri.accel_memwrite_active = false;
// Windows 3.1 TGUI9440AGi drivers do not set the pointer colour registers?
tri.cursor_bg = 0x00000000;
tri.cursor_fg = 0xffffffff;
tri.pixel_depth = 0x10; //disable 8bpp mode by default
}
uint32_t trident_vga_device::screen_update(screen_device &screen, bitmap_rgb32 &bitmap, const rectangle &cliprect)
{
uint8_t cur_mode;
svga_device::screen_update(screen,bitmap,cliprect);
cur_mode = pc_vga_choosevideomode();
// draw hardware graphics cursor
if(tri.cursor_ctrl & 0x80) // if cursor is enabled
{
uint32_t src;
uint32_t* dst;
uint8_t val;
int x,y;
uint16_t cx = tri.cursor_x & 0x0fff;
uint16_t cy = tri.cursor_y & 0x0fff;
uint32_t bg_col;
uint32_t fg_col;
uint8_t cursor_size = (tri.cursor_ctrl & 0x01) ? 64 : 32;
if(cur_mode == SCREEN_OFF || cur_mode == TEXT_MODE || cur_mode == MONO_MODE || cur_mode == CGA_MODE || cur_mode == EGA_MODE)
return 0; // cursor only works in VGA or SVGA modes
src = tri.cursor_loc * 1024; // start address is in units of 1024 bytes
if(cur_mode == RGB16_MODE)
{
bg_col = tri.cursor_bg;
fg_col = tri.cursor_fg;
}
else /* TODO: other modes */
{
bg_col = pen(tri.cursor_bg & 0xff);
fg_col = pen(tri.cursor_fg & 0xff);
}
for(y=0;y<cursor_size;y++)
{
uint8_t bitcount = 31;
dst = &bitmap.pix32(cy + y, cx);
for(x=0;x<cursor_size;x++)
{
uint32_t bitb = (vga.memory[(src+3) % vga.svga_intf.vram_size]
| ((vga.memory[(src+2) % vga.svga_intf.vram_size]) << 8)
| ((vga.memory[(src+1) % vga.svga_intf.vram_size]) << 16)
| ((vga.memory[(src+0) % vga.svga_intf.vram_size]) << 24));
uint32_t bita = (vga.memory[(src+7) % vga.svga_intf.vram_size]
| ((vga.memory[(src+6) % vga.svga_intf.vram_size]) << 8)
| ((vga.memory[(src+5) % vga.svga_intf.vram_size]) << 16)
| ((vga.memory[(src+4) % vga.svga_intf.vram_size]) << 24));
val = (BIT(bita << 1,bitcount+1) << 1 | BIT(bitb,bitcount));
if(tri.cursor_ctrl & 0x40)
{ // X11 mode
switch(val)
{
case 0x00:
// no change
break;
case 0x01:
dst[x] = bg_col;
break;
case 0x02:
// no change
break;
case 0x03:
dst[x] = fg_col;
break;
}
}
else
{ // Windows mode
switch(val)
{
case 0x00:
dst[x] = bg_col;
break;
case 0x01:
// no change
break;
case 0x02: // screen data
dst[x] = fg_col;
break;
case 0x03: // inverted screen data
dst[x] = ~(dst[x]);
break;
}
}
bitcount--;
if(x % 32 == 31)
{
src+=8;
bitcount=31;
}
}
}
}
return 0;
}
uint16_t trident_vga_device::offset()
{
uint16_t off = svga_device::offset();
if (svga.rgb8_en || svga.rgb15_en || svga.rgb16_en || svga.rgb32_en)
return vga.crtc.offset << 3; // don't know if this is right, but Eggs Playing Chicken switches off doubleword mode, but expects the same offset length
else
return off;
}
int trident_vga_device::calculate_clock()
{
// Bits 0-6: M
// Bits 7-11: N
// Bit 12: K
// Later formula extends each variable by one extra bit (Providia 9685 and later)
double freq;
uint8_t m,n,k;
m = tri.vid_clock & 0x007f;
n = (tri.vid_clock & 0x0f80) >> 7;
k = (tri.vid_clock & 0x1000) >> 12;
freq = ((double)(m+8) / (double)((n+2)*(pow(2.0,k)))) * 14.31818; // there is a 14.31818MHz clock on the board
return freq * 1000000;
}
void trident_vga_device::trident_define_video_mode()
{
int divisor = 1;
int xtal;
/* // clock select for TGUI9440CXi and earlier
switch(tri.clock)
{
case 0:
default: xtal = 25174800; break;
case 1: xtal = 28636363; break;
case 2: xtal = 44900000; break;
case 3: xtal = 36000000; break;
case 4: xtal = 57272000; break;
case 5: xtal = 65000000; break;
case 6: xtal = 50350000; break;
case 7: xtal = 40000000; break;
case 8: xtal = 88000000; break;
case 9: xtal = 98000000; break;
case 10: xtal = 118800000; break;
case 11: xtal = 108000000; break;
case 12: xtal = 72000000; break;
case 13: xtal = 77000000; break;
case 14: xtal = 80000000; break;
case 15: xtal = 75000000; break;
}
switch((tri.sr0d_new & 0x06) >> 1)
{
case 0:
default: break; // no division
case 1: xtal = xtal / 2; break;
case 2: xtal = xtal / 4; break;
case 3: xtal = xtal / 1.5; break;
}*/
// TGUI9440AGi/9660/9680/9682 programmable clock
switch((vga.miscellaneous_output & 0x0c) >> 2)
{
case 0:
default: xtal = 25174800; break;
case 1: xtal = 28636363; break;
case 2: xtal = calculate_clock(); break;
}
if(tri.gc0f & 0x08) // 16 pixels per character clock
xtal = xtal / 2;
if(tri.port_3db & 0x20)
xtal = xtal / 2; // correct?
svga.rgb8_en = svga.rgb15_en = svga.rgb16_en = svga.rgb32_en = 0;
switch((tri.pixel_depth & 0x0c) >> 2)
{
case 0:
default: if(!(tri.pixel_depth & 0x10) || (tri.cr1e & 0x80)) svga.rgb8_en = 1; break;
case 1: if((tri.dac & 0xf0) == 0x30) svga.rgb16_en = 1; else svga.rgb15_en = 1; break;
case 2: svga.rgb32_en = 1; break;
}
if((tri.cr1e & 0x80) && (svga.id == 0x43))
divisor = 2;
recompute_params_clock(divisor, xtal);
}
uint8_t trident_vga_device::trident_seq_reg_read(uint8_t index)
{
uint8_t res;
res = 0xff;
if(index <= 0x04)
res = vga.sequencer.data[index];
else
{
switch(index)
{
case 0x09:
res = tri.revision;
break;
case 0x0b:
res = svga.id;
tri.new_mode = true;
break;
case 0x0c: // Power Up Mode register 1
res = tri.sr0c & 0xef;
if(tri.port_3c3)
res |= 0x10;
break;
case 0x0d: // Mode Control 2
//res = svga.rgb15_en;
if(tri.new_mode)
res = tri.sr0d_new;
else
res = tri.sr0d_old;
break;
case 0x0e: // Mode Control 1
if(tri.new_mode)
res = tri.sr0e_new;
else
res = tri.sr0e_old;
break;
case 0x0f: // Power Up Mode 2
res = tri.sr0f;
break;
default:
res = vga.sequencer.data[index];
if(!LOG) logerror("Trident: Sequencer index %02x read\n",index);
}
}
if(LOG) logerror("Trident SR%02X: read %02x\n",index,res);
return res;
}
void trident_vga_device::trident_seq_reg_write(uint8_t index, uint8_t data)
{
vga.sequencer.data[vga.sequencer.index] = data;
if(index <= 0x04)
{
seq_reg_write(vga.sequencer.index,data);
recompute_params();
}
else
{
switch(index)
{
case 0x0b:
tri.new_mode = false;
break;
case 0x0c: // Power Up Mode register 1
if(data & 0x10)
tri.port_3c3 = true; // 'post port at 0x3c3'
else
tri.port_3c3 = false; // 'post port at 0x46e8'
tri.sr0c = data;
break;
case 0x0d: // Mode Control 2
if(tri.new_mode)
{
tri.sr0d_new = data;
tri.clock = ((vga.miscellaneous_output & 0x0c) >> 2) | ((data & 0x01) << 2) | ((data & 0x40) >> 3);
trident_define_video_mode();
}
else
tri.sr0d_old = data;
break;
case 0x0e: // Mode Control 1
if(tri.new_mode)
{
tri.sr0e_new = data ^ 0x02;
svga.bank_w = (data & 0x3f) ^ 0x02; // bit 1 is inverted, used for card detection, it is not XORed on reading
if(!(tri.gc0f & 0x01))
svga.bank_r = (data & 0x3f) ^ 0x02;
// TODO: handle planar modes, where bits 0 and 2 only are used
}
else
{
tri.sr0e_old = data;
svga.bank_w = data & 0x0e;
if(!(tri.gc0f & 0x01))
svga.bank_r = data & 0x0e;
}
break;
case 0x0f: // Power Up Mode 2
tri.sr0f = data;
break;
default:
if(!LOG) logerror("Trident: Sequencer index %02x read\n",index);
}
}
if(LOG) logerror("Trident SR%02X: %s mode write %02x\n",index,tri.new_mode ? "new" : "old",data);
}
uint8_t trident_vga_device::trident_crtc_reg_read(uint8_t index)
{
uint8_t res = 0;
if(index <= 0x18)
res = crtc_reg_read(index);
else
{
switch(index)
{
case 0x1e:
res = tri.cr1e;
break;
case 0x1f:
res = tri.cr1f;
break;
case 0x20:
res = tri.cr20;
break;
case 0x21:
res = tri.cr21;
break;
case 0x24:
if(vga.attribute.state != 0)
res |= 0x80;
break;
case 0x26:
res = vga.attribute.index;
break;
case 0x27:
res = (vga.crtc.start_addr & 0x60000) >> 17;
break;
case 0x29:
res = tri.cr29;
break;
case 0x2a:
res = tri.cr2a;
break;
case 0x38:
res = tri.pixel_depth;
break;
case 0x39:
res = tri.cr39;
break;
case 0x40:
res = (tri.cursor_x & 0x00ff);
break;
case 0x41:
res = (tri.cursor_x & 0xff00) >> 8;
break;
case 0x42:
res = (tri.cursor_y & 0x00ff);
break;
case 0x43:
res = (tri.cursor_y & 0xff00) >> 8;
break;
case 0x44:
res = (tri.cursor_loc & 0x00ff);
break;
case 0x45:
res = (tri.cursor_loc & 0xff00) >> 8;
break;
case 0x46:
res = tri.cursor_x_off;
break;
case 0x47:
res = tri.cursor_y_off;
break;
case 0x48:
res = (tri.cursor_fg & 0x000000ff);
break;
case 0x49:
res = (tri.cursor_fg & 0x0000ff00) >> 8;
break;
case 0x4a:
res = (tri.cursor_fg & 0x00ff0000) >> 16;
break;
case 0x4b:
res = (tri.cursor_fg & 0xff000000) >> 24;
break;
case 0x4c:
res = (tri.cursor_bg & 0x000000ff);
break;
case 0x4d:
res = (tri.cursor_bg & 0x0000ff00) >> 8;
break;
case 0x4e:
res = (tri.cursor_bg & 0x00ff0000) >> 16;
break;
case 0x4f:
res = (tri.cursor_bg & 0xff000000) >> 24;
break;
case 0x50:
res = tri.cursor_ctrl;
break;
default:
res = vga.crtc.data[index];
if(!LOG) logerror("Trident: CRTC index %02x read\n",index);
break;
}
}
if(LOG) logerror("Trident CR%02X: read %02x\n",index,res);
return res;
}
void trident_vga_device::trident_crtc_reg_write(uint8_t index, uint8_t data)
{
if(index <= 0x18)
{
crtc_reg_write(index,data);
trident_define_video_mode();
}
else
{
switch(index)
{
case 0x1e: // Module Testing Register
tri.cr1e = data;
vga.crtc.start_addr = (vga.crtc.start_addr & 0xfffeffff) | ((data & 0x20)<<11);
break;
case 0x1f:
tri.cr1f = data; // "Software Programming Register" written to by the BIOS
break;
case 0x20: // FIFO Control (old MMIO enable? no documentation of this register)
tri.cr20 = data;
break;
case 0x21: // Linear aperture
tri.cr21 = data;
tri.linear_address = ((data & 0xc0)<<18) | ((data & 0x0f)<<20);
tri.linear_active = data & 0x20;
if(tri.linear_active)
popmessage("Trident: Linear Aperture active - %08x, %s",tri.linear_address,(tri.cr21 & 0x10) ? "2MB" : "1MB" );
break;
case 0x27:
vga.crtc.start_addr = (vga.crtc.start_addr & 0xfff9ffff) | ((data & 0x03)<<17);
break;
case 0x29:
tri.cr29 = data;
vga.crtc.offset = (vga.crtc.offset & 0xfeff) | ((data & 0x10)<<4);
break;
case 0x2a:
tri.cr2a = data;
break;
case 0x38:
// bit 0: 16 bit bus
// bits 2-3: pixel depth (1=15/16bit, 2=24/32bit, 0=anything else)
// bit 5: packed mode
tri.pixel_depth = data;
trident_define_video_mode();
break;
case 0x39:
tri.cr39 = data;
tri.mmio_active = data & 0x01;
if(tri.mmio_active)
popmessage("Trident: MMIO activated");
break;
case 0x40:
tri.cursor_x = (tri.cursor_x & 0xff00) | data;
break;
case 0x41:
tri.cursor_x = (tri.cursor_x & 0x00ff) | (data << 8);
break;
case 0x42:
tri.cursor_y = (tri.cursor_y & 0xff00) | data;
break;
case 0x43:
tri.cursor_y = (tri.cursor_y & 0x00ff) | (data << 8);
break;
case 0x44:
tri.cursor_loc = (tri.cursor_loc & 0xff00) | data;
break;
case 0x45:
tri.cursor_loc = (tri.cursor_loc & 0x00ff) | (data << 8);
break;
case 0x46:
tri.cursor_x_off = data;
break;
case 0x47:
tri.cursor_y_off = data;
break;
case 0x48:
tri.cursor_fg = (tri.cursor_fg & 0xffffff00) | data;
break;
case 0x49:
tri.cursor_fg = (tri.cursor_fg & 0xffff00ff) | (data << 8);
break;
case 0x4a:
tri.cursor_fg = (tri.cursor_fg & 0xff00ffff) | (data << 16);
break;
case 0x4b:
tri.cursor_fg = (tri.cursor_fg & 0x00ffffff) | (data << 24);
break;
case 0x4c:
tri.cursor_bg = (tri.cursor_bg & 0xffffff00) | data;
break;
case 0x4d:
tri.cursor_bg = (tri.cursor_bg & 0xffff00ff) | (data << 8);
break;
case 0x4e:
tri.cursor_bg = (tri.cursor_bg & 0xff00ffff) | (data << 16);
break;
case 0x4f:
tri.cursor_bg = (tri.cursor_bg & 0x00ffffff) | (data << 24);
break;
case 0x50:
tri.cursor_ctrl = data;
break;
default:
if(!LOG) logerror("Trident: 3D4 index %02x write %02x\n",index,data);
break;
}
}
if(LOG) logerror("Trident CR%02X: write %02x\n",index,data);
}
uint8_t trident_vga_device::trident_gc_reg_read(uint8_t index)
{
uint8_t res;
if(index <= 0x0d)
res = gc_reg_read(index);
else
{
switch(index)
{
case 0x0e:
res = tri.gc0e;
break;
case 0x0f:
res = tri.gc0f;
break;
case 0x2f:
res = tri.gc2f;
break;
default:
res = 0xff;
if(!LOG) logerror("Trident: Sequencer index %02x read\n",index);
break;
}
}
if(LOG) logerror("Trident GC%02X: read %02x\n",index,res);
return res;
}
void trident_vga_device::trident_gc_reg_write(uint8_t index, uint8_t data)
{
if(index <= 0x0d)
gc_reg_write(index,data);
else
{
if(LOG) logerror("Trident GC%02X: write %02x\n",index,data);
switch(index)
{
case 0x0e: // New Source Address Register (bit 1 is inverted here, also)
tri.gc0e = data ^ 0x02;
if(!(tri.gc0f & 0x04)) // if bank regs at 0x3d8/9 are not enabled
{
if(tri.gc0f & 0x01) // if bank regs are separated
svga.bank_r = (data & 0x1f) ^ 0x02;
}
break;
case 0x0f:
tri.gc0f = data;
trident_define_video_mode();
break;
case 0x2f: // XFree86 refers to this register as "MiscIntContReg", setting bit 2, but gives no indication as to what it does
tri.gc2f = data;
break;
default:
if(!LOG) logerror("Trident: Unimplemented GC register %02x write %02x\n",index,data);
break;
}
}
if(LOG) logerror("Trident GC%02X: write %02x\n",index,data);
}
READ8_MEMBER(trident_vga_device::port_03c0_r)
{
uint8_t res;
switch(offset)
{
case 0x05:
res = trident_seq_reg_read(vga.sequencer.index);
break;
case 0x06:
tri.dac_count++;
if(tri.dac_count > 3)
tri.dac_active = true;
if(tri.dac_active)
res = tri.dac;
else
res = vga_device::port_03c0_r(space,offset,mem_mask);
break;
case 0x07:
case 0x08:
case 0x09:
tri.dac_active = false;
tri.dac_count = 0;
res = vga_device::port_03c0_r(space,offset,mem_mask);
break;
case 0x0f:
res = trident_gc_reg_read(vga.gc.index);
break;
default:
res = vga_device::port_03c0_r(space,offset,mem_mask);
break;
}
return res;
}
WRITE8_MEMBER(trident_vga_device::port_03c0_w)
{
switch(offset)
{
case 0x05:
trident_seq_reg_write(vga.sequencer.index,data);
break;
case 0x06:
if(tri.dac_active)
{
tri.dac = data; // DAC command register
tri.dac_active = false;
tri.dac_count = 0;
trident_define_video_mode();
}
else
vga_device::port_03c0_w(space,offset,data,mem_mask);
break;
case 0x07:
case 0x08:
case 0x09:
tri.dac_active = false;
tri.dac_count = 0;
vga_device::port_03c0_w(space,offset,data,mem_mask);
break;
case 0x0f:
trident_gc_reg_write(vga.gc.index,data);
break;
default:
vga_device::port_03c0_w(space,offset,data,mem_mask);
break;
}
}
READ8_MEMBER(trident_vga_device::port_03d0_r)
{
uint8_t res = 0xff;
if (CRTC_PORT_ADDR == 0x3d0)
{
switch(offset)
{
case 5:
res = trident_crtc_reg_read(vga.crtc.index);
break;
case 8:
if(tri.gc0f & 0x04) // if enabled
{
res = svga.bank_w & 0x3f;
}
else
res = 0xff;
break;
case 9:
if(tri.gc0f & 0x04) // if enabled
if(tri.gc0f & 0x01) // and if bank regs are separated
res = svga.bank_r & 0x3f;
else
res = 0xff;
else
res = 0xff;
break;
case 11:
res = tri.port_3db;
break;
default:
res = vga_device::port_03d0_r(space,offset,mem_mask);
break;
}
}
return res;
}
WRITE8_MEMBER(trident_vga_device::port_03d0_w)
{
if (CRTC_PORT_ADDR == 0x3d0)
{
switch(offset)
{
case 5:
vga.crtc.data[vga.crtc.index] = data;
trident_crtc_reg_write(vga.crtc.index,data);
break;
case 8:
if(tri.gc0f & 0x04) // if enabled
{
svga.bank_w = data & 0x3f;
if(LOG) logerror("Trident: Write Bank set to %02x\n",data);
if(!(tri.gc0f & 0x01)) // if bank regs are not separated
{
svga.bank_r = data & 0x3f; // then this is also the read bank register
if(LOG) logerror("Trident: Read Bank set to %02x\n",data);
}
}
break;
case 9:
if(tri.gc0f & 0x04) // if enabled
{
if(tri.gc0f & 0x01) // and if bank regs are separated
{
svga.bank_r = data & 0x3f;
if(LOG) logerror("Trident: Read Bank set to %02x\n",data);
}
}
break;
case 11:
tri.port_3db = data; // no info on this port? Bit 5 appears to be a clock divider...
break;
default:
vga_device::port_03d0_w(space,offset,data,mem_mask);
break;
}
}
}
READ8_MEMBER(trident_vga_device::port_43c6_r)
{
uint8_t res = 0xff;
switch(offset)
{
case 2:
res = tri.mem_clock & 0xff;
break;
case 3:
res = tri.mem_clock >> 8;
break;
case 4:
res = tri.vid_clock & 0xff;
break;
case 5:
res = tri.vid_clock >> 8;
break;
}
return res;
}
WRITE8_MEMBER(trident_vga_device::port_43c6_w)
{
switch(offset)
{
case 2:
if(!(tri.sr0e_new & 0x02) && (tri.sr0e_new & 0x80))
{
tri.mem_clock = (tri.mem_clock & 0xff00) | (data);
if(LOG) logerror("Trident: Memory clock write %04x\n",tri.mem_clock);
}
break;
case 3:
if(!(tri.sr0e_new & 0x02) && (tri.sr0e_new & 0x80))
{
tri.mem_clock = (tri.mem_clock & 0x00ff) | (data << 8);
if(LOG) logerror("Trident: Memory clock write %04x\n",tri.mem_clock);
}
break;
case 4:
if(!(tri.sr0e_new & 0x02) && (tri.sr0e_new & 0x80))
{
tri.vid_clock = (tri.vid_clock & 0xff00) | (data);
if(LOG) logerror("Trident: Video clock write %04x\n",tri.vid_clock);
}
break;
case 5:
if(!(tri.sr0e_new & 0x02) && (tri.sr0e_new & 0x80))
{
tri.vid_clock = (tri.vid_clock & 0x00ff) | (data << 8);
if(LOG) logerror("Trident: Video clock write %04x\n",tri.vid_clock);
}
break;
}
}
// Trident refers to these registers as a LUTDAC
// Not much else is known. XFree86 uses register 4 for something related to DPMS
READ8_MEMBER(trident_vga_device::port_83c6_r)
{
uint8_t res = 0xff;
switch(offset)
{
case 2:
res = tri.lutdac_reg[tri.lutdac_index];
if(LOG) logerror("Trident: LUTDAC reg read %02x\n",res);
break;
case 4:
res = tri.lutdac_index;
if(LOG) logerror("Trident: LUTDAC index read %02x\n",res);
break;
}
return res;
}
WRITE8_MEMBER(trident_vga_device::port_83c6_w)
{
switch(offset)
{
case 2:
if(LOG) logerror("Trident: LUTDAC reg write %02x\n",data);
tri.lutdac_reg[tri.lutdac_index] = data;
break;
case 4:
if(LOG) logerror("Trident: LUTDAC index write %02x\n",data);
tri.lutdac_index = data;
break;
}
}
READ8_MEMBER(trident_vga_device::vram_r)
{
if (tri.linear_active)
return vga.memory[offset % vga.svga_intf.vram_size];
else
return 0xff;
}
WRITE8_MEMBER(trident_vga_device::vram_w)
{
if (tri.linear_active)
{
if(tri.accel_memwrite_active)
{
tri.accel_transfer = (tri.accel_transfer & (~(0x000000ff << (24-(8*(offset % 4)))))) | (data << (24-(8 * (offset % 4))));
if(offset % 4 == 3)
accel_data_write(tri.accel_transfer);
return;
}
vga.memory[offset % vga.svga_intf.vram_size] = data;
}
}
READ8_MEMBER(trident_vga_device::mem_r )
{
if((tri.cr20 & 0x10) && (offset >= 0x1ff00)) // correct for old MMIO?
{
return old_mmio_r(space,offset-0x1ff00);
}
if (svga.rgb8_en || svga.rgb15_en || svga.rgb16_en || svga.rgb32_en)
{
int data;
if(tri.new_mode) // 64k from 0xA0000-0xAFFFF
{
offset &= 0xffff;
data=vga.memory[(offset + (svga.bank_r*0x10000)) % vga.svga_intf.vram_size];
}
else // 128k from 0xA0000-0xBFFFF
{
data=vga.memory[(offset + (svga.bank_r*0x10000)) % vga.svga_intf.vram_size];
}
return data;
}
return vga_device::mem_r(space,offset,mem_mask);
}
WRITE8_MEMBER(trident_vga_device::mem_w)
{
if((tri.cr20 & 0x10) && (offset >= 0x1ff00)) // correct for old MMIO?
{
old_mmio_w(space,offset-0x1ff00,data);
return;
}
if(tri.accel_memwrite_active)
{
tri.accel_transfer = (tri.accel_transfer & (~(0x000000ff << (24-(8*(offset % 4)))))) | (data << (24-(8 * (offset % 4))));
if(offset % 4 == 3)
accel_data_write(tri.accel_transfer);
return;
}
if (svga.rgb8_en || svga.rgb15_en || svga.rgb16_en || svga.rgb32_en)
{
if(tri.new_mode) // 64k from 0xA0000-0xAFFFF
{
offset &= 0xffff;
vga.memory[(offset + (svga.bank_w*0x10000)) % vga.svga_intf.vram_size] = data;
}
else // 128k from 0xA0000-0xBFFFF
{
vga.memory[(offset + (svga.bank_w*0x10000)) % vga.svga_intf.vram_size] = data;
}
return;
}
vga_device::mem_w(space,offset,data,mem_mask);
}
// Old style MMIO (maps to 0xbff00)
void trident_vga_device::old_mmio_w(address_space& space, uint32_t offset, uint8_t data)
{
if(offset >= 0x20)
accel_w(space,offset-0x20,data);
}
uint8_t trident_vga_device::old_mmio_r(address_space& space, uint32_t offset)
{
if(offset == 0x20)
{
if(tri.accel_busy)
return 0x20;
}
if(offset > 0x20)
return accel_r(space,offset-0x20);
else
return 0x00;
}
// 2D Acceleration functions (very WIP)
// From XFree86 source:
/*
Graphics Engine for 9440/9660/9680
#define GER_STATUS 0x2120
#define GE_BUSY 0x80
#define GER_OPERMODE 0x2122 Byte for 9440, Word for 96xx
#define DST_ENABLE 0x200 // Destination Transparency
#define GER_COMMAND 0x2124
#define GE_NOP 0x00 // No Operation
#define GE_BLT 0x01 // BitBLT ROP3 only
#define GE_BLT_ROP4 0x02 // BitBLT ROP4 (96xx only)
#define GE_SCANLINE 0x03 // Scan Line
#define GE_BRESLINE 0x04 // Bresenham Line
#define GE_SHVECTOR 0x05 // Short Vector
#define GE_FASTLINE 0x06 // Fast Line (96xx only)
#define GE_TRAPEZ 0x07 // Trapezoidal fill (96xx only)
#define GE_ELLIPSE 0x08 // Ellipse (96xx only) (RES)
#define GE_ELLIP_FILL 0x09 // Ellipse Fill (96xx only) (RES)
#define GER_FMIX 0x2127
#define GER_DRAWFLAG 0x2128 // long
#define FASTMODE 1<<28
#define STENCIL 0x8000
#define SOLIDFILL 0x4000
#define TRANS_ENABLE 0x1000
#define TRANS_REVERSE 0x2000
#define YMAJ 0x0400
#define XNEG 0x0200
#define YNEG 0x0100
#define SRCMONO 0x0040
#define PATMONO 0x0020
#define SCR2SCR 0x0004
#define PAT2SCR 0x0002
#define GER_FCOLOUR 0x212C // Word for 9440, long for 96xx
#define GER_BCOLOUR 0x2130 // Word for 9440, long for 96xx
#define GER_PATLOC 0x2134 // Word
#define GER_DEST_XY 0x2138
#define GER_DEST_X 0x2138 // Word
#define GER_DEST_Y 0x213A // Word
#define GER_SRC_XY 0x213C
#define GER_SRC_X 0x213C // Word
#define GER_SRC_Y 0x213E // Word
#define GER_DIM_XY 0x2140
#define GER_DIM_X 0x2140 // Word
#define GER_DIM_Y 0x2142 // Word
#define GER_STYLE 0x2144 // Long
#define GER_CKEY 0x2168 // Long
#define GER_FPATCOL 0x2178
#define GER_BPATCOL 0x217C
#define GER_PATTERN 0x2180 // from 0x2180 to 0x21FF
Additional - Graphics Engine for 96xx
#define GER_SRCCLIP_XY 0x2148
#define GER_SRCCLIP_X 0x2148 // Word
#define GER_SRCCLIP_Y 0x214A // Word
#define GER_DSTCLIP_XY 0x214C
#define GER_DSTCLIP_X 0x214C // Word
#define GER_DSTCLIP_Y 0x214E // Word
*/
READ8_MEMBER(trident_vga_device::accel_r)
{
uint8_t res = 0xff;
if(offset >= 0x60)
return tri.accel_pattern[(offset-0x60) % 0x80];
switch(offset)
{
case 0x00: // Status
if(tri.accel_busy)
res = 0x80;
else
res = 0x00;
break;
// Operation mode:
// bit 8: disable clipping if set
case 0x02: // Operation Mode
res = tri.accel_opermode & 0x00ff;
break;
case 0x03:
res = (tri.accel_opermode & 0xff00) >> 8;
break;
case 0x04: // Command register
res = tri.accel_command;
break;
case 0x07: // Foreground Mix?
res = tri.accel_fmix;
break;
default:
logerror("Trident: unimplemented acceleration register offset %02x read\n",offset);
}
return res;
}
WRITE8_MEMBER(trident_vga_device::accel_w)
{
if(offset >= 0x60)
{
tri.accel_pattern[(offset-0x60) % 0x80] = data;
return;
}
switch(offset)
{
case 0x02: // Operation Mode
tri.accel_opermode = (tri.accel_opermode & 0xff00) | data;
if(LOG_ACCEL) logerror("Trident: Operation Mode set to %04x\n",tri.accel_opermode);
break;
case 0x03:
tri.accel_opermode = (tri.accel_opermode & 0x00ff) | (data << 8);
if(LOG_ACCEL) logerror("Trident: Operation Mode set to %04x\n",tri.accel_opermode);
break;
case 0x04: // Command register
tri.accel_command = data;
accel_command();
break;
case 0x07: // Foreground Mix?
tri.accel_fmix = data;
if(LOG_ACCEL) logerror("Trident: FMIX set to %02x\n",data);
break;
case 0x08: // Draw flags
tri.accel_drawflags = (tri.accel_drawflags & 0xffffff00) | data;
if(LOG_ACCEL) logerror("Trident: Draw flags set to %08x\n",tri.accel_drawflags);
break;
case 0x09:
tri.accel_drawflags = (tri.accel_drawflags & 0xffff00ff) | (data << 8);
if(LOG_ACCEL) logerror("Trident: Draw flags set to %08x\n",tri.accel_drawflags);
break;
case 0x0a:
tri.accel_drawflags = (tri.accel_drawflags & 0xff00ffff) | (data << 16);
if(LOG_ACCEL) logerror("Trident: Draw flags set to %08x\n",tri.accel_drawflags);
break;
case 0x0b:
tri.accel_drawflags = (tri.accel_drawflags & 0x00ffffff) | (data << 24);
if(LOG_ACCEL) logerror("Trident: Draw flags set to %08x\n",tri.accel_drawflags);
break;
case 0x0c: // Foreground Colour
tri.accel_fgcolour = (tri.accel_fgcolour & 0xffffff00) | data;
if(LOG_ACCEL) logerror("Trident: Foreground Colour set to %08x\n",tri.accel_fgcolour);
break;
case 0x0d:
tri.accel_fgcolour = (tri.accel_fgcolour & 0xffff00ff) | (data << 8);
if(LOG_ACCEL) logerror("Trident: Foreground Colour set to %08x\n",tri.accel_fgcolour);
break;
case 0x0e:
tri.accel_fgcolour = (tri.accel_fgcolour & 0xff00ffff) | (data << 16);
if(LOG_ACCEL) logerror("Trident: Foreground Colour set to %08x\n",tri.accel_fgcolour);
break;
case 0x0f:
tri.accel_fgcolour = (tri.accel_fgcolour & 0x00ffffff) | (data << 24);
if(LOG_ACCEL) logerror("Trident: Foreground Colour set to %08x\n",tri.accel_fgcolour);
break;
case 0x10: // Background Colour
tri.accel_bgcolour = (tri.accel_bgcolour & 0xffffff00) | data;
if(LOG_ACCEL) logerror("Trident: Background Colour set to %08x\n",tri.accel_bgcolour);
break;
case 0x11:
tri.accel_bgcolour = (tri.accel_bgcolour & 0xffff00ff) | (data << 8);
if(LOG_ACCEL) logerror("Trident: Background Colour set to %08x\n",tri.accel_bgcolour);
break;
case 0x12:
tri.accel_bgcolour = (tri.accel_bgcolour & 0xff00ffff) | (data << 16);
if(LOG_ACCEL) logerror("Trident: Background Colour set to %08x\n",tri.accel_bgcolour);
break;
case 0x13:
tri.accel_bgcolour = (tri.accel_bgcolour & 0x00ffffff) | (data << 24);
if(LOG_ACCEL) logerror("Trident: Background Colour set to %08x\n",tri.accel_bgcolour);
break;
case 0x14: // Pattern Location
tri.accel_pattern_loc = (tri.accel_pattern_loc & 0xff00) | data;
if(LOG_ACCEL) logerror("Trident: Pattern Location set to %04x\n",tri.accel_pattern_loc);
break;
case 0x15:
tri.accel_pattern_loc = (tri.accel_pattern_loc & 0x00ff) | (data << 8);
if(LOG_ACCEL) logerror("Trident: Pattern Location set to %04x\n",tri.accel_pattern_loc);
break;
case 0x18: // Destination X
tri.accel_dest_x = (tri.accel_dest_x & 0xff00) | data;
if(LOG_ACCEL) logerror("Trident: Destination X set to %04x\n",tri.accel_dest_x);
break;
case 0x19:
tri.accel_dest_x = (tri.accel_dest_x & 0x00ff) | (data << 8);
if(LOG_ACCEL) logerror("Trident: Destination X set to %04x\n",tri.accel_dest_x);
break;
case 0x1a: // Destination Y
tri.accel_dest_y = (tri.accel_dest_y & 0xff00) | data;
if(LOG_ACCEL) logerror("Trident: Destination Y set to %04x\n",tri.accel_dest_y);
break;
case 0x1b:
tri.accel_dest_y = (tri.accel_dest_y & 0x00ff) | (data << 8);
if(LOG_ACCEL) logerror("Trident: Destination Y set to %04x\n",tri.accel_dest_y);
break;
case 0x1c: // Source X
tri.accel_source_x = (tri.accel_source_x & 0xff00) | data;
if(LOG_ACCEL) logerror("Trident: Source X set to %04x\n",tri.accel_source_x);
break;
case 0x1d:
tri.accel_source_x = (tri.accel_source_x & 0x00ff) | (data << 8);
if(LOG_ACCEL) logerror("Trident: Source X set to %04x\n",tri.accel_source_x);
break;
case 0x1e: // Source Y
tri.accel_source_y = (tri.accel_source_y & 0xff00) | data;
if(LOG_ACCEL) logerror("Trident: Source Y set to %04x\n",tri.accel_source_y);
break;
case 0x1f:
tri.accel_source_y = (tri.accel_source_y & 0x00ff) | (data << 8);
if(LOG_ACCEL) logerror("Trident: Source Y set to %04x\n",tri.accel_source_y);
break;
case 0x20: // Dimension(?) X
tri.accel_dim_x = (tri.accel_dim_x & 0xff00) | data;
if(LOG_ACCEL) logerror("Trident: Dimension X set to %04x\n",tri.accel_dim_x);
break;
case 0x21:
tri.accel_dim_x = (tri.accel_dim_x & 0x00ff) | (data << 8);
if(LOG_ACCEL) logerror("Trident: Dimension X set to %04x\n",tri.accel_dim_x);
break;
case 0x22: // Dimension(?) Y
tri.accel_dim_y = (tri.accel_dim_y & 0xff00) | data;
if(LOG_ACCEL) logerror("Trident: Dimension y set to %04x\n",tri.accel_dim_y);
break;
case 0x23:
tri.accel_dim_y = (tri.accel_dim_y & 0x00ff) | (data << 8);
if(LOG_ACCEL) logerror("Trident: Dimension y set to %04x\n",tri.accel_dim_y);
break;
case 0x24: // Style
tri.accel_style = (tri.accel_style & 0xffffff00) | data;
if(LOG_ACCEL) logerror("Trident: Style set to %08x\n",tri.accel_style);
break;
case 0x25:
tri.accel_style = (tri.accel_style & 0xffff00ff) | (data << 8);
if(LOG_ACCEL) logerror("Trident: Style set to %08x\n",tri.accel_style);
break;
case 0x26:
tri.accel_style = (tri.accel_style & 0xff00ffff) | (data << 16);
if(LOG_ACCEL) logerror("Trident: Style set to %08x\n",tri.accel_style);
break;
case 0x27:
tri.accel_style = (tri.accel_style & 0x00ffffff) | (data << 24);
if(LOG_ACCEL) logerror("Trident: Style set to %08x\n",tri.accel_style);
break;
case 0x28: // Source Clip X
tri.accel_source_x_clip = (tri.accel_source_x_clip & 0xff00) | data;
if(LOG_ACCEL) logerror("Trident: Source X Clip set to %04x\n",tri.accel_source_x_clip);
break;
case 0x29:
tri.accel_source_x_clip = (tri.accel_source_x_clip & 0x00ff) | (data << 8);
if(LOG_ACCEL) logerror("Trident: Source X Clip set to %04x\n",tri.accel_source_x_clip);
break;
case 0x2a: // Source Clip Y
tri.accel_source_y_clip = (tri.accel_source_y_clip & 0xff00) | data;
if(LOG_ACCEL) logerror("Trident: Source Y Clip set to %04x\n",tri.accel_source_y_clip);
break;
case 0x2b:
tri.accel_source_y_clip = (tri.accel_source_y_clip & 0x00ff) | (data << 8);
if(LOG_ACCEL) logerror("Trident: Source Y Clip set to %04x\n",tri.accel_source_y_clip);
break;
case 0x2c: // Destination Clip X
tri.accel_dest_x_clip = (tri.accel_dest_x_clip & 0xff00) | data;
if(LOG_ACCEL) logerror("Trident: Destination X Clip set to %04x\n",tri.accel_dest_x_clip);
break;
case 0x2d:
tri.accel_dest_x_clip = (tri.accel_dest_x_clip & 0x00ff) | (data << 8);
if(LOG_ACCEL) logerror("Trident: Destination X Clip set to %04x\n",tri.accel_dest_x_clip);
break;
case 0x2e: // Destination Clip Y
tri.accel_dest_y_clip = (tri.accel_dest_y_clip & 0xff00) | data;
if(LOG_ACCEL) logerror("Trident: Destination Y Clip set to %04x\n",tri.accel_dest_y_clip);
break;
case 0x2f:
tri.accel_dest_y_clip = (tri.accel_dest_y_clip & 0x00ff) | (data << 8);
if(LOG_ACCEL) logerror("Trident: Destination Y Clip set to %04x\n",tri.accel_dest_y_clip);
break;
case 0x48: // CKEY (Chromakey?)
tri.accel_ckey = (tri.accel_ckey & 0xffffff00) | data;
if(LOG_ACCEL) logerror("Trident: CKey set to %08x\n",tri.accel_ckey);
break;
case 0x49:
tri.accel_ckey = (tri.accel_ckey & 0xffff00ff) | (data << 8);
if(LOG_ACCEL) logerror("Trident: CKey set to %08x\n",tri.accel_ckey);
break;
case 0x4a:
tri.accel_ckey = (tri.accel_ckey & 0xff00ffff) | (data << 16);
if(LOG_ACCEL) logerror("Trident: CKey set to %08x\n",tri.accel_ckey);
break;
case 0x4b:
tri.accel_ckey = (tri.accel_ckey & 0x00ffffff) | (data << 24);
if(LOG_ACCEL) logerror("Trident: CKey set to %08x\n",tri.accel_ckey);
break;
case 0x58: // Foreground Pattern Colour
tri.accel_fg_pattern_colour = (tri.accel_fg_pattern_colour & 0xffffff00) | data;
if(LOG_ACCEL) logerror("Trident: FG Pattern Colour set to %08x\n",tri.accel_fg_pattern_colour);
break;
case 0x59:
tri.accel_fg_pattern_colour = (tri.accel_fg_pattern_colour & 0xffff00ff) | (data << 8);
if(LOG_ACCEL) logerror("Trident: FG Pattern Colour set to %08x\n",tri.accel_fg_pattern_colour);
break;
case 0x5a:
tri.accel_fg_pattern_colour = (tri.accel_fg_pattern_colour & 0xff00ffff) | (data << 16);
if(LOG_ACCEL) logerror("Trident: FG Pattern Colour set to %08x\n",tri.accel_fg_pattern_colour);
break;
case 0x5b:
tri.accel_fg_pattern_colour = (tri.accel_fg_pattern_colour & 0x00ffffff) | (data << 24);
if(LOG_ACCEL) logerror("Trident: FG Pattern Colour set to %08x\n",tri.accel_fg_pattern_colour);
break;
case 0x5c: // Background Pattern Colour
tri.accel_bg_pattern_colour = (tri.accel_bg_pattern_colour & 0xffffff00) | data;
if(LOG_ACCEL) logerror("Trident: BG Pattern Colour set to %08x\n",tri.accel_bg_pattern_colour);
break;
case 0x5d:
tri.accel_bg_pattern_colour = (tri.accel_bg_pattern_colour & 0xffff00ff) | (data << 8);
if(LOG_ACCEL) logerror("Trident: BG Pattern Colour set to %08x\n",tri.accel_bg_pattern_colour);
break;
case 0x5e:
tri.accel_bg_pattern_colour = (tri.accel_bg_pattern_colour & 0xff00ffff) | (data << 16);
if(LOG_ACCEL) logerror("Trident: BG Pattern Colour set to %08x\n",tri.accel_bg_pattern_colour);
break;
case 0x5f:
tri.accel_bg_pattern_colour = (tri.accel_bg_pattern_colour & 0x00ffffff) | (data << 24);
if(LOG_ACCEL) logerror("Trident: BG Pattern Colour set to %08x\n",tri.accel_bg_pattern_colour);
break;
default:
logerror("Trident: unimplemented acceleration register offset %02x write %02x\n",offset,data);
}
}
void trident_vga_device::accel_command()
{
switch(tri.accel_command)
{
case 0x00:
if(LOG) logerror("Trident: Command: NOP\n");
break;
case 0x01:
if(LOG) logerror("Trident: Command: BitBLT ROP3 (Source %i,%i Dest %i,%i Size %i,%i)\n",tri.accel_source_x,tri.accel_source_y,tri.accel_dest_x,tri.accel_dest_y,tri.accel_dim_x,tri.accel_dim_y);
if(LOG) logerror("BitBLT: Drawflags = %08x FMIX = %02x\n",tri.accel_drawflags,tri.accel_fmix);
accel_bitblt();
break;
case 0x02:
if(LOG) logerror("Trident: Command: BitBLT ROP4\n");
break;
case 0x03:
if(LOG) logerror("Trident: Command: Scanline\n");
break;
case 0x04:
if(LOG) logerror("Trident: Command: Bresenham Line (Source %i,%i Dest %i,%i Size %i,%i)\n",tri.accel_source_x,tri.accel_source_y,tri.accel_dest_x,tri.accel_dest_y,tri.accel_dim_x,tri.accel_dim_y);
if(LOG) logerror("BLine: Drawflags = %08x FMIX = %02x\n",tri.accel_drawflags,tri.accel_fmix);
accel_line();
break;
case 0x05:
if(LOG) logerror("Trident: Command: Short Vector\n");
break;
case 0x06:
if(LOG) logerror("Trident: Command: Fast Line\n");
break;
case 0x07:
if(LOG) logerror("Trident: Command: Trapezoid Fill\n");
break;
case 0x08:
if(LOG) logerror("Trident: Command: Ellipse\n");
break;
case 0x09:
if(LOG) logerror("Trident: Command: Ellipse Fill\n");
break;
default:
logerror("Trident: Unknown acceleration command %02x\n",tri.accel_command);
}
}
void trident_vga_device::accel_bitblt()
{
int x,y;
int sx,sy;
int xdir,ydir;
int xstart,xend,ystart,yend;
if(tri.accel_drawflags & 0x0040) // TODO: handle PATMONO also
{
tri.accel_mem_x = tri.accel_dest_x;
tri.accel_mem_y = tri.accel_dest_y;
tri.accel_memwrite_active = true;
return;
}
if(tri.accel_drawflags & 0x0200)
{
xdir = -1;
xstart = tri.accel_dest_x;
xend = tri.accel_dest_x-tri.accel_dim_x-1;
}
else
{
xdir = 1;
xstart = tri.accel_dest_x;
xend = tri.accel_dest_x+tri.accel_dim_x+1;
}
if(tri.accel_drawflags & 0x0100)
{
ydir = -1;
ystart = tri.accel_dest_y;
yend = tri.accel_dest_y-tri.accel_dim_y-1;
}
else
{
ydir = 1;
ystart = tri.accel_dest_y;
yend = tri.accel_dest_y+tri.accel_dim_y+1;
}
sy = tri.accel_source_y;
for(y=ystart;y!=yend;y+=ydir,sy+=ydir)
{
sx = tri.accel_source_x;
for(x=xstart;x!=xend;x+=xdir,sx+=xdir)
{
if(tri.accel_drawflags & 0x4000) // Solid fill
{
WRITEPIXEL(x,y,tri.accel_fgcolour);
}
else
{
WRITEPIXEL(x,y,READPIXEL(sx,sy));
}
}
}
}
void trident_vga_device::accel_line()
{
uint32_t col = tri.accel_fgcolour;
// TGUI_SRC_XY(dmin-dmaj,dmin);
// TGUI_DEST_XY(x,y);
// TGUI_DIM_XY(dmin+e,len);
int16_t dx = tri.accel_source_y - tri.accel_source_x;
int16_t dy = tri.accel_source_y;
int16_t err = tri.accel_dim_x + tri.accel_source_y;
int sx = (tri.accel_drawflags & 0x0200) ? -1 : 1;
int sy = (tri.accel_drawflags & 0x0100) ? -1 : 1;
int x,y,z;
x = tri.accel_dest_x;
y = tri.accel_dest_y;
WRITEPIXEL(x,y,col);
for(z=0;z<tri.accel_dim_y;z++)
{
if(tri.accel_drawflags & 0x0400)
y += sy;
else
x += sx;
if(err > 0)
{
if(tri.accel_drawflags & 0x0400)
x += sx;
else
y += sy;
WRITEPIXEL(x,y,col);
err += (dy-dx);
}
else
{
WRITEPIXEL(x,y,col);
err += dy;
}
}
}
// feed data written to VRAM to an active BitBLT command
void trident_vga_device::accel_data_write(uint32_t data)
{
int xdir = 1,ydir = 1;
if(tri.accel_drawflags & 0x0200) // XNEG
xdir = -1;
if(tri.accel_drawflags & 0x0100) // YNEG
ydir = -1;
for(int x=31;x>=0;x--)
{
if(tri.accel_mem_x <= tri.accel_dest_x+tri.accel_dim_x && tri.accel_mem_x >= tri.accel_dest_x-tri.accel_dim_x)
{
if(((data >> x) & 0x01) != 0)
WRITEPIXEL(tri.accel_mem_x,tri.accel_mem_y,tri.accel_fgcolour);
else
WRITEPIXEL(tri.accel_mem_x,tri.accel_mem_y,tri.accel_bgcolour);
}
tri.accel_mem_x+=xdir;
}
if(tri.accel_mem_x > tri.accel_dest_x+tri.accel_dim_x || tri.accel_mem_x < tri.accel_dest_x-tri.accel_dim_x)
{
tri.accel_mem_x = tri.accel_dest_x;
tri.accel_mem_y+=ydir;
if(tri.accel_mem_y > tri.accel_dest_y+tri.accel_dim_y || tri.accel_mem_y < tri.accel_dest_y-tri.accel_dim_y)
tri.accel_memwrite_active = false; // completed
}
}
| 27.738066 | 198 | 0.664527 | [
"vector",
"solid"
] |
a3cd169390b8a9227bfc9a57ab02f706e0fa46be | 3,686 | cpp | C++ | Coding_Exercises/1st/teleports/mytelefinal.cpp | Costopoulos/NTUA-Algorithms | ad67f8ee2fbac3f3933cffca0e2da465f73a6181 | [
"MIT"
] | null | null | null | Coding_Exercises/1st/teleports/mytelefinal.cpp | Costopoulos/NTUA-Algorithms | ad67f8ee2fbac3f3933cffca0e2da465f73a6181 | [
"MIT"
] | null | null | null | Coding_Exercises/1st/teleports/mytelefinal.cpp | Costopoulos/NTUA-Algorithms | ad67f8ee2fbac3f3933cffca0e2da465f73a6181 | [
"MIT"
] | 1 | 2022-01-04T12:37:11.000Z | 2022-01-04T12:37:11.000Z | #include <iostream>
#include <algorithm> //sort
#include <vector>
#include <bits/stdc++.h>
using namespace std;
int N, M;
int subgraph_num = 0;
//int belongs_to_subgraph[M];
struct portal {
int a, b, w;
};
void addEdge(vector<int> adj[], int u, int v)
{
adj[u].push_back(v);
adj[v].push_back(u);
}
/*void printGraph(vector<int> adj[], int V)
{
for (int v = 1; v < V; ++v)
{
cout << "\n Adjacency list of vertex "
<< v << "\n head ";
for (auto x : adj[v])
cout << "-> " << x;
printf("\n");
}
}*/
void DFSUtil2(int v, vector<int> adj[], bool visited[], int belongs[]) {
//belongs[v] = subgraph_num;
vector<int>::iterator i;
for (i = adj[v].begin(); i != adj[v].end(); ++i) {
if (!visited[*i]) {
visited[*i] = true;
//subgraph_num++;
belongs[*i] = subgraph_num;
DFSUtil2(*i, adj, visited, belongs);
}
}
}
bool regarding_width(portal p1, portal p2) {
return (p1.w < p2.w);
}
int binsearch(portal p[], int l, int r, int belongs_to_sub[], int carray[]) {
int solution;
bool isconnected;
//subgraph_num = 1;
int m;
while (l <= r) {
isconnected = true;
int templeft = l;
subgraph_num = 1;
//int solution;
m = l + (r - l) / 2;
vector<int> adj[N + 1];
for (int i = 1; i < M + 1; i++)
{
if (p[i].w >= p[m].w) { //create graph for portals >= binsearch selected portal
addEdge(adj, p[i].a, p[i].b);
}
}
//bool* visited = new bool[N + 1];
bool visited[N + 1];
for (int i = 1; i < N + 1; i++) {
belongs_to_sub[i] = 0;
visited[i] = false;
}
for (int i = 1; i < N + 1; i++) {
if (!visited[i]) {
subgraph_num++;
visited[i] = true;
belongs_to_sub[i] = subgraph_num;
DFSUtil2(i, adj, visited, belongs_to_sub);
}
}
for (int i = 1; i < N + 1; i++) {
if (belongs_to_sub[carray[i]] == belongs_to_sub[i]) {
solution = p[m].w;
l = m + 1;
continue;
}
else {
isconnected = false;
r = m - 1;
l = templeft;
break;
}
}
}
//cout << "Sol is " << solution;
if (!isconnected) {
return p[m - 1].w;
}
else return solution;
}
int main() {
//int N, M;
//int M;
//cin >> N >> M;
scanf("%d %d", &N, &M);
int c[N + 1];/*, a[M+1], b[M+1], w[M+1]*/ //c -> universes, a, b -> unified universes, w -> width
portal portalarray[M + 1];
int belongs_to_subgraph[N + 1];
for (int i = 1; i < N + 1; i++)
{
//cin >> c[i];
scanf("%d", &c[i]);
}
for (int i = 1; i < M + 1; i++)
{
//cin >> portalarray[i].a >> portalarray[i].b >> portalarray[i].w;
scanf("%d %d %d", &portalarray[i].a, &portalarray[i].b, &portalarray[i].w);
}
sort(portalarray + 1, portalarray + M + 1, regarding_width);
/*for (int i = 1; i <=10 ; i++)
{
cout << portalarray[i].w << endl;
}*/
/*for (int i = 1; i < N + 1; i++)
{
belongs_to_subgraph[i] = 0;
}*/
int result = binsearch(portalarray, 1, M, belongs_to_subgraph, c);
//cout << result << endl;
printf("%d\n", result);
} | 27.102941 | 115 | 0.426479 | [
"vector"
] |
a3d224889c4b9ace5284998a0dd089d5c81233fa | 4,296 | cpp | C++ | modules/slideio/src/imagetools/jxrcodec.cpp | Booritas/opencv_slideio | 86789b833cb5411c71757e7a1d49d481b1b905cd | [
"BSD-3-Clause"
] | null | null | null | modules/slideio/src/imagetools/jxrcodec.cpp | Booritas/opencv_slideio | 86789b833cb5411c71757e7a1d49d481b1b905cd | [
"BSD-3-Clause"
] | null | null | null | modules/slideio/src/imagetools/jxrcodec.cpp | Booritas/opencv_slideio | 86789b833cb5411c71757e7a1d49d481b1b905cd | [
"BSD-3-Clause"
] | null | null | null | // This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
#include "opencv2/slideio/imagetools.hpp"
#include "opencv2/slideio.hpp"
#include <boost/format.hpp>
#include <boost/filesystem.hpp>
#include <JXRGlue.h>
#include <JXRTest.h>
using namespace cv;
template <class T>
class JxrObjectKeeper
{
public:
JxrObjectKeeper(T *object=nullptr) : m_object(object)
{
}
~JxrObjectKeeper()
{
if(m_object)
{
m_object->Release(&m_object);
}
}
operator T*&()
{
return m_object;
}
T*& object()
{
return m_object;
}
T* operator->()
{
return m_object;
}
T* m_object;
};
void slideio::ImageTools::readJxrImage(const std::string& path, cv::OutputArray output)
{
namespace fs = boost::filesystem;
if(!fs::exists(path))
{
throw std::runtime_error(
(boost::format("File %1% does not exist") % path).str()
);
}
JxrObjectKeeper<PKCodecFactory> codecFactory(nullptr);
PKCreateCodecFactory(&codecFactory.object(), WMP_SDK_VERSION);
JxrObjectKeeper<PKImageDecode> decoder(nullptr);
ERR err = codecFactory->CreateDecoderFromFile(path.c_str(), &decoder.object());
if(err!=WMP_errSuccess)
{
throw std::runtime_error(
(boost::format("Cannot create decoder from file. Error code: %1%") % err).str());
}
U32 numFrames = 0;
decoder->GetFrameCount(decoder, &numFrames);
if(numFrames>1)
{
throw std::runtime_error(
(boost::format("JxrDecoder: unexpected number of sub-images: %1%") % numFrames).str());
}
PKPixelInfo pixelFormatInfo;
pixelFormatInfo.pGUIDPixFmt = &decoder->guidPixFormat;
err = PixelFormatLookup(&pixelFormatInfo, LOOKUP_FORWARD);
if(err!=WMP_errSuccess)
{
throw std::runtime_error("Unsupported pixel format");
}
const int numChannels = pixelFormatInfo.cChannel;
int dataSize = (pixelFormatInfo.uBitsPerSample-1)/8 + 1;
JxrObjectKeeper<PKFactory> factory(nullptr);
PKCreateFactory(&factory.object(), PK_SDK_VERSION);
decoder->WMP.wmiI.cROILeftX = 0;
decoder->WMP.wmiI.cROITopY = 0;
decoder->WMP.wmiI.cROIWidth = decoder->WMP.wmiI.cWidth;
decoder->WMP.wmiI.cROIHeight = decoder->WMP.wmiI.cHeight;
output.create(decoder->uHeight, decoder->uWidth, CV_MAKETYPE(CV_8U, 3));
cv::Mat raster = output.getMat();
char* outputFileExtension = ".bmp";
Float rX = 0.0, rY = 0.0;
PKRect rect = {0, 0, 0, 0};
rect.Width = (I32)(decoder->WMP.wmiI.cROIWidth);
rect.Height = (I32)(decoder->WMP.wmiI.cROIHeight);
decoder->GetResolution(decoder.object(), &rX, &rY);
const int rasterSize = rect.Height*rect.Width*numChannels;
const int size = rasterSize + 100;
std::vector<uint8_t> buff(size);
const auto outFormat = GUID_PKPixelFormat24bppRGB;
struct WMPStream* encodeStream = nullptr;
JxrObjectKeeper<PKFormatConverter> converter(nullptr);
codecFactory->CreateFormatConverter(&converter.object());
err = converter->Initialize(converter, decoder.object(), outputFileExtension, outFormat);
if(err!=WMP_errSuccess)
{
throw std::runtime_error(
(boost::format("Error by initialization of format converter: %1%") % err).str());
}
factory->CreateStreamFromMemory(&encodeStream, buff.data(), size);
const PKIID* encoderIID(nullptr);
GetTestEncodeIID(outputFileExtension, &encoderIID);
JxrObjectKeeper<PKImageEncode> encoder(nullptr);
PKTestFactory_CreateCodec(encoderIID, (void**)&encoder.object());
encoder->Initialize(encoder, encodeStream, nullptr, 0);
encoder->SetPixelFormat(encoder, outFormat);
encoder->SetResolution(encoder, rX, rY);
encoder->WMP.wmiSCP.bBlackWhite = decoder->WMP.wmiSCP.bBlackWhite;
encoder->SetSize(encoder, rect.Width, rect.Height);
encoder->WriteSource = PKImageEncode_Transcode;
encoder->WriteSource(encoder, converter, &rect);
const size_t offset = encoder->offPixel;
std::copy(buff.data() + offset, buff.data()+offset+rasterSize, raster.data);
cv::flip(raster, raster, 0);
}
| 33.302326 | 99 | 0.671322 | [
"object",
"vector"
] |
a3daf8ae1a6ab2440ee40579260c70acc4796c09 | 3,653 | cpp | C++ | src/components/behaviors/ParticleSystem.cpp | maksmaisak/Saxion_Y2Q2_Rendering | 14cf23c4e333599f16d200879301e8d5548e562b | [
"MIT"
] | null | null | null | src/components/behaviors/ParticleSystem.cpp | maksmaisak/Saxion_Y2Q2_Rendering | 14cf23c4e333599f16d200879301e8d5548e562b | [
"MIT"
] | null | null | null | src/components/behaviors/ParticleSystem.cpp | maksmaisak/Saxion_Y2Q2_Rendering | 14cf23c4e333599f16d200879301e8d5548e562b | [
"MIT"
] | null | null | null | //
// Created by Maksym Maisak on 14/10/18.
//
#include <cmath>
#include <iostream>
#include <algorithm>
#include "Transform.h"
#include "ParticleSystem.h"
#include "MyMath.h"
#include "GameTime.h"
#include "EntityRegistry.h"
#include "Actor.h"
void ParticleSystem::draw() {
throw "Not implemented";
/*if (!m_pDrawable) return;
auto& target = m_engine->getWindow();
for (std::size_t i = 0; i < m_numActiveParticles; ++i) {
target.draw(
*m_pDrawable,
sf::RenderStates(sf::BlendAlpha, m_particles.at(i).transform, nullptr, nullptr)
);
}*/
}
void ParticleSystem::update(float dt) {
if (m_isEmissionActive) {
sf::Time timeSinceEmission = m_emissionTimer.getElapsedTime();
if (timeSinceEmission > m_settings.emissionInterval) {
do {
timeSinceEmission -= m_settings.emissionInterval;
updateParticle(emitParticle(), timeSinceEmission.asSeconds());
} while (timeSinceEmission > m_settings.emissionInterval);
}
m_emissionTimer.restart();
}
for (ParticleIndex i = 0; i < m_numActiveParticles; ++i) {
updateParticle(i, dt);
}
}
const std::shared_ptr<sf::Drawable>& ParticleSystem::getDrawable() const {
return m_pDrawable;
}
void ParticleSystem::setDrawable(const std::shared_ptr<sf::Drawable>& m_pDrawable) {
ParticleSystem::m_pDrawable = m_pDrawable;
}
const ParticleSystem::Settings& ParticleSystem::getSettings() const {
return m_settings;
}
void ParticleSystem::setSettings(const ParticleSystem::Settings& settings) {
m_settings = settings;
}
const bool ParticleSystem::getIsEmissionActive() const {
return m_isEmissionActive;
}
void ParticleSystem::setIsEmissionActive(bool isEmissionActive) {
if (isEmissionActive && !m_isEmissionActive) m_emissionTimer.restart();
m_isEmissionActive = isEmissionActive;
}
ParticleSystem::ParticleIndex ParticleSystem::emitParticle() {
if (m_numActiveParticles >= m_maxNumParticles) {
destroyOldestParticle();
} else if (m_particles.size() <= m_numActiveParticles) {
m_particles.emplace_back();
}
Particle& particle = m_particles.at(m_numActiveParticles);
particle.transformMatrix = m_actor.get<en::Transform>().getWorldTransform();
particle.transformMatrix = glm::translate(particle.transformMatrix, glm::sphericalRand(m_settings.emissionRadius));
particle.timeToDestroy = GameTime::now() + m_settings.particleLifetime;
particle.velocity = m_settings.startVelocity + glm::sphericalRand(m_settings.startVelocityRandomness);
return m_numActiveParticles++;
}
void ParticleSystem::updateParticle(ParticleIndex i, float dt) {
Particle& particle = m_particles.at(i);
if (GameTime::now() >= particle.timeToDestroy) {
destroyParticle(i);
return;
}
particle.transformMatrix = glm::translate(particle.transformMatrix, particle.velocity * dt);
}
void ParticleSystem::destroyParticle(ParticleIndex i) {
assert(m_numActiveParticles > 0);
m_numActiveParticles -= 1;
std::swap(m_particles.at(i), m_particles.at(m_numActiveParticles));
// For safety. Can just remove to improve performance, as long as everything gets reinitialized when emitting.
m_particles.at(m_numActiveParticles) = {};
}
void ParticleSystem::destroyOldestParticle() {
auto it = std::min_element(m_particles.begin(), m_particles.end(), [](Particle& a, Particle& b){return a.timeToDestroy < b.timeToDestroy;});
auto index = static_cast<ParticleIndex>(std::distance(m_particles.begin(), it));
destroyParticle(index);
}
| 28.76378 | 144 | 0.7049 | [
"transform"
] |
a3dc2374516da72cc8e3e9e26aa314347624772b | 2,811 | cpp | C++ | aws-cpp-sdk-dms/source/model/AuthMechanismValue.cpp | ploki/aws-sdk-cpp | 17074e3e48c7411f81294e2ee9b1550c4dde842c | [
"Apache-2.0"
] | 1 | 2020-07-16T19:03:13.000Z | 2020-07-16T19:03:13.000Z | aws-cpp-sdk-dms/source/model/AuthMechanismValue.cpp | ploki/aws-sdk-cpp | 17074e3e48c7411f81294e2ee9b1550c4dde842c | [
"Apache-2.0"
] | 18 | 2018-05-15T16:41:07.000Z | 2018-05-21T00:46:30.000Z | aws-cpp-sdk-dms/source/model/AuthMechanismValue.cpp | ploki/aws-sdk-cpp | 17074e3e48c7411f81294e2ee9b1550c4dde842c | [
"Apache-2.0"
] | 1 | 2019-01-18T13:03:55.000Z | 2019-01-18T13:03:55.000Z | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/dms/model/AuthMechanismValue.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>
using namespace Aws::Utils;
namespace Aws
{
namespace DatabaseMigrationService
{
namespace Model
{
namespace AuthMechanismValueMapper
{
static const int default__HASH = HashingUtils::HashString("default");
static const int mongodb_cr_HASH = HashingUtils::HashString("mongodb_cr");
static const int scram_sha_1_HASH = HashingUtils::HashString("scram_sha_1");
AuthMechanismValue GetAuthMechanismValueForName(const Aws::String& name)
{
int hashCode = HashingUtils::HashString(name.c_str());
if (hashCode == default__HASH)
{
return AuthMechanismValue::default_;
}
else if (hashCode == mongodb_cr_HASH)
{
return AuthMechanismValue::mongodb_cr;
}
else if (hashCode == scram_sha_1_HASH)
{
return AuthMechanismValue::scram_sha_1;
}
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
overflowContainer->StoreOverflow(hashCode, name);
return static_cast<AuthMechanismValue>(hashCode);
}
return AuthMechanismValue::NOT_SET;
}
Aws::String GetNameForAuthMechanismValue(AuthMechanismValue enumValue)
{
switch(enumValue)
{
case AuthMechanismValue::default_:
return "default";
case AuthMechanismValue::mongodb_cr:
return "mongodb_cr";
case AuthMechanismValue::scram_sha_1:
return "scram_sha_1";
default:
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
}
return "";
}
}
} // namespace AuthMechanismValueMapper
} // namespace Model
} // namespace DatabaseMigrationService
} // namespace Aws
| 31.943182 | 92 | 0.651014 | [
"model"
] |
a3dd20c770b8af8c315bf57fc71314ee905cbc66 | 2,854 | cpp | C++ | 3rdParty/boost/1.71.0/libs/range/test/reversible_range.cpp | rajeev02101987/arangodb | 817e6c04cb82777d266f3b444494140676da98e2 | [
"Apache-2.0"
] | 12,278 | 2015-01-29T17:11:33.000Z | 2022-03-31T21:12:00.000Z | 3rdParty/boost/1.71.0/libs/range/test/reversible_range.cpp | rajeev02101987/arangodb | 817e6c04cb82777d266f3b444494140676da98e2 | [
"Apache-2.0"
] | 9,469 | 2015-01-30T05:33:07.000Z | 2022-03-31T16:17:21.000Z | 3rdParty/boost/1.71.0/libs/range/test/reversible_range.cpp | rajeev02101987/arangodb | 817e6c04cb82777d266f3b444494140676da98e2 | [
"Apache-2.0"
] | 892 | 2015-01-29T16:26:19.000Z | 2022-03-20T07:44:30.000Z | // Boost.Range library
//
// Copyright Thorsten Ottosen 2003-2004. 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)
//
// For more information, see http://www.boost.org/libs/range/
//
#include <boost/detail/workaround.hpp>
#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
# pragma warn -8091 // suppress warning in Boost.Test
# pragma warn -8057 // unused argument argc/argv in Boost.Test
#endif
#include <boost/range/rbegin.hpp>
#include <boost/range/rend.hpp>
#include <boost/range/begin.hpp>
#include <boost/range/end.hpp>
#include <boost/static_assert.hpp>
#include <boost/type_traits.hpp>
#include <boost/test/test_tools.hpp>
#include <boost/test/unit_test.hpp>
#include <vector>
#include <algorithm>
void check_iterator()
{
typedef std::vector<int> vec_t;
typedef vec_t::iterator iterator;
typedef std::pair<iterator,iterator> pair_t;
typedef boost::range_reverse_iterator<pair_t>::type rev_iterator;
typedef std::pair<rev_iterator,rev_iterator> rev_pair_t;
vec_t vec;
pair_t p = std::make_pair( vec.begin(), vec.end() );
rev_pair_t rp = std::make_pair( boost::rbegin( p ), boost::rend( p ) );
int a[] = {1,2,3,4,5,6,7,8,9,10};
const int ca[] = {1,2,3,4,5,6,7,8,9,10,11,12};
BOOST_CHECK( boost::rbegin( vec ) == boost::range_reverse_iterator<vec_t>::type( vec.end() ) );
BOOST_CHECK( boost::rend( vec ) == boost::range_reverse_iterator<vec_t>::type( vec.begin() ) );
BOOST_CHECK( std::distance( boost::rbegin( vec ), boost::rend( vec ) ) == std::distance( boost::begin( vec ), boost::end( vec ) ) );
BOOST_CHECK( boost::rbegin( p ) == boost::begin( rp ) );
BOOST_CHECK( boost::rend( p ) == boost::end( rp ) );
BOOST_CHECK( std::distance( boost::rbegin( p ), boost::rend( p ) ) == std::distance( boost::begin( rp ), boost::end( rp ) ) );
BOOST_CHECK( std::distance( boost::begin( p ), boost::end( p ) ) == std::distance( boost::rbegin( rp ), boost::rend( rp ) ) );
BOOST_CHECK_EQUAL( &*boost::begin( a ), &*( boost::rend( a ) - 1 ) );
BOOST_CHECK_EQUAL( &*( boost::end( a ) - 1 ), &*boost::rbegin( a ) );
BOOST_CHECK_EQUAL( &*boost::begin( ca ), &*( boost::rend( ca ) - 1 ) );
BOOST_CHECK_EQUAL( &*( boost::end( ca ) - 1 ), &*boost::rbegin( ca ) );
}
boost::unit_test::test_suite* init_unit_test_suite( int argc, char* argv[] )
{
boost::unit_test::test_suite* test = BOOST_TEST_SUITE( "Range Test Suite" );
test->add( BOOST_TEST_CASE( &check_iterator ) );
return test;
}
| 38.053333 | 136 | 0.611423 | [
"vector"
] |
a3e040b3405c246eb808dc0dce13aa197a385b08 | 9,047 | cpp | C++ | physx/samples/samplenorthpole/SampleNorthPole.cpp | Toolchefs/PhysX | bf983b19f763698e41e10766482679c6e2278400 | [
"BSD-3-Clause"
] | 2,372 | 2018-12-20T18:01:39.000Z | 2022-03-31T09:58:37.000Z | physx/samples/samplenorthpole/SampleNorthPole.cpp | Toolchefs/PhysX | bf983b19f763698e41e10766482679c6e2278400 | [
"BSD-3-Clause"
] | 534 | 2018-12-20T20:04:42.000Z | 2022-03-31T19:00:50.000Z | physx/samples/samplenorthpole/SampleNorthPole.cpp | Toolchefs/PhysX | bf983b19f763698e41e10766482679c6e2278400 | [
"BSD-3-Clause"
] | 694 | 2018-12-20T18:32:36.000Z | 2022-03-16T03:45:42.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-2021 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 "characterkinematic/PxControllerManager.h"
#include "PxPhysicsAPI.h"
#include "SampleNorthPole.h"
#include "SampleNorthPoleCameraController.h"
#include "SampleUtils.h"
#include "SampleCommandLine.h"
#include "SampleAllocatorSDKClasses.h"
#include "RendererMemoryMacros.h"
#include "RenderMaterial.h"
#include "SampleNorthPoleInputEventIds.h"
#include <SamplePlatform.h>
#include <SampleUserInput.h>
REGISTER_SAMPLE(SampleNorthPole, "SampleNorthPole")
using namespace SampleFramework;
using namespace SampleRenderer;
///////////////////////////////////////////////////////////////////////////////
SampleNorthPole::SampleNorthPole(PhysXSampleApplication& app) :
PhysXSample (app),
mNorthPoleCamera (NULL),
mController (NULL),
mControllerManager (NULL),
mDoStandup (false)
{
mCreateGroundPlane = false;
//mStepperType = FIXED_STEPPER;
mStandingSize = 1.0f;
mCrouchingSize = 0.20f;
mControllerRadius = 0.3f;
mControllerInitialPosition = PxExtendedVec3(5,mStandingSize,5);
memset(mSnowBalls,0,sizeof(mSnowBalls));
memset(mSnowBallsRenderActors,0,sizeof(mSnowBallsRenderActors));
}
SampleNorthPole::~SampleNorthPole()
{
}
///////////////////////////////////////////////////////////////////////////////
void SampleNorthPole::customizeSample(SampleSetup& setup)
{
setup.mName = "SampleNorthPole";
}
///////////////////////////////////////////////////////////////////////////////
void SampleNorthPole::onInit()
{
PhysXSample::onInit();
PxSceneWriteLock scopedLock(*mScene);
mApplication.setMouseCursorHiding(true);
mApplication.setMouseCursorRecentering(true);
getRenderer()->setAmbientColor(RendererColor(100, 100, 100));
// some colors for the rendering
mSnowMaterial = SAMPLE_NEW(RenderMaterial)(*getRenderer(), PxVec3(0.85f, 0.85f, 0.95f), 1.0f, false, 0, NULL);
mCarrotMaterial = SAMPLE_NEW(RenderMaterial)(*getRenderer(), PxVec3(1.00f, 0.50f, 0.00f), 1.0f, false, 1, NULL);
mButtonMaterial = SAMPLE_NEW(RenderMaterial)(*getRenderer(), PxVec3(0.00f, 0.00f, 0.00f), 1.0f, false, 2, NULL);
mRenderMaterials.push_back(mSnowMaterial);
mRenderMaterials.push_back(mCarrotMaterial);
mRenderMaterials.push_back(mButtonMaterial);
// PhysX
buildHeightField();
buildIglooTriMesh();
// add some stand-up characters
cookCarrotConvexMesh();
createSnowMen();
mControllerManager = PxCreateControllerManager(getActiveScene());
mController = createCharacter(mControllerInitialPosition);
mNorthPoleCamera = SAMPLE_NEW(SampleNorthPoleCameraController)(*mController,*this);
setCameraController(mNorthPoleCamera);
mNorthPoleCamera->setView(0,0);
}
void SampleNorthPole::onShutdown()
{
{
PxSceneWriteLock scopedLock(*mScene);
DELETESINGLE(mNorthPoleCamera);
mControllerManager->release();
}
PhysXSample::onShutdown();
}
void SampleNorthPole::helpRender(PxU32 x, PxU32 y, PxU8 textAlpha)
{
Renderer* renderer = getRenderer();
const PxU32 yInc = 18;
const PxReal scale = 0.5f;
const PxReal shadowOffset = 6.0f;
const RendererColor textColor(255, 255, 255, textAlpha);
const bool isMouseSupported = getApplication().getPlatform()->getSampleUserInput()->mouseSupported();
const bool isPadSupported = getApplication().getPlatform()->getSampleUserInput()->gamepadSupported();
const char* msg;
if (isMouseSupported && isPadSupported)
renderer->print(x, y += yInc, "Use mouse or right stick to rotate the camera", scale, shadowOffset, textColor);
else if (isMouseSupported)
renderer->print(x, y += yInc, "Use mouse to rotate the camera", scale, shadowOffset, textColor);
else if (isPadSupported)
renderer->print(x, y += yInc, "Use right stick to rotate the camera", scale, shadowOffset, textColor);
if (isPadSupported)
renderer->print(x, y += yInc, "Use left stick to move",scale, shadowOffset, textColor);
msg = mApplication.inputMoveInfoMsg("Press "," to move", CAMERA_MOVE_FORWARD,CAMERA_MOVE_BACKWARD, CAMERA_MOVE_LEFT, CAMERA_MOVE_RIGHT);
if(msg)
renderer->print(x, y += yInc, msg,scale, shadowOffset, textColor);
msg = mApplication.inputInfoMsg("Press "," to move fast", CAMERA_SHIFT_SPEED, -1);
if(msg)
renderer->print(x, y += yInc, msg, scale, shadowOffset, textColor);
msg = mApplication.inputInfoMsg("Press "," to crouch", CROUCH, -1);
if(msg)
renderer->print(x, y += yInc, msg,scale, shadowOffset, textColor);
msg = mApplication.inputInfoMsg("Press "," to reset scene", RESET_SCENE, -1);
if(msg)
renderer->print(x, y += yInc, msg,scale, shadowOffset, textColor);
msg = mApplication.inputInfoMsg("Press "," to throw a ball", THROW_BALL, -1);
if(msg)
renderer->print(x, y += yInc, msg,scale, shadowOffset, textColor);
}
void SampleNorthPole::descriptionRender(PxU32 x, PxU32 y, PxU8 textAlpha)
{
bool print=(textAlpha!=0.0f);
if(print)
{
Renderer* renderer = getRenderer();
const PxU32 yInc = 24;
const PxReal scale = 0.5f;
const PxReal shadowOffset = 6.0f;
const RendererColor textColor(255, 255, 255, textAlpha);
char line0[256]="This sample demonstrates the creation of dynamic objects (snowmen) with";
char line1[256]="multiple shapes. The snowmen, though visibly identical, are configured";
char line2[256]="with different masses, inertias and centres of mass in order to show how";
char line3[256]="to set up these properties using the sdk, and the effect they have on";
char line4[256]="behavior. A technical description of the snowmen's rigid body properties";
char line5[256]="can be found in the PhysX Guide documentation in Rigid Body Dynamics:";
char line6[256]="Mass Properties. The sample also introduces contact notification reports as";
char line7[256]="a mechanism to detach snowman body parts, and applies ccd flags in order";
char line8[256]="to prevent small objects such as snowballs and detached snowman body parts ";
char line9[256]="from tunneling through collision geometry.";
renderer->print(x, y+=yInc, line0, scale, shadowOffset, textColor);
renderer->print(x, y+=yInc, line1, scale, shadowOffset, textColor);
renderer->print(x, y+=yInc, line2, scale, shadowOffset, textColor);
renderer->print(x, y+=yInc, line3, scale, shadowOffset, textColor);
renderer->print(x, y+=yInc, line4, scale, shadowOffset, textColor);
renderer->print(x, y+=yInc, line5, scale, shadowOffset, textColor);
renderer->print(x, y+=yInc, line6, scale, shadowOffset, textColor);
renderer->print(x, y+=yInc, line7, scale, shadowOffset, textColor);
renderer->print(x, y+=yInc, line8, scale, shadowOffset, textColor);
renderer->print(x, y+=yInc, line9, scale, shadowOffset, textColor);
}
}
void SampleNorthPole::onTickPreRender(PxReal dtime)
{
if(mDoStandup)
tryStandup();
PhysXSample::onTickPreRender(dtime);
}
void SampleNorthPole::onSubstep(float dtime)
{
detach();
}
void SampleNorthPole::onPointerInputEvent(const SampleFramework::InputEvent& ie, physx::PxU32 x, physx::PxU32 y, physx::PxReal dx, physx::PxReal dy, bool val)
{
if((ie.m_Id == THROW_BALL) && val)
{
throwBall();
}
if((ie.m_Id == RAYCAST_HIT) && val)
{
PxRaycastBuffer hit;
getActiveScene().raycast(getCamera().getPos()+getCamera().getViewDir(), getCamera().getViewDir(), 1.0f, hit);
shdfnd::printFormatted("hits: %p\n",hit.block.shape);
}
PhysXSample::onPointerInputEvent(ie,x,y,dx,dy,val);
}
///////////////////////////////////////////////////////////////////////////////
| 37.853556 | 158 | 0.722892 | [
"geometry",
"shape"
] |
a3e15eb57cc50ffa47624cd3adb63b37f2ddb713 | 2,256 | cpp | C++ | modules/modified_stack_minimums/src/modified_stack_minimums.cpp | WolfCub15/devtools-course-practice | 680941b93baffac260f4eb6ad94b7dc03b2461f2 | [
"CC-BY-4.0"
] | null | null | null | modules/modified_stack_minimums/src/modified_stack_minimums.cpp | WolfCub15/devtools-course-practice | 680941b93baffac260f4eb6ad94b7dc03b2461f2 | [
"CC-BY-4.0"
] | 3 | 2021-04-22T17:12:19.000Z | 2021-05-14T12:16:25.000Z | modules/modified_stack_minimums/src/modified_stack_minimums.cpp | taktaev-artyom/devtools-course-practice | 7cf19defe061c07cfb3ebb71579456e807430a5d | [
"CC-BY-4.0"
] | null | null | null | // Copyright 2021 Novozhilova Ekaterina
#include "include/modified_stack_minimums.h"
#include <vector>
#include <utility>
ModifiedStack::ModifiedStack(int _size) {
if (_size < 0) {
throw -1;
} else {
st_size = _size;
last = -1;
mem.resize(st_size);
}
}
ModifiedStack::ModifiedStack(const ModifiedStack &tmp) {
st_size = tmp.st_size;
last = tmp.last;
mem.resize(st_size);
mem = tmp.mem;
}
ModifiedStack& ModifiedStack::operator=(const ModifiedStack &tmp) {
if (this != &tmp) {
if (st_size != tmp.st_size) {
if (st_size != 0) {
mem.resize(0);
}
st_size = tmp.st_size;
mem.resize(st_size);
}
last = tmp.last;
mem = tmp.mem;
}
return *this;
}
bool ModifiedStack::operator==(const ModifiedStack& tmp) const {
if (st_size != tmp.st_size) {
return false;
} else {
for (int i = 0; i < st_size; i++) {
if (mem[i] != tmp.mem[i]) {
return false;
}
}
}
return true;
}
bool ModifiedStack::operator!=(const ModifiedStack& tmp) const {
return !this->operator==(tmp);
}
void ModifiedStack::pop() {
mem[last] = std::pair<double, double>(0.0, 0.0);
last--;
}
void ModifiedStack::push(double el) {
if (last == -1) {
mem[++last] = std::make_pair(el, el);
} else if (last < st_size - 1) {
double last_min = mem[last].second;
if (last_min > el) {
mem[++last] = std::make_pair(el, el);
} else if (last_min < el) {
mem[++last] = std::make_pair(el, last_min);
}
} else if (last == st_size - 1) {
throw -1;
}
}
bool ModifiedStack::isFull() const {
if (last == st_size - 1) {
return true;
} else {
return false;
}
}
bool ModifiedStack::isEmpty() const {
if (last == -1) {
return true;
} else {
return false;
}
}
double ModifiedStack::getTop() const {
return mem[last].first;
}
double ModifiedStack::getMin() const {
return mem[last].second;
}
int ModifiedStack::getSize() const {
return st_size;
}
int ModifiedStack::getLast() const {
return last;
}
| 21.084112 | 67 | 0.54211 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.