hexsha stringlengths 40 40 | size int64 22 2.4M | ext stringclasses 5
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 260 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 78 | 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 260 | max_issues_repo_name stringlengths 5 109 | 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 260 | max_forks_repo_name stringlengths 5 109 | 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 22 2.4M | avg_line_length float64 5 169k | max_line_length int64 5 786k | alphanum_fraction float64 0.06 0.95 | matches listlengths 1 11 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c4bfa458101cf0a827c205fa3379fd80bc0814e1 | 4,424 | h | C | Image_Loading/nvImage.h | dn-projects/Tank-O-Mania | cadb8a6aac88291e896885bc60b7ad4be01cabff | [
"CC0-1.0"
] | null | null | null | Image_Loading/nvImage.h | dn-projects/Tank-O-Mania | cadb8a6aac88291e896885bc60b7ad4be01cabff | [
"CC0-1.0"
] | null | null | null | Image_Loading/nvImage.h | dn-projects/Tank-O-Mania | cadb8a6aac88291e896885bc60b7ad4be01cabff | [
"CC0-1.0"
] | null | null | null | #pragma once
#pragma comment(lib, "Image_Loading/nvImage.lib")
//
// nvImage.h - Image support class
//
// The nvImage class implements an interface for a multipurpose image
// object. This class is useful for loading and formating images
// for use as textures. The class supports dds, png, and hdr formats.
//
// Author: Evan Hart
// Email: sdkfeedback@nvidia.com
//
// Copyright (c) NVIDIA Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////
#ifndef NV_IMAGE_H
#define NV_IMAGE_H
#ifdef WIN32
#ifdef NVIMAGE_EXPORTS
#define NVSDKENTRY __declspec(dllexport)
#else
#define NVSDKENTRY __declspec(dllimport)
#endif
#endif
#include <vector>
#include <assert.h>
#include "glew.h"
namespace nv {
class Image {
public:
NVSDKENTRY Image();
NVSDKENTRY virtual ~Image();
// return the width of the image
NVSDKENTRY int getWidth() const { return _width; }
//return the height of the image
NVSDKENTRY int getHeight() const { return _height; }
//return the dpeth of the image (0 for images with no depth)
NVSDKENTRY int getDepth() const { return _depth; }
//return the number of mipmap levels available for the image
NVSDKENTRY int getMipLevels() const { return _levelCount; }
//return the number of cubemap faces available for the image (0 for non-cubemap images)
NVSDKENTRY int getFaces() const { return _faces; }
//return the format of the image data (GL_RGB, GL_BGR, etc)
NVSDKENTRY GLenum getFormat() const { return _format; }
//return the suggested internal format for the data
NVSDKENTRY GLenum getInternalFormat() const { return _internalFormat; }
//return the type of the image data
NVSDKENTRY GLenum getType() const { return _type; }
//return the Size in bytes of a level of the image
NVSDKENTRY int getImageSize(int level = 0) const;
//return whether the data is a crompressed format
NVSDKENTRY bool isCompressed() const {
switch(_format) {
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT:
return true;
}
return false;
}
//return whether the image represents a cubemap
NVSDKENTRY bool isCubeMap() const { return _faces > 0; }
//return whether the image represents a volume
NVSDKENTRY bool isVolume() const { return _depth > 0; }
//get a pointer to level data
NVSDKENTRY const void* getLevel( int level, GLenum face = GL_TEXTURE_CUBE_MAP_POSITIVE_X) const;
NVSDKENTRY void* getLevel( int level, GLenum face = GL_TEXTURE_CUBE_MAP_POSITIVE_X);
//initialize an image from a file
NVSDKENTRY bool loadImageFromFile( const char* file);
//convert a suitable image from a cubemap cross to a cubemap (returns false for unsuitable images)
NVSDKENTRY bool convertCrossToCubemap();
protected:
int _width;
int _height;
int _depth;
int _levelCount;
int _faces;
GLenum _format;
GLenum _internalFormat;
GLenum _type;
int _elementSize;
//pointers to the levels
std::vector<GLubyte*> _data;
NVSDKENTRY void freeData();
NVSDKENTRY void flipSurface(GLubyte *surf, int width, int height, int depth);
//
// Static elements used to dispatch to proper sub-readers
//
//////////////////////////////////////////////////////////////
struct FormatInfo {
const char* extension;
bool (*reader)( const char* file, Image& i);
};
static FormatInfo formatTable[];
NVSDKENTRY static bool readPng( const char *file, Image& i);
NVSDKENTRY static bool readDDS( const char *file, Image& i);
NVSDKENTRY static bool readHdr( const char *file, Image& i);
NVSDKENTRY static void flip_blocks_dxtc1(GLubyte *ptr, unsigned int numBlocks);
NVSDKENTRY static void flip_blocks_dxtc3(GLubyte *ptr, unsigned int numBlocks);
NVSDKENTRY static void flip_blocks_dxtc5(GLubyte *ptr, unsigned int numBlocks);
};
};
#endif //NV_IMAGE_H | 32.291971 | 106 | 0.633816 | [
"object",
"vector"
] |
c4c15555b8d163894c7a23c6f9649cc685ebf295 | 10,173 | h | C | src/cascadia/WindowsTerminal/AppHost.h | rasc0l/terminal | f0c2ef361a0354e0c0a34117a99985cef1ba7804 | [
"MIT"
] | 1 | 2022-03-29T09:09:19.000Z | 2022-03-29T09:09:19.000Z | src/cascadia/WindowsTerminal/AppHost.h | rasc0l/terminal | f0c2ef361a0354e0c0a34117a99985cef1ba7804 | [
"MIT"
] | 2 | 2022-03-13T04:56:20.000Z | 2022-03-13T04:59:18.000Z | src/cascadia/WindowsTerminal/AppHost.h | rasc0l/terminal | f0c2ef361a0354e0c0a34117a99985cef1ba7804 | [
"MIT"
] | 2 | 2022-03-21T17:02:47.000Z | 2022-03-30T15:53:39.000Z | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
#include "pch.h"
#include "NonClientIslandWindow.h"
#include "NotificationIcon.h"
#include <til/throttled_func.h>
class AppHost
{
public:
AppHost() noexcept;
virtual ~AppHost();
void AppTitleChanged(const winrt::Windows::Foundation::IInspectable& sender, winrt::hstring newTitle);
void LastTabClosed(const winrt::Windows::Foundation::IInspectable& sender, const winrt::TerminalApp::LastTabClosedEventArgs& args);
void Initialize();
bool OnDirectKeyEvent(const uint32_t vkey, const uint8_t scanCode, const bool down);
void SetTaskbarProgress(const winrt::Windows::Foundation::IInspectable& sender, const winrt::Windows::Foundation::IInspectable& args);
bool HasWindow();
private:
std::unique_ptr<IslandWindow> _window;
winrt::TerminalApp::App _app;
winrt::TerminalApp::AppLogic _logic;
winrt::Microsoft::Terminal::Remoting::WindowManager _windowManager{ nullptr };
std::vector<winrt::Microsoft::Terminal::Settings::Model::GlobalSummonArgs> _hotkeys;
winrt::com_ptr<IVirtualDesktopManager> _desktopManager{ nullptr };
bool _shouldCreateWindow{ false };
bool _useNonClientArea{ false };
std::optional<til::throttled_func_trailing<>> _getWindowLayoutThrottler;
winrt::Windows::Foundation::IAsyncAction _SaveWindowLayouts();
winrt::fire_and_forget _SaveWindowLayoutsRepeat();
void _HandleCommandlineArgs();
winrt::Microsoft::Terminal::Settings::Model::LaunchPosition _GetWindowLaunchPosition();
void _HandleCreateWindow(const HWND hwnd, RECT proposedRect, winrt::Microsoft::Terminal::Settings::Model::LaunchMode& launchMode);
void _UpdateTitleBarContent(const winrt::Windows::Foundation::IInspectable& sender,
const winrt::Windows::UI::Xaml::UIElement& arg);
void _UpdateTheme(const winrt::Windows::Foundation::IInspectable&,
const winrt::Windows::UI::Xaml::ElementTheme& arg);
void _FocusModeChanged(const winrt::Windows::Foundation::IInspectable& sender,
const winrt::Windows::Foundation::IInspectable& arg);
void _FullscreenChanged(const winrt::Windows::Foundation::IInspectable& sender,
const winrt::Windows::Foundation::IInspectable& arg);
void _ChangeMaximizeRequested(const winrt::Windows::Foundation::IInspectable& sender,
const winrt::Windows::Foundation::IInspectable& arg);
void _AlwaysOnTopChanged(const winrt::Windows::Foundation::IInspectable& sender,
const winrt::Windows::Foundation::IInspectable& arg);
void _RaiseVisualBell(const winrt::Windows::Foundation::IInspectable& sender,
const winrt::Windows::Foundation::IInspectable& arg);
void _WindowMouseWheeled(const til::point coord, const int32_t delta);
winrt::fire_and_forget _WindowActivated();
void _WindowMoved();
void _DispatchCommandline(winrt::Windows::Foundation::IInspectable sender,
winrt::Microsoft::Terminal::Remoting::CommandlineArgs args);
winrt::Windows::Foundation::IAsyncOperation<winrt::hstring> _GetWindowLayoutAsync();
void _FindTargetWindow(const winrt::Windows::Foundation::IInspectable& sender,
const winrt::Microsoft::Terminal::Remoting::FindTargetWindowArgs& args);
void _BecomeMonarch(const winrt::Windows::Foundation::IInspectable& sender,
const winrt::Windows::Foundation::IInspectable& args);
void _GlobalHotkeyPressed(const long hotkeyIndex);
void _HandleSummon(const winrt::Windows::Foundation::IInspectable& sender,
const winrt::Microsoft::Terminal::Remoting::SummonWindowBehavior& args);
winrt::fire_and_forget _IdentifyWindowsRequested(const winrt::Windows::Foundation::IInspectable sender,
const winrt::Windows::Foundation::IInspectable args);
void _DisplayWindowId(const winrt::Windows::Foundation::IInspectable& sender,
const winrt::Windows::Foundation::IInspectable& args);
winrt::fire_and_forget _RenameWindowRequested(const winrt::Windows::Foundation::IInspectable sender,
const winrt::TerminalApp::RenameWindowRequestedArgs args);
GUID _CurrentDesktopGuid();
bool _LazyLoadDesktopManager();
void _listenForInboundConnections();
winrt::fire_and_forget _setupGlobalHotkeys();
winrt::fire_and_forget _createNewTerminalWindow(winrt::Microsoft::Terminal::Settings::Model::GlobalSummonArgs args);
void _HandleSettingsChanged(const winrt::Windows::Foundation::IInspectable& sender,
const winrt::Windows::Foundation::IInspectable& args);
void _IsQuakeWindowChanged(const winrt::Windows::Foundation::IInspectable& sender,
const winrt::Windows::Foundation::IInspectable& args);
void _SummonWindowRequested(const winrt::Windows::Foundation::IInspectable& sender,
const winrt::Windows::Foundation::IInspectable& args);
void _OpenSystemMenu(const winrt::Windows::Foundation::IInspectable& sender,
const winrt::Windows::Foundation::IInspectable& args);
void _SystemMenuChangeRequested(const winrt::Windows::Foundation::IInspectable& sender,
const winrt::TerminalApp::SystemMenuChangeArgs& args);
winrt::fire_and_forget _QuitRequested(const winrt::Windows::Foundation::IInspectable& sender,
const winrt::Windows::Foundation::IInspectable& args);
void _RequestQuitAll(const winrt::Windows::Foundation::IInspectable& sender,
const winrt::Windows::Foundation::IInspectable& args);
void _CloseRequested(const winrt::Windows::Foundation::IInspectable& sender,
const winrt::Windows::Foundation::IInspectable& args);
void _QuitAllRequested(const winrt::Windows::Foundation::IInspectable& sender,
const winrt::Microsoft::Terminal::Remoting::QuitAllRequestedArgs& args);
void _CreateNotificationIcon();
void _DestroyNotificationIcon();
void _ShowNotificationIconRequested(const winrt::Windows::Foundation::IInspectable& sender,
const winrt::Windows::Foundation::IInspectable& args);
void _HideNotificationIconRequested(const winrt::Windows::Foundation::IInspectable& sender,
const winrt::Windows::Foundation::IInspectable& args);
std::unique_ptr<NotificationIcon> _notificationIcon;
winrt::event_token _ReAddNotificationIconToken;
winrt::event_token _NotificationIconPressedToken;
winrt::event_token _ShowNotificationIconContextMenuToken;
winrt::event_token _NotificationIconMenuItemSelectedToken;
winrt::event_token _GetWindowLayoutRequestedToken;
winrt::event_token _WindowCreatedToken;
winrt::event_token _WindowClosedToken;
// Helper struct. By putting these all into one struct, we can revoke them
// all at once, by assigning _revokers to a fresh Revokers instance. That'll
// cause us to dtor the old one, which will immediately call revoke on all
// the members as a part of their own dtors.
struct Revokers
{
// Event handlers to revoke in ~AppHost, before calling App.Close
winrt::Microsoft::Terminal::Remoting::WindowManager::BecameMonarch_revoker BecameMonarch;
winrt::Microsoft::Terminal::Remoting::Peasant::ExecuteCommandlineRequested_revoker peasantExecuteCommandlineRequested;
winrt::Microsoft::Terminal::Remoting::Peasant::SummonRequested_revoker peasantSummonRequested;
winrt::Microsoft::Terminal::Remoting::Peasant::DisplayWindowIdRequested_revoker peasantDisplayWindowIdRequested;
winrt::Microsoft::Terminal::Remoting::Peasant::QuitRequested_revoker peasantQuitRequested;
winrt::TerminalApp::AppLogic::CloseRequested_revoker CloseRequested;
winrt::TerminalApp::AppLogic::RequestedThemeChanged_revoker RequestedThemeChanged;
winrt::TerminalApp::AppLogic::FullscreenChanged_revoker FullscreenChanged;
winrt::TerminalApp::AppLogic::FocusModeChanged_revoker FocusModeChanged;
winrt::TerminalApp::AppLogic::AlwaysOnTopChanged_revoker AlwaysOnTopChanged;
winrt::TerminalApp::AppLogic::RaiseVisualBell_revoker RaiseVisualBell;
winrt::TerminalApp::AppLogic::SystemMenuChangeRequested_revoker SystemMenuChangeRequested;
winrt::TerminalApp::AppLogic::ChangeMaximizeRequested_revoker ChangeMaximizeRequested;
winrt::TerminalApp::AppLogic::TitleChanged_revoker TitleChanged;
winrt::TerminalApp::AppLogic::LastTabClosed_revoker LastTabClosed;
winrt::TerminalApp::AppLogic::SetTaskbarProgress_revoker SetTaskbarProgress;
winrt::TerminalApp::AppLogic::IdentifyWindowsRequested_revoker IdentifyWindowsRequested;
winrt::TerminalApp::AppLogic::RenameWindowRequested_revoker RenameWindowRequested;
winrt::TerminalApp::AppLogic::SettingsChanged_revoker SettingsChanged;
winrt::TerminalApp::AppLogic::IsQuakeWindowChanged_revoker IsQuakeWindowChanged;
winrt::TerminalApp::AppLogic::SummonWindowRequested_revoker SummonWindowRequested;
winrt::TerminalApp::AppLogic::OpenSystemMenu_revoker OpenSystemMenu;
winrt::TerminalApp::AppLogic::QuitRequested_revoker QuitRequested;
winrt::Microsoft::Terminal::Remoting::WindowManager::ShowNotificationIconRequested_revoker ShowNotificationIconRequested;
winrt::Microsoft::Terminal::Remoting::WindowManager::HideNotificationIconRequested_revoker HideNotificationIconRequested;
winrt::Microsoft::Terminal::Remoting::WindowManager::QuitAllRequested_revoker QuitAllRequested;
} _revokers{};
};
| 61.654545 | 139 | 0.712474 | [
"vector",
"model"
] |
c4c1f71f51538e84052b38494ca615095f1bddad | 3,232 | h | C | src/reflection/interface_std_string.h | HolyBlackCat/world-line | 07c5a956bdb0be0dd77886bd57bbc436c3e7ecce | [
"Zlib"
] | 7 | 2018-10-02T21:37:29.000Z | 2022-01-06T02:39:11.000Z | src/reflection/interface_std_string.h | HolyBlackCat/world-line | 07c5a956bdb0be0dd77886bd57bbc436c3e7ecce | [
"Zlib"
] | null | null | null | src/reflection/interface_std_string.h | HolyBlackCat/world-line | 07c5a956bdb0be0dd77886bd57bbc436c3e7ecce | [
"Zlib"
] | 2 | 2019-06-10T21:38:35.000Z | 2019-06-11T12:40:58.000Z | #pragma once
#include <cstddef>
#include <cstdint>
#include <exception>
#include <string>
#include <type_traits>
#include "program/errors.h"
#include "reflection/interface_basic.h"
#include "reflection/interface_container.h"
#include "strings/escape.h"
#include "utils/robust_math.h"
namespace Refl
{
class Interface_StdString : public InterfaceBasic<std::string>
{
public:
void ToString(const std::string &object, Stream::Output &output, const ToStringOptions &options, impl::ToStringState state) const override
{
(void)state;
Strings::EscapeFlags flags = Strings::EscapeFlags::escape_double_quotes;
if (options.multiline_strings)
flags = flags | Strings::EscapeFlags::multiline;
output.WriteByte('"');
Strings::Escape(object, output.GetOutputIterator(), flags);
output.WriteByte('"');
}
void FromString(std::string &object, Stream::Input &input, const FromStringOptions &options, impl::FromStringState state) const override
{
(void)options;
(void)state;
input.Discard('"');
std::string temp_str;
while (true)
{
char ch = input.ReadChar();
if (ch == '"')
break;
temp_str += ch;
if (ch == '\\')
temp_str += input.ReadChar();
}
try
{
object = Strings::Unescape(temp_str, Strings::UnescapeFlags::strip_cr_bytes);
}
catch (std::exception &e)
{
Program::Error(input.GetExceptionPrefix() + e.what());
}
}
void ToBinary(const std::string &object, Stream::Output &output, const ToBinaryOptions &options, impl::ToBinaryState state) const override
{
(void)options;
(void)state;
impl::container_length_binary_t len;
if (Robust::conversion_fails(object.size(), len))
Program::Error(output.GetExceptionPrefix() + "The string is too long.");
output.WriteWithByteOrder<impl::container_length_binary_t>(impl::container_length_byte_order, len);
output.WriteString(object);
}
void FromBinary(std::string &object, Stream::Input &input, const FromBinaryOptions &options, impl::FromBinaryState state) const override
{
(void)state;
std::size_t len;
if (Robust::conversion_fails(input.ReadWithByteOrder<impl::container_length_binary_t>(impl::container_length_byte_order), len))
Program::Error(input.GetExceptionPrefix() + "The string is too long.");
object = {};
object.reserve(len < options.max_reserved_size ? len : options.max_reserved_size);
while (len-- > 0)
object += input.ReadChar();
}
};
template <typename T>
struct impl::SelectInterface<T, std::enable_if_t<std::is_same_v<T, std::string>>>
{
using type = Interface_StdString;
};
template <>
struct impl::ForceNotContainer<std::string> : std::true_type {};
}
| 32.979592 | 146 | 0.586015 | [
"object"
] |
c4c3457ccc8fa49311bcbca92e7342beb7c30065 | 4,568 | h | C | encryption/des/des.h | Parahoo/baselib | 24b4b08eaf9657e785e19334a96e24afaa639647 | [
"MIT"
] | 1 | 2019-09-09T03:08:29.000Z | 2019-09-09T03:08:29.000Z | encryption/des/des.h | Parahoo/baselib | 24b4b08eaf9657e785e19334a96e24afaa639647 | [
"MIT"
] | null | null | null | encryption/des/des.h | Parahoo/baselib | 24b4b08eaf9657e785e19334a96e24afaa639647 | [
"MIT"
] | null | null | null | /**
* \file des.h
*/
#ifndef _DES_H
#define _DES_H
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief DES context structure
*/
typedef struct
{
unsigned long esk[32]; /*!< DES encryption subkeys */
unsigned long dsk[32]; /*!< DES decryption subkeys */
}
des_context;
/**
* \brief Triple-DES context structure
*/
typedef struct
{
unsigned long esk[96]; /*!< Triple-DES encryption subkeys */
unsigned long dsk[96]; /*!< Triple-DES decryption subkeys */
}
des3_context;
/**
* \brief DES key schedule (56-bit)
*
* \param ctx DES context to be initialized
* \param key 8-byte secret key
*/
void des_set_key( des_context *ctx, unsigned char key[8] );
/**
* \brief DES block encryption (ECB mode)
*
* \param ctx DES context
* \param input plaintext block
* \param output ciphertext block
*/
void des_encrypt( des_context *ctx,
unsigned char input[8],
unsigned char output[8] );
/**
* \brief DES block decryption (ECB mode)
*
* \param ctx DES context
* \param input ciphertext block
* \param output plaintext block
*/
void des_decrypt( des_context *ctx,
unsigned char input[8],
unsigned char output[8] );
/**
* \brief DES-CBC buffer encryption
*
* \param ctx DES context
* \param iv initialization vector (modified after use)
* \param input buffer holding the plaintext
* \param output buffer holding the ciphertext
* \param len length of the data to be encrypted
*/
void des_cbc_encrypt( des_context *ctx,
unsigned char iv[8],
unsigned char *input,
unsigned char *output,
int len );
/**
* \brief DES-CBC buffer decryption
*
* \param ctx DES context
* \param iv initialization vector (modified after use)
* \param input buffer holding the ciphertext
* \param output buffer holding the plaintext
* \param len length of the data to be decrypted
*/
void des_cbc_decrypt( des_context *ctx,
unsigned char iv[8],
unsigned char *input,
unsigned char *output,
int len );
/**
* \brief Triple-DES key schedule (112-bit)
*
* \param ctx 3DES context to be initialized
* \param key 16-byte secret key
*/
void des3_set_2keys( des3_context *ctx, unsigned char key[16] );
/**
* \brief Triple-DES key schedule (168-bit)
*
* \param ctx 3DES context to be initialized
* \param key 24-byte secret key
*/
void des3_set_3keys( des3_context *ctx, unsigned char key[24] );
/**
* \brief Triple-DES block encryption (ECB mode)
*
* \param ctx 3DES context
* \param input plaintext block
* \param output ciphertext block
*/
void des3_encrypt( des3_context *ctx,
unsigned char input[8],
unsigned char output[8] );
/**
* \brief Triple-DES block decryption (ECB mode)
*
* \param ctx 3DES context
* \param input ciphertext block
* \param output plaintext block
*/
void des3_decrypt( des3_context *ctx,
unsigned char input[8],
unsigned char output[8] );
/**
* \brief 3DES-CBC buffer encryption
*
* \param ctx 3DES context
* \param iv initialization vector (modified after use)
* \param input buffer holding the plaintext
* \param output buffer holding the ciphertext
* \param len length of the data to be encrypted
*/
void des3_cbc_encrypt( des3_context *ctx,
unsigned char iv[8],
unsigned char *input,
unsigned char *output,
int len );
/**
* \brief 3DES-CBC buffer decryption
*
* \param ctx 3DES context
* \param iv initialization vector (modified after use)
* \param input buffer holding the ciphertext
* \param output buffer holding the plaintext
* \param len length of the data to be decrypted
*/
void des3_cbc_decrypt( des3_context *ctx,
unsigned char iv[8],
unsigned char *input,
unsigned char *output,
int len );
/*
* \brief Checkup routine
*
* \return 0 if successful, or 1 if the test failed
*/
int des_self_test( void );
#ifdef __cplusplus
}
#endif
#endif /* des.h */
| 26.71345 | 68 | 0.580342 | [
"vector"
] |
c4c9117b0cd44a1be0d83132706d07b6408be54d | 3,806 | h | C | src/planning/scenario_planning/lane_driving/motion_planning/obstacle_avoidance_planner/include/obstacle_avoidance_planner/util.h | zqw-hooper/AutowareArchitectureProposal | 93ca87fd7255be697219a100a97a639a56f6c4a7 | [
"Apache-2.0"
] | null | null | null | src/planning/scenario_planning/lane_driving/motion_planning/obstacle_avoidance_planner/include/obstacle_avoidance_planner/util.h | zqw-hooper/AutowareArchitectureProposal | 93ca87fd7255be697219a100a97a639a56f6c4a7 | [
"Apache-2.0"
] | null | null | null | src/planning/scenario_planning/lane_driving/motion_planning/obstacle_avoidance_planner/include/obstacle_avoidance_planner/util.h | zqw-hooper/AutowareArchitectureProposal | 93ca87fd7255be697219a100a97a639a56f6c4a7 | [
"Apache-2.0"
] | 4 | 2021-06-21T11:58:51.000Z | 2021-08-06T08:25:54.000Z | /*
* Copyright 2020 Tier IV, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// #ifndef UTIL_H
// #define UTIL_H
#ifndef OBSTACLE_AVOIDANCE_PLANNER_UTIL_H
#define OBSTACLE_AVOIDANCE_PLANNER_UTIL_H
#include <Eigen/Core>
namespace autoware_planning_msgs
{
ROS_DECLARE_MESSAGE(PathPoint);
ROS_DECLARE_MESSAGE(TrajectoryPoint);
} // namespace autoware_planning_msgs
namespace util
{
template <typename T>
geometry_msgs::Point transformToRelativeCoordinate2D(
const T & point, const geometry_msgs::Pose & origin);
geometry_msgs::Point transformToAbsoluteCoordinate2D(
const geometry_msgs::Point & point, const geometry_msgs::Pose & origin);
double calculate2DDistance(const geometry_msgs::Point & a, const geometry_msgs::Point & b);
double calculateSquaredDistance(const geometry_msgs::Point & a, const geometry_msgs::Point & b);
double getYawFromPoints(const geometry_msgs::Point & a, const geometry_msgs::Point & a_root);
double normalizeRadian(const double angle);
geometry_msgs::Quaternion getQuaternionFromPoints(
const geometry_msgs::Point & a, const geometry_msgs::Point & a_root);
template <typename T>
geometry_msgs::Point transformMapToImage(
const T & map_point, const nav_msgs::MapMetaData & occupancy_grid_info);
std::shared_ptr<geometry_msgs::Point> transformMapToImagePtr(
const geometry_msgs::Point & map_point, const nav_msgs::MapMetaData & occupancy_grid_info);
bool transformMapToImage(
const geometry_msgs::Point & map_point, const nav_msgs::MapMetaData & occupancy_grid_info,
geometry_msgs::Point & image_point);
bool interpolate2DPoints(
const std::vector<double> & x, const std::vector<double> & y, const double resolution,
std::vector<geometry_msgs::Point> & interpolated_points);
std::vector<geometry_msgs::Point> getInterpolatedPoints(
const std::vector<geometry_msgs::Pose> & first_points,
const std::vector<geometry_msgs::Pose> & second_points, const double delta_arc_length);
std::vector<geometry_msgs::Point> getInterpolatedPoints(
const std::vector<geometry_msgs::Pose> & points, const double delta_arc_length);
template <typename T>
std::vector<geometry_msgs::Point> getInterpolatedPoints(
const T & points, const double delta_arc_length);
template <typename T>
int getNearestIdx(
const T & points, const geometry_msgs::Pose & pose, const int default_idx,
const double delta_yaw_threshold);
int getNearestIdx(
const std::vector<geometry_msgs::Point> & points, const geometry_msgs::Pose & pose,
const int default_idx, const double delta_yaw_threshold);
int getNearestIdx(
const std::vector<autoware_planning_msgs::PathPoint> & points, const geometry_msgs::Pose & pose,
const int default_idx);
std::vector<autoware_planning_msgs::TrajectoryPoint> convertPathToTrajectory(
const std::vector<autoware_planning_msgs::PathPoint> & path_points);
struct Rectangle
{
int min_x_idx = 0;
int min_y_idx = 0;
int max_x_idx = 0;
int max_y_idx = 0;
int area = 0;
};
std::vector<std::vector<int>> getHistogramTable(const std::vector<std::vector<int>> & input);
Rectangle getLargestRectancleInRow(
const std::vector<int> & histo, const int curret_row, const int row_size);
Rectangle getLargestRectangle(const std::vector<std::vector<int>> & input);
} // namespace util
#endif
| 34.917431 | 98 | 0.776406 | [
"vector"
] |
c4ca8866b67a7d3b3ab48c927ee3ad772dba6978 | 265 | h | C | Example/Pods/DLFoundationLib/DLFoundationLib/Classes/View/DLCheckBox.h | bawangflower/DLPrintSetLib | 315a4ace9442be2740cb5364cc720afbe50dc6e1 | [
"MIT"
] | null | null | null | Example/Pods/DLFoundationLib/DLFoundationLib/Classes/View/DLCheckBox.h | bawangflower/DLPrintSetLib | 315a4ace9442be2740cb5364cc720afbe50dc6e1 | [
"MIT"
] | null | null | null | Example/Pods/DLFoundationLib/DLFoundationLib/Classes/View/DLCheckBox.h | bawangflower/DLPrintSetLib | 315a4ace9442be2740cb5364cc720afbe50dc6e1 | [
"MIT"
] | null | null | null | //
// DLCheckBox.h
// PocketSLH
//
// Created by yunyu on 16/3/3.
//
//
#import <UIKit/UIKit.h>
@interface DLCheckBox : UIButton
@property (nonatomic, strong) id object;
/**
* default is YES
*/
@property (nonatomic, assign) BOOL isAutoChangeStatus;
@end
| 12.619048 | 54 | 0.660377 | [
"object"
] |
c4cc3733841954ce683f7fc95256b06323b723ff | 817 | c | C | gcc-gcc-7_3_0-release/gcc/testsuite/gcc.target/powerpc/pr81959.c | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | 7 | 2020-05-02T17:34:05.000Z | 2021-10-17T10:15:18.000Z | gcc-gcc-7_3_0-release/gcc/testsuite/gcc.target/powerpc/pr81959.c | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | null | null | null | gcc-gcc-7_3_0-release/gcc/testsuite/gcc.target/powerpc/pr81959.c | best08618/asylo | 5a520a9f5c461ede0f32acc284017b737a43898c | [
"Apache-2.0"
] | 2 | 2020-07-27T00:22:36.000Z | 2021-04-01T09:41:02.000Z | /* { dg-do compile { target { powerpc64*-*-* && lp64 } } } */
/* { dg-require-effective-target powerpc_p9vector_ok } */
/* { dg-options "-mpower9-vector -O2 -mfloat128" } */
/* PR 81959, the compiler raised on unrecognizable insn message in converting
int to __float128, where the int had a PRE_INC in the address. */
#ifndef ARRAY_SIZE
#define ARRAY_SIZE 1024
#endif
void
convert_int_to_float128 (__float128 * __restrict__ p,
int * __restrict__ q)
{
unsigned long i;
for (i = 0; i < ARRAY_SIZE; i++)
p[i] = (__float128)q[i];
}
/* { dg-final { scan-assembler {\mlfiwax\M|\mlxsiwax\M} } } */
/* { dg-final { scan-assembler {\mxscvsdqp\M} } } */
/* { dg-final { scan-assembler-not {\mmtvsrd\M} } } */
/* { dg-final { scan-assembler-not {\mmtvsrw[sz]\M} } } */
| 31.423077 | 77 | 0.611995 | [
"vector"
] |
c4cc6de1a95bf92da3c440930f935fd4067a862b | 1,464 | c | C | deps/mceliece/kem/mceliece8192128f/decrypt.c | tniessen/node-mceliece-nist | 4737b287ca09196ddd5ec2dee9e8fe66bbb17547 | [
"ISC"
] | 1 | 2020-07-25T23:10:34.000Z | 2020-07-25T23:10:34.000Z | deps/mceliece/kem/mceliece6688128f/decrypt.c | tniessen/node-mceliece-nist | 4737b287ca09196ddd5ec2dee9e8fe66bbb17547 | [
"ISC"
] | 1 | 2021-06-04T06:06:01.000Z | 2021-06-07T18:33:37.000Z | deps/mceliece/kem/mceliece460896f/decrypt.c | tniessen/node-mceliece-nist | 4737b287ca09196ddd5ec2dee9e8fe66bbb17547 | [
"ISC"
] | 1 | 2021-02-27T19:14:25.000Z | 2021-02-27T19:14:25.000Z | /*
This file is for Niederreiter decryption
*/
#include <stdio.h>
#include "decrypt.h"
#include "params.h"
#include "benes.h"
#include "util.h"
#include "synd.h"
#include "root.h"
#include "gf.h"
#include "bm.h"
/* Niederreiter decryption with the Berlekamp decoder */
/* intput: sk, secret key */
/* c, ciphertext */
/* output: e, error vector */
/* return: 0 for success; 1 for failure */
int decrypt(unsigned char *e, const unsigned char *sk, const unsigned char *c)
{
int i, w = 0;
uint16_t check;
unsigned char r[ SYS_N/8 ];
gf g[ SYS_T+1 ];
gf L[ SYS_N ];
gf s[ SYS_T*2 ];
gf s_cmp[ SYS_T*2 ];
gf locator[ SYS_T+1 ];
gf images[ SYS_N ];
gf t;
//
for (i = 0; i < SYND_BYTES; i++) r[i] = c[i];
for (i = SYND_BYTES; i < SYS_N/8; i++) r[i] = 0;
for (i = 0; i < SYS_T; i++) { g[i] = load_gf(sk); sk += 2; } g[ SYS_T ] = 1;
support_gen(L, sk);
synd(s, g, L, r);
bm(locator, s);
root(images, locator, L);
//
for (i = 0; i < SYS_N/8; i++)
e[i] = 0;
for (i = 0; i < SYS_N; i++)
{
t = gf_iszero(images[i]) & 1;
e[ i/8 ] |= t << (i%8);
w += t;
}
#ifdef KAT
{
int k;
printf("decrypt e: positions");
for (k = 0;k < SYS_N;++k)
if (e[k/8] & (1 << (k&7)))
printf(" %d",k);
printf("\n");
}
#endif
synd(s_cmp, g, L, e);
//
check = w;
check ^= SYS_T;
for (i = 0; i < SYS_T*2; i++)
check |= s[i] ^ s_cmp[i];
check -= 1;
check >>= 15;
return check ^ 1;
}
| 15.574468 | 78 | 0.525956 | [
"vector"
] |
c4d7b067e5bff97bec8f27f65fb8ed289a579e2a | 3,529 | c | C | src/common/face.c | Lilith5th/Radiance | 3aff252e57e6d2ca9205cf7caf20aaa1a897aaf2 | [
"BSD-3-Clause-LBNL"
] | 41 | 2017-05-17T18:56:53.000Z | 2022-03-08T16:38:57.000Z | src/common/face.c | Lilith5th/Radiance | 3aff252e57e6d2ca9205cf7caf20aaa1a897aaf2 | [
"BSD-3-Clause-LBNL"
] | 6 | 2019-04-28T10:06:26.000Z | 2021-02-04T14:20:48.000Z | src/common/face.c | Lilith5th/Radiance | 3aff252e57e6d2ca9205cf7caf20aaa1a897aaf2 | [
"BSD-3-Clause-LBNL"
] | 5 | 2019-02-27T02:45:10.000Z | 2021-01-20T21:15:56.000Z | #ifndef lint
static const char RCSid[] = "$Id: face.c,v 2.13 2016/09/16 15:09:21 greg Exp $";
#endif
/*
* face.c - routines dealing with polygonal faces.
*/
#include "copyright.h"
#include "standard.h"
#include "object.h"
#include "face.h"
/*
* A face is given as a list of 3D vertices. The normal
* direction and therefore the surface orientation is determined
* by the ordering of the vertices. Looking in the direction opposite
* the normal (at the front of the face), the vertices will be
* listed in counter-clockwise order.
* There is no checking done to insure that the edges do not cross
* one another. This was considered too expensive and should be unnecessary.
* The last vertex is automatically connected to the first.
*/
#ifdef SMLFLT
#define VERTEPS 1e-3 /* allowed vertex error */
#else
#define VERTEPS 1e-5 /* allowed vertex error */
#endif
FACE *
getface( /* get arguments for a face */
OBJREC *o
)
{
double d1;
int smalloff, badvert;
FVECT v1, v2, v3;
FACE *f;
int i;
if ((f = (FACE *)o->os) != NULL)
return(f); /* already done */
f = (FACE *)malloc(sizeof(FACE));
if (f == NULL)
error(SYSTEM, "out of memory in makeface");
if (o->oargs.nfargs < 9 || o->oargs.nfargs % 3)
objerror(o, USER, "bad # arguments");
o->os = (char *)f; /* save face */
f->va = o->oargs.farg;
f->nv = o->oargs.nfargs / 3;
/* check for last==first */
if (dist2(VERTEX(f,0),VERTEX(f,f->nv-1)) <= FTINY*FTINY)
f->nv--;
/* compute area and normal */
f->norm[0] = f->norm[1] = f->norm[2] = 0.0;
v1[0] = VERTEX(f,1)[0] - VERTEX(f,0)[0];
v1[1] = VERTEX(f,1)[1] - VERTEX(f,0)[1];
v1[2] = VERTEX(f,1)[2] - VERTEX(f,0)[2];
for (i = 2; i < f->nv; i++) {
v2[0] = VERTEX(f,i)[0] - VERTEX(f,0)[0];
v2[1] = VERTEX(f,i)[1] - VERTEX(f,0)[1];
v2[2] = VERTEX(f,i)[2] - VERTEX(f,0)[2];
fcross(v3, v1, v2);
f->norm[0] += v3[0];
f->norm[1] += v3[1];
f->norm[2] += v3[2];
VCOPY(v1, v2);
}
f->area = normalize(f->norm);
if (f->area == 0.0) {
objerror(o, WARNING, "zero area"); /* used to be fatal */
f->offset = 0.0;
f->ax = 0;
return(f);
}
f->area *= 0.5;
/* compute offset */
badvert = 0;
f->offset = DOT(f->norm, VERTEX(f,0));
smalloff = fabs(f->offset) <= VERTEPS;
for (i = 1; i < f->nv; i++) {
d1 = DOT(f->norm, VERTEX(f,i));
if (smalloff)
badvert += fabs(d1 - f->offset/i) > VERTEPS;
else
badvert += fabs(1.0 - d1*i/f->offset) > VERTEPS;
f->offset += d1;
}
f->offset /= (double)f->nv;
if (f->nv > 3 && badvert)
objerror(o, WARNING, "non-planar vertex");
/* find axis */
f->ax = fabs(f->norm[0]) > fabs(f->norm[1]) ? 0 : 1;
if (fabs(f->norm[2]) > fabs(f->norm[f->ax]))
f->ax = 2;
return(f);
}
void
freeface( /* free memory associated with face */
OBJREC *o
)
{
if (o->os == NULL)
return;
free(o->os);
o->os = NULL;
}
int
inface( /* determine if point is in face */
FVECT p,
FACE *f
)
{
int ncross, n;
double x, y;
int tst;
int xi, yi;
RREAL *p0, *p1;
if ((xi = f->ax + 1) >= 3) xi -= 3;
if ((yi = xi + 1) >= 3) yi -= 3;
x = p[xi];
y = p[yi];
n = f->nv;
p0 = f->va + 3*(n-1); /* connect last to first */
p1 = f->va;
ncross = 0;
/* positive x axis cross test */
while (n--) {
if ((p0[yi] > y) ^ (p1[yi] > y)) {
tst = (p0[xi] > x) + (p1[xi] > x);
if (tst == 2)
ncross++;
else if (tst)
ncross += (p1[yi] > p0[yi]) ^
((p0[yi]-y)*(p1[xi]-x) >
(p0[xi]-x)*(p1[yi]-y));
}
p0 = p1;
p1 += 3;
}
return(ncross & 01);
}
| 22.477707 | 80 | 0.552281 | [
"object",
"3d"
] |
c4d9020c752f2b73ac991ab486ca9c312031da1b | 23,837 | c | C | ctp2_code/libs/anet/src/dp/dpgroup.c | xiaolanchong/call_to_power2 | 39f19d18b363cefb151bbbf050c6b672ee544117 | [
"DOC"
] | null | null | null | ctp2_code/libs/anet/src/dp/dpgroup.c | xiaolanchong/call_to_power2 | 39f19d18b363cefb151bbbf050c6b672ee544117 | [
"DOC"
] | null | null | null | ctp2_code/libs/anet/src/dp/dpgroup.c | xiaolanchong/call_to_power2 | 39f19d18b363cefb151bbbf050c6b672ee544117 | [
"DOC"
] | null | null | null | /*
Copyright (C) 1995-2001 Activision, Inc.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*-------------------------------------------------------------------------
Multiplayer game layer: group management.
Copyright (C) 1997, Activision.
$Log: dpgroup.c $
Revision 1.18 1997/05/31 22:49:22 dkegel
Moved pragma pack into dp*pack*.h for portability.
Revision 1.17 1997/05/29 19:38:55 dkegel
Fixed minor type mismatches caught by Codewarrior.
Revision 1.16 1997/05/28 17:31:34 anitalee
Made portable to big-endian machines - calls SwapBtyes2 now when reading
or wirting 16-bit integers to or from the net. See comments in dpio.c.
Revision 1.15 1997/03/12 22:25:12 dkegel
Don't validate player id's when handling addPlayerToGroup packets,
since the player database may lag behind the group database!
See gtest\regroup.in for a regression test.
Revision 1.14 1997/03/12 04:08:00 dkegel
Get arguments to deletePlayerLocal right. Sheesh.
Revision 1.13 1997/03/10 03:30:33 dkegel
1. Added dpGroup_DeletePlayerFromAllGroups for when players die.
2. Fixed horrible bug in addplayertogroup/deleteplayerfromgroup -
had args to memmove backwards.
Revision 1.12 1997/03/09 03:52:37 dkegel
Added a little more dprint info on group operations.
Revision 1.11 1997/03/09 03:25:23 dkegel
Validate arg to addplayertogroup.
Revision 1.10 1997/03/05 02:39:15 dkegel
ini.h and dprint.h now integrated into anet.h;
to compile or use DP as a DLL, define DP_DLL;
win\build.bat now creates debugging and nondebugging versions
of both the static dp.lib and the dynamic anetdll.dll.
Revision 1.9 1997/03/01 18:21:45 dkegel
Fixed compiler warning.
Revision 1.8 1997/03/01 08:54:57 dkegel
Better dprints.
Revision 1.7 1997/02/24 01:34:16 dkegel
Made it clear that s must be NULL for dpEnumGroup*, and why.
Revision 1.6 1997/02/16 04:05:30 dkegel
1. group add packets now carry entire group contents, so
informNewNode works now.
2. use pragma pack() around structures that need to be portable
3. Reduced max group size to dp_MAXREALPLAYERS.
Revision 1.5 1997/02/13 00:29:16 dkegel
Groups now saved by freeze/thaw.
Revision 1.4 1997/02/12 03:46:05 dkegel
Tie in to player variable system - delete group variables when group
deleted.
Revision 1.3 1997/02/12 03:02:36 dkegel
Finished converting to use playerHdl_t instead of dpid_t for sending
group info.
Added more null-pointer checks.
Revision 1.2 1997/02/10 07:10:12 dkegel
1. Added handleAddGroupPacket, handleDelGroupPacket.
2. Fixed bug in sendAddGroupPacket.
Revision 1.1 1997/02/07 00:08:14 dkegel
Initial revision
--------------------------------------------------------------------------*/
#include "dp.h"
#include "dpprivy.h"
#include "dpgroup.h"
/*#undef DPRINT*/
/*#define DPRINT(s)*/
/********************** Internal Functions ******************************/
/* Function to dump a block of memory in hex */
#if 1
static void dumpBuf(char *buf, int len)
{
int i;
for (i=0; i<len; i++) {
DPRINT(("%02x ", buf[i]));
}
DPRINT(("\n"));
}
#endif
/* Function to dump the group table in ascii. */
static void dpGroup_dump(dp_t *dp)
{
int i;
if (!dp->groups) {
DPRINT(("dpGroup_dump: no group table\n"));
return;
}
DPRINT(("dpGroup_dump: n_used %d\n", dp->groups->n_used));
for (i=0; i<dp->groups->n_used; i++) {
assoctab_item_t *pe;
dp_group_t *pg;
int j;
pe = assoctab_getkey(dp->groups, i);
if (!pe) {
DPRINT(("dpGroup_dump: no group entry for index %d\n", i));
continue;
}
pg = (dp_group_t *) &pe->value;
DPRINT(("dpGroup_dump: group id %d, karma %x, name '%s', n %d [",
pg->id, pg->karma, pg->name, pg->n));
for (j=0; j<pg->n; j++)
DPRINT(("%d,", pg->members[j]));
DPRINT(("]\n"));
}
}
/*----------------------------------------------------------------------
Create the dp->groups object. Return dp_RES_OK upon success.
Called by dpOpen and its ilk.
----------------------------------------------------------------------*/
dp_result_t dpGroup_create(dp_t *dp)
{
dp->groups = assoctab_create(sizeof(dp_group_t));
if (!dp->groups) return dp_RES_NOMEM;
return dp_RES_OK;
}
/*----------------------------------------------------------------------
Destroy the dp->groups object. Don't destroy it if it's NULL.
Call this when opening a session.
Called by dpClose and its ilk.
----------------------------------------------------------------------*/
void dpGroup_destroy(dp_t *dp)
{
if (dp->groups) {
assoctab_destroy(dp->groups);
dp->groups = NULL;
}
}
/*-----------------------------------------------------------------------
Save the state of the groups table to disk.
-----------------------------------------------------------------------*/
dp_result_t dpGroup_freeze(dp_t *dp, FILE *fp)
{
DPRINT(("dpGroup_freeze: "));
dpGroup_dump(dp);
(void) assoctab_freeze(dp->groups, fp);
return dp_RES_OK;
}
/*-----------------------------------------------------------------------
Restore the state of the groups table from disk.
-----------------------------------------------------------------------*/
dp_result_t dpGroup_thaw(dp_t *dp, FILE *fp)
{
if (!assoctab_thaw(dp->groups, fp))
return dp_RES_BAD;
DPRINT(("dpGroup_thaw: "));
dpGroup_dump(dp);
return dp_RES_OK;
}
/*----------------------------------------------------------------------
Handle an add group packet. Creates the group locally.
Group starts out fully formed, with all members.
(No group variables yet, though. Those come later.)
----------------------------------------------------------------------*/
dp_result_t dpGroup_HandleAddGroupPacket(
dp_t *dp,
dp_group_t *body,
size_t len)
{
dp_group_t *pg;
DPRINT(("dpGroup_HandleAddGroupPacket(dp, ...): id %d, name %s, n %d\n",
body->id, body->name, body->n));
if (!dp->groups) {
DPRINT(("dpGroup_HandleAddGroupPacket: not in session\n"));
return dp_RES_BUG;
}
if (body->sessionKarma != dp->s.karma) {
DPRINT(("dpGroup_HandleAddGroupLocal: bad karma; got %d, wanted %d\n", body->sessionKarma, dp->s.karma));
return dp_RES_BAD;
}
if (len != sizeof_dp_group_t(body->n)) {
DPRINT(("dpGroup_HandleAddGroupLocal: bad len; was %d, wanted %d\n", len, sizeof_dp_group_t(body->n)));
return dp_RES_BAD;
}
/* Allocate storage */
pg = (dp_group_t *)assoctab_subscript_grow(dp->groups, body->id);
if (!pg) {
DPRINT(("dpGroup_HandleAddGroupLocal: bug\n"));
return dp_RES_BUG;
}
/* Fill group */
memcpy(pg, body, sizeof_dp_group_t(body->n));
pg->name[sizeof(pg->name)-1] = 0;
dpGroup_dump(dp);
return dp_RES_OK;
}
/*----------------------------------------------------------------------
Handle an del group packet. Deletes the group locally.
----------------------------------------------------------------------*/
dp_result_t dpGroup_HandleDelGroupPacket(
dp_t *dp,
dp_user_delGroup_packet_t *body)
{
dp_result_t err;
DPRINT(("dpGroup_HandleDelGroupPacket(dp, %d, %s):\n", body->id, body->name));
if (!dp->groups) {
DPRINT(("dpGroup_HandleDelGroupPacket: not in session\n"));
return dp_RES_BUG;
}
if (body->sessionKarma != dp->s.karma) {
DPRINT(("dpGroup_HandleDelGroupLocal: bad karma\n"));
return dp_RES_BAD;
}
/* Deallocate storage */
if (assoctab_subscript_delete(dp->groups, body->id)) {
DPRINT(("dpGroup_HandleDelGroupLocal: bug\n"));
return dp_RES_BUG;
}
/* Delete the group's variables. */
err = pv_deletePlayer(dp->pv, body->id);
if ((err != dp_RES_OK) && (err != dp_RES_EMPTY)) {
DPRINT(("dpGroup_handleDelGroupPacket: can't del group %d's variables, err %d\n", body->id, err));
return err;
}
return dp_RES_OK;
}
/*----------------------------------------------------------------------
Inform some machine about the given group. Only called by host.
Sends a dp_user_addGroup_packet_t or dp_user_delGroup_packet_t reliably.
dest should be either dp_ID_BROADCAST (when creating/deleting group)
or a particular machine's pseudoplayer (when adding machine).
----------------------------------------------------------------------*/
static dp_result_t dpGroup_SendAddGroupPacket(
dp_t *dp,
dp_group_t *pg,
playerHdl_t dest,
dp_packetType_t tag)
{
dp_result_t err;
playerHdl_t errHdl;
size_t pktlen;
#include "dppack1.h"
struct {
dp_packetType_t tag;
union {
dp_group_t add PACK;
dp_user_delGroup_packet_t del PACK;
} b PACK;
char pad[6] PACK;
} pkt;
#include "dpunpack.h"
if (!dp || !dp->groups || !pg) {
DPRINT(("dpGroup_SendAddGroupPacket: null\n"));
return dp_RES_BUG;
}
if (!dp->bMaster) {
DPRINT(("dpGroup_SendAddGroupPacket: must be master\n"));
return dp_RES_BAD;
}
pkt.tag = tag;
/* If it's an addGroup packet, copy the whole thing.
* If it's a delGroup packet, just copy the beginning.
*/
if (tag == dp_USER_ADDGROUP_PACKET_ID)
pktlen = sizeof_dp_group_t(pg->n);
else
pktlen = sizeof(dp_user_delGroup_packet_t);
memcpy(&pkt.b, pg, pktlen);
pktlen += sizeof(pkt.tag);
pkt.b.add.sessionKarma = dp->s.karma;
DPRINT(("dpGroup_SendAddGroupPacket(dp, pg->name %s, dest %d, tag %c%c; bytes %d):\n",
pg->name, dest, ((char *)&tag)[0], ((char *)&tag)[1], pktlen));
dumpBuf((char *)&pkt, pktlen);
if (tag == dp_USER_ADDGROUP_PACKET_ID)
{
int i;
for (i=0; i<pkt.b.add.n; i++) {
DPRINT(("dpGroup_SendAddGroupPacket: player %d in group is %d = %d\n",
i, pkt.b.add.members[i], pg->members[i]));
}
/* call dpSwapUserAddGroup to byte swap pkt.b.add) */
dpSwapUserAddGroup(&pkt.b.add, pkt.b.add.n);
}
else
{
/* call dpSwapUserDelGroup to byte swap pkt.b.del) */
dpSwapUserDelGroup(&pkt.b.del);
}
if (dest == PLAYER_BROADCAST)
err = dp_broadcast_reliable(dp, &pkt, pktlen, &errHdl);
else
err = dpio_put_reliable(dp->dpio, &dest, 1, &pkt, pktlen, &errHdl);
if (err != dp_RES_OK)
DPRINT(("dpGroup_SendAddGroupPacket: send failed, err %d, errHdl %d\n", err, errHdl));
return err;
}
/*----------------------------------------------------------------------
Inform some machine about the given new player in the given group.
Sends a dp_addPlayerToGroup_packet_t or dp_DeletePlayerFromGroup_packet_t
reliably.
dest should be dp_ID_BROADCAST (when creating/deleting player to/from group)
or a particular machine's pseudoplayer (when adding machine).
----------------------------------------------------------------------*/
static dp_result_t dpGroup_SendAddPlayerPacket(
dp_t *dp,
dpid_t idGroup,
dpid_t idPlayer,
playerHdl_t dest,
dp_packetType_t tag)
{
dp_result_t err;
playerHdl_t errHdl;
size_t pktlen;
#include "dppack1.h"
struct {
dp_packetType_t tag;
dp_addPlayerToGroup_packet_t body PACK;
char pad[6] PACK;
} pkt;
#include "dpunpack.h"
if (!dp) {
DPRINT(("dpGroup_SendAddPlayerPacket: null\n"));
return dp_RES_BUG;
}
DPRINT(("dpGroup_SendAddPlayerPacket(dp, gr %d, pl %d, dest %d, tag %c%c):\n",
idGroup, idPlayer, dest, tag & 0xff, tag >> 8));
pkt.tag = tag;
pkt.body.dpIdGroup = idGroup;
pkt.body.dpIdPlayer = idPlayer;
pkt.body.sessionKarma = dp->s.karma; /* so destination can reject if not same session */
pktlen = sizeof(pkt.tag)+sizeof(pkt.body);
/* call dpSwapPlayerToFromGroup to byte swap pkt.body */
dpSwapPlayerToFromGroup(&pkt.body);
if (dest == PLAYER_BROADCAST)
err = dp_broadcast_reliable(dp, &pkt, pktlen, &errHdl);
else
err = dpio_put_reliable(dp->dpio, &dest, 1, &pkt, pktlen, &errHdl);
if (err != dp_RES_OK)
DPRINT(("dpGroup_SendAddPlayerPacket: send failed, err %d\n", err));
return err;
}
/*--------------------------------------------------------------------------
Notify a new player about every existing player group.
Called only by dpReceive on host.
Should only be called if
we're the host,
we're creating a new player,
the new player is remote,
this is the first time we've received a request to create him,
AND it's a pseudoplayer.
--------------------------------------------------------------------------*/
dp_result_t dpGroup_InformNewMachine(
dp_t *dp,
playerHdl_t dest)
{
int i;
for (i=0; i<dp->groups->n_used; i++) {
assoctab_item_t *pe;
dp_group_t *pg;
pe = assoctab_getkey(dp->groups, i);
if (!pe) {
DPRINT(("dpGroup_InformNewMachine: no group entry for index %d\n", i));
return dp_RES_BUG;
}
pg = (dp_group_t *) &pe->value;
DPRINT(("dpGroup_InformNewMachine: telling dest %d about group id %d, karma %x, name %p = '%s'\n",
dest, pg->id, pg->karma, pg->name, pg->name));
/* Hope we don't send too many packets here! */
(void) dpGroup_SendAddGroupPacket(dp, pg, dest, dp_USER_ADDGROUP_PACKET_ID);
}
dpGroup_dump(dp);
return dp_RES_OK;
}
/*----------------------------------------------------------------------
Add player idPlayer to the group idGroup, but don't broadcast notification.
Called only by dpReceive and dpAddPlayerToGroup.
----------------------------------------------------------------------*/
dp_result_t dpGroup_AddPlayerLocal(
dp_t *dp,
dpid_t idGroup,
dpid_t idPlayer)
{
dp_group_t *pg;
int i;
DPRINT(("dpGroup_AddPlayerLocal(dp, group %d, player %d)\n", idGroup, idPlayer));
if (!dp->groups) {
DPRINT(("dpGroup_AddPlayerLocal: not in session\n"));
return dp_RES_BUG;
}
pg = (dp_group_t *)assoctab_subscript(dp->groups, idGroup);
if (!pg) {
DPRINT(("dpGroup_AddPlayerLocal(%d, %d): no such group\n", idGroup, idPlayer));
return dp_RES_BAD;
}
/* Verify that player exists */
if (dpGetPlayerName(dp, idPlayer, NULL, 0) != dp_RES_OK) {
DPRINT(("dpGroup_AddPlayerLocal(%d, %d): warning: no such player\n", idGroup, idPlayer));
/* Can't be sure our player database is up to date yet. Grr. */
/*return dp_RES_BAD;*/
}
if (pg->n >= dp_MAXREALPLAYERS) {
/* Unlikely */
DPRINT(("dpGroup_AddPlayerLocal(%d, %d): group full\n", idGroup, idPlayer));
return dp_RES_FULL;
}
/* Find proper point at which to insert player */
for (i=0; i<pg->n; i++)
if (idPlayer <= pg->members[i]) break;
if ((i < pg->n) && (idPlayer == pg->members[i])) {
DPRINT(("dpGroup_AddPlayerLocal(%d, %d): player already in group\n", idGroup, idPlayer));
return dp_RES_ALREADY;
}
/* Move other players up */
/* If no other players, then i is zero, n is zero, and no bytes are moved. */
memmove(pg->members+i+1, pg->members+i, sizeof(pg->members[0]) * (pg->n - i));
/* Add new player */
pg->members[i] = idPlayer;
pg->n++;
dpGroup_dump(dp);
return dp_RES_OK;
}
/*----------------------------------------------------------------------
Delete player idPlayer from idGroup, but don't broadcast notification.
Called only by dpReceive and dpDeletePlayerFromGroup.
----------------------------------------------------------------------*/
dp_result_t dpGroup_DeletePlayerLocal(
dp_t *dp,
dpid_t idGroup,
dpid_t idPlayer)
{
dp_group_t *pg;
int i;
if (!dp->groups) {
DPRINT(("dpGroup_DeletePlayerLocal: not in session\n"));
return dp_RES_BUG;
}
pg = (dp_group_t *)assoctab_subscript(dp->groups, idGroup);
if (!pg) {
DPRINT(("dpGroup_DeletePlayerLocal(%d, %d): no such group\n", idGroup, idPlayer));
return dp_RES_BAD;
}
/* Find player */
for (i=0; i<pg->n; i++)
if (idPlayer <= pg->members[i]) break;
if ((i == pg->n) || (idPlayer != pg->members[i])) {
DPRINT(("dpGroup_DeletePlayerLocal(%d, %d): player not in group\n", idGroup, idPlayer));
return dp_RES_ALREADY;
}
/* Move other players down */
pg->n--;
/* If no other players, then i is zero, n is zero, and no bytes are moved. */
memmove(pg->members+i, pg->members+i+1, sizeof(pg->members[0]) * (pg->n - i));
dpGroup_dump(dp);
return dp_RES_OK;
}
/*----------------------------------------------------------------------
Delete player idPlayer from all groups.
Only called by dpNotifyDeletePlayer.
Bug: should generate messages to user code, but doesn't.
----------------------------------------------------------------------*/
dp_result_t dpGroup_DeletePlayerFromAllGroups(
dp_t *dp,
dpid_t idPlayer)
{
int i;
if (!dp->groups) {
DPRINT(("dpGroup_DeletePlayerFromAllGroups: not in session\n"));
return dp_RES_BUG;
}
for (i=0; i<dp->groups->n_used; i++) {
assoctab_item_t *pe;
pe = assoctab_getkey(dp->groups, i);
if (!pe) {
DPRINT(("dpGroup_DeletePlayerFromAllGroups: no group entry for index %d\n", i));
return dp_RES_BUG;
}
DPRINT(("dpGroup_DeletePlayerFromAllGroups: deleting id %d from group id %d\n",
idPlayer, pe->key));
if (dpGroup_DeletePlayerLocal(dp, pe->key, idPlayer) == dp_RES_OK) {
/* send message to user code that player no longer in group */
/* BUG */
;
}
}
return dp_RES_OK;
}
/********************** User-Callable Functions **************************/
/*----------------------------------------------------------------------
Add a new group to the currently open session.
Can only be called on game host!
----------------------------------------------------------------------*/
DP_API dp_result_t dpCreateGroup(
dp_t *dp,
dpid_t *id,
char_t *name)
{
dp_group_t *pg;
dpid_t groupId;
if (!dp || !dp->groups) {
DPRINT(("dpCreateGroup: null\n"));
return dp_RES_BUG;
}
if (!dp->bMaster) {
DPRINT(("dpCreateGroup: must be master\n"));
return dp_RES_BAD;
}
DPRINT(("dpCreateGroup(dp, %p, %s):\n", id, name));
/* Allocate group id and storage */
groupId = dp->nextId++;
pg = (dp_group_t *)assoctab_subscript_grow(dp->groups, groupId);
if (!pg) {
DPRINT(("dpCreateGroup: bug\n"));
return dp_RES_BUG;
}
/* Fill group */
pg->id = groupId;
do
pg->karma = rand();
while (pg->karma == dp_KARMA_NONE);
strncpy(pg->name, name, sizeof(pg->name));
pg->name[sizeof(pg->name)-1] = 0;
DPRINT(("dpCreateGroup(%s): pg->name %s\n", name, pg->name));
pg->n = 0;
*id = groupId;
/* Notify all existing systems about new group */
return dpGroup_SendAddGroupPacket(dp, pg, PLAYER_BROADCAST, dp_USER_ADDGROUP_PACKET_ID);
}
/*----------------------------------------------------------------------
Destroy the given group; removes the group from the game session.
The dpID will not be reused during the current session.
Can only be called on game host!
----------------------------------------------------------------------*/
DP_API dp_result_t dpDestroyGroup(
dp_t *dp,
dpid_t id)
{
dp_group_t *pg;
dp_result_t err;
int fail;
if (!dp || !dp->groups) {
DPRINT(("dpDestroyGroup: null\n"));
return dp_RES_BUG;
}
if (!dp->bMaster) {
DPRINT(("dpDestroyGroup: must be master\n"));
return dp_RES_BAD;
}
pg = (dp_group_t *)assoctab_subscript(dp->groups, id);
if (!pg) return dp_RES_EMPTY;
/* Notify all existing systems about loss of group */
err = dpGroup_SendAddGroupPacket(dp, pg, PLAYER_BROADCAST, dp_USER_DELGROUP_PACKET_ID);
if (err != dp_RES_OK) return err;
fail = assoctab_subscript_delete(dp->groups, id);
if (fail) return dp_RES_EMPTY;
return dp_RES_OK;
}
/*----------------------------------------------------------------------
Add player idPlayer to the group idGroup. Broadcast notification to others.
Called by user code.
----------------------------------------------------------------------*/
DP_API dp_result_t dpAddPlayerToGroup(
dp_t *dp,
dpid_t idGroup,
dpid_t idPlayer)
{
dp_result_t err;
DPRINT(("dpAddPlayerToGroup(dp, group %d, player %d)\n", idGroup, idPlayer));
if (dpid2commHdl(dp, idPlayer) == PLAYER_NONE) {
DPRINT(("dpAddPlayerToGroup: player %d has no comm handle, can't add\n", idPlayer));
return dp_RES_BAD;
}
err = dpGroup_AddPlayerLocal(dp, idGroup, idPlayer);
if (err != dp_RES_OK)
return err;
/* Propagate this to all other machines in game */
return dpGroup_SendAddPlayerPacket(dp, idGroup, idPlayer, PLAYER_BROADCAST,
dp_USER_ADDPLAYERTOGROUP_PACKET_ID);
}
/*----------------------------------------------------------------------
Delete player idPlayer from the group idGroup.
----------------------------------------------------------------------*/
DP_API dp_result_t dpDeletePlayerFromGroup(
dp_t *dp,
dpid_t idGroup,
dpid_t idPlayer)
{
dp_result_t err;
DPRINT(("dpDeletePlayerFromGroup(dp, group %d, player %d)\n", idGroup, idPlayer));
err = dpGroup_DeletePlayerLocal(dp, idGroup, idPlayer);
if (err != dp_RES_OK)
return err;
/* Propagate this to all other machines in game */
return dpGroup_SendAddPlayerPacket(dp, idGroup, idPlayer, PLAYER_BROADCAST,
dp_USER_DELPLAYERFROMGROUP_PACKET_ID);
}
/*----------------------------------------------------------------------
Calls the given function once for each group in the given session, then
calls the given function once with dp_ID_NONE to indicate end of list.
If s is NULL, lists the group in the current session.
If s is not NULL, it must be a value from dpEnumSessions.
s must currently be NULL - that is, you can't yet enumerate the groups
of sessions you haven't joined.
----------------------------------------------------------------------*/
DP_API dp_result_t dpEnumGroups(
dp_t *dp,
dp_session_t *s,
dpEnumPlayersCallback_t cb,
void *context,
long timeout /* How long in milliseconds to wait. */
)
{
dp_group_t *pg;
int i;
(void) timeout;
if (s) {
DPRINT(("dpEnumGroups: can't enum other sessions' groups yet.\n"));
return dp_RES_BUG;
}
if (!dp->groups) {
DPRINT(("dpEnumGroups: not in session\n"));
return dp_RES_BUG;
}
for (i=0; i<dp->groups->n_used; i++) {
assoctab_item_t *pe;
pe = assoctab_getkey(dp->groups, i);
if (!pe) {
DPRINT(("dpEnumGroups: no entry for index %d\n", i));
return dp_RES_BUG;
}
pg = (dp_group_t *) &pe->value;
if (pe->key != pg->id)
DPRINT(("dpEnumGroups: bug\n"));
DPRINT(("dpEnumGroups: id %d, karma %x, name %p = '%s'\n",
pg->id, pg->karma, pg->name, pg->name));
cb(pg->id, pg->name, 0, context);
}
cb(dp_ID_NONE, NULL, 0, context);
return dp_RES_OK;
}
/*----------------------------------------------------------------------
Calls the given function once for each player in the given group, then
calls the given function once with dp_ID_NONE to indicate end of list.
If s is NULL, lists the players in the current session.
If s is not NULL, it must be a value from dpEnumSessions.
s must currently be NULL - that is, you can't yet enumerate the group
members of sessions you haven't joined.
----------------------------------------------------------------------*/
DP_API dp_result_t dpEnumGroupPlayers(
dp_t *dp,
dpid_t idGroup,
dp_session_t *s,
dpEnumPlayersCallback_t cb,
void *context,
long timeout /* How long in milliseconds to wait. */
)
{
dp_group_t *pg;
int i;
if (s) {
DPRINT(("dpEnumGroupPlayers: can't enum other sessions' groups yet.\n"));
return dp_RES_BAD;
}
if (!dp->groups) {
DPRINT(("dpEnumGroupPlayers: not in session\n"));
return dp_RES_BUG;
}
pg = (dp_group_t *)assoctab_subscript(dp->groups, idGroup);
if (!pg) {
DPRINT(("dpEnumGroupPlayers(%d): no such group\n", idGroup));
return dp_RES_BAD;
}
/* Go through the players in the group; fetch name and status; call back. */
for (i=0; i<pg->n; i++) {
char name[256];
if (dpGetPlayerName(dp, pg->members[i], name, sizeof(name)) != dp_RES_OK)
continue;
/* Should check whether player is local or remote here... */
/* Should also check return value of callback. */
cb(pg->members[i], name, 0, context);
}
(void) timeout;
return dp_RES_OK;
}
| 31.44723 | 107 | 0.616814 | [
"object"
] |
c4e2823eb19f2c9214f19d2a032af993c1bdbbe5 | 1,391 | h | C | digsby/ext/src/Animation/Interpolation.h | ifwe/digsby | f5fe00244744aa131e07f09348d10563f3d8fa99 | [
"Python-2.0"
] | 35 | 2015-08-15T14:32:38.000Z | 2021-12-09T16:21:26.000Z | digsby/ext/src/Animation/Interpolation.h | niterain/digsby | 16a62c7df1018a49eaa8151c0f8b881c7e252949 | [
"Python-2.0"
] | 4 | 2015-09-12T10:42:57.000Z | 2017-02-27T04:05:51.000Z | digsby/ext/src/Animation/Interpolation.h | niterain/digsby | 16a62c7df1018a49eaa8151c0f8b881c7e252949 | [
"Python-2.0"
] | 15 | 2015-07-10T23:58:07.000Z | 2022-01-23T22:16:33.000Z | #ifndef _CGUI_INTERPOLATION_H_
#define _CGUI_INTERPOLATION_H_
#include <wx/colour.h>
#include <vector>
using std::vector;
/*
things to interpolate
- numbers
- colors
- points
- rectangles
- images
interpolation methods
- linear
- polynomial, etc.
- strobe
*/
static wxColour interpolate(wxColour c1, wxColour c2, double factor)
{
return wxColour(
(c2.Red() - c1.Red()) * factor + c1.Red(),
(c2.Green() - c1.Green()) * factor + c1.Green(),
(c2.Blue() - c1.Blue()) * factor + c1.Blue(),
(c2.Alpha() - c1.Alpha()) * factor + c1.Alpha()
);
}
static double interpolate(double d1, double d2, double factor)
{
return (d2 - d1) * factor + d1;
}
template<typename T>
class Fader : Interpolator
{
};
template<typename T>
class SineWave : Interpolator<T>
{
public:
SineWave(T peak, T valley, double period)
: m_peak(peak)
, m_valley(valley)
, m_period(period)
{
}
T peak() const { return peak; }
T valley() const { return m_valley; }
double period() const { return m_period; }
protected:
T peak;
T valley;
double m_period;
};
/*
usage:
// oscillate between red and blue every 1.5 seconds.
vector<wxColour> colors;
colors.push_back(wxRED);
colors.push_back(wxBLUE);
m_colour = new SineWaveInterpolator<wxColour>(colors, 1.5);
*/
#endif // _CGUI_INTERPOLATION_H_
| 17.3875 | 68 | 0.637671 | [
"vector"
] |
c4e7ca04f2d5669118da7a5e5f71d377bd40e1c8 | 1,527 | h | C | sp/src/common/proto_version.h | joshmartel/source-sdk-2013 | 524e87f708d6c30360613b1f65ee174deafa20f4 | [
"Unlicense"
] | 2,268 | 2015-01-01T19:31:56.000Z | 2022-03-31T20:15:31.000Z | sp/src/common/proto_version.h | joshmartel/source-sdk-2013 | 524e87f708d6c30360613b1f65ee174deafa20f4 | [
"Unlicense"
] | 241 | 2015-01-01T15:26:14.000Z | 2022-03-31T22:09:59.000Z | sp/src/common/proto_version.h | DimasDSF/SMI | 76cc2df8d1f51eb06743d66169524c3493b6d407 | [
"Unlicense"
] | 2,174 | 2015-01-01T08:18:05.000Z | 2022-03-31T10:43:59.000Z | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#if !defined( PROTO_VERSION_H )
#define PROTO_VERSION_H
#ifdef _WIN32
#pragma once
#endif
// The current network protocol version. Changing this makes clients and servers incompatible
#define PROTOCOL_VERSION 24
#define DEMO_BACKWARDCOMPATABILITY
// For backward compatibility of demo files (NET_MAX_PAYLOAD_BITS went away)
#define PROTOCOL_VERSION_23 23
// For backward compatibility of demo files (sound index bits used to = 13 )
#define PROTOCOL_VERSION_22 22
// For backward compatibility of demo files (before the special DSP was shipped to public)
#define PROTOCOL_VERSION_21 21
// For backward compatibility of demo files (old-style dynamic model loading)
#define PROTOCOL_VERSION_20 20
// For backward compatibility of demo files (post Halloween sound flag extra bit)
#define PROTOCOL_VERSION_19 19
// For backward compatibility of demo files (pre Halloween sound flag extra bit)
#define PROTOCOL_VERSION_18 18
// For backward compatibility of demo files (MD5 in map version)
#define PROTOCOL_VERSION_17 17
// For backward compatibility of demo files (create string tables compression flag)
#define PROTOCOL_VERSION_14 14
// For backward compatibility of demo files
#define PROTOCOL_VERSION_12 12
// The PROTOCOL_VERSION when replay shipped to public
#define PROTOCOL_VERSION_REPLAY 16
#endif
| 30.54 | 94 | 0.735429 | [
"model"
] |
c4e819c9cec52401aca075a7e122f319b846ee11 | 3,228 | c | C | src/scopmath/abort.c | tommorse/nrn | 73236b12977118ae0a98d7dbbed60973994cdaee | [
"BSD-3-Clause"
] | 203 | 2018-05-03T11:02:11.000Z | 2022-03-31T14:18:31.000Z | src/scopmath/abort.c | tommorse/nrn | 73236b12977118ae0a98d7dbbed60973994cdaee | [
"BSD-3-Clause"
] | 1,228 | 2018-04-25T09:00:48.000Z | 2022-03-31T21:42:21.000Z | src/scopmath/abort.c | tommorse/nrn | 73236b12977118ae0a98d7dbbed60973994cdaee | [
"BSD-3-Clause"
] | 134 | 2018-04-23T09:14:13.000Z | 2022-03-16T08:57:11.000Z | #include <../../nrnconf.h>
/******************************************************************************
*
* File: abort.c
*
* Copyright (c) 1984, 1985, 1986, 1987, 1988, 1989, 1990
* Duke University
*
******************************************************************************/
#ifndef LINT
static char RCSid[] =
"abort.c,v 1.2 1997/08/30 14:32:00 hines Exp" ;
#endif
/*-----------------------------------------------------------------------------
*
* ABORT_RUN()
*
* Prints out an error message and returns to the main menu if a solver
* routine returns a nonzero error code.
*
* Calling sequence: abort_run(code)
*
* Argument: code int flag for error
*
* Returns:
*
* Functions called: abs(), cls(), cursrpos(), puts(), gets()
*
* Files accessed:
*---------------------------------------------------------------------------*/
#include <stdio.h>
#include <setjmp.h>
#include "errcodes.h"
extern void hoc_execerror(const char*, const char*);
int abort_run(code)
int code;
{
#ifndef MAC
extern int abs();
#endif
extern int _modl_cleanup();
#if HOC == 0
extern jmp_buf ibuf;
#endif
char tmpstr[4];
#if !HOC
cls();
cursrpos(10, 0, 0);
#endif
switch (abs(code))
{
case EXCEED_ITERS:
puts("Convergence not achieved in maximum number of iterations");
break;
case SINGULAR:
puts("The matrix in the solution method is singular or ill-conditioned");
break;
case PRECISION:
puts("The increment in the independent variable is less than machine roundoff error");
break;
case CORR_FAIL:
puts("The corrector failed to satisfy the error check");
break;
case DIVERGED:
puts("The corrector iteration diverged");
break;
case INCONSISTENT:
puts("Inconsistent boundary conditions");
puts("Convergence not acheived in maximum number of iterations");
break;
case BAD_START:
puts("Poor starting estimate for initial conditions");
puts("The matrix in the solution method is singular or ill-conditioned");
break;
case NODATA:
puts("No data found in data file");
break;
case NO_SOLN:
puts("No solution was obtained for the coefficients");
break;
case LOWMEM:
puts("Insufficient memory to run the model");
break;
case DIVCHECK:
puts("Attempt to divide by zero");
break;
case NOFORCE:
puts("Could not open forcing function file\nThe model cannot be run without the forcing function");
break;
case NEG_ARG:
puts("Cannot compute factorial of negative argument");
break;
case RANGE:
puts("Value of variable is outside the range of the forcing function data table");
break;
default:
puts("Origin of error is unknown");
}
#if HOC
_modl_cleanup();
hoc_execerror("scopmath library error", (char*)0);
#else
puts("\nPress <Enter> to abort the run");
gets(tmpstr);
longjmp(ibuf, 0);
#endif
return 0;
}
/* define some routines needed for shared libraries to work */
#if HOC
int prterr(const char* s) {
hoc_execerror(s, "from prterr");
return 0;
}
#if 0
_modl_set_dt(newdt) double newdt; { printf("ssimplic.c :: _modl_set_dt can't be called\n");
exit(1);
}
#endif
#endif
| 24.270677 | 104 | 0.596035 | [
"model"
] |
c4eab304a239e2077039c6288d16954a43b97163 | 3,383 | h | C | services/audiopolicy/common/managerdefinitions/include/EffectDescriptor.h | Dreadwyrm/lhos_frameworks_av | 62c63ccfdf5c79a3ad9be4836f473da9398c671b | [
"Apache-2.0"
] | null | null | null | services/audiopolicy/common/managerdefinitions/include/EffectDescriptor.h | Dreadwyrm/lhos_frameworks_av | 62c63ccfdf5c79a3ad9be4836f473da9398c671b | [
"Apache-2.0"
] | null | null | null | services/audiopolicy/common/managerdefinitions/include/EffectDescriptor.h | Dreadwyrm/lhos_frameworks_av | 62c63ccfdf5c79a3ad9be4836f473da9398c671b | [
"Apache-2.0"
] | 2 | 2021-07-08T07:42:11.000Z | 2021-07-09T21:56:10.000Z | /*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <policy.h>
#include <system/audio_effect.h>
#include <utils/KeyedVector.h>
#include <utils/RefBase.h>
#include <utils/Errors.h>
#include <utils/String8.h>
namespace android {
class EffectDescriptor : public RefBase
{
public:
EffectDescriptor(const effect_descriptor_t *desc, bool isMusicEffect,
int id, audio_io_handle_t io, audio_session_t session) :
mId(id), mIo(io), mSession(session), mEnabled(false), mSuspended(false),
mIsMusicEffect(isMusicEffect)
{
memcpy (&mDesc, desc, sizeof(effect_descriptor_t));
}
void dump(String8 *dst, int spaces = 0) const;
int mId; // effect unique ID
audio_io_handle_t mIo; // io the effect is attached to
audio_session_t mSession; // audio session the effect is on
effect_descriptor_t mDesc; // effect descriptor
bool mEnabled; // enabled state: CPU load being used or not
bool mSuspended; // enabled but suspended by concurent capture policy
bool isMusicEffect() const { return mIsMusicEffect; }
private:
bool mIsMusicEffect;
};
class EffectDescriptorCollection : public KeyedVector<int, sp<EffectDescriptor> >
{
public:
EffectDescriptorCollection();
status_t registerEffect(const effect_descriptor_t *desc, audio_io_handle_t io,
int session, int id, bool isMusicEffect);
status_t unregisterEffect(int id);
sp<EffectDescriptor> getEffect(int id) const;
EffectDescriptorCollection getEffectsForIo(audio_io_handle_t io) const;
status_t setEffectEnabled(int id, bool enabled);
bool isEffectEnabled(int id) const;
uint32_t getMaxEffectsCpuLoad() const;
uint32_t getMaxEffectsMemory() const;
bool isNonOffloadableEffectEnabled() const;
void moveEffects(audio_session_t session,
audio_io_handle_t srcOutput,
audio_io_handle_t dstOutput);
void moveEffects(const std::vector<int>& ids, audio_io_handle_t dstOutput);
void dump(String8 *dst, int spaces = 0, bool verbose = true) const;
private:
status_t setEffectEnabled(const sp<EffectDescriptor> &effectDesc, bool enabled);
uint32_t mTotalEffectsCpuLoad; // current CPU load used by effects (in MIPS)
uint32_t mTotalEffectsMemory; // current memory used by effects (in KB)
uint32_t mTotalEffectsMemoryMaxUsed; // maximum memory used by effects (in KB)
/**
* Maximum CPU load allocated to audio effects in 0.1 MIPS (ARMv5TE, 0 WS memory) units
*/
static const uint32_t MAX_EFFECTS_CPU_LOAD = 1000;
/**
* Maximum memory allocated to audio effects in KB
*/
static const uint32_t MAX_EFFECTS_MEMORY = 512;
};
} // namespace android
| 35.610526 | 91 | 0.706769 | [
"vector"
] |
c4f359a4d5d4c9b32b81815af75f01bd424b785f | 44,807 | c | C | src/database/serialization/code/sd_serializerXMLMetadata.c | brezillon/opensplice | 725ae9d949c83fce1746bd7d8a154b9d0a81fe3e | [
"Apache-2.0"
] | 133 | 2017-11-09T02:10:00.000Z | 2022-03-29T09:45:10.000Z | src/database/serialization/code/sd_serializerXMLMetadata.c | brezillon/opensplice | 725ae9d949c83fce1746bd7d8a154b9d0a81fe3e | [
"Apache-2.0"
] | 131 | 2017-11-07T14:48:43.000Z | 2022-03-13T15:30:47.000Z | src/database/serialization/code/sd_serializerXMLMetadata.c | brezillon/opensplice | 725ae9d949c83fce1746bd7d8a154b9d0a81fe3e | [
"Apache-2.0"
] | 94 | 2017-11-09T02:26:19.000Z | 2022-02-24T06:38:25.000Z | /*
* Vortex OpenSplice
*
* This software and documentation are Copyright 2006 to TO_YEAR ADLINK
* Technology Limited, its affiliated companies and licensors. 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.
*
*/
/** \file database/serialization/include/sd_serializerXMLMetadata.h
* \brief Declaration of the \b serializerXMLMetadata class.
*/
/* Interface */
#include "sd__serializer.h"
#include "sd_serializerXMLMetadata.h"
/* Implementation */
#include "os_stdlib.h"
#include "os_heap.h"
#include "c_collection.h"
#include "sd_misc.h"
#include "sd__serializerXML.h"
#include "sd__confidence.h"
#include "sd__resultCodesXMLMetadata.h"
#include "sd_stringsXML.h"
#include "sd__deepwalkMeta.h"
#include "c_stringSupport.h"
#define SD_FORMAT_ID 0x584DU /* currently the same as XML */
#define SD_FORMAT_VERSION 0x0001U
#ifndef NDEBUG
/* -------------------------- checking routines -----------------------*/
/** \brief Check if a serializer is an instance of the serializerXMLMetadata
* class implemented in this file.
*
* Functions implemented in this file assume that an instance of
* the serializerXMLMetadata class is sent as first parameter. This routine
* can be used as a confidence check to avoid mixing of instances.
*
* \param serializer The serializer object (self).
* \return TRUE is serializer is indeed a serializerXMLMetadata instance,
FALSE otherwise.
*/
static c_bool
sd_checkSerializerType(
sd_serializer serializer)
{
return (c_bool)(
((unsigned int)serializer->formatID == SD_FORMAT_ID) &&
((unsigned int)serializer->formatVersion == SD_FORMAT_VERSION));
}
#endif
/* ---------- Helper struct for special treatment of some attributes -------- */
typedef struct sd_specialAddresses_s {
struct baseObject {
c_object kind;
} baseObject;
struct metaObject {
c_object definedIn;
c_object name;
} metaObject;
struct ignore {
struct type {
c_object alignment;
c_object base;
c_object size;
c_object objectCount;
} type;
struct structure {
c_object references;
c_object scope;
} structure;
struct v_union {
c_object references;
c_object scope;
} v_union;
struct constant {
c_object operand;
c_object type;
} constant;
struct member {
c_object offset;
} member;
} ignore;
struct abstractTypes {
c_object structure;
c_object type;
c_object typeDef;
} abstractTypes;
struct specialTypes {
c_object enumeration;
c_object constant;
} specialTypes;
struct currentContext {
c_set processedTypes;
c_type existingType;
c_bool doDefinedIn;
c_bool doEnumeration;
c_metaObject enumerationScope;
c_bool doCompare;
} currentContext;
} *sd_specialAddresses;
#define SD_CBASEOBJECTNAME "c_baseObject"
#define SD_KINDNAME "kind"
#define SD_CMETAOBJECTNAME "c_metaObject"
#define SD_DEFINEDINNAME "definedIn"
#define SD_NAMENAME "name"
#define SD_CTYPENAME "c_type"
#define SD_ALIGNMENTNAME "alignment"
#define SD_BASENAME "base"
#define SD_SIZENAME "size"
#define SD_COUNTNAME "objectCount"
#define SD_CSTRUCTURENAME "c_structure"
#define SD_SCOPENAME "scope"
#define SD_REFERENCESNAME "references"
#define SD_CUNIONNAME "c_union"
#define SD_CCONSTANTNAME "c_constant"
#define SD_OPERANDNAME "operand"
#define SD_TYPENAME "type"
#define SD_CMEMBERNAME "c_member"
#define SD_OFFSETNAME "offset"
#define SD_CTYPEDEFNAME "c_typeDef"
#define SD_CENUMERATIONNAME "c_enumeration"
static sd_specialAddresses
sd_getSpecialAddresses(
c_base base)
{
sd_specialAddresses result;
c_metaObject metaObject;
result = os_malloc(sizeof(*result));
metaObject = (c_metaObject)c_resolve(base, SD_CBASEOBJECTNAME);
SD_CONFIDENCE(metaObject);
result->baseObject.kind = c_metaResolve(metaObject, SD_KINDNAME);
SD_CONFIDENCE(result->baseObject.kind);
c_free(metaObject);
metaObject = (c_metaObject)c_resolve(base, SD_CMETAOBJECTNAME);
SD_CONFIDENCE(metaObject);
result->metaObject.definedIn = c_metaResolve(metaObject, SD_DEFINEDINNAME);
SD_CONFIDENCE(result->metaObject.definedIn);
result->metaObject.name = c_metaResolve(metaObject, SD_NAMENAME);
SD_CONFIDENCE(result->metaObject.name);
c_free(metaObject);
metaObject = (c_metaObject)c_resolve(base, SD_CTYPENAME);
SD_CONFIDENCE(metaObject);
result->abstractTypes.type = c_keep(metaObject);
result->ignore.type.alignment = c_metaResolve(metaObject, SD_ALIGNMENTNAME);
SD_CONFIDENCE(result->ignore.type.alignment);
result->ignore.type.base = c_metaResolve(metaObject, SD_BASENAME);
SD_CONFIDENCE(result->ignore.type.base);
result->ignore.type.size = c_metaResolve(metaObject, SD_SIZENAME);
SD_CONFIDENCE(result->ignore.type.size);
result->ignore.type.objectCount = c_metaResolve(metaObject, SD_COUNTNAME);
SD_CONFIDENCE(result->ignore.type.objectCount);
c_free(metaObject);
metaObject = (c_metaObject)c_resolve(base, SD_CSTRUCTURENAME);
SD_CONFIDENCE(metaObject);
result->abstractTypes.structure = c_keep(metaObject);
result->ignore.structure.references = c_metaResolve(metaObject, SD_REFERENCESNAME);
SD_CONFIDENCE(result->ignore.structure.references);
result->ignore.structure.scope = c_metaResolve(metaObject, SD_SCOPENAME);
SD_CONFIDENCE(result->ignore.structure.scope);
c_free(metaObject);
metaObject = (c_metaObject)c_resolve(base, SD_CUNIONNAME);
SD_CONFIDENCE(metaObject);
result->ignore.v_union.references = c_metaResolve(metaObject, SD_REFERENCESNAME);
SD_CONFIDENCE(result->ignore.v_union.references);
result->ignore.v_union.scope = c_metaResolve(metaObject, SD_SCOPENAME);
SD_CONFIDENCE(result->ignore.v_union.scope);
c_free(metaObject);
metaObject = (c_metaObject)c_resolve(base, SD_CTYPEDEFNAME);
SD_CONFIDENCE(metaObject);
result->abstractTypes.typeDef = c_keep(metaObject);
c_free(metaObject);
metaObject = (c_metaObject)c_resolve(base, SD_CENUMERATIONNAME);
SD_CONFIDENCE(metaObject);
result->specialTypes.enumeration = c_keep(metaObject);
c_free(metaObject);
metaObject = (c_metaObject)c_resolve(base, SD_CCONSTANTNAME);
SD_CONFIDENCE(metaObject);
result->specialTypes.constant = c_keep(metaObject);
result->ignore.constant.operand = c_metaResolve(metaObject, SD_OPERANDNAME);
SD_CONFIDENCE(result->ignore.constant.operand);
result->ignore.constant.type = c_metaResolve(metaObject, SD_TYPENAME);
SD_CONFIDENCE(result->ignore.constant.type);
c_free(metaObject);
metaObject = (c_metaObject)c_resolve(base, SD_CMEMBERNAME);
SD_CONFIDENCE(metaObject);
result->ignore.member.offset = c_metaResolve(metaObject, SD_OFFSETNAME);
SD_CONFIDENCE(result->ignore.member.offset);
c_free(metaObject);
result->currentContext.existingType = NULL;
result->currentContext.doDefinedIn = FALSE;
result->currentContext.doEnumeration = FALSE;
result->currentContext.enumerationScope = NULL;
result->currentContext.doCompare = FALSE;
result->currentContext.processedTypes = c_setNew((c_type)result->abstractTypes.type);
return result;
}
#undef SD_METAOBJECTNAME
#undef SD_DEFINEDINNAME
#undef SD_NAMENAME
#undef SD_TYPENAME
#undef SD_ALIGNMENTNAME
#undef SD_BASENAME
#undef SD_SIZENAME
#undef SD_STRUCTURENAME
#undef SD_SCOPENAME
#undef SD_REFERENCESNAME
#undef SD_UNIONNAME
#undef SD_MEMBERNAME
#undef SD_OFFSETNAME
static void
sd_releaseSpecialAddresses(
sd_specialAddresses addresses)
{
c_object *current;
c_object *end;
current = (c_object *)addresses;
end = (c_object *)&(addresses->currentContext.existingType);
while (current != end) {
c_free(*current);
current = ¤t[1];
}
os_free(addresses);
}
static c_bool
sd_matchesIgnoreAddresses(
sd_specialAddresses addresses,
c_object object)
{
c_bool result = FALSE;
c_object *current;
c_object *end;
current = (c_object *)&(addresses->ignore);
end = (c_object *)SD_DISPLACE(current, C_ADDRESS(sizeof(addresses->ignore)));
while (!result && (current != end)) {
result = result || (C_ADDRESS(*current) == C_ADDRESS(object));
current = ¤t[1];
}
return result;
}
static c_bool
sd_matchesAbstractTypeAddresses(
sd_specialAddresses addresses,
c_object object)
{
c_bool result = FALSE;
c_object *current;
c_object *end;
current = (c_object *)&(addresses->abstractTypes);
end = (c_object *)SD_DISPLACE(current, C_ADDRESS(sizeof(addresses->abstractTypes)));
while (!result && (current != end)) {
result = result || (C_ADDRESS(*current) == C_ADDRESS(object));
current = ¤t[1];
}
return result;
}
/* --------------- action argument for (de)serialiazation actions ---------- */
struct sd_metaActionSerArg {
os_size_t *sizePtr;
c_char **dataPtrPtr;
};
/* -------------------- more string helper routines -------------------*/
static c_size
sd_printTaggedString(
c_string dst,
c_string src,
const c_char *tagName)
{
int len;
c_ulong ulen;
c_ulong result = 0;
c_char *current;
current = dst;
len = os_sprintf(current, "<%s>", tagName);
result += (c_ulong)len;
current = SD_DISPLACE(current, C_ADDRESS(len));
ulen = sd_printCharData(current, src);
result += ulen;
current = SD_DISPLACE(current, C_ADDRESS(ulen));
len = os_sprintf(current, "</%s>", tagName);
result += (c_ulong)len;
return result;
}
static c_bool sd_scanTaggedString(c_char **dst, c_char **src, c_char *tagName, sd_errorInfo *errorInfo) __nonnull_all__ __attribute_warn_unused_result__;
static c_bool
sd_scanTaggedString(
c_char **dst,
c_char **src,
c_char *tagName,
sd_errorInfo *errorInfo)
{
c_char *foundTagName;
foundTagName = sd_strGetOpeningTag(src);
if ((foundTagName == NULL) || (strncmp(foundTagName, tagName, strlen(tagName)) != 0)) {
SD_VALIDATION_SET_ERROR(errorInfo, UNEXPECTED_OPENING_TAG, tagName, *src);
os_free(foundTagName);
return FALSE;
}
os_free(foundTagName);
if (!sd_scanCharData(dst, src, errorInfo)) {
SD_VALIDATION_ERROR_SET_NAME(errorInfo, tagName);
return FALSE;
}
foundTagName = sd_strGetClosingTag(src);
if ((foundTagName == NULL) || (strncmp(foundTagName, tagName, strlen(tagName)) != 0)) {
SD_VALIDATION_SET_ERROR(errorInfo, UNEXPECTED_CLOSING_TAG, tagName, *src);
os_free(*dst);
os_free(foundTagName);
return FALSE;
}
os_free(foundTagName);
return TRUE;
}
#define SD_SCOPE_IDENTIFIER "::"
static c_char *
sd_concatScoped(
c_char *scopeName,
c_char *name)
{
c_char *result;
os_size_t len;
if (scopeName && *scopeName) {
len = strlen(scopeName) + sizeof(SD_SCOPE_IDENTIFIER) + strlen(name) + 1;
result = os_malloc(len);
snprintf(result, len, "%s%s%s", scopeName, SD_SCOPE_IDENTIFIER, name);
} else {
len = strlen(name) + 1;
result = os_malloc(len);
os_strcpy(result, name);
}
return result;
}
#undef SD_SCOPE_IDENTIFIER
static void
sd_printScopedMetaObjectName(
c_metaObject object,
c_char **dataPtrPtr)
{
c_char *scopeName;
c_ulong len;
scopeName = c_metaScopedName(object);
if (scopeName) {
len = sd_printCharData(*dataPtrPtr, scopeName);
*dataPtrPtr = SD_DISPLACE(*dataPtrPtr, C_ADDRESS(len));
os_free(scopeName);
}
}
static void
sd_printDefinedIn(
c_object object,
c_char **dataPtrPtr)
{
c_metaObject scope;
scope = *(c_metaObject *)object;
sd_printScopedMetaObjectName(scope, dataPtrPtr);
}
#define SD_CHARS_SPACES " \t\n"
static c_bool
sd_stringSkipIgnoreSpaces(
c_char **dataPtrPtr,
c_char *buffer)
{
c_char *currentPtr;
c_bool result = TRUE;
currentPtr = buffer;
while (result && *currentPtr) {
sd_strSkipChars(dataPtrPtr, SD_CHARS_SPACES);
result = (*currentPtr == **dataPtrPtr);
currentPtr = &(currentPtr[1]);
*dataPtrPtr = &((*dataPtrPtr)[1]);
}
return result;
}
#undef SD_CHARS_SPACES
/* --------------------- Serialization driving functions -------------------- */
static c_bool sd_XMLMetadataSerCallbackPre(const c_char *name, c_type type, c_object *objectPtr, void *actionArg, sd_errorInfo *errorInfo, void *userData) __nonnull((2, 3, 4, 5, 6)) __attribute_warn_unused_result__;
static c_bool
sd_XMLMetadataSerCallbackPre(
const c_char *name,
c_type type,
c_object *objectPtr,
void *actionArg,
sd_errorInfo *errorInfo,
void *userData)
{
struct sd_metaActionSerArg *metaActionArg = actionArg;
sd_specialAddresses special = userData;
c_char **dataPtrPtr = metaActionArg->dataPtrPtr;
c_ulong len;
c_char *tagName;
int spRes;
OS_UNUSED_ARG(errorInfo);
/* Opening tag */
tagName = sd_getTagName(name, type);
spRes = os_sprintf(*dataPtrPtr, "<%s>", tagName);
if (spRes > 0) {
*dataPtrPtr = SD_DISPLACE(*dataPtrPtr, C_ADDRESS(spRes));
}
os_free(tagName);
/* Special treatment for c_voidp definedIn */
if (special->currentContext.doDefinedIn) {
sd_printDefinedIn(*objectPtr, dataPtrPtr);
special->currentContext.doDefinedIn = FALSE;
} else {
/* Normal situation */
len = sd_XMLSerType(type, *objectPtr, *dataPtrPtr);
*dataPtrPtr = SD_DISPLACE(*dataPtrPtr, len);
}
return TRUE;
}
static c_bool sd_XMLMetadataSerCallbackPost(const c_char *name, c_type type, c_object *objectPtr, void *actionArg, sd_errorInfo *errorInfo, void *userData) __nonnull((2, 3, 4, 5, 6)) __attribute_warn_unused_result__;
static c_bool
sd_XMLMetadataSerCallbackPost(
const c_char *name,
c_type type,
c_object *objectPtr,
void *actionArg,
sd_errorInfo *errorInfo,
void *userData)
{
struct sd_metaActionSerArg *metaActionArg = actionArg;
sd_specialAddresses special = userData;
c_char **dataPtrPtr = metaActionArg->dataPtrPtr;
c_long len;
c_char *tagName;
c_object found;
c_metaObject typeInstance;
OS_UNUSED_ARG(errorInfo);
SD_CONFIDENCE(objectPtr);
/* Closing tag */
tagName = sd_getTagName(name, type);
len = os_sprintf(*dataPtrPtr, "</%s>", tagName);
if (len > 0) {
*dataPtrPtr = SD_DISPLACE(*dataPtrPtr, C_ADDRESS(len));
}
os_free(tagName);
if (sd_matchesAbstractTypeAddresses(special, c_typeActualType(type))) {
typeInstance = *(c_metaObject *)(*objectPtr);
found = c_remove(special->currentContext.processedTypes, typeInstance, NULL, NULL);
SD_CONFIDENCE(found == typeInstance);
OS_UNUSED_ARG(found);
}
return TRUE;
}
/* An implementation for counting: do the serialization but overwrite
* a static buffer. Count anyway and return the count.
*/
static c_bool sd_XMLMetadataCountCallbackPre(const c_char *name, c_type type, c_object *objectPtr, void *actionArg, sd_errorInfo *errorInfo, void *userData) __nonnull((2, 3, 4, 5, 6)) __attribute_warn_unused_result__;
static c_bool
sd_XMLMetadataCountCallbackPre(
const c_char *name,
c_type type,
c_object *objectPtr,
void *actionArg,
sd_errorInfo *errorInfo,
void *userData)
{
struct sd_metaActionSerArg *metaActionArg = actionArg;
os_size_t *size = metaActionArg->sizePtr;
c_char *start, *end;
start = *metaActionArg->dataPtrPtr;
if (!sd_XMLMetadataSerCallbackPre(name, type, objectPtr, actionArg, errorInfo, userData)) {
assert(0);
}
end = *metaActionArg->dataPtrPtr;
*size += (C_ADDRESS(end)-C_ADDRESS(start));
*metaActionArg->dataPtrPtr = start;
return TRUE;
}
static c_bool sd_XMLMetadataCountCallbackPost(const c_char *name, c_type type, c_object *objectPtr, void *actionArg, sd_errorInfo *errorInfo, void *userData) __nonnull((2, 3, 4, 5, 6)) __attribute_warn_unused_result__;
static c_bool
sd_XMLMetadataCountCallbackPost(
const c_char *name,
c_type type,
c_object *objectPtr,
void *actionArg,
sd_errorInfo *errorInfo,
void *userData)
{
struct sd_metaActionSerArg *metaActionArg = actionArg;
os_size_t *size = metaActionArg->sizePtr;
c_char *start, *end;
start = *metaActionArg->dataPtrPtr;
if (!sd_XMLMetadataSerCallbackPost(name, type, objectPtr, actionArg, errorInfo, userData)) {
assert(0);
}
end = *metaActionArg->dataPtrPtr;
*size += (C_ADDRESS(end)-C_ADDRESS(start));
*metaActionArg->dataPtrPtr = start;
return TRUE;
}
static c_bool sd_XMLMetadataSerHook(c_bool *doRecurse, const c_char *name, c_baseObject propOrMem, c_object *objectPtr, void *actionArg, sd_errorInfo *errorInfo, void *userData) __nonnull((1, 3, 4, 5, 6, 7)) __attribute_warn_unused_result__;
static c_bool
sd_XMLMetadataSerHook(
c_bool *doRecurse,
const c_char *name,
c_baseObject propOrMem,
c_object *objectPtr,
void *actionArg,
sd_errorInfo *errorInfo,
void *userData)
{
struct sd_metaActionSerArg *metaActionArg = actionArg;
sd_specialAddresses special = userData;
c_char **dataPtrPtr = metaActionArg->dataPtrPtr;
os_size_t *size = metaActionArg->sizePtr;
c_object found;
c_metaObject typeInstance;
c_type type;
c_char *scopedName;
c_size len;
OS_UNUSED_ARG(errorInfo);
SD_CONFIDENCE(propOrMem->kind == M_ATTRIBUTE);
*doRecurse = !sd_matchesIgnoreAddresses(special, (c_object)propOrMem);
if (*doRecurse) {
switch(propOrMem->kind) {
case M_MEMBER:
type = c_specifier(propOrMem)->type;
break;
case M_ATTRIBUTE:
type = c_property(propOrMem)->type;
break;
default:
SD_CONFIDENCE(FALSE);
type = NULL;
}
if (sd_matchesAbstractTypeAddresses(special, c_typeActualType(type))) {
typeInstance = *(c_metaObject *)(*objectPtr);
found = c_replace(special->currentContext.processedTypes, typeInstance, NULL, NULL);
if (found) {
/* Recursive type definition, do special things and stop */
scopedName = c_metaScopedName(typeInstance);
SD_CONFIDENCE(scopedName);
if (scopedName) {
len = sd_printTaggedString(*dataPtrPtr, scopedName, name);
if (size != NULL) {
(*size) += len;
} else {
*dataPtrPtr = SD_DISPLACE(*dataPtrPtr, len);
}
os_free(scopedName);
}
*doRecurse = FALSE;
}
}
}
if (C_ADDRESS(propOrMem) == C_ADDRESS(special->metaObject.definedIn)) {
special->currentContext.doDefinedIn = TRUE;
}
return TRUE;
}
static sd_serializedData
sd_serializerXMLMetadataSerialize(
sd_serializer serializer,
c_object object)
{
sd_serializedData result;
os_size_t size;
c_char *startPtr;
c_type type;
C_STRUCT(sd_deepwalkMetaContext) context;
sd_specialAddresses specialAddresses;
struct sd_metaActionSerArg metaActionArg;
c_char *buffer;
c_bool ok;
SD_CONFIDENCE(sd_checkSerializerType(serializer));
OS_UNUSED_ARG(serializer);
specialAddresses = sd_getSpecialAddresses(c_getBase(object));
ospl_c_insert(specialAddresses->currentContext.processedTypes, object);
type = c_getType(object);
SD_CONFIDENCE(c_metaObject(type)->name != NULL);
/* Determine the size */
size = 1U /* '\0' */;
buffer = os_malloc(256);
metaActionArg.sizePtr = &size;
metaActionArg.dataPtrPtr = &buffer;
sd_deepwalkMetaContextInit(&context, sd_XMLMetadataCountCallbackPre, sd_XMLMetadataCountCallbackPost, sd_XMLMetadataSerHook, &metaActionArg, specialAddresses);
ok = sd_deepwalkMeta(type, c_metaObject(type)->name, &object, &context);
SD_CONFIDENCE(c_count(specialAddresses->currentContext.processedTypes) == 0);
sd_deepwalkMetaContextDeinit(&context);
os_free(buffer);
if (!ok) {
sd_releaseSpecialAddresses(specialAddresses);
return NULL;
}
/* Instantiate the serialized data */
result = sd_serializedDataNew(SD_FORMAT_ID, SD_FORMAT_VERSION, size);
/* Fill the block, then do the walk */
startPtr = (c_char *)result->data;
metaActionArg.sizePtr = NULL;
metaActionArg.dataPtrPtr = &startPtr;
ospl_c_insert(specialAddresses->currentContext.processedTypes, object);
sd_deepwalkMetaContextInit(&context, sd_XMLMetadataSerCallbackPre, sd_XMLMetadataSerCallbackPost, sd_XMLMetadataSerHook, &metaActionArg, specialAddresses);
if (!sd_deepwalkMeta(type, c_metaObject(type)->name, &object, &context)) {
sd_serializedDataFree(result);
result = NULL;
}
SD_CONFIDENCE(c_count(specialAddresses->currentContext.processedTypes) == 0);
sd_deepwalkMetaContextDeinit(&context);
if (result) {
/* Terminator */
*startPtr++ = 0;
SD_CONFIDENCE((C_ADDRESS(startPtr) - C_ADDRESS(result->data)) == size);
}
sd_releaseSpecialAddresses(specialAddresses);
return result;
}
/* ----------------- Special deserialization action routines ------------- */
static c_metaObject
sd_createOrLookupScope(
c_base base,
c_char *scopeName)
{
c_metaObject foundScope;
c_metaObject prevScope = NULL;
c_metaObject result;
c_char *helperString, *lastName;
c_char *currentLastName;
c_char *currentSrc, *currentDst;
os_size_t len;
c_object o;
/* if the scopeName is the empty string, then the scope is the general scope, i.e.
* the general module, thus the base.
*/
if(c_compareString(scopeName, "") == C_EQ)
{
return c_keep(c_metaObject(base));
}
len = strlen(scopeName) + 1;
helperString = os_malloc(len);
memset(helperString, 0, len);
lastName = os_malloc(len);
currentSrc = scopeName;
currentDst = helperString;
foundScope = c_keep(base);
do {
memset(lastName, 0, len);
currentLastName = lastName;
while ((*currentSrc != ':') && (*currentSrc != 0)) {
*currentDst = *currentSrc;
*currentLastName = *currentSrc;
currentSrc = &(currentSrc[1]);
currentDst = &(currentDst[1]);
currentLastName = &(currentLastName[1]);
}
c_free(prevScope);
prevScope = foundScope;
o = c_resolve(base, helperString);
if (o) {
SD_CONFIDENCE((c_baseObject(o)->kind == M_MODULE) ||
(c_baseObject(o)->kind == M_STRUCTURE) ||
(c_baseObject(o)->kind == M_UNION));
}
foundScope = c_metaObject(o);
while (*currentSrc == ':') {
*currentDst = *currentSrc;
currentSrc = &(currentSrc[1]);
currentDst = &(currentDst[1]);
}
} while ((*currentSrc != 0) && (foundScope != NULL));
if (foundScope == NULL) {
/* Resolving failed, create all modules needed from here */
result = c_metaDeclare(prevScope, lastName, M_MODULE);
while (*currentSrc != 0) {
memset(lastName, 0, len);
currentLastName = lastName;
while ((*currentSrc != ':') && (*currentSrc != 0)) {
*currentDst = *currentSrc;
*currentLastName = *currentSrc;
currentSrc = &(currentSrc[1]);
currentDst = &(currentDst[1]);
currentLastName = &(currentLastName[1]);
}
/* result is already kept in the prevScope, so can already be freed */
c_free(result);
result = c_metaDeclare(result, lastName, M_MODULE);
while (*currentSrc == ':') {
*currentDst = *currentSrc;
currentSrc = &(currentSrc[1]);
currentDst = &(currentDst[1]);
}
/* Do not free result as it is returned by this function */
}
} else {
result = c_keep(foundScope);
}
c_free(prevScope);
c_free(foundScope);
os_free(helperString);
os_free(lastName);
return result;
}
#define SD_BASEOBJECT_KIND_NAME "kind"
#define SD_METAOBJECT_NAME_NAME "name"
#define SD_METAOBJECT_DEFINEDIN_NAME "definedIn"
static c_bool sd_createOrLookupType(c_object *objectPtr, c_char *dataPtr, c_type *actualType, c_bool *typeExisted, sd_errorInfo *errorInfo, sd_specialAddresses special) __nonnull_all__ __attribute_warn_unused_result__;
static c_bool
sd_createOrLookupType(
c_object *objectPtr,
c_char *dataPtr,
c_type *actualType,
c_bool *typeExisted,
sd_errorInfo *errorInfo,
sd_specialAddresses special)
{
c_metaKind kind;
c_metaKind *kindPtr = &kind;
c_metaKind **kindPtrPtr;
c_char *scopeName;
c_char *name;
c_char *fullName;
c_base base;
c_type existingType;
c_object newObject, found;
c_metaObject scope;
c_char **helperPtrPtr;
/* Initialize out-params */
*actualType = NULL;
*typeExisted = FALSE;
helperPtrPtr = &dataPtr;
kindPtrPtr = &kindPtr;
if (!sd_XMLDeserCallbackPre(SD_BASEOBJECT_KIND_NAME, c_property(special->baseObject.kind)->type, (c_object *)kindPtrPtr, helperPtrPtr, errorInfo, NULL)) {
return FALSE;
}
if (!sd_XMLDeserCallbackPost(SD_BASEOBJECT_KIND_NAME, c_property(special->baseObject.kind)->type, (c_object *)kindPtrPtr, helperPtrPtr, errorInfo, NULL)) {
return FALSE;
}
if (!sd_scanTaggedString(&name, helperPtrPtr, SD_METAOBJECT_NAME_NAME, errorInfo)) {
return FALSE;
}
if (!sd_scanTaggedString(&scopeName, helperPtrPtr, SD_METAOBJECT_DEFINEDIN_NAME, errorInfo)) {
os_free(name);
return FALSE;
}
fullName = sd_concatScoped(scopeName, name);
/* Check if this type already exists */
base = c_getBase(special->baseObject.kind);
existingType = c_resolve(base, fullName);
if (existingType != NULL) {
/* Type already existed in the database */
*typeExisted = TRUE;
/* Keep a reference to the found type */
*actualType = c_keep(existingType);
/* transfer refcount from c_resolve */
*(c_object *)(*objectPtr) = existingType;
} else {
/* Type did not yet exist, check if modules exist */
*typeExisted = FALSE;
/* Make an instance of the metadata of the found type */
newObject = c_metaDefine(c_metaObject(base), kind);
*(c_object *)(*objectPtr) = newObject; /* transfer refcount */
*actualType = c_keep(c_getType(newObject));
/* Bind it now */
scope = c_metaResolve(c_metaObject(base), scopeName);
if (!scope) {
/* Scope not yet found, so this is a module. Create it. */
scope = sd_createOrLookupScope(base, scopeName);
}
SD_CONFIDENCE(scope != NULL);
found = c_metaBind(scope, name, (c_metaObject)newObject);
assert(found == newObject);
c_free(found);
c_free(scope);
}
os_free(scopeName);
os_free(name);
os_free(fullName);
return TRUE;
}
#undef SD_BASEOBJECT_KIND_NAME
#undef SD_METAOBJECT_NAME_NAME
#undef SD_METAOBJECT_DEFINEDIN_NAME
/* --------------------- Deserialization driving functions ----------------- */
static c_bool sd_XMLMetadataDeserCallbackPre(const c_char *name, c_type type, c_object *objectPtr, void *actionArg, sd_errorInfo *errorInfo, void *userData) __nonnull((2, 3, 4, 5, 6)) __attribute_warn_unused_result__;
static c_bool
sd_XMLMetadataDeserCallbackPre(
const c_char *name,
c_type type,
c_object *objectPtr,
void *actionArg,
sd_errorInfo *errorInfo,
void *userData)
{
c_char **dataPtrPtr = actionArg;
sd_specialAddresses special = userData;
c_char *startPtr = *dataPtrPtr;
c_char *tagName;
c_char *openingTag;
c_char *scopeName;
c_bool typeAction;
c_type actualType;
c_bool typeExisted;
c_metaObject scope;
c_char *enumName;
c_type insertedType;
if (special->currentContext.doCompare) {
c_char *buffer;
c_char *start;
c_char *toFree;
c_bool equals;
struct sd_metaActionSerArg metaActionArg;
start = *dataPtrPtr;
buffer = os_malloc(256);
toFree = buffer;
memset(buffer, 0, 256);
metaActionArg.dataPtrPtr = &buffer;
metaActionArg.sizePtr = NULL;
if (!sd_XMLMetadataSerCallbackPre(name, type, objectPtr, &metaActionArg, errorInfo, userData)) {
assert(0);
}
equals = sd_stringSkipIgnoreSpaces(dataPtrPtr, toFree);
if (!equals) {
SD_VALIDATION_SET_ERROR(errorInfo, UNMATCHING_TYPE, name, start);
os_free(toFree);
return FALSE;
}
os_free(toFree);
return TRUE;
}
/* Opening tag */
openingTag = sd_strGetOpeningTag(dataPtrPtr);
tagName = sd_getTagName(name, type);
if ((openingTag == NULL) ||
(strncmp(openingTag, tagName, strlen(openingTag)) != 0)) {
SD_VALIDATION_SET_ERROR(errorInfo, UNEXPECTED_OPENING_TAG, tagName, startPtr);
os_free(openingTag);
os_free(tagName);
return FALSE;
}
os_free(openingTag);
/* Determine the deserialization action */
/* definedIn requires special actions */
if (special->currentContext.doDefinedIn) {
if (!sd_scanCharData(&scopeName, dataPtrPtr, errorInfo)) {
SD_VALIDATION_ERROR_SET_NAME(errorInfo, tagName);
os_free(tagName);
return FALSE;
}
if (*(c_metaObject *)(*objectPtr) == NULL) {
scope = sd_createOrLookupScope(c_getBase(type), scopeName);
*(c_metaObject *)(*objectPtr) = scope;
} else {
#ifndef NDEBUG
char *foundName;
#endif
scope = *(c_metaObject *)(*objectPtr);
#ifndef NDEBUG
foundName = c_metaScopedName(scope);
SD_CONFIDENCE(strcmp(foundName, scopeName) == 0);
os_free(foundName);
#endif
}
special->currentContext.doDefinedIn = FALSE;
if (special->currentContext.doEnumeration) {
special->currentContext.enumerationScope = c_keep(scope);
}
os_free(scopeName);
} else {
if (C_ADDRESS(type) == C_ADDRESS(special->specialTypes.constant)) {
SD_CONFIDENCE(special->currentContext.doEnumeration);
SD_CONFIDENCE(special->currentContext.enumerationScope);
if (!sd_scanCharData(&enumName, dataPtrPtr, errorInfo)) {
SD_VALIDATION_ERROR_SET_NAME(errorInfo, tagName);
os_free(tagName);
return FALSE;
}
*(c_metaObject *)(*objectPtr) = c_metaDeclare(special->currentContext.enumerationScope, enumName, M_CONSTANT);
os_free(enumName);
} else {
/* The data */
/* Deserialization also updates dataPtrPtr */
if (!sd_XMLDeserType(type, objectPtr, dataPtrPtr, errorInfo)) {
os_free(tagName);
return FALSE;
}
}
}
/* If an error has occurred, fill its name */
SD_VALIDATION_ERROR_SET_NAME(errorInfo, tagName);
os_free(tagName);
/* Now determine if we start comparing with existing types from here on */
typeAction = sd_matchesAbstractTypeAddresses(special, c_typeActualType(type));
if (typeAction) {
/* This is an abstract type. Lookup the concrete instance type and
* create it, if it does not exist
*/
if (!sd_createOrLookupType(objectPtr, *dataPtrPtr, &actualType, &typeExisted, errorInfo, special)) {
return FALSE;
}
if (typeExisted) {
special->currentContext.existingType = actualType;
special->currentContext.doCompare = TRUE;
} else {
if (actualType == special->specialTypes.enumeration) {
special->currentContext.doEnumeration = TRUE;
}
}
insertedType = *(c_type *)(*objectPtr);
c_replace(special->currentContext.processedTypes, insertedType, NULL, NULL);
}
return TRUE;
}
static c_bool sd_XMLMetadataDeserCallbackPost (const c_char *name, c_type type, c_object *objectPtr, void *actionArg, sd_errorInfo *errorInfo, void *userData) __nonnull((2, 3, 4, 5, 6)) __attribute_warn_unused_result__;
static c_bool
sd_XMLMetadataDeserCallbackPost(
const c_char *name,
c_type type,
c_object *objectPtr,
void *actionArg,
sd_errorInfo *errorInfo,
void *userData)
{
c_char **dataPtrPtr = actionArg;
sd_specialAddresses special = userData;
c_char *startPtr = *dataPtrPtr;
c_char *tagName;
c_char *closingTag;
c_metaObject metaObject;
c_bool typeAction;
c_metaObject typeInstance;
c_metaObject found;
SD_CONFIDENCE(objectPtr);
/* Do the DB finalization actions */
typeAction = sd_matchesAbstractTypeAddresses(special, c_typeActualType(type));
if (typeAction) {
typeInstance = *(c_metaObject *)(*objectPtr);
if (special->currentContext.doCompare) {
if (c_type(typeInstance) == special->currentContext.existingType) {
c_free(special->currentContext.existingType);
special->currentContext.existingType = NULL;
special->currentContext.doCompare = FALSE;
}
} else {
metaObject = *(c_metaObject *)(*objectPtr);
c_metaFinalize(metaObject);
if (special->currentContext.doEnumeration) {
special->currentContext.doEnumeration = FALSE;
c_free(special->currentContext.enumerationScope);
special->currentContext.enumerationScope = NULL;
}
}
if (!special->currentContext.doCompare) {
found = c_remove(special->currentContext.processedTypes, typeInstance, NULL, NULL);
SD_CONFIDENCE(found == typeInstance);
OS_UNUSED_ARG(found);
}
}
if (special->currentContext.doCompare) {
c_char *buffer;
c_char *toFree;
c_bool equals;
struct sd_metaActionSerArg metaActionArg;
buffer = os_malloc(256);
memset(buffer, 0, 256);
toFree = buffer;
metaActionArg.dataPtrPtr = &buffer;
metaActionArg.sizePtr = NULL;
if (!sd_XMLMetadataSerCallbackPost(name, type, objectPtr, &metaActionArg, errorInfo, userData)) {
assert(0);
}
equals = sd_stringSkipIgnoreSpaces(dataPtrPtr, toFree);
if (!equals) {
SD_VALIDATION_SET_ERROR(errorInfo, UNMATCHING_TYPE, name, startPtr);
os_free(toFree);
return FALSE;
}
os_free(toFree);
} else {
/* Closing tag */
/* Check if it has the correct name */
closingTag = sd_strGetClosingTag(dataPtrPtr);
tagName = sd_getTagName(name, type);
if ((closingTag == NULL) || (strncmp(closingTag, tagName, strlen(closingTag)) != 0)) {
SD_VALIDATION_SET_ERROR(errorInfo, UNEXPECTED_CLOSING_TAG, tagName, startPtr);
os_free(closingTag);
os_free(tagName);
return FALSE;
}
os_free(closingTag);
os_free(tagName);
}
return TRUE;
}
static c_bool doSerHook(c_bool *doRecurse, const c_char *name, c_baseObject propOrMem, c_object *objectPtr, char **dataPtrPtr, sd_errorInfo *errorInfo, sd_specialAddresses special) __nonnull((1, 3, 4, 5, 6, 7)) __attribute_warn_unused_result__;
static c_bool
doSerHook(
c_bool *doRecurse,
const c_char *name,
c_baseObject propOrMem,
c_object *objectPtr,
char **dataPtrPtr,
sd_errorInfo *errorInfo,
sd_specialAddresses special)
{
struct sd_metaActionSerArg metaActionArg;
c_bool result;
c_char *buffer;
c_char *toFree;
c_bool equals;
buffer = os_malloc(256);
memset(buffer, 0, 256);
toFree = buffer;
metaActionArg.dataPtrPtr = &buffer;
metaActionArg.sizePtr = NULL;
result = sd_XMLMetadataSerHook(doRecurse, name, propOrMem, objectPtr, &metaActionArg, errorInfo, special);
equals = sd_stringSkipIgnoreSpaces(dataPtrPtr, toFree);
SD_CONFIDENCE(equals);
OS_UNUSED_ARG(equals);
os_free(toFree);
return result;
}
static c_bool sd_XMLMetadataDeserHook(c_bool *doRecurse, const c_char *name, c_baseObject propOrMem, c_object *objectPtr, void *actionArg, sd_errorInfo *errorInfo, void *userData) __nonnull((1, 3, 4, 5, 6, 7)) __attribute_warn_unused_result__;
static c_bool
sd_XMLMetadataDeserHook(
c_bool *doRecurse,
const c_char *name,
c_baseObject propOrMem,
c_object *objectPtr,
void *actionArg,
sd_errorInfo *errorInfo,
void *userData)
{
c_char **dataPtrPtr = actionArg;
sd_specialAddresses special = userData;
c_metaObject typeInstance;
c_type type;
c_string memberName;
c_char *scopedName;
SD_CONFIDENCE(propOrMem->kind == M_ATTRIBUTE);
if (special->currentContext.doCompare) {
return doSerHook(doRecurse, name, propOrMem, objectPtr, dataPtrPtr, errorInfo, special);
} else {
*doRecurse = !sd_matchesIgnoreAddresses(special, (c_object)propOrMem);
if (*doRecurse) {
switch(propOrMem->kind) {
case M_MEMBER:
type = c_specifier(propOrMem)->type;
memberName = c_specifier(propOrMem)->name;
break;
case M_ATTRIBUTE:
type = c_property(propOrMem)->type;
memberName = c_metaObject(propOrMem)->name;
break;
default:
SD_CONFIDENCE(FALSE);
type = NULL;
memberName = NULL;
}
if (sd_matchesAbstractTypeAddresses(special, c_typeActualType(type))) {
typeInstance = *(c_metaObject *)(*objectPtr);
if (typeInstance == NULL) {
scopedName = sd_peekTaggedCharData(*dataPtrPtr, memberName);
if (scopedName) {
typeInstance = c_metaResolve(c_metaObject(c_getBase(propOrMem)), scopedName);
SD_CONFIDENCE(typeInstance);
*(c_metaObject *)(*objectPtr) = c_keep(typeInstance);
c_free(typeInstance);
os_free(scopedName);
if (!sd_scanTaggedString(&scopedName, dataPtrPtr, memberName, errorInfo)) {
return FALSE;
}
os_free(scopedName);
*doRecurse = FALSE;
}
} else {
/* This is a special case. The type has already been set
* before the deserializer has processed it. The only known
* situation for this is c_string: c_stringNew sets the
* subtype.
*/
special->currentContext.existingType = c_type(typeInstance);
special->currentContext.doCompare = TRUE;
if (!doSerHook(doRecurse, name, propOrMem, objectPtr, dataPtrPtr, errorInfo, special)) {
return FALSE;
}
}
}
}
if (C_ADDRESS(propOrMem) == C_ADDRESS(special->metaObject.definedIn)) {
special->currentContext.doDefinedIn = TRUE;
}
return TRUE;
}
}
#define SD_MESSAGE_FORMAT "Error in tag %s: %s"
static c_bool
sd_serializerXMLDeserializeInternal(
sd_serializer serializer,
c_type type,
const c_char *name,
c_object *objectPtr,
c_char **dataPtrPtr)
{
C_STRUCT(sd_deepwalkMetaContext) context;
c_ulong errorNumber;
c_char *errname;
c_char *message;
c_char *location;
c_bool result;
c_char *XMLmessage;
sd_specialAddresses specialAddresses;
sd_serializerResetValidationState(serializer);
if (!*objectPtr) {
if (c_typeIsRef(type)) {
*objectPtr = NULL;
} else if ((*objectPtr = c_new_s(type)) == NULL) {
sd_serializerSetOutOfMemory(serializer);
return FALSE;
}
}
specialAddresses = sd_getSpecialAddresses(c_getBase(type));
sd_deepwalkMetaContextInit(&context, sd_XMLMetadataDeserCallbackPre, sd_XMLMetadataDeserCallbackPost, sd_XMLMetadataDeserHook, dataPtrPtr, specialAddresses);
result = sd_deepwalkMeta(type, name, objectPtr, &context);
if (!result) {
os_size_t size;
if (!sd_deepwalkMetaContextGetErrorInfo(&context, &errorNumber, &errname, &message, &location)) {
assert(0);
}
size = strlen(SD_MESSAGE_FORMAT) + strlen(errname) + strlen(message) - 4U + 1U; /* 4 = 2strlen ("%s")*/
XMLmessage = os_malloc(size);
snprintf(XMLmessage, size, SD_MESSAGE_FORMAT, errname, message);
sd_serializerSetValidationInfo(serializer, errorNumber, XMLmessage, sd_stringDup(location));
os_free(message);
/* Free the partially deserialized data */
c_free(*objectPtr);
*objectPtr = NULL;
} else {
assert (!sd_deepwalkMetaContextGetErrorInfo(&context, &errorNumber, &errname, &message, &location));
SD_CONFIDENCE(c_count(specialAddresses->currentContext.processedTypes) == 0);
SD_CONFIDENCE(*objectPtr);
}
sd_deepwalkMetaContextDeinit(&context);
sd_releaseSpecialAddresses(specialAddresses);
return result;
}
#undef SD_MESSAGE_FORMAT
static c_object
sd_serializerXMLMetadataDeserialize(
sd_serializer serializer,
sd_serializedData serData)
{
c_char *xmlString, *dummy;
c_char *typeName;
c_char *openingTag;
c_type resultType;
c_object result = NULL;
c_bool deserOK;
SD_CONFIDENCE(sd_checkSerializerType(serializer));
xmlString = (c_char *)serData->data;
/* First determine type from data */
dummy = xmlString;
openingTag = sd_strGetOpeningTag(&dummy);
typeName = os_strdup(openingTag);
SD_CONFIDENCE((strcmp(typeName, "c_structure") == 0) || (strcmp(typeName, "c_typeDef") == 0));
resultType = c_resolve(serializer->base, typeName);
/* resultType is c_class or c_struct or whatever metatype */
if (resultType) {
deserOK = sd_serializerXMLDeserializeInternal(serializer, resultType, openingTag, &result, &xmlString);
/* Check if we reached the end */
if (deserOK) {
SD_CONFIDENCE((int)*xmlString == '\0');
SD_CONFIDENCE(result);
} else {
SD_CONFIDENCE(result == NULL);
}
c_free(resultType);
}
os_free(openingTag);
os_free(typeName);
return result;
}
/* ---------------------------- constructor --------------------- */
/** \brief Constructor for the XML MetaData format serializer
*
* The \b serializerXMLMetadata class is a descendant of the
* \b serializerXML class. In order to use this class, create it with this
* function and call the methods as defined on \b serializer.
*
* \param base The database to serialize from and deserialize to.
*/
sd_serializer
sd_serializerXMLMetadataNew(
c_base base)
{
struct sd_serializerVMT VMT;
VMT.serialize = sd_serializerXMLMetadataSerialize;
VMT.deserialize = sd_serializerXMLMetadataDeserialize;
VMT.deserializeInto = NULL;
VMT.toString = sd_serializerXMLToString;
VMT.fromString = sd_serializerXMLFromString;
return sd_serializerNew(SD_FORMAT_ID, SD_FORMAT_VERSION, base, NULL, VMT);
}
| 32.258459 | 244 | 0.651729 | [
"object"
] |
f20542c1625d5e77ace4acb4c0e2edc1125d40d9 | 4,978 | h | C | cpp/coln/api.h | propaganda-gold/deeprev | 0c6ccf83131a879ed858acdb0675e75ebf2f2d3d | [
"BSD-3-Clause"
] | null | null | null | cpp/coln/api.h | propaganda-gold/deeprev | 0c6ccf83131a879ed858acdb0675e75ebf2f2d3d | [
"BSD-3-Clause"
] | 2 | 2021-05-11T16:29:38.000Z | 2022-01-22T12:28:49.000Z | cpp/coln/api.h | propaganda-gold/deeprev | 0c6ccf83131a879ed858acdb0675e75ebf2f2d3d | [
"BSD-3-Clause"
] | null | null | null | // Unique - constant pointer.. not mutable.. caller doesn't have ownership,
// unless they copy.
// Unique - an moveable object we have owenrship of
// Shared - a copyable object we have owernship of
// Mutable - mutable pointer, we do not have owernship of
// Outside of the collections code, almost no code should use:
// * unique_ptr (use Unique)
// * shared_ptr (use Shared)
//
// There should be a rationale listed any time we do not use error-protected
// code.
#ifndef coln_api_h
#define coln_api_h
#include "absl/memory/memory.h"
#include "absl/strings/str_cat.h"
#include "coln/option.h"
#include <memory>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
namespace vectorbook {
template <typename T> class ConstIterator {
public:
virtual Const<T> current() const = 0;
virtual bool done() = 0;
virtual void advance() = 0;
};
template <typename T> class MutableIterator {
public:
virtual Mutable<T> current() = 0;
virtual bool done() = 0;
virtual void advance() = 0;
};
// We use shared_ptr instead of Unique because a c++ iterator must be copyable.
// http://www.cplusplus.com/reference/iterator
template <typename T> class ConstCppIterator {
public:
ConstCppIterator<T>() {}
// 'underyling' must be non-null. We do not use Shared because we will not do
// error checking.
ConstCppIterator<T>(const std::shared_ptr<ConstIterator<T>> &underlying)
: underlying_(underlying) {}
ConstCppIterator<T> &operator++() {
underlying_->advance();
return *this;
}
bool operator!=(const ConstCppIterator<T> &iterator) const {
if (underlying_ && underlying_->done()) {
return false;
} else {
return true;
}
}
Const<T> operator*() const { return underlying_->current(); }
private:
std::shared_ptr<ConstIterator<T>> underlying_;
};
// We use shared_ptr instead of Unique because a c++ iterator must be copyable.
// http://www.cplusplus.com/reference/iterator
template <typename T> class MutableCppIterator {
public:
MutableCppIterator<T>() {}
MutableCppIterator<T>(const std::shared_ptr<MutableIterator<T>> &underlying)
: underlying_(underlying) {}
MutableCppIterator<T> &operator++() {
underlying_->advance();
return *this;
}
bool operator!=(const MutableCppIterator<T> &iterator) const {
if (underlying_ && underlying_->done()) {
return false;
} else {
return true;
}
}
Mutable<T> operator*() { return underlying_->current(); }
private:
std::shared_ptr<MutableIterator<T>> underlying_;
};
class Countable {
public:
virtual Size size() const = 0;
};
template <typename T> class ConstIterable {
public:
// We return Shared instead of Unique because the cpp iterator must be
// copyable.
virtual Shared<ConstIterator<T>> iterator() const = 0;
ConstCppIterator<T> begin() const {
return ConstCppIterator<T>(iterator().expose());
}
ConstCppIterator<T> end() const { return ConstCppIterator<T>(); }
};
template <typename T> class MutableIterable {
public:
virtual Shared<MutableIterator<T>> iterator() = 0;
MutableCppIterator<T> begin() {
return MutableCppIterator<T>(iterator());
}
MutableCppIterator<T> end() { return MutableCppIterator<T>(); }
};
template <typename T>
class ConstCollection : public Countable, public ConstIterable<T> {};
template <typename T>
class MutableCollection : public Countable, public MutableIterable<T> {};
template <typename T> class QueueLike {
public:
virtual Void append(const T &t) = 0;
virtual Void append(T &&t) = 0;
// Returns 1) a value if there is one, 2) Null() if nothing left but no
// error, or an error otherwise. An implementation can throw NOT_IMPLEMENTED.
virtual Option<T> pop() = 0;
};
template <typename T>
class Queue : public QueueLike<T>, public ConstCollection<T> {};
template <typename K> class Set : public ConstCollection<K> {
public:
virtual Boolean contains(const K &k) const = 0;
virtual Void insert(const K &k) = 0;
virtual Void insert(K &&k) = 0;
virtual Void erase(const K &k) = 0;
};
// A sub-class may return "not implemented" for some of these if there is a
// reason, especially 'mutable_get' and 'erase'.
template <typename K, typename V> class MapLike {
public:
virtual Boolean contains(const K &k) const = 0;
virtual Const<V> const_get(const K &k) const = 0;
virtual Void put(const K &k, const V &v) = 0;
virtual Void put(const K &k, V &&v) = 0;
virtual Mutable<V> mutable_get(const K &k) = 0;
virtual Void erase(const K &k) = 0;
};
// A generic map.
// NOTE: Don't make this mutable iterable yet.
template <typename K, typename V>
class Map : public MapLike<K, V>, public ConstCollection<KV<K, V>> {};
template <typename V>
class Seq : public MapLike<size_t, V>,
public QueueLike<V>,
public ConstCollection<V> {};
using StringSeq = Seq<std::string>;
using StringMap = Map<std::string, std::string>;
} // namespace vectorbook
#endif /* coln_api_h */
| 29.455621 | 79 | 0.694656 | [
"object",
"vector"
] |
f20b7296e107005f8bcdbef64947b8500d9e223b | 3,651 | h | C | newVdpDemo/deps/include/codecParameters.h | hrobrty/newVdpDemo | dac610929a4501d6cc7b2580aeff9239a4e77f6d | [
"MIT"
] | null | null | null | newVdpDemo/deps/include/codecParameters.h | hrobrty/newVdpDemo | dac610929a4501d6cc7b2580aeff9239a4e77f6d | [
"MIT"
] | 1 | 2021-04-14T06:10:35.000Z | 2021-04-14T06:10:35.000Z | newVdpDemo/deps/include/codecParameters.h | hrobrty/newVdpDemo | dac610929a4501d6cc7b2580aeff9239a4e77f6d | [
"MIT"
] | null | null | null | /*
codecParameters.h
Copyright (C) 2011 Belledonne Communications, Grenoble, France
Author : Johan Pascal
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#ifndef CODECPARAMETERS_H
#define CODECPARAMETERS_H
#define L_FRAME 80 /* Frame size. */
#define L_SUBFRAME 40 /* subFrame size. */
#define L_LP_ANALYSIS_WINDOW 240 /* Size of the window used in the LP Analysis */
/******************************************************************************/
/*** LSP coefficients ***/
/******************************************************************************/
/* define each coefficient bit number and range */
#define L0_LENGTH 1
#define L1_LENGTH 7
#define L2_LENGTH 5
#define L3_LENGTH 5
#define L0_RANGE (1<<L0_LENGTH)
#define L1_RANGE (1<<L1_LENGTH)
#define L2_RANGE (1<<L2_LENGTH)
#define L3_RANGE (1<<L3_LENGTH)
/* MA Prediction history length: maximum number of previous LSP used */
#define MA_MAX_K 4
/* Linear Prediction filters order: 10th order filters gives 10 (quantized) LP coefficients */
/* NB_LSP_COEFF is the number of LSP coefficient */
#define NB_LSP_COEFF 10
/* Maximum value of integer part of pitch delay */
#define MAXIMUM_INT_PITCH_DELAY 143
/* past excitation vector length: Maximum Pitch Delay (143 + 1(fractionnal part)) + Interpolation Windows Length (10) */
#define L_PAST_EXCITATION 154
/* rearrange coefficient gap in Q13 */
/* GAP1 is 0.0012, GAP2 is 0.0006 */
#define GAP1 10
#define GAP2 5
/* qLSF stability in Q13*/
/* Limits for quantized LSF */
/* in Q2.13, Max is 3.135 and Min is 0.005 */
#define qLSF_MIN 40
#define qLSF_MAX 25681
/* min distance between 2 consecutive qLSF is 0.0391 */
#define MIN_qLSF_DISTANCE 321
/* pitch gain boundaries in Q14 */
#define BOUNDED_PITCH_GAIN_MIN 3277
#define BOUNDED_PITCH_GAIN_MAX 13107
/* post filters values defined in 4.2.2 in Q15 pow 1 to 10 */
#define GAMMA_N1 18022
#define GAMMA_N2 9912
#define GAMMA_N3 5452
#define GAMMA_N4 2998
#define GAMMA_N5 1649
#define GAMMA_N6 907
#define GAMMA_N7 499
#define GAMMA_N8 274
#define GAMMA_N9 151
#define GAMMA_N10 83
#define GAMMA_D1 22938
#define GAMMA_D2 16056
#define GAMMA_D3 11239
#define GAMMA_D4 7868
#define GAMMA_D5 5507
#define GAMMA_D6 3855
#define GAMMA_D7 2699
#define GAMMA_D8 1889
#define GAMMA_D9 1322
#define GAMMA_D10 926
/* post filter value GAMMA_T 0.8 in Q15 (spec A.4.2.3)*/
#define GAMMA_T 26214
/* weighted speech for open-loop pitch delay (spec A3.3.3) in Q15 0.75^(1..10)*/
#define GAMMA_E1 24756
#define GAMMA_E2 18432
#define GAMMA_E3 13824
#define GAMMA_E4 10368
#define GAMMA_E5 7776
#define GAMMA_E6 5832
#define GAMMA_E7 4374
#define GAMMA_E8 3280
#define GAMMA_E9 2460
#define GAMMA_E10 1845
/*** Number of parameters in the encoded signal ***/
#define NB_PARAMETERS 15
/*** LP to LSP conversion ***/
#define NB_COMPUTED_VALUES_CHEBYSHEV_POLYNOMIAL 51
#endif /* ifndef CODECPARAMETERS_H */
| 32.026316 | 120 | 0.701452 | [
"vector"
] |
4f5dc0d77e823cd3a1c1577f12a275138b4b8810 | 716 | h | C | Engine/OmegaEngine/Inc/TransformComponent.h | CyroPCJr/OmegaEngine | 65fbd6cff54266a9c934e3a875a4493d26758661 | [
"MIT"
] | 1 | 2021-04-23T19:18:12.000Z | 2021-04-23T19:18:12.000Z | Engine/OmegaEngine/Inc/TransformComponent.h | CyroPCJr/OmegaEngine | 65fbd6cff54266a9c934e3a875a4493d26758661 | [
"MIT"
] | null | null | null | Engine/OmegaEngine/Inc/TransformComponent.h | CyroPCJr/OmegaEngine | 65fbd6cff54266a9c934e3a875a4493d26758661 | [
"MIT"
] | 1 | 2021-06-15T10:42:08.000Z | 2021-06-15T10:42:08.000Z | #pragma once
#include "Component.h"
namespace Omega
{
class TransformComponent final : public Component
{
public:
META_CLASS_DECLARE
// TODO : Ver como eh q usa isso nos videos do Peter
//SET_COMPONENT_ID(1)
void Initialize() override;
void Terminate() override;
void Update(float deltaTime) override;
void Render() override;
void DebugUI() override;
void EnableDebugUI(bool isActivated) { mIsDebugActivated = isActivated; }
Math::Matrix4 GetTransform() const;
Math::Vector3 position = Math::Vector3::Zero;
Math::Quaternion rotation = Math::Quaternion::Zero;
Math::Vector3 scale = Math::Vector3::Zero;
bool mIsDebugActivated = false;
};
}
| 21.058824 | 76 | 0.688547 | [
"render"
] |
4f64c8f4741cd9ab13bd7c673048f82327fc43f6 | 5,518 | h | C | components/signin/core/browser/account_investigator.h | Yannic/chromium | ab32e8aacb08c9fce0dc4bf09eec456ba46e3710 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 76 | 2020-09-02T03:05:41.000Z | 2022-03-30T04:40:55.000Z | components/signin/core/browser/account_investigator.h | blueboxd/chromium-legacy | 07223bc94bd97499909c9ed3c3f5769d718fe2e0 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 45 | 2020-09-02T03:21:37.000Z | 2022-03-31T22:19:45.000Z | components/signin/core/browser/account_investigator.h | Yannic/chromium | ab32e8aacb08c9fce0dc4bf09eec456ba46e3710 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 8 | 2020-07-22T18:49:18.000Z | 2022-02-08T10:27:16.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.
#ifndef COMPONENTS_SIGNIN_CORE_BROWSER_ACCOUNT_INVESTIGATOR_H_
#define COMPONENTS_SIGNIN_CORE_BROWSER_ACCOUNT_INVESTIGATOR_H_
#include <string>
#include <vector>
#include "base/macros.h"
#include "base/timer/timer.h"
#include "components/keyed_service/core/keyed_service.h"
#include "components/signin/public/identity_manager/identity_manager.h"
struct CoreAccountInfo;
class PrefRegistrySimple;
class PrefService;
namespace base {
class Time;
} // namespace base
namespace signin {
struct AccountsInCookieJarInfo;
} // namespace signin
namespace signin_metrics {
enum class AccountRelation;
enum class ReportingType;
} // namespace signin_metrics
// While it is common for the account signed into Chrome and the content area
// to be identical, this is not the only scenario. The purpose of this class
// is to watch for changes in relation between Chrome and content area accounts
// and emit metrics about their relation.
class AccountInvestigator : public KeyedService,
public signin::IdentityManager::Observer {
public:
// The targeted interval to perform periodic reporting. If chrome is not
// active at the end of an interval, reporting will be done as soon as
// possible.
static const base::TimeDelta kPeriodicReportingInterval;
AccountInvestigator(PrefService* pref_service,
signin::IdentityManager* identity_manager);
AccountInvestigator(const AccountInvestigator&) = delete;
AccountInvestigator& operator=(const AccountInvestigator&) = delete;
~AccountInvestigator() override;
static void RegisterPrefs(PrefRegistrySimple* registry);
// Sets up initial state and starts the timer to perform periodic reporting.
void Initialize();
// KeyedService:
void Shutdown() override;
// signin::IdentityManager::Observer:
void OnAccountsInCookieUpdated(
const signin::AccountsInCookieJarInfo& accounts_in_cookie_jar_info,
const GoogleServiceAuthError& error) override;
void OnExtendedAccountInfoUpdated(const AccountInfo& info) override;
private:
friend class AccountInvestigatorTest;
// Calculates the amount of time to wait/delay before the given |interval| has
// passed since |previous|, given |now|.
static base::TimeDelta CalculatePeriodicDelay(base::Time previous,
base::Time now,
base::TimeDelta interval);
// Calculate a hash of the listed accounts. Order of accounts should not
// affect the hashed values, but signed in and out status should.
static std::string HashAccounts(
const std::vector<gaia::ListedAccount>& signed_in_accounts,
const std::vector<gaia::ListedAccount>& signed_out_accounts);
// Compares the |info| object, which should correspond to the currently or
// potentially signed into Chrome account, to the various account(s) in the
// given cookie jar.
static signin_metrics::AccountRelation DiscernRelation(
const CoreAccountInfo& info,
const std::vector<gaia::ListedAccount>& signed_in_accounts,
const std::vector<gaia::ListedAccount>& signed_out_accounts);
// Tries to perform periodic reporting, potentially performing it now if the
// cookie information is cached, otherwise sets things up to perform this
// reporting asynchronously.
void TryPeriodicReport();
// Performs periodic reporting with the given cookie jar data and restarts
// the periodic reporting timer.
void DoPeriodicReport(
const std::vector<gaia::ListedAccount>& signed_in_accounts,
const std::vector<gaia::ListedAccount>& signed_out_accounts);
// Performs the reporting that's shared between the periodic case and the
// on change case.
void SharedCookieJarReport(
const std::vector<gaia::ListedAccount>& signed_in_accounts,
const std::vector<gaia::ListedAccount>& signed_out_accounts,
const base::Time now,
const signin_metrics::ReportingType type);
// Performs only the account relation reporting, which means comparing the
// signed in account to the cookie jar accounts(s).
void SignedInAccountRelationReport(
const std::vector<gaia::ListedAccount>& signed_in_accounts,
const std::vector<gaia::ListedAccount>& signed_out_accounts,
signin_metrics::ReportingType type);
PrefService* pref_service_;
signin::IdentityManager* identity_manager_;
// Handles invoking our periodic logic at the right time. As part of our
// handling of this call we reset the timer for the next loop.
base::OneShotTimer timer_;
// If the GaiaCookieManagerService hasn't already cached the cookie data, it
// will not be able to return enough information for us to always perform
// periodic reporting synchronously. This flag is flipped to true when we're
// waiting for this, and will allow us to perform periodic reporting when
// we're called as an observer on a potential cookie jar data change. The
// typical time this is occurs occurs during startup.
bool periodic_pending_ = false;
// Gets set upon initialization and on potential cookie jar change. This
// allows us ot emit AccountRelation metrics during a sign in that doesn't
// actually change the cookie jar.
bool previously_authenticated_ = false;
};
#endif // COMPONENTS_SIGNIN_CORE_BROWSER_ACCOUNT_INVESTIGATOR_H_
| 39.985507 | 80 | 0.750453 | [
"object",
"vector"
] |
4f6dad08801b88c490e62f18017642512748c12b | 1,546 | h | C | aws-cpp-sdk-wisdom/include/aws/wisdom/model/GetSessionResult.h | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-wisdom/include/aws/wisdom/model/GetSessionResult.h | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-wisdom/include/aws/wisdom/model/GetSessionResult.h | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/wisdom/ConnectWisdomService_EXPORTS.h>
#include <aws/wisdom/model/SessionData.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace ConnectWisdomService
{
namespace Model
{
class AWS_CONNECTWISDOMSERVICE_API GetSessionResult
{
public:
GetSessionResult();
GetSessionResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
GetSessionResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p>The session.</p>
*/
inline const SessionData& GetSession() const{ return m_session; }
/**
* <p>The session.</p>
*/
inline void SetSession(const SessionData& value) { m_session = value; }
/**
* <p>The session.</p>
*/
inline void SetSession(SessionData&& value) { m_session = std::move(value); }
/**
* <p>The session.</p>
*/
inline GetSessionResult& WithSession(const SessionData& value) { SetSession(value); return *this;}
/**
* <p>The session.</p>
*/
inline GetSessionResult& WithSession(SessionData&& value) { SetSession(std::move(value)); return *this;}
private:
SessionData m_session;
};
} // namespace Model
} // namespace ConnectWisdomService
} // namespace Aws
| 22.735294 | 108 | 0.680466 | [
"model"
] |
4f6fbad4f6e6b09c4b9622857f59c8560a5c6958 | 4,049 | h | C | server/deps/nodejs/include/crypto/crypto_rsa.h | ZackaryH8/altv-js-module | afc4be85967850016357dade2fdcad717c1ce882 | [
"MIT"
] | 57 | 2022-01-23T11:43:38.000Z | 2022-03-18T09:56:50.000Z | server/deps/nodejs/include/crypto/crypto_rsa.h | ZackaryH8/altv-js-module | afc4be85967850016357dade2fdcad717c1ce882 | [
"MIT"
] | null | null | null | server/deps/nodejs/include/crypto/crypto_rsa.h | ZackaryH8/altv-js-module | afc4be85967850016357dade2fdcad717c1ce882 | [
"MIT"
] | null | null | null | #ifndef SRC_CRYPTO_CRYPTO_RSA_H_
#define SRC_CRYPTO_CRYPTO_RSA_H_
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
#include "crypto/crypto_cipher.h"
#include "crypto/crypto_keygen.h"
#include "crypto/crypto_keys.h"
#include "crypto/crypto_util.h"
#include "allocated_buffer.h"
#include "env.h"
#include "memory_tracker.h"
#include "v8.h"
namespace node {
namespace crypto {
enum RSAKeyVariant {
kKeyVariantRSA_SSA_PKCS1_v1_5,
kKeyVariantRSA_PSS,
kKeyVariantRSA_OAEP
};
struct RsaKeyPairParams final : public MemoryRetainer {
RSAKeyVariant variant;
unsigned int modulus_bits;
unsigned int exponent;
// The following options are used for RSA-PSS. If any of them are set, a
// RSASSA-PSS-params sequence will be added to the key.
const EVP_MD* md = nullptr;
const EVP_MD* mgf1_md = nullptr;
int saltlen = -1;
SET_NO_MEMORY_INFO()
SET_MEMORY_INFO_NAME(RsaKeyPairParams)
SET_SELF_SIZE(RsaKeyPairParams)
};
using RsaKeyPairGenConfig = KeyPairGenConfig<RsaKeyPairParams>;
struct RsaKeyGenTraits final {
using AdditionalParameters = RsaKeyPairGenConfig;
static constexpr const char* JobName = "RsaKeyPairGenJob";
static EVPKeyCtxPointer Setup(RsaKeyPairGenConfig* params);
static v8::Maybe<bool> AdditionalConfig(
CryptoJobMode mode,
const v8::FunctionCallbackInfo<v8::Value>& args,
unsigned int* offset,
RsaKeyPairGenConfig* params);
};
using RSAKeyPairGenJob = KeyGenJob<KeyPairGenTraits<RsaKeyGenTraits>>;
struct RSAKeyExportConfig final : public MemoryRetainer {
RSAKeyVariant variant = kKeyVariantRSA_SSA_PKCS1_v1_5;
SET_NO_MEMORY_INFO()
SET_MEMORY_INFO_NAME(RSAKeyExportConfig)
SET_SELF_SIZE(RSAKeyExportConfig)
};
struct RSAKeyExportTraits final {
static constexpr const char* JobName = "RSAKeyExportJob";
using AdditionalParameters = RSAKeyExportConfig;
static v8::Maybe<bool> AdditionalConfig(
const v8::FunctionCallbackInfo<v8::Value>& args,
unsigned int offset,
RSAKeyExportConfig* config);
static WebCryptoKeyExportStatus DoExport(
std::shared_ptr<KeyObjectData> key_data,
WebCryptoKeyFormat format,
const RSAKeyExportConfig& params,
ByteSource* out);
};
using RSAKeyExportJob = KeyExportJob<RSAKeyExportTraits>;
struct RSACipherConfig final : public MemoryRetainer {
CryptoJobMode mode;
ByteSource label;
int padding = 0;
const EVP_MD* digest = nullptr;
RSACipherConfig() = default;
RSACipherConfig(RSACipherConfig&& other) noexcept;
void MemoryInfo(MemoryTracker* tracker) const override;
SET_MEMORY_INFO_NAME(RSACipherConfig)
SET_SELF_SIZE(RSACipherConfig)
};
struct RSACipherTraits final {
static constexpr const char* JobName = "RSACipherJob";
using AdditionalParameters = RSACipherConfig;
static v8::Maybe<bool> AdditionalConfig(
CryptoJobMode mode,
const v8::FunctionCallbackInfo<v8::Value>& args,
unsigned int offset,
WebCryptoCipherMode cipher_mode,
RSACipherConfig* config);
static WebCryptoCipherStatus DoCipher(
Environment* env,
std::shared_ptr<KeyObjectData> key_data,
WebCryptoCipherMode cipher_mode,
const RSACipherConfig& params,
const ByteSource& in,
ByteSource* out);
};
using RSACipherJob = CipherJob<RSACipherTraits>;
v8::Maybe<bool> ExportJWKRsaKey(
Environment* env,
std::shared_ptr<KeyObjectData> key,
v8::Local<v8::Object> target);
std::shared_ptr<KeyObjectData> ImportJWKRsaKey(
Environment* env,
v8::Local<v8::Object> jwk,
const v8::FunctionCallbackInfo<v8::Value>& args,
unsigned int offset);
v8::Maybe<bool> GetRsaKeyDetail(
Environment* env,
std::shared_ptr<KeyObjectData> key,
v8::Local<v8::Object> target);
namespace RSAAlg {
void Initialize(Environment* env, v8::Local<v8::Object> target);
void RegisterExternalReferences(ExternalReferenceRegistry* registry);
} // namespace RSAAlg
} // namespace crypto
} // namespace node
#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
#endif // SRC_CRYPTO_CRYPTO_RSA_H_
| 28.314685 | 74 | 0.758459 | [
"object"
] |
4f82069b5733640a2f10a34f74cc40c9f646083d | 505 | h | C | service_router/doc/RegistryServiceIf.h | algo-data-platform/PredictorService | a7da427617885546c5b5e07aa7740b3dee690337 | [
"Apache-2.0"
] | 2 | 2021-06-29T13:42:22.000Z | 2021-09-06T10:57:34.000Z | service_router/doc/RegistryServiceIf.h | algo-data-platform/PredictorService | a7da427617885546c5b5e07aa7740b3dee690337 | [
"Apache-2.0"
] | null | null | null | service_router/doc/RegistryServiceIf.h | algo-data-platform/PredictorService | a7da427617885546c5b5e07aa7740b3dee690337 | [
"Apache-2.0"
] | 5 | 2021-06-29T13:42:26.000Z | 2022-02-08T02:41:34.000Z |
struct Service {
std::string ip;
int port;
std::string name;
};
/*
* 服务注册接口
*
* 服务注册分为注册列表、可用列表,可用列表主要是用来做服务的完美启动、停机设计
*/
class RegistryServiceIf {
// 向注册中心注册
virtual void register(Service service) = 0;
// 从注册中心摘除服务
virtual void unregister(Service service) = 0;
// 变更服务状态为可用,客户端可调用的服务
virtual void available(Service service) = 0;
// 将服务变为不可用状态,但是心跳探测还会继续
virtual void unavailable(Service service) = 0;
// 返回所有注册的服务列表
virtual std::vector<Service> getRegisteredServices() = 0;
};
| 16.833333 | 58 | 0.710891 | [
"vector"
] |
4f857aa261ef4c4f6cce6d3f93c5208e1d5e987d | 1,302 | h | C | CPP_SourceCode/AgentPlus/AgentPlus.h | GonguanLu/Lagrangian-Relaxation-Algorithm-For-RRSLRP | d06a9e19c91c63c7041dabc0516871093d143f9e | [
"MIT"
] | 6 | 2015-12-31T11:26:36.000Z | 2021-06-15T08:49:46.000Z | CPP_SourceCode/AgentPlus/AgentPlus.h | Shi-Justin/Lagrangian-Relaxation-Algorithm-For-RRSLRP | d06a9e19c91c63c7041dabc0516871093d143f9e | [
"MIT"
] | null | null | null | CPP_SourceCode/AgentPlus/AgentPlus.h | Shi-Justin/Lagrangian-Relaxation-Algorithm-For-RRSLRP | d06a9e19c91c63c7041dabc0516871093d143f9e | [
"MIT"
] | 10 | 2016-05-06T15:02:29.000Z | 2022-03-05T09:40:20.000Z | #pragma once
#include "resource.h"
#include "stdafx.h"
#define _MAX_LABEL_COST 9999
extern void g_GenerateGAMSInputData();
void prepare_demand_link_path();
float g_Optimization_Lagrangian_Method_Resource_Constrained_Location_Routing_Problem();
template <typename T>
T ***Allocate3DDynamicArray(int nX, int nY, int nZ)
{
T ***dynamicArray;
dynamicArray = new (std::nothrow) T**[nX];
if (dynamicArray == NULL)
{
cout << "Error: insufficient memory.";
g_ProgramStop();
}
for (int x = 0; x < nX; x++)
{
if (x % 1000 ==0)
{
cout << "allocating 3D memory for " << x << endl;
}
dynamicArray[x] = new (std::nothrow) T*[nY];
if (dynamicArray[x] == NULL)
{
cout << "Error: insufficient memory.";
g_ProgramStop();
}
for (int y = 0; y < nY; y++)
{
dynamicArray[x][y] = new (std::nothrow) T[nZ];
if (dynamicArray[x][y] == NULL)
{
cout << "Error: insufficient memory.";
g_ProgramStop();
}
}
}
return dynamicArray;
}
template <typename T>
void Deallocate3DDynamicArray(T*** dArray, int nX, int nY)
{
if (!dArray)
return;
for (int x = 0; x < nX; x++)
{
for (int y = 0; y < nY; y++)
{
delete[] dArray[x][y];
}
delete[] dArray[x];
}
delete[] dArray;
} | 17.835616 | 88 | 0.583717 | [
"3d"
] |
4f87f21cb260f8756064e93fdda851a6a3b30a98 | 1,360 | h | C | sdl/6821OT_code_bundle/common-framework/Level.h | numfo/tryme | 596b48160cc1c2377bee05675570f62df4f37d9d | [
"MIT"
] | null | null | null | sdl/6821OT_code_bundle/common-framework/Level.h | numfo/tryme | 596b48160cc1c2377bee05675570f62df4f37d9d | [
"MIT"
] | null | null | null | sdl/6821OT_code_bundle/common-framework/Level.h | numfo/tryme | 596b48160cc1c2377bee05675570f62df4f37d9d | [
"MIT"
] | null | null | null | //
// Map.h
// SDL Game Programming Book
//
// Created by shaun mitchell on 09/03/2013.
// Copyright (c) 2013 shaun mitchell. All rights reserved.
//
#ifndef __SDL_Game_Programming_Book__Map__
#define __SDL_Game_Programming_Book__Map__
#include <iostream>
#include <vector>
#include "Layer.h"
#include "LevelParser.h"
#include "Player.h"
#include "CollisionManager.h"
class TileLayer;
struct Tileset
{
int firstGridID;
int tileWidth;
int tileHeight;
int spacing;
int margin;
int width;
int height;
int numColumns;
std::string name;
};
class Level
{
public:
~Level();
void update();
void render();
std::vector<Tileset>* getTilesets() { return &m_tilesets; }
std::vector<Layer*>* getLayers() { return &m_layers; }
std::vector<TileLayer*>* getCollisionLayers() { return &m_collisionLayers; }
const std::vector<TileLayer*>& getCollidableLayers() { return m_collisionLayers; }
Player* getPlayer() { return m_pPlayer; }
void setPlayer(Player* pPlayer) { m_pPlayer = pPlayer; }
private:
friend class LevelParser;
Level();
Player* m_pPlayer;
std::vector<Layer*> m_layers;
std::vector<Tileset> m_tilesets;
std::vector<TileLayer*> m_collisionLayers;
};
#endif /* defined(__SDL_Game_Programming_Book__Map__) */
| 20.606061 | 86 | 0.663971 | [
"render",
"vector"
] |
4f8954df72d5399b24e9e7f137f5f83b2721dad0 | 5,774 | h | C | third/include/atlas/serialization/function.h | galaxyeye/pioneer | cfc3aa3c4917b19000753ea3144bded79380d289 | [
"Apache-2.0"
] | 4 | 2017-05-12T07:37:17.000Z | 2019-11-14T10:52:28.000Z | third/include/atlas/serialization/function.h | galaxyeye/pioneer | cfc3aa3c4917b19000753ea3144bded79380d289 | [
"Apache-2.0"
] | null | null | null | third/include/atlas/serialization/function.h | galaxyeye/pioneer | cfc3aa3c4917b19000753ea3144bded79380d289 | [
"Apache-2.0"
] | 7 | 2017-06-21T03:35:51.000Z | 2020-10-14T04:58:26.000Z | /*
* function.h
*
* Created on: Jan 29, 2013
* Author: vincent ivincent.zhang@gmail.com
*/
#ifndef ATLAS_FUNCTION_H_
#define ATLAS_FUNCTION_H_
#include <cstddef> // std::nullptr
#include <memory>
#include <tuple>
#include <functional> // std::function
#include <utility> // std::move
#include <type_traits> // std::decay, and others
#include <atlas/serialization/tuple.h>
#include <atlas/apply_tuple.h>
namespace atlas {
namespace serialization {
namespace { struct useless { }; }
template<typename Signature> class function;
template<typename Res, typename ... Args>
class function<Res(Args...)> {
public:
typedef Res result_type;
function() = default;
function(std::nullptr_t) {}
function(const function& other) : _args(other._args), _f(other._f) { }
function(function&& other) : _args(std::move(other._args)), _f(std::move(other._f)) {}
template<typename Archive, typename Functor>
function(Functor f, Args... args, Archive& ar,
typename std::enable_if<!std::is_integral<Functor>::value, useless>::type = useless())
: _args(args...), _f(f)
{
ar & _args;
}
/*
* The last parameter can be replaced by a local variable
* */
template<typename Functor, typename IArchiver>
function(Functor f, IArchiver& ia,
typename std::enable_if<!std::is_integral<Functor>::value, useless>::type = useless()) :
_f(f)
{
ia >> _args;
}
/**
* @brief %function assignment operator.
* @param other A %function with identical call signature.
* @post @c (bool)*this == (bool)x
* @returns @c *this
*
* The target of @a other is copied to @c *this. If @a other has no
* target, then @c *this will be empty.
*
* If @a other targets a function pointer or a reference to a function
* object, then this operation will not throw an %exception.
*/
function& operator=(const function& other) {
function(other).swap(*this);
return *this;
}
/**
* @brief %function move-assignment operator.
* @param other A %function rvalue with identical call signature.
* @returns @c *this
*
* The target of @a other is moved to @c *this. If @a other has no
* target, then @c *this will be empty.
*
* If @a other targets a function pointer or a reference to a function
* object, then this operation will not throw an %exception.
*/
function& operator=(function&& other) {
function(std::move(other)).swap(*this);
return *this;
}
/**
* @brief %function assignment to zero.
* @returns @c *this
*/
function& operator=(std::nullptr_t) {
function().swap(*this);
return *this;
}
/**
* @brief %function assignment to a new target.
* @param f A %function object that is callable with parameters of
* type @c T1, @c T2, ..., @c TN and returns a value convertible
* to @c Res.
* @return @c *this
*
* This %function object wrapper will target a copy of @a
* f. If @a f is @c std::reference_wrapper<F>, then this function
* object will contain a reference to the function object @c
* f.get(). If @a f is a NULL function pointer or NULL
* pointer-to-member, @c this object will be empty.
*
* If @a f is a non-NULL function pointer or an object of type @c
* std::reference_wrapper<F>, this function will not throw.
*/
template<typename Functor>
typename std::enable_if<!std::is_integral<Functor>::value, function&>::type
operator=(Functor&& f) {
function(std::forward<Functor>(f)).swap(*this);
return *this;
}
template<typename Functor>
typename std::enable_if<!std::is_integral<Functor>::value, function&>::type
operator=(std::reference_wrapper<Functor> f) {
function(f).swap(*this);
return *this;
}
/**
* @brief Swap the targets of two %function objects.
* @param other A %function with identical call signature.
*
* Swap the targets of @c this function object and @a f. This
* function will not throw an %exception.
*/
void swap(function& other) {
std::swap(_args, other._args);
std::swap(_f, other._f);
}
/**
* @brief Determine if the %function wrapper has a target.
*
* @return @c true when this %function object contains a target,
* or @c false when it is empty.
*
* This function will not throw an %exception.
*/
explicit operator bool() const
{ return _f.operator bool();}
// [3.7.2.4] function invocation
/**
* @brief Invokes the function targeted by @c *this.
* @returns the result of the target.
* @throws bad_function_call when @c !(bool)*this
*
* The function call operator invokes the target function object
* stored by @c this.
*/
Res operator()() const { return apply_tuple(_f, _args); }
public:
std::tuple<typename std::decay<Args>::type...> _args;
std::function<Res(Args...)> _f;
};
}
} // atlas
// i hope so
//namespace boost {
// namespace serialization {
//
// template <typename Archive, typename Res, typename... Args>
// void serialize(Archive& ar, std::function<Res(Args...)>& fun, const unsigned int /* version */) {
// ar & boost::serialization::make_nvp("function", fun);
// }
//
// } // serialization
//} // boost
#endif /* ATLAS_FUNCTION_H_ */
| 30.230366 | 103 | 0.587807 | [
"object"
] |
4f92cda32923660aa641af53b0d8ae35bbcf0119 | 1,159 | h | C | include/website.h | khernyo/lgogdownloader | 0a7648d80b014c00072012f0104dc71786e0225e | [
"WTFPL"
] | null | null | null | include/website.h | khernyo/lgogdownloader | 0a7648d80b014c00072012f0104dc71786e0225e | [
"WTFPL"
] | null | null | null | include/website.h | khernyo/lgogdownloader | 0a7648d80b014c00072012f0104dc71786e0225e | [
"WTFPL"
] | null | null | null | /* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2, as published by Sam Hocevar. See
* http://www.wtfpl.net/ for more details. */
#ifndef WEBSITE_H
#define WEBSITE_H
#include "config.h"
#include "util.h"
#include "globals.h"
#include <curl/curl.h>
#include <json/json.h>
#include <fstream>
class Website
{
public:
Website();
int Login(const std::string& email, const std::string& password);
std::string getResponse(const std::string& url);
Json::Value getGameDetailsJSON(const std::string& gameid);
std::vector<gameItem> getGames();
std::vector<wishlistItem> getWishlistItems();
bool IsLoggedIn();
virtual ~Website();
protected:
private:
static size_t writeMemoryCallback(char *ptr, size_t size, size_t nmemb, void *userp);
CURL* curlhandle;
bool IsloggedInSimple();
bool IsLoggedInComplex(const std::string& email);
int retries;
};
#endif // WEBSITE_H
| 30.5 | 93 | 0.673857 | [
"vector"
] |
4f978f9549676860916eb284187b31cb84695fb6 | 2,193 | h | C | src/input/FileReader.h | karelhala-cz/BitstampTax | 361b94a8acf233082badc21da256b4089aad2188 | [
"MIT"
] | null | null | null | src/input/FileReader.h | karelhala-cz/BitstampTax | 361b94a8acf233082badc21da256b4089aad2188 | [
"MIT"
] | null | null | null | src/input/FileReader.h | karelhala-cz/BitstampTax | 361b94a8acf233082badc21da256b4089aad2188 | [
"MIT"
] | null | null | null | //*********************************************************************************************************************
// Author: Karel Hala, hala.karel@gmail.com
// Copyright: (c) 2021-2022 Karel Hala
// License: MIT
//*********************************************************************************************************************
#pragma once
#include "utils/HashName.h"
#include "trade_book/TradeItem.h"
#include <string>
#include <map>
#include <vector>
#include <memory>
class C_FileReader
{
enum class E_Item
{
Type,
Datetime,
Account,
Amount,
Value,
Rate,
Fee,
SubType,
LastToGetCount
};
static char const * const ITEM_NAMES[];
typedef std::vector<std::string> T_FileLines;
typedef std::map<C_HashName, E_Item> T_ItemNames;
typedef std::vector<E_Item> T_Header;
typedef std::vector<T_TradeItemUniquePtr> T_TradeItems;
public:
C_FileReader(std::string const & filename);
bool Read();
std::string const & GetErrorMsg() const { return m_ErrorMsg; }
template<typename Fn>
void EnumerateLines(Fn & fn) const;
T_TradeItems && MoveTradeItems() { return std::move(m_TradeItems); }
private:
void ReadFileLines(std::ifstream & stream);
bool ReadHeaderLine();
bool ReadDataLine(size_t const lineIndex);
T_TradeItemUniquePtr ReadTradeItemDeposit(size_t const inputFileLine, std::stringstream & stream);
T_TradeItemUniquePtr ReadTradeItemWithdrawal(size_t const inputFileLine, std::stringstream & stream);
T_TradeItemUniquePtr ReadTradeItemMarket(size_t const inputFileLine, std::stringstream & stream);
bool ReadTime(std::stringstream & stream, std::tm & time);
bool ReadTimeMonth(std::string const & text, int & month);
T_CurrencyValueConstPtr ReadCurrencyValue(std::stringstream & stream);
bool ReadTradeType(std::stringstream & stream, E_TradeType & type);
bool ReadEmptyString(std::stringstream & stream);
private:
std::string m_FileName;
T_FileLines m_FileLines;
std::string m_ErrorMsg;
T_ItemNames m_ItemNames;
T_Header m_Header;
T_TradeItems m_TradeItems;
};
template<typename Fn>
void C_FileReader::EnumerateLines(Fn & fn) const
{
for (std::string const & line : m_FileLines)
{
fn(line);
}
}
| 26.107143 | 119 | 0.663475 | [
"vector"
] |
4f990055fcbd9b0b16299b35941570d8567d4055 | 1,892 | h | C | components/offline_pages/core/prefetch/generate_page_bundle_task.h | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/offline_pages/core/prefetch/generate_page_bundle_task.h | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/offline_pages/core/prefetch/generate_page_bundle_task.h | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_OFFLINE_PAGES_CORE_PREFETCH_GENERATE_PAGE_BUNDLE_TASK_H_
#define COMPONENTS_OFFLINE_PAGES_CORE_PREFETCH_GENERATE_PAGE_BUNDLE_TASK_H_
#include <string>
#include <vector>
#include "base/memory/weak_ptr.h"
#include "components/gcm_driver/instance_id/instance_id.h"
#include "components/offline_pages/core/prefetch/prefetch_types.h"
#include "components/offline_pages/core/task.h"
namespace offline_pages {
class PrefetchGCMHandler;
class PrefetchNetworkRequestFactory;
// Task that attempts to start archiving the URLs the prefetch service has
// determined are viable to prefetch.
class GeneratePageBundleTask : public Task {
public:
// TODO(dewittj): remove the list of prefetch URLs when the DB operation can
// supply the current set of URLs.
GeneratePageBundleTask(const std::vector<PrefetchURL>& prefetch_urls,
PrefetchGCMHandler* gcm_handler,
PrefetchNetworkRequestFactory* request_factory,
const PrefetchRequestFinishedCallback& callback);
~GeneratePageBundleTask() override;
// Task implementation.
void Run() override;
private:
void StartGeneratePageBundle(int updated_entry_count);
void GotRegistrationId(const std::string& id,
instance_id::InstanceID::Result result);
std::vector<PrefetchURL> prefetch_urls_;
PrefetchGCMHandler* gcm_handler_;
PrefetchNetworkRequestFactory* request_factory_;
PrefetchRequestFinishedCallback callback_;
base::WeakPtrFactory<GeneratePageBundleTask> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(GeneratePageBundleTask);
};
} // namespace offline_pages
#endif // COMPONENTS_OFFLINE_PAGES_CORE_PREFETCH_GENERATE_PAGE_BUNDLE_TASK_H_
| 35.698113 | 78 | 0.778013 | [
"vector"
] |
4facaac3ea8a41ba87958c8bad7d5e453e027613 | 3,948 | h | C | src/mfx/pi/pidet/PitchDetect.h | D-J-Roberts/pedalevite | 157611b5ccf2bb97f0007d7d17b4c07bd6a21fba | [
"WTFPL"
] | 69 | 2017-01-17T13:17:31.000Z | 2022-03-01T14:56:32.000Z | src/mfx/pi/pidet/PitchDetect.h | D-J-Roberts/pedalevite | 157611b5ccf2bb97f0007d7d17b4c07bd6a21fba | [
"WTFPL"
] | 1 | 2020-11-03T14:52:45.000Z | 2020-12-01T20:31:15.000Z | src/mfx/pi/pidet/PitchDetect.h | D-J-Roberts/pedalevite | 157611b5ccf2bb97f0007d7d17b4c07bd6a21fba | [
"WTFPL"
] | 8 | 2017-02-08T13:30:42.000Z | 2021-12-09T08:43:09.000Z | /*****************************************************************************
PitchDetect.h
Author: Laurent de Soras, 2018
--- Legal stuff ---
This program is free software. It comes without any warranty, to
the extent permitted by applicable law. You can redistribute it
and/or modify it under the terms of the Do What The Fuck You Want
To Public License, Version 2, as published by Sam Hocevar. See
http://sam.zoy.org/wtfpl/COPYING for more details.
*Tab=3***********************************************************************/
#pragma once
#if ! defined (mfx_pi_pidet_PitchDetect_HEADER_INCLUDED)
#define mfx_pi_pidet_PitchDetect_HEADER_INCLUDED
#if defined (_MSC_VER)
#pragma warning (4 : 4250)
#endif
/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
#include "fstb/util/NotificationFlag.h"
#include "fstb/AllocAlign.h"
#include "mfx/dsp/ana/FreqPeak.h"
#include "mfx/pi/pidet/PitchDetectDesc.h"
#include "mfx/pi/ParamProcSimple.h"
#include "mfx/pi/ParamStateSet.h"
#include "mfx/piapi/PluginInterface.h"
#include <array>
#include <vector>
namespace mfx
{
namespace pi
{
namespace pidet
{
class PitchDetect final
: public piapi::PluginInterface
{
/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
public:
explicit PitchDetect (piapi::HostInterface &host);
/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
protected:
// mfx::piapi::PluginInterface
State do_get_state () const final;
double do_get_param_val (piapi::ParamCateg categ, int index, int note_id) const final;
int do_reset (double sample_freq, int max_buf_len, int &latency) final;
void do_process_block (piapi::ProcInfo &proc) final;
/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
private:
enum OutType
{
OutType_PITCH = 0,
OutType_FREQ,
OutType_NBR_ELT
};
static const int _sub_spl_max = 16;
typedef std::vector <float, fstb::AllocAlign <float, 16> > BufAlign;
typedef std::array <float, _sub_spl_max> BufPrevSpl;
void clear_buffers ();
void update_param (bool force_flag = false);
piapi::HostInterface &
_host;
State _state;
PitchDetectDesc
_desc;
ParamStateSet _state_set;
ParamProcSimple
_param_proc;
float _sample_freq; // Hz, > 0. <= 0: not initialized
float _inv_fs; // 1 / _sample_freq
fstb::util::NotificationFlag
_param_change_flag;
BufPrevSpl _buf_prev_spl; // Buffer containing the last samples of the previous frame that were not downsampled
int _nbr_spl_in_buf; // Number of samples contained in the buffer
int _sub_spl; // Downsampling ratio. Currently 1 (none), 8 or 16 only
dsp::ana::FreqPeak
_analyser;
float _freq; // Hz. 0 = not found
float _last_valid_output;
OutType _output_type;
BufAlign _buffer;
/*\\\ FORBIDDEN MEMBER FUNCTIONS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
private:
PitchDetect () = delete;
PitchDetect (const PitchDetect &other) = delete;
PitchDetect (PitchDetect &&other) = delete;
PitchDetect & operator = (const PitchDetect &other) = delete;
PitchDetect & operator = (PitchDetect &&other) = delete;
bool operator == (const PitchDetect &other) const = delete;
bool operator != (const PitchDetect &other) const = delete;
}; // class PitchDetect
} // namespace pidet
} // namespace pi
} // namespace mfx
//#include "mfx/pi/pidet/PitchDetect.hpp"
#endif // mfx_pi_pidet_PitchDetect_HEADER_INCLUDED
/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
| 25.636364 | 122 | 0.56079 | [
"vector"
] |
4fadbd1729e6a03ac7252e7489ae26394770ecbc | 5,517 | h | C | OpenSim 3.2-64bit-VS12/sdk/include/SimTK/include/SimTKcommon/internal/ThreadLocal.h | chrisdembia/opensim-metabolicsprobes | 7be20df24c2a3f1f3fb4a56e244ba4a3295b4fc0 | [
"Apache-2.0"
] | 2 | 2020-01-15T05:03:30.000Z | 2021-01-16T06:18:47.000Z | OpenSim 3.2-64bit-VS12/sdk/include/SimTK/include/SimTKcommon/internal/ThreadLocal.h | chrisdembia/opensim-metabolicsprobes | 7be20df24c2a3f1f3fb4a56e244ba4a3295b4fc0 | [
"Apache-2.0"
] | 1 | 2021-01-11T13:45:54.000Z | 2021-01-11T13:45:54.000Z | OpenSim 3.2-64bit-VS12/sdk/include/SimTK/include/SimTKcommon/internal/ThreadLocal.h | chrisdembia/opensim-metabolicsprobes | 7be20df24c2a3f1f3fb4a56e244ba4a3295b4fc0 | [
"Apache-2.0"
] | 3 | 2019-05-17T02:17:10.000Z | 2020-11-05T20:31:55.000Z | #ifndef SimTK_SimTKCOMMON_THREAD_LOCAL_H_
#define SimTK_SimTKCOMMON_THREAD_LOCAL_H_
/* -------------------------------------------------------------------------- *
* Simbody(tm): SimTKcommon *
* -------------------------------------------------------------------------- *
* This is part of the SimTK biosimulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody. *
* *
* Portions copyright (c) 2008-12 Stanford University and the Authors. *
* Authors: Peter Eastman *
* Contributors: *
* *
* 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 <pthread.h>
#include <map>
#include <set>
namespace SimTK {
static std::map<void*, pthread_key_t> instanceMap;
static std::map<pthread_key_t, std::set<void*> > keyInstances;
static pthread_mutex_t keyLock = PTHREAD_MUTEX_INITIALIZER;
template <class T>
static void cleanUpThreadLocalStorage(void* value) {
// Delete the value.
T* t = reinterpret_cast<T*>(value);
delete t;
// Remove it from the set of values needing to be deleted.
pthread_mutex_lock(&keyLock);
pthread_key_t key = instanceMap[value];
instanceMap.erase(value);
if (keyInstances.find(key) != keyInstances.end())
keyInstances.find(key)->second.erase(value);
pthread_mutex_unlock(&keyLock);
}
/**
* This class represents a "thread local" variable: one which has a different value on each thread.
* This is useful in many situations when writing multithreaded code. For example, it can be used
* as temporary workspace for calculations. If a single workspace object were created, all access
* to it would need to be synchronized to prevent threads from overwriting each other's values.
* Using a ThreadLocal instead means that a separate workspace object will automatically be created
* for each thread.
*
* To use it, simply create a ThreadLocal, then call get() or upd() to get a readable or writable
* reference to the value for the current thread:
*
* <pre>
* ThreadLocal<int> x;
* ...
* x.upd() = 5;
* assert(x.get() == 5);
* </pre>
*/
template <class T>
class ThreadLocal {
public:
/**
* Create a new ThreadLocal variable.
*/
ThreadLocal() {
this->initialize();
}
/**
* Create a new ThreadLocal variable.
*
* @param defaultValue the initial value which the variable will have on each thread
*/
ThreadLocal(const T& defaultValue) : defaultValue(defaultValue) {
this->initialize();
}
~ThreadLocal() {
// Delete the key.
pthread_key_delete(key);
// Once the key is deleted, cleanUpThreadLocalStorage() will no longer be called, so delete
// all instances now.
pthread_mutex_lock(&keyLock);
std::set<void*>& instances = keyInstances[key];
for (std::set<void*>::const_iterator iter = instances.begin(); iter != instances.end(); ++iter) {
instanceMap.erase(*iter);
delete (T*) *iter;
}
keyInstances.erase(key);
pthread_mutex_unlock(&keyLock);
}
/**
* Get a reference to the value for the current thread.
*/
T& upd() {
T* value = reinterpret_cast<T*>(pthread_getspecific(key));
if (value == NULL)
return createValue();
return *value;
}
/**
* Get a const reference to the value for the current thread.
*/
const T& get() const {
T* value = reinterpret_cast<T*>(pthread_getspecific(key));
if (value == NULL)
return createValue();
return *value;
}
private:
void initialize() {
pthread_key_create(&key, cleanUpThreadLocalStorage<T>);
pthread_mutex_lock(&keyLock);
keyInstances[key] = std::set<void*>();
pthread_mutex_unlock(&keyLock);
}
T& createValue() const {
T* value = new T(defaultValue);
pthread_setspecific(key, value);
pthread_mutex_lock(&keyLock);
instanceMap[value] = key;
keyInstances[key].insert(value);
pthread_mutex_unlock(&keyLock);
return *value;
}
pthread_key_t key;
T defaultValue;
};
} // namespace SimTK
#endif // SimTK_SimTKCOMMON_THREAD_LOCAL_H_
| 36.536424 | 105 | 0.570781 | [
"object"
] |
4fb71e8091e4f4a4dafc017b67a65db7a36b2322 | 35,138 | c | C | slprj/_sfprj/Expriment_FacialExpr/_self/sfun/src/c50_Expriment_FacialExpr.c | maryamsab/realact | 90fbf3fcb4696353c8a14d76797e5908126a9525 | [
"BSD-3-Clause"
] | 1 | 2020-12-02T21:41:36.000Z | 2020-12-02T21:41:36.000Z | slprj/_sfprj/Expriment_FacialExpr/_self/sfun/src/c50_Expriment_FacialExpr.c | maryamsab/realact | 90fbf3fcb4696353c8a14d76797e5908126a9525 | [
"BSD-3-Clause"
] | null | null | null | slprj/_sfprj/Expriment_FacialExpr/_self/sfun/src/c50_Expriment_FacialExpr.c | maryamsab/realact | 90fbf3fcb4696353c8a14d76797e5908126a9525 | [
"BSD-3-Clause"
] | 1 | 2018-06-23T11:59:06.000Z | 2018-06-23T11:59:06.000Z | /* Include files */
#include <stddef.h>
#include "blas.h"
#include "Expriment_FacialExpr_sfun.h"
#include "c50_Expriment_FacialExpr.h"
#define CHARTINSTANCE_CHARTNUMBER (chartInstance->chartNumber)
#define CHARTINSTANCE_INSTANCENUMBER (chartInstance->instanceNumber)
#include "Expriment_FacialExpr_sfun_debug_macros.h"
#define _SF_MEX_LISTEN_FOR_CTRL_C(S) sf_mex_listen_for_ctrl_c(sfGlobalDebugInstanceStruct,S);
/* Type Definitions */
/* Named Constants */
#define CALL_EVENT (-1)
/* Variable Declarations */
/* Variable Definitions */
static real_T _sfTime_;
static const char * c50_debug_family_names[6] = { "aVarTruthTableCondition_1",
"aVarTruthTableCondition_2", "nargin", "nargout", "a1", "a2" };
/* Function Declarations */
static void initialize_c50_Expriment_FacialExpr
(SFc50_Expriment_FacialExprInstanceStruct *chartInstance);
static void initialize_params_c50_Expriment_FacialExpr
(SFc50_Expriment_FacialExprInstanceStruct *chartInstance);
static void enable_c50_Expriment_FacialExpr
(SFc50_Expriment_FacialExprInstanceStruct *chartInstance);
static void disable_c50_Expriment_FacialExpr
(SFc50_Expriment_FacialExprInstanceStruct *chartInstance);
static void c50_update_debugger_state_c50_Expriment_FacialExpr
(SFc50_Expriment_FacialExprInstanceStruct *chartInstance);
static const mxArray *get_sim_state_c50_Expriment_FacialExpr
(SFc50_Expriment_FacialExprInstanceStruct *chartInstance);
static void set_sim_state_c50_Expriment_FacialExpr
(SFc50_Expriment_FacialExprInstanceStruct *chartInstance, const mxArray
*c50_st);
static void finalize_c50_Expriment_FacialExpr
(SFc50_Expriment_FacialExprInstanceStruct *chartInstance);
static void sf_gateway_c50_Expriment_FacialExpr
(SFc50_Expriment_FacialExprInstanceStruct *chartInstance);
static void initSimStructsc50_Expriment_FacialExpr
(SFc50_Expriment_FacialExprInstanceStruct *chartInstance);
static void init_script_number_translation(uint32_T c50_machineNumber, uint32_T
c50_chartNumber, uint32_T c50_instanceNumber);
static const mxArray *c50_sf_marshallOut(void *chartInstanceVoid, void
*c50_inData);
static real_T c50_emlrt_marshallIn(SFc50_Expriment_FacialExprInstanceStruct
*chartInstance, const mxArray *c50_a2, const char_T *c50_identifier);
static real_T c50_b_emlrt_marshallIn(SFc50_Expriment_FacialExprInstanceStruct
*chartInstance, const mxArray *c50_u, const emlrtMsgIdentifier *c50_parentId);
static void c50_sf_marshallIn(void *chartInstanceVoid, const mxArray
*c50_mxArrayInData, const char_T *c50_varName, void *c50_outData);
static const mxArray *c50_b_sf_marshallOut(void *chartInstanceVoid, void
*c50_inData);
static boolean_T c50_c_emlrt_marshallIn(SFc50_Expriment_FacialExprInstanceStruct
*chartInstance, const mxArray *c50_u, const emlrtMsgIdentifier *c50_parentId);
static void c50_b_sf_marshallIn(void *chartInstanceVoid, const mxArray
*c50_mxArrayInData, const char_T *c50_varName, void *c50_outData);
static const mxArray *c50_c_sf_marshallOut(void *chartInstanceVoid, void
*c50_inData);
static int32_T c50_d_emlrt_marshallIn(SFc50_Expriment_FacialExprInstanceStruct
*chartInstance, const mxArray *c50_u, const emlrtMsgIdentifier *c50_parentId);
static void c50_c_sf_marshallIn(void *chartInstanceVoid, const mxArray
*c50_mxArrayInData, const char_T *c50_varName, void *c50_outData);
static uint8_T c50_e_emlrt_marshallIn(SFc50_Expriment_FacialExprInstanceStruct
*chartInstance, const mxArray *c50_b_is_active_c50_Expriment_FacialExpr, const
char_T *c50_identifier);
static uint8_T c50_f_emlrt_marshallIn(SFc50_Expriment_FacialExprInstanceStruct
*chartInstance, const mxArray *c50_u, const emlrtMsgIdentifier *c50_parentId);
static void init_dsm_address_info(SFc50_Expriment_FacialExprInstanceStruct
*chartInstance);
/* Function Definitions */
static void initialize_c50_Expriment_FacialExpr
(SFc50_Expriment_FacialExprInstanceStruct *chartInstance)
{
chartInstance->c50_sfEvent = CALL_EVENT;
_sfTime_ = sf_get_time(chartInstance->S);
chartInstance->c50_is_active_c50_Expriment_FacialExpr = 0U;
}
static void initialize_params_c50_Expriment_FacialExpr
(SFc50_Expriment_FacialExprInstanceStruct *chartInstance)
{
(void)chartInstance;
}
static void enable_c50_Expriment_FacialExpr
(SFc50_Expriment_FacialExprInstanceStruct *chartInstance)
{
_sfTime_ = sf_get_time(chartInstance->S);
}
static void disable_c50_Expriment_FacialExpr
(SFc50_Expriment_FacialExprInstanceStruct *chartInstance)
{
_sfTime_ = sf_get_time(chartInstance->S);
}
static void c50_update_debugger_state_c50_Expriment_FacialExpr
(SFc50_Expriment_FacialExprInstanceStruct *chartInstance)
{
(void)chartInstance;
}
static const mxArray *get_sim_state_c50_Expriment_FacialExpr
(SFc50_Expriment_FacialExprInstanceStruct *chartInstance)
{
const mxArray *c50_st;
const mxArray *c50_y = NULL;
real_T c50_hoistedGlobal;
real_T c50_u;
const mxArray *c50_b_y = NULL;
uint8_T c50_b_hoistedGlobal;
uint8_T c50_b_u;
const mxArray *c50_c_y = NULL;
real_T *c50_a2;
c50_a2 = (real_T *)ssGetOutputPortSignal(chartInstance->S, 1);
c50_st = NULL;
c50_st = NULL;
c50_y = NULL;
sf_mex_assign(&c50_y, sf_mex_createcellmatrix(2, 1), false);
c50_hoistedGlobal = *c50_a2;
c50_u = c50_hoistedGlobal;
c50_b_y = NULL;
sf_mex_assign(&c50_b_y, sf_mex_create("y", &c50_u, 0, 0U, 0U, 0U, 0), false);
sf_mex_setcell(c50_y, 0, c50_b_y);
c50_b_hoistedGlobal = chartInstance->c50_is_active_c50_Expriment_FacialExpr;
c50_b_u = c50_b_hoistedGlobal;
c50_c_y = NULL;
sf_mex_assign(&c50_c_y, sf_mex_create("y", &c50_b_u, 3, 0U, 0U, 0U, 0), false);
sf_mex_setcell(c50_y, 1, c50_c_y);
sf_mex_assign(&c50_st, c50_y, false);
return c50_st;
}
static void set_sim_state_c50_Expriment_FacialExpr
(SFc50_Expriment_FacialExprInstanceStruct *chartInstance, const mxArray
*c50_st)
{
const mxArray *c50_u;
real_T *c50_a2;
c50_a2 = (real_T *)ssGetOutputPortSignal(chartInstance->S, 1);
chartInstance->c50_doneDoubleBufferReInit = true;
c50_u = sf_mex_dup(c50_st);
*c50_a2 = c50_emlrt_marshallIn(chartInstance, sf_mex_dup(sf_mex_getcell(c50_u,
0)), "a2");
chartInstance->c50_is_active_c50_Expriment_FacialExpr = c50_e_emlrt_marshallIn
(chartInstance, sf_mex_dup(sf_mex_getcell(c50_u, 1)),
"is_active_c50_Expriment_FacialExpr");
sf_mex_destroy(&c50_u);
c50_update_debugger_state_c50_Expriment_FacialExpr(chartInstance);
sf_mex_destroy(&c50_st);
}
static void finalize_c50_Expriment_FacialExpr
(SFc50_Expriment_FacialExprInstanceStruct *chartInstance)
{
(void)chartInstance;
}
static void sf_gateway_c50_Expriment_FacialExpr
(SFc50_Expriment_FacialExprInstanceStruct *chartInstance)
{
real_T c50_hoistedGlobal;
real_T c50_a1;
uint32_T c50_debug_family_var_map[6];
boolean_T c50_aVarTruthTableCondition_1;
boolean_T c50_aVarTruthTableCondition_2;
real_T c50_nargin = 1.0;
real_T c50_nargout = 1.0;
real_T c50_a2;
real_T *c50_b_a2;
real_T *c50_b_a1;
c50_b_a1 = (real_T *)ssGetInputPortSignal(chartInstance->S, 0);
c50_b_a2 = (real_T *)ssGetOutputPortSignal(chartInstance->S, 1);
_SFD_SYMBOL_SCOPE_PUSH(0U, 0U);
_sfTime_ = sf_get_time(chartInstance->S);
_SFD_CC_CALL(CHART_ENTER_SFUNCTION_TAG, 26U, chartInstance->c50_sfEvent);
chartInstance->c50_sfEvent = CALL_EVENT;
_SFD_CC_CALL(CHART_ENTER_DURING_FUNCTION_TAG, 26U, chartInstance->c50_sfEvent);
c50_hoistedGlobal = *c50_b_a1;
c50_a1 = c50_hoistedGlobal;
_SFD_SYMBOL_SCOPE_PUSH_EML(0U, 6U, 6U, c50_debug_family_names,
c50_debug_family_var_map);
_SFD_SYMBOL_SCOPE_ADD_EML_IMPORTABLE(&c50_aVarTruthTableCondition_1, 0U,
c50_b_sf_marshallOut, c50_b_sf_marshallIn);
_SFD_SYMBOL_SCOPE_ADD_EML_IMPORTABLE(&c50_aVarTruthTableCondition_2, 1U,
c50_b_sf_marshallOut, c50_b_sf_marshallIn);
_SFD_SYMBOL_SCOPE_ADD_EML_IMPORTABLE(&c50_nargin, 2U, c50_sf_marshallOut,
c50_sf_marshallIn);
_SFD_SYMBOL_SCOPE_ADD_EML_IMPORTABLE(&c50_nargout, 3U, c50_sf_marshallOut,
c50_sf_marshallIn);
_SFD_SYMBOL_SCOPE_ADD_EML(&c50_a1, 4U, c50_sf_marshallOut);
_SFD_SYMBOL_SCOPE_ADD_EML_IMPORTABLE(&c50_a2, 5U, c50_sf_marshallOut,
c50_sf_marshallIn);
CV_EML_FCN(0, 0);
_SFD_EML_CALL(0U, chartInstance->c50_sfEvent, 3);
c50_aVarTruthTableCondition_1 = false;
_SFD_EML_CALL(0U, chartInstance->c50_sfEvent, 4);
c50_aVarTruthTableCondition_2 = false;
_SFD_EML_CALL(0U, chartInstance->c50_sfEvent, 8);
c50_aVarTruthTableCondition_1 = (c50_a1 > 25.0);
_SFD_EML_CALL(0U, chartInstance->c50_sfEvent, 11);
c50_aVarTruthTableCondition_2 = (c50_a1 < -25.0);
_SFD_EML_CALL(0U, chartInstance->c50_sfEvent, 13);
if (CV_EML_IF(0, 1, 0, c50_aVarTruthTableCondition_1)) {
_SFD_EML_CALL(0U, chartInstance->c50_sfEvent, 14);
CV_EML_FCN(0, 1);
_SFD_EML_CALL(0U, chartInstance->c50_sfEvent, 24);
c50_a2 = c50_a1;
_SFD_EML_CALL(0U, chartInstance->c50_sfEvent, -24);
} else {
_SFD_EML_CALL(0U, chartInstance->c50_sfEvent, 15);
if (CV_EML_IF(0, 1, 1, c50_aVarTruthTableCondition_2)) {
_SFD_EML_CALL(0U, chartInstance->c50_sfEvent, 16);
CV_EML_FCN(0, 2);
_SFD_EML_CALL(0U, chartInstance->c50_sfEvent, 29);
c50_a2 = c50_a1;
_SFD_EML_CALL(0U, chartInstance->c50_sfEvent, -29);
} else {
_SFD_EML_CALL(0U, chartInstance->c50_sfEvent, 18);
CV_EML_FCN(0, 3);
_SFD_EML_CALL(0U, chartInstance->c50_sfEvent, 34);
c50_a2 = 0.0;
_SFD_EML_CALL(0U, chartInstance->c50_sfEvent, -34);
}
}
_SFD_EML_CALL(0U, chartInstance->c50_sfEvent, -18);
_SFD_SYMBOL_SCOPE_POP();
*c50_b_a2 = c50_a2;
_SFD_CC_CALL(EXIT_OUT_OF_FUNCTION_TAG, 26U, chartInstance->c50_sfEvent);
_SFD_SYMBOL_SCOPE_POP();
_SFD_CHECK_FOR_STATE_INCONSISTENCY(_Expriment_FacialExprMachineNumber_,
chartInstance->chartNumber, chartInstance->instanceNumber);
_SFD_DATA_RANGE_CHECK(*c50_b_a2, 0U);
_SFD_DATA_RANGE_CHECK(*c50_b_a1, 1U);
}
static void initSimStructsc50_Expriment_FacialExpr
(SFc50_Expriment_FacialExprInstanceStruct *chartInstance)
{
(void)chartInstance;
}
static void init_script_number_translation(uint32_T c50_machineNumber, uint32_T
c50_chartNumber, uint32_T c50_instanceNumber)
{
(void)c50_machineNumber;
(void)c50_chartNumber;
(void)c50_instanceNumber;
}
static const mxArray *c50_sf_marshallOut(void *chartInstanceVoid, void
*c50_inData)
{
const mxArray *c50_mxArrayOutData = NULL;
real_T c50_u;
const mxArray *c50_y = NULL;
SFc50_Expriment_FacialExprInstanceStruct *chartInstance;
chartInstance = (SFc50_Expriment_FacialExprInstanceStruct *)chartInstanceVoid;
c50_mxArrayOutData = NULL;
c50_u = *(real_T *)c50_inData;
c50_y = NULL;
sf_mex_assign(&c50_y, sf_mex_create("y", &c50_u, 0, 0U, 0U, 0U, 0), false);
sf_mex_assign(&c50_mxArrayOutData, c50_y, false);
return c50_mxArrayOutData;
}
static real_T c50_emlrt_marshallIn(SFc50_Expriment_FacialExprInstanceStruct
*chartInstance, const mxArray *c50_a2, const char_T *c50_identifier)
{
real_T c50_y;
emlrtMsgIdentifier c50_thisId;
c50_thisId.fIdentifier = c50_identifier;
c50_thisId.fParent = NULL;
c50_y = c50_b_emlrt_marshallIn(chartInstance, sf_mex_dup(c50_a2), &c50_thisId);
sf_mex_destroy(&c50_a2);
return c50_y;
}
static real_T c50_b_emlrt_marshallIn(SFc50_Expriment_FacialExprInstanceStruct
*chartInstance, const mxArray *c50_u, const emlrtMsgIdentifier *c50_parentId)
{
real_T c50_y;
real_T c50_d0;
(void)chartInstance;
sf_mex_import(c50_parentId, sf_mex_dup(c50_u), &c50_d0, 1, 0, 0U, 0, 0U, 0);
c50_y = c50_d0;
sf_mex_destroy(&c50_u);
return c50_y;
}
static void c50_sf_marshallIn(void *chartInstanceVoid, const mxArray
*c50_mxArrayInData, const char_T *c50_varName, void *c50_outData)
{
const mxArray *c50_a2;
const char_T *c50_identifier;
emlrtMsgIdentifier c50_thisId;
real_T c50_y;
SFc50_Expriment_FacialExprInstanceStruct *chartInstance;
chartInstance = (SFc50_Expriment_FacialExprInstanceStruct *)chartInstanceVoid;
c50_a2 = sf_mex_dup(c50_mxArrayInData);
c50_identifier = c50_varName;
c50_thisId.fIdentifier = c50_identifier;
c50_thisId.fParent = NULL;
c50_y = c50_b_emlrt_marshallIn(chartInstance, sf_mex_dup(c50_a2), &c50_thisId);
sf_mex_destroy(&c50_a2);
*(real_T *)c50_outData = c50_y;
sf_mex_destroy(&c50_mxArrayInData);
}
static const mxArray *c50_b_sf_marshallOut(void *chartInstanceVoid, void
*c50_inData)
{
const mxArray *c50_mxArrayOutData = NULL;
boolean_T c50_u;
const mxArray *c50_y = NULL;
SFc50_Expriment_FacialExprInstanceStruct *chartInstance;
chartInstance = (SFc50_Expriment_FacialExprInstanceStruct *)chartInstanceVoid;
c50_mxArrayOutData = NULL;
c50_u = *(boolean_T *)c50_inData;
c50_y = NULL;
sf_mex_assign(&c50_y, sf_mex_create("y", &c50_u, 11, 0U, 0U, 0U, 0), false);
sf_mex_assign(&c50_mxArrayOutData, c50_y, false);
return c50_mxArrayOutData;
}
static boolean_T c50_c_emlrt_marshallIn(SFc50_Expriment_FacialExprInstanceStruct
*chartInstance, const mxArray *c50_u, const emlrtMsgIdentifier *c50_parentId)
{
boolean_T c50_y;
boolean_T c50_b0;
(void)chartInstance;
sf_mex_import(c50_parentId, sf_mex_dup(c50_u), &c50_b0, 1, 11, 0U, 0, 0U, 0);
c50_y = c50_b0;
sf_mex_destroy(&c50_u);
return c50_y;
}
static void c50_b_sf_marshallIn(void *chartInstanceVoid, const mxArray
*c50_mxArrayInData, const char_T *c50_varName, void *c50_outData)
{
const mxArray *c50_aVarTruthTableCondition_2;
const char_T *c50_identifier;
emlrtMsgIdentifier c50_thisId;
boolean_T c50_y;
SFc50_Expriment_FacialExprInstanceStruct *chartInstance;
chartInstance = (SFc50_Expriment_FacialExprInstanceStruct *)chartInstanceVoid;
c50_aVarTruthTableCondition_2 = sf_mex_dup(c50_mxArrayInData);
c50_identifier = c50_varName;
c50_thisId.fIdentifier = c50_identifier;
c50_thisId.fParent = NULL;
c50_y = c50_c_emlrt_marshallIn(chartInstance, sf_mex_dup
(c50_aVarTruthTableCondition_2), &c50_thisId);
sf_mex_destroy(&c50_aVarTruthTableCondition_2);
*(boolean_T *)c50_outData = c50_y;
sf_mex_destroy(&c50_mxArrayInData);
}
const mxArray *sf_c50_Expriment_FacialExpr_get_eml_resolved_functions_info(void)
{
const mxArray *c50_nameCaptureInfo = NULL;
c50_nameCaptureInfo = NULL;
sf_mex_assign(&c50_nameCaptureInfo, sf_mex_create("nameCaptureInfo", NULL, 0,
0U, 1U, 0U, 2, 0, 1), false);
return c50_nameCaptureInfo;
}
static const mxArray *c50_c_sf_marshallOut(void *chartInstanceVoid, void
*c50_inData)
{
const mxArray *c50_mxArrayOutData = NULL;
int32_T c50_u;
const mxArray *c50_y = NULL;
SFc50_Expriment_FacialExprInstanceStruct *chartInstance;
chartInstance = (SFc50_Expriment_FacialExprInstanceStruct *)chartInstanceVoid;
c50_mxArrayOutData = NULL;
c50_u = *(int32_T *)c50_inData;
c50_y = NULL;
sf_mex_assign(&c50_y, sf_mex_create("y", &c50_u, 6, 0U, 0U, 0U, 0), false);
sf_mex_assign(&c50_mxArrayOutData, c50_y, false);
return c50_mxArrayOutData;
}
static int32_T c50_d_emlrt_marshallIn(SFc50_Expriment_FacialExprInstanceStruct
*chartInstance, const mxArray *c50_u, const emlrtMsgIdentifier *c50_parentId)
{
int32_T c50_y;
int32_T c50_i0;
(void)chartInstance;
sf_mex_import(c50_parentId, sf_mex_dup(c50_u), &c50_i0, 1, 6, 0U, 0, 0U, 0);
c50_y = c50_i0;
sf_mex_destroy(&c50_u);
return c50_y;
}
static void c50_c_sf_marshallIn(void *chartInstanceVoid, const mxArray
*c50_mxArrayInData, const char_T *c50_varName, void *c50_outData)
{
const mxArray *c50_b_sfEvent;
const char_T *c50_identifier;
emlrtMsgIdentifier c50_thisId;
int32_T c50_y;
SFc50_Expriment_FacialExprInstanceStruct *chartInstance;
chartInstance = (SFc50_Expriment_FacialExprInstanceStruct *)chartInstanceVoid;
c50_b_sfEvent = sf_mex_dup(c50_mxArrayInData);
c50_identifier = c50_varName;
c50_thisId.fIdentifier = c50_identifier;
c50_thisId.fParent = NULL;
c50_y = c50_d_emlrt_marshallIn(chartInstance, sf_mex_dup(c50_b_sfEvent),
&c50_thisId);
sf_mex_destroy(&c50_b_sfEvent);
*(int32_T *)c50_outData = c50_y;
sf_mex_destroy(&c50_mxArrayInData);
}
static uint8_T c50_e_emlrt_marshallIn(SFc50_Expriment_FacialExprInstanceStruct
*chartInstance, const mxArray *c50_b_is_active_c50_Expriment_FacialExpr, const
char_T *c50_identifier)
{
uint8_T c50_y;
emlrtMsgIdentifier c50_thisId;
c50_thisId.fIdentifier = c50_identifier;
c50_thisId.fParent = NULL;
c50_y = c50_f_emlrt_marshallIn(chartInstance, sf_mex_dup
(c50_b_is_active_c50_Expriment_FacialExpr), &c50_thisId);
sf_mex_destroy(&c50_b_is_active_c50_Expriment_FacialExpr);
return c50_y;
}
static uint8_T c50_f_emlrt_marshallIn(SFc50_Expriment_FacialExprInstanceStruct
*chartInstance, const mxArray *c50_u, const emlrtMsgIdentifier *c50_parentId)
{
uint8_T c50_y;
uint8_T c50_u0;
(void)chartInstance;
sf_mex_import(c50_parentId, sf_mex_dup(c50_u), &c50_u0, 1, 3, 0U, 0, 0U, 0);
c50_y = c50_u0;
sf_mex_destroy(&c50_u);
return c50_y;
}
static void init_dsm_address_info(SFc50_Expriment_FacialExprInstanceStruct
*chartInstance)
{
(void)chartInstance;
}
/* SFunction Glue Code */
#ifdef utFree
#undef utFree
#endif
#ifdef utMalloc
#undef utMalloc
#endif
#ifdef __cplusplus
extern "C" void *utMalloc(size_t size);
extern "C" void utFree(void*);
#else
extern void *utMalloc(size_t size);
extern void utFree(void*);
#endif
void sf_c50_Expriment_FacialExpr_get_check_sum(mxArray *plhs[])
{
((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(3328797340U);
((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(1069987066U);
((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(1424295356U);
((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(2993789229U);
}
mxArray *sf_c50_Expriment_FacialExpr_get_autoinheritance_info(void)
{
const char *autoinheritanceFields[] = { "checksum", "inputs", "parameters",
"outputs", "locals" };
mxArray *mxAutoinheritanceInfo = mxCreateStructMatrix(1,1,5,
autoinheritanceFields);
{
mxArray *mxChecksum = mxCreateString("OyIZ4INnb2VrYIt5UCJNU");
mxSetField(mxAutoinheritanceInfo,0,"checksum",mxChecksum);
}
{
const char *dataFields[] = { "size", "type", "complexity" };
mxArray *mxData = mxCreateStructMatrix(1,1,3,dataFields);
{
mxArray *mxSize = mxCreateDoubleMatrix(1,2,mxREAL);
double *pr = mxGetPr(mxSize);
pr[0] = (double)(1);
pr[1] = (double)(1);
mxSetField(mxData,0,"size",mxSize);
}
{
const char *typeFields[] = { "base", "fixpt" };
mxArray *mxType = mxCreateStructMatrix(1,1,2,typeFields);
mxSetField(mxType,0,"base",mxCreateDoubleScalar(10));
mxSetField(mxType,0,"fixpt",mxCreateDoubleMatrix(0,0,mxREAL));
mxSetField(mxData,0,"type",mxType);
}
mxSetField(mxData,0,"complexity",mxCreateDoubleScalar(0));
mxSetField(mxAutoinheritanceInfo,0,"inputs",mxData);
}
{
mxSetField(mxAutoinheritanceInfo,0,"parameters",mxCreateDoubleMatrix(0,0,
mxREAL));
}
{
const char *dataFields[] = { "size", "type", "complexity" };
mxArray *mxData = mxCreateStructMatrix(1,1,3,dataFields);
{
mxArray *mxSize = mxCreateDoubleMatrix(1,2,mxREAL);
double *pr = mxGetPr(mxSize);
pr[0] = (double)(1);
pr[1] = (double)(1);
mxSetField(mxData,0,"size",mxSize);
}
{
const char *typeFields[] = { "base", "fixpt" };
mxArray *mxType = mxCreateStructMatrix(1,1,2,typeFields);
mxSetField(mxType,0,"base",mxCreateDoubleScalar(10));
mxSetField(mxType,0,"fixpt",mxCreateDoubleMatrix(0,0,mxREAL));
mxSetField(mxData,0,"type",mxType);
}
mxSetField(mxData,0,"complexity",mxCreateDoubleScalar(0));
mxSetField(mxAutoinheritanceInfo,0,"outputs",mxData);
}
{
mxSetField(mxAutoinheritanceInfo,0,"locals",mxCreateDoubleMatrix(0,0,mxREAL));
}
return(mxAutoinheritanceInfo);
}
mxArray *sf_c50_Expriment_FacialExpr_third_party_uses_info(void)
{
mxArray * mxcell3p = mxCreateCellMatrix(1,0);
return(mxcell3p);
}
mxArray *sf_c50_Expriment_FacialExpr_updateBuildInfo_args_info(void)
{
mxArray *mxBIArgs = mxCreateCellMatrix(1,0);
return mxBIArgs;
}
static const mxArray *sf_get_sim_state_info_c50_Expriment_FacialExpr(void)
{
const char *infoFields[] = { "chartChecksum", "varInfo" };
mxArray *mxInfo = mxCreateStructMatrix(1, 1, 2, infoFields);
const char *infoEncStr[] = {
"100 S1x2'type','srcId','name','auxInfo'{{M[1],M[4],T\"a2\",},{M[8],M[0],T\"is_active_c50_Expriment_FacialExpr\",}}"
};
mxArray *mxVarInfo = sf_mex_decode_encoded_mx_struct_array(infoEncStr, 2, 10);
mxArray *mxChecksum = mxCreateDoubleMatrix(1, 4, mxREAL);
sf_c50_Expriment_FacialExpr_get_check_sum(&mxChecksum);
mxSetField(mxInfo, 0, infoFields[0], mxChecksum);
mxSetField(mxInfo, 0, infoFields[1], mxVarInfo);
return mxInfo;
}
static void chart_debug_initialization(SimStruct *S, unsigned int
fullDebuggerInitialization)
{
if (!sim_mode_is_rtw_gen(S)) {
SFc50_Expriment_FacialExprInstanceStruct *chartInstance;
ChartRunTimeInfo * crtInfo = (ChartRunTimeInfo *)(ssGetUserData(S));
ChartInfoStruct * chartInfo = (ChartInfoStruct *)(crtInfo->instanceInfo);
chartInstance = (SFc50_Expriment_FacialExprInstanceStruct *)
chartInfo->chartInstance;
if (ssIsFirstInitCond(S) && fullDebuggerInitialization==1) {
/* do this only if simulation is starting */
{
unsigned int chartAlreadyPresent;
chartAlreadyPresent = sf_debug_initialize_chart
(sfGlobalDebugInstanceStruct,
_Expriment_FacialExprMachineNumber_,
50,
1,
1,
0,
2,
0,
0,
0,
0,
0,
&(chartInstance->chartNumber),
&(chartInstance->instanceNumber),
(void *)S);
/* Each instance must initialize ist own list of scripts */
init_script_number_translation(_Expriment_FacialExprMachineNumber_,
chartInstance->chartNumber,chartInstance->instanceNumber);
if (chartAlreadyPresent==0) {
/* this is the first instance */
sf_debug_set_chart_disable_implicit_casting
(sfGlobalDebugInstanceStruct,_Expriment_FacialExprMachineNumber_,
chartInstance->chartNumber,1);
sf_debug_set_chart_event_thresholds(sfGlobalDebugInstanceStruct,
_Expriment_FacialExprMachineNumber_,
chartInstance->chartNumber,
0,
0,
0);
_SFD_SET_DATA_PROPS(0,2,0,1,"a2");
_SFD_SET_DATA_PROPS(1,1,1,0,"a1");
_SFD_STATE_INFO(0,0,2);
_SFD_CH_SUBSTATE_COUNT(0);
_SFD_CH_SUBSTATE_DECOMP(0);
}
_SFD_CV_INIT_CHART(0,0,0,0);
{
_SFD_CV_INIT_STATE(0,0,0,0,0,0,NULL,NULL);
}
_SFD_CV_INIT_TRANS(0,0,NULL,NULL,0,NULL);
/* Initialization of MATLAB Function Model Coverage */
_SFD_CV_INIT_EML(0,1,4,2,0,0,0,0,0,0,0);
_SFD_CV_INIT_EML_FCN(0,0,"tt_blk_kernel",0,-1,364);
_SFD_CV_INIT_EML_FCN(0,1,"aFcnTruthTableAction_1",364,-1,408);
_SFD_CV_INIT_EML_FCN(0,2,"aFcnTruthTableAction_2",408,-1,452);
_SFD_CV_INIT_EML_FCN(0,3,"aFcnTruthTableAction_3",452,-1,494);
_SFD_CV_INIT_EML_IF(0,1,0,188,218,249,362);
_SFD_CV_INIT_EML_IF(0,1,1,249,283,314,362);
_SFD_SET_DATA_COMPILED_PROPS(0,SF_DOUBLE,0,NULL,0,0,0,0.0,1.0,0,0,
(MexFcnForType)c50_sf_marshallOut,(MexInFcnForType)c50_sf_marshallIn);
_SFD_SET_DATA_COMPILED_PROPS(1,SF_DOUBLE,0,NULL,0,0,0,0.0,1.0,0,0,
(MexFcnForType)c50_sf_marshallOut,(MexInFcnForType)NULL);
{
real_T *c50_a2;
real_T *c50_a1;
c50_a1 = (real_T *)ssGetInputPortSignal(chartInstance->S, 0);
c50_a2 = (real_T *)ssGetOutputPortSignal(chartInstance->S, 1);
_SFD_SET_DATA_VALUE_PTR(0U, c50_a2);
_SFD_SET_DATA_VALUE_PTR(1U, c50_a1);
}
}
} else {
sf_debug_reset_current_state_configuration(sfGlobalDebugInstanceStruct,
_Expriment_FacialExprMachineNumber_,chartInstance->chartNumber,
chartInstance->instanceNumber);
}
}
}
static const char* sf_get_instance_specialization(void)
{
return "LTvX8lll5piFXxb8H1s43";
}
static void sf_opaque_initialize_c50_Expriment_FacialExpr(void *chartInstanceVar)
{
chart_debug_initialization(((SFc50_Expriment_FacialExprInstanceStruct*)
chartInstanceVar)->S,0);
initialize_params_c50_Expriment_FacialExpr
((SFc50_Expriment_FacialExprInstanceStruct*) chartInstanceVar);
initialize_c50_Expriment_FacialExpr((SFc50_Expriment_FacialExprInstanceStruct*)
chartInstanceVar);
}
static void sf_opaque_enable_c50_Expriment_FacialExpr(void *chartInstanceVar)
{
enable_c50_Expriment_FacialExpr((SFc50_Expriment_FacialExprInstanceStruct*)
chartInstanceVar);
}
static void sf_opaque_disable_c50_Expriment_FacialExpr(void *chartInstanceVar)
{
disable_c50_Expriment_FacialExpr((SFc50_Expriment_FacialExprInstanceStruct*)
chartInstanceVar);
}
static void sf_opaque_gateway_c50_Expriment_FacialExpr(void *chartInstanceVar)
{
sf_gateway_c50_Expriment_FacialExpr((SFc50_Expriment_FacialExprInstanceStruct*)
chartInstanceVar);
}
extern const mxArray* sf_internal_get_sim_state_c50_Expriment_FacialExpr
(SimStruct* S)
{
ChartRunTimeInfo * crtInfo = (ChartRunTimeInfo *)(ssGetUserData(S));
ChartInfoStruct * chartInfo = (ChartInfoStruct *)(crtInfo->instanceInfo);
mxArray *plhs[1] = { NULL };
mxArray *prhs[4];
int mxError = 0;
prhs[0] = mxCreateString("chart_simctx_raw2high");
prhs[1] = mxCreateDoubleScalar(ssGetSFuncBlockHandle(S));
prhs[2] = (mxArray*) get_sim_state_c50_Expriment_FacialExpr
((SFc50_Expriment_FacialExprInstanceStruct*)chartInfo->chartInstance);/* raw sim ctx */
prhs[3] = (mxArray*) sf_get_sim_state_info_c50_Expriment_FacialExpr();/* state var info */
mxError = sf_mex_call_matlab(1, plhs, 4, prhs, "sfprivate");
mxDestroyArray(prhs[0]);
mxDestroyArray(prhs[1]);
mxDestroyArray(prhs[2]);
mxDestroyArray(prhs[3]);
if (mxError || plhs[0] == NULL) {
sf_mex_error_message("Stateflow Internal Error: \nError calling 'chart_simctx_raw2high'.\n");
}
return plhs[0];
}
extern void sf_internal_set_sim_state_c50_Expriment_FacialExpr(SimStruct* S,
const mxArray *st)
{
ChartRunTimeInfo * crtInfo = (ChartRunTimeInfo *)(ssGetUserData(S));
ChartInfoStruct * chartInfo = (ChartInfoStruct *)(crtInfo->instanceInfo);
mxArray *plhs[1] = { NULL };
mxArray *prhs[3];
int mxError = 0;
prhs[0] = mxCreateString("chart_simctx_high2raw");
prhs[1] = mxDuplicateArray(st); /* high level simctx */
prhs[2] = (mxArray*) sf_get_sim_state_info_c50_Expriment_FacialExpr();/* state var info */
mxError = sf_mex_call_matlab(1, plhs, 3, prhs, "sfprivate");
mxDestroyArray(prhs[0]);
mxDestroyArray(prhs[1]);
mxDestroyArray(prhs[2]);
if (mxError || plhs[0] == NULL) {
sf_mex_error_message("Stateflow Internal Error: \nError calling 'chart_simctx_high2raw'.\n");
}
set_sim_state_c50_Expriment_FacialExpr
((SFc50_Expriment_FacialExprInstanceStruct*)chartInfo->chartInstance,
mxDuplicateArray(plhs[0]));
mxDestroyArray(plhs[0]);
}
static const mxArray* sf_opaque_get_sim_state_c50_Expriment_FacialExpr(SimStruct*
S)
{
return sf_internal_get_sim_state_c50_Expriment_FacialExpr(S);
}
static void sf_opaque_set_sim_state_c50_Expriment_FacialExpr(SimStruct* S, const
mxArray *st)
{
sf_internal_set_sim_state_c50_Expriment_FacialExpr(S, st);
}
static void sf_opaque_terminate_c50_Expriment_FacialExpr(void *chartInstanceVar)
{
if (chartInstanceVar!=NULL) {
SimStruct *S = ((SFc50_Expriment_FacialExprInstanceStruct*) chartInstanceVar)
->S;
ChartRunTimeInfo * crtInfo = (ChartRunTimeInfo *)(ssGetUserData(S));
if (sim_mode_is_rtw_gen(S) || sim_mode_is_external(S)) {
sf_clear_rtw_identifier(S);
unload_Expriment_FacialExpr_optimization_info();
}
finalize_c50_Expriment_FacialExpr((SFc50_Expriment_FacialExprInstanceStruct*)
chartInstanceVar);
utFree((void *)chartInstanceVar);
if (crtInfo != NULL) {
utFree((void *)crtInfo);
}
ssSetUserData(S,NULL);
}
}
static void sf_opaque_init_subchart_simstructs(void *chartInstanceVar)
{
initSimStructsc50_Expriment_FacialExpr
((SFc50_Expriment_FacialExprInstanceStruct*) chartInstanceVar);
}
extern unsigned int sf_machine_global_initializer_called(void);
static void mdlProcessParameters_c50_Expriment_FacialExpr(SimStruct *S)
{
int i;
for (i=0;i<ssGetNumRunTimeParams(S);i++) {
if (ssGetSFcnParamTunable(S,i)) {
ssUpdateDlgParamAsRunTimeParam(S,i);
}
}
if (sf_machine_global_initializer_called()) {
ChartRunTimeInfo * crtInfo = (ChartRunTimeInfo *)(ssGetUserData(S));
ChartInfoStruct * chartInfo = (ChartInfoStruct *)(crtInfo->instanceInfo);
initialize_params_c50_Expriment_FacialExpr
((SFc50_Expriment_FacialExprInstanceStruct*)(chartInfo->chartInstance));
}
}
static void mdlSetWorkWidths_c50_Expriment_FacialExpr(SimStruct *S)
{
if (sim_mode_is_rtw_gen(S) || sim_mode_is_external(S)) {
mxArray *infoStruct = load_Expriment_FacialExpr_optimization_info();
int_T chartIsInlinable =
(int_T)sf_is_chart_inlinable(sf_get_instance_specialization(),infoStruct,
50);
ssSetStateflowIsInlinable(S,chartIsInlinable);
ssSetRTWCG(S,sf_rtw_info_uint_prop(sf_get_instance_specialization(),
infoStruct,50,"RTWCG"));
ssSetEnableFcnIsTrivial(S,1);
ssSetDisableFcnIsTrivial(S,1);
ssSetNotMultipleInlinable(S,sf_rtw_info_uint_prop
(sf_get_instance_specialization(),infoStruct,50,
"gatewayCannotBeInlinedMultipleTimes"));
sf_update_buildInfo(sf_get_instance_specialization(),infoStruct,50);
if (chartIsInlinable) {
ssSetInputPortOptimOpts(S, 0, SS_REUSABLE_AND_LOCAL);
sf_mark_chart_expressionable_inputs(S,sf_get_instance_specialization(),
infoStruct,50,1);
sf_mark_chart_reusable_outputs(S,sf_get_instance_specialization(),
infoStruct,50,1);
}
{
unsigned int outPortIdx;
for (outPortIdx=1; outPortIdx<=1; ++outPortIdx) {
ssSetOutputPortOptimizeInIR(S, outPortIdx, 1U);
}
}
{
unsigned int inPortIdx;
for (inPortIdx=0; inPortIdx < 1; ++inPortIdx) {
ssSetInputPortOptimizeInIR(S, inPortIdx, 1U);
}
}
sf_set_rtw_dwork_info(S,sf_get_instance_specialization(),infoStruct,50);
ssSetHasSubFunctions(S,!(chartIsInlinable));
} else {
}
ssSetOptions(S,ssGetOptions(S)|SS_OPTION_WORKS_WITH_CODE_REUSE);
ssSetChecksum0(S,(3590708238U));
ssSetChecksum1(S,(336408773U));
ssSetChecksum2(S,(3435281869U));
ssSetChecksum3(S,(1654825720U));
ssSetmdlDerivatives(S, NULL);
ssSetExplicitFCSSCtrl(S,1);
ssSupportsMultipleExecInstances(S,1);
}
static void mdlRTW_c50_Expriment_FacialExpr(SimStruct *S)
{
if (sim_mode_is_rtw_gen(S)) {
ssWriteRTWStrParam(S, "StateflowChartType", "Truth Table");
}
}
static void mdlStart_c50_Expriment_FacialExpr(SimStruct *S)
{
SFc50_Expriment_FacialExprInstanceStruct *chartInstance;
ChartRunTimeInfo * crtInfo = (ChartRunTimeInfo *)utMalloc(sizeof
(ChartRunTimeInfo));
chartInstance = (SFc50_Expriment_FacialExprInstanceStruct *)utMalloc(sizeof
(SFc50_Expriment_FacialExprInstanceStruct));
memset(chartInstance, 0, sizeof(SFc50_Expriment_FacialExprInstanceStruct));
if (chartInstance==NULL) {
sf_mex_error_message("Could not allocate memory for chart instance.");
}
chartInstance->chartInfo.chartInstance = chartInstance;
chartInstance->chartInfo.isEMLChart = 0;
chartInstance->chartInfo.chartInitialized = 0;
chartInstance->chartInfo.sFunctionGateway =
sf_opaque_gateway_c50_Expriment_FacialExpr;
chartInstance->chartInfo.initializeChart =
sf_opaque_initialize_c50_Expriment_FacialExpr;
chartInstance->chartInfo.terminateChart =
sf_opaque_terminate_c50_Expriment_FacialExpr;
chartInstance->chartInfo.enableChart =
sf_opaque_enable_c50_Expriment_FacialExpr;
chartInstance->chartInfo.disableChart =
sf_opaque_disable_c50_Expriment_FacialExpr;
chartInstance->chartInfo.getSimState =
sf_opaque_get_sim_state_c50_Expriment_FacialExpr;
chartInstance->chartInfo.setSimState =
sf_opaque_set_sim_state_c50_Expriment_FacialExpr;
chartInstance->chartInfo.getSimStateInfo =
sf_get_sim_state_info_c50_Expriment_FacialExpr;
chartInstance->chartInfo.zeroCrossings = NULL;
chartInstance->chartInfo.outputs = NULL;
chartInstance->chartInfo.derivatives = NULL;
chartInstance->chartInfo.mdlRTW = mdlRTW_c50_Expriment_FacialExpr;
chartInstance->chartInfo.mdlStart = mdlStart_c50_Expriment_FacialExpr;
chartInstance->chartInfo.mdlSetWorkWidths =
mdlSetWorkWidths_c50_Expriment_FacialExpr;
chartInstance->chartInfo.extModeExec = NULL;
chartInstance->chartInfo.restoreLastMajorStepConfiguration = NULL;
chartInstance->chartInfo.restoreBeforeLastMajorStepConfiguration = NULL;
chartInstance->chartInfo.storeCurrentConfiguration = NULL;
chartInstance->chartInfo.debugInstance = sfGlobalDebugInstanceStruct;
chartInstance->S = S;
crtInfo->instanceInfo = (&(chartInstance->chartInfo));
crtInfo->isJITEnabled = false;
ssSetUserData(S,(void *)(crtInfo)); /* register the chart instance with simstruct */
init_dsm_address_info(chartInstance);
if (!sim_mode_is_rtw_gen(S)) {
}
sf_opaque_init_subchart_simstructs(chartInstance->chartInfo.chartInstance);
chart_debug_initialization(S,1);
}
void c50_Expriment_FacialExpr_method_dispatcher(SimStruct *S, int_T method, void
*data)
{
switch (method) {
case SS_CALL_MDL_START:
mdlStart_c50_Expriment_FacialExpr(S);
break;
case SS_CALL_MDL_SET_WORK_WIDTHS:
mdlSetWorkWidths_c50_Expriment_FacialExpr(S);
break;
case SS_CALL_MDL_PROCESS_PARAMETERS:
mdlProcessParameters_c50_Expriment_FacialExpr(S);
break;
default:
/* Unhandled method */
sf_mex_error_message("Stateflow Internal Error:\n"
"Error calling c50_Expriment_FacialExpr_method_dispatcher.\n"
"Can't handle method %d.\n", method);
break;
}
}
| 36.602083 | 121 | 0.741733 | [
"model"
] |
4fba322f80c75cb24cc7be5e3685df3ebfbf59aa | 7,212 | h | C | src/server/frame/model.h | jvirkki/heliod | efdf2d105e342317bd092bab2d727713da546174 | [
"BSD-3-Clause"
] | 13 | 2015-10-09T05:59:20.000Z | 2021-11-12T10:38:51.000Z | src/server/frame/model.h | JamesLinus/heliod | efdf2d105e342317bd092bab2d727713da546174 | [
"BSD-3-Clause"
] | null | null | null | src/server/frame/model.h | JamesLinus/heliod | efdf2d105e342317bd092bab2d727713da546174 | [
"BSD-3-Clause"
] | 6 | 2016-05-23T10:53:29.000Z | 2019-12-13T17:57:32.000Z | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2008 Sun Microsystems, Inc. All rights reserved.
*
* THE BSD LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the 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.
*/
#ifndef FRAME_MODEL_H
#define FRAME_MODEL_H
/*
* model.h: String and pblock interpolation
*
* Chris Elving
*/
/*
* ModelString is a model from which a synthetic string may be constructed.
*/
typedef struct ModelString ModelString;
/*
* ModelPblock is a model from which a synthetic pblock may be constructed.
*/
typedef struct ModelPblock ModelPblock;
PR_BEGIN_EXTERN_C
/*
* model_unescape_interpolative constructs a string in which "\$" escape
* sequences have been changed to "$$" and all other \escapes have been
* unescaped. The caller should free the returned string using FREE().
* Returns NULL on error; system_errmsg can be used to retrieve a localized
* description of the error.
*/
NSAPI_PUBLIC char *INTmodel_unescape_interpolative(const char *s);
/*
* model_unescape_noninterpolative constructs a string in which all \escapes
* have been unescaped. The caller should free the returned string using
* FREE(). Returns NULL on error; system_errmsg can be used to retrieve a
* localized description of the error.
*/
NSAPI_PUBLIC char *INTmodel_unescape_noninterpolative(const char *s);
/*
* model_fragment_scan returns the length of the of the non-\escaped
* interpolative string fragment that begins at f. A fragment is a span of
* characters that consists entirely of either a) a single $fragment (e.g. a
* single $variable reference), b) a single escaped '$' (that is, the "$$"
* sequence), or c) nonescaped text. Returns 0 if p points to an empty string.
* Returns -1 on error; system_errmsg can be used to retrieve a localized
* description of the error.
*/
NSAPI_PUBLIC int INTmodel_fragment_scan(const char *f);
/*
* model_fragment_is_invariant indicates whether the fragment that begins at f
* consists of either a single escaped '$' (that is, the "$$" sequence) or
* nonescaped text. If the it does, *ptext and *plen are set to point to the
* text.
*/
NSAPI_PUBLIC PRBool INTmodel_fragment_is_invariant(const char *f, const char **ptext, int *plen);
/*
* model_fragment_is_var_ref indicates whether the fragment that begins at f is
* a reference to a subscriptless (that is, non-map) $variable. If the
* fragments is a subscriptless $variable reference, *pname and and *plen are
* set to point to the variable name.
*/
NSAPI_PUBLIC PRBool INTmodel_fragment_is_var_ref(const char *f, const char **pname, int *plen);
/*
* model_str_create constructs a string model from a non-\escaped interpolative
* string. Non-\escaped interpolative strings may contain $fragments but do
* not contain \escapes. Returns NULL on error; system_errmsg can be used to
* retrieve a localized description of the error.
*/
NSAPI_PUBLIC ModelString *INTmodel_str_create(const char *s);
/*
* model_str_dup creates a copy of a string model.
*/
NSAPI_PUBLIC ModelString *INTmodel_str_dup(const ModelString *model);
/*
* model_str_free destroys a string model.
*/
NSAPI_PUBLIC void INTmodel_str_free(ModelString *model);
/*
* model_str_interpolate constructs a synthetic string in which $fragments have
* been interpolated and "$$" sequences have been unescaped. On return, *pp
* and *plen will point to a nul-terminated string or will be NULL and 0.
* Returns 0 if no errors were encountered. Returns -1 if any errors were
* encountered; system_errmsg can be used to a retrieve a localized description
* of the error. Note that a partially interpolated string may be returned
* through *pp and *plen even on error.
*/
NSAPI_PUBLIC int INTmodel_str_interpolate(const ModelString *model, Session *sn, Request *rq, const char **pp, int *plen);
/*
* model_pb_create constructs a pblock model from a pblock whose values may
* contain $fragments.
*/
NSAPI_PUBLIC ModelPblock *INTmodel_pb_create(const pblock *pb);
/*
* model_pb_dup creates a copy of a pblock model.
*/
NSAPI_PUBLIC ModelPblock *INTmodel_pb_dup(const ModelPblock *model);
/*
* model_pb_free destroys a pblock model.
*/
NSAPI_PUBLIC void INTmodel_pb_free(ModelPblock *model);
/*
* model_pb_is_noninterpolative indicates whether a pblock model consists
* entirely of nonescaped, noninterpolative text. That is, whether
* interpolation of the model will always result in a pblock identical to the
* pblock from which the model was constructed.
*/
NSAPI_PUBLIC PRBool INTmodel_pb_is_noninterpolative(const ModelPblock *model);
/*
* model_pb_interpolate constructs a synthetic pblock in which $fragments have
* been interpolated and "$$" sequences have been unescaped.. Returns a pblock
* allocated from rq's pool on success. Returns NULL on error; system_errmsg
* can be used to a retrieve a localized description of the error.
*/
NSAPI_PUBLIC pblock *INTmodel_pb_interpolate(const ModelPblock *model, Session *sn, Request *rq);
PR_END_EXTERN_C
#define model_unescape_interpolative INTmodel_unescape_interpolative
#define model_unescape_noninterpolative INTmodel_unescape_noninterpolative
#define model_fragment_scan INTmodel_fragment_scan
#define model_fragment_is_invariant INTmodel_fragment_is_invariant
#define model_fragment_is_var_ref INTmodel_fragment_is_var_ref
#define model_str_create INTmodel_str_create
#define model_str_dup INTmodel_str_dup
#define model_str_free INTmodel_str_free
#define model_str_interpolate INTmodel_str_interpolate
#define model_pb_create INTmodel_pb_create
#define model_pb_dup INTmodel_pb_dup
#define model_pb_free INTmodel_pb_free
#define model_pb_is_noninterpolative INTmodel_pb_is_noninterpolative
#define model_pb_interpolate INTmodel_pb_interpolate
#endif /* FRAME_MODEL_H */
| 40.516854 | 122 | 0.77995 | [
"model"
] |
4fbc935c9f3b9053313297e863c1ba8ef24fd67c | 56,233 | h | C | message/generation/swift-mt-generation/repository/SR2018/parsers/SwiftMtParser_MT566BaseListener.h | Yanick-Salzmann/message-converter-c | 6dfdf56e12f19e0f0b63ee0354fda16968f36415 | [
"MIT"
] | null | null | null | message/generation/swift-mt-generation/repository/SR2018/parsers/SwiftMtParser_MT566BaseListener.h | Yanick-Salzmann/message-converter-c | 6dfdf56e12f19e0f0b63ee0354fda16968f36415 | [
"MIT"
] | null | null | null | message/generation/swift-mt-generation/repository/SR2018/parsers/SwiftMtParser_MT566BaseListener.h | Yanick-Salzmann/message-converter-c | 6dfdf56e12f19e0f0b63ee0354fda16968f36415 | [
"MIT"
] | null | null | null |
#include "repository/ISwiftMtParser.h"
#include "SwiftMtMessage.pb.h"
#include <vector>
#include <string>
#include "BaseErrorListener.h"
#include "SwiftMtParser_MT566Lexer.h"
// Generated from C:/programming/message-converter-c/message/generation/swift-mt-generation/repository/SR2018/grammars/SwiftMtParser_MT566.g4 by ANTLR 4.7.2
#pragma once
#include "antlr4-runtime.h"
#include "SwiftMtParser_MT566Listener.h"
namespace message::definition::swift::mt::parsers::sr2018 {
/**
* This class provides an empty implementation of SwiftMtParser_MT566Listener,
* which can be extended to create a listener which only needs to handle a subset
* of the available methods.
*/
class SwiftMtParser_MT566BaseListener : public SwiftMtParser_MT566Listener {
public:
virtual void enterMessage(SwiftMtParser_MT566Parser::MessageContext * /*ctx*/) override { }
virtual void exitMessage(SwiftMtParser_MT566Parser::MessageContext * /*ctx*/) override { }
virtual void enterBh(SwiftMtParser_MT566Parser::BhContext * /*ctx*/) override { }
virtual void exitBh(SwiftMtParser_MT566Parser::BhContext * /*ctx*/) override { }
virtual void enterBh_content(SwiftMtParser_MT566Parser::Bh_contentContext * /*ctx*/) override { }
virtual void exitBh_content(SwiftMtParser_MT566Parser::Bh_contentContext * /*ctx*/) override { }
virtual void enterAh(SwiftMtParser_MT566Parser::AhContext * /*ctx*/) override { }
virtual void exitAh(SwiftMtParser_MT566Parser::AhContext * /*ctx*/) override { }
virtual void enterAh_content(SwiftMtParser_MT566Parser::Ah_contentContext * /*ctx*/) override { }
virtual void exitAh_content(SwiftMtParser_MT566Parser::Ah_contentContext * /*ctx*/) override { }
virtual void enterUh(SwiftMtParser_MT566Parser::UhContext * /*ctx*/) override { }
virtual void exitUh(SwiftMtParser_MT566Parser::UhContext * /*ctx*/) override { }
virtual void enterTr(SwiftMtParser_MT566Parser::TrContext * /*ctx*/) override { }
virtual void exitTr(SwiftMtParser_MT566Parser::TrContext * /*ctx*/) override { }
virtual void enterSys_block(SwiftMtParser_MT566Parser::Sys_blockContext * /*ctx*/) override { }
virtual void exitSys_block(SwiftMtParser_MT566Parser::Sys_blockContext * /*ctx*/) override { }
virtual void enterSys_element(SwiftMtParser_MT566Parser::Sys_elementContext * /*ctx*/) override { }
virtual void exitSys_element(SwiftMtParser_MT566Parser::Sys_elementContext * /*ctx*/) override { }
virtual void enterSys_element_key(SwiftMtParser_MT566Parser::Sys_element_keyContext * /*ctx*/) override { }
virtual void exitSys_element_key(SwiftMtParser_MT566Parser::Sys_element_keyContext * /*ctx*/) override { }
virtual void enterSys_element_content(SwiftMtParser_MT566Parser::Sys_element_contentContext * /*ctx*/) override { }
virtual void exitSys_element_content(SwiftMtParser_MT566Parser::Sys_element_contentContext * /*ctx*/) override { }
virtual void enterMt(SwiftMtParser_MT566Parser::MtContext * /*ctx*/) override { }
virtual void exitMt(SwiftMtParser_MT566Parser::MtContext * /*ctx*/) override { }
virtual void enterSeq_A(SwiftMtParser_MT566Parser::Seq_AContext * /*ctx*/) override { }
virtual void exitSeq_A(SwiftMtParser_MT566Parser::Seq_AContext * /*ctx*/) override { }
virtual void enterSeq_A1(SwiftMtParser_MT566Parser::Seq_A1Context * /*ctx*/) override { }
virtual void exitSeq_A1(SwiftMtParser_MT566Parser::Seq_A1Context * /*ctx*/) override { }
virtual void enterSeq_B(SwiftMtParser_MT566Parser::Seq_BContext * /*ctx*/) override { }
virtual void exitSeq_B(SwiftMtParser_MT566Parser::Seq_BContext * /*ctx*/) override { }
virtual void enterSeq_B1(SwiftMtParser_MT566Parser::Seq_B1Context * /*ctx*/) override { }
virtual void exitSeq_B1(SwiftMtParser_MT566Parser::Seq_B1Context * /*ctx*/) override { }
virtual void enterSeq_C(SwiftMtParser_MT566Parser::Seq_CContext * /*ctx*/) override { }
virtual void exitSeq_C(SwiftMtParser_MT566Parser::Seq_CContext * /*ctx*/) override { }
virtual void enterSeq_D(SwiftMtParser_MT566Parser::Seq_DContext * /*ctx*/) override { }
virtual void exitSeq_D(SwiftMtParser_MT566Parser::Seq_DContext * /*ctx*/) override { }
virtual void enterSeq_D1(SwiftMtParser_MT566Parser::Seq_D1Context * /*ctx*/) override { }
virtual void exitSeq_D1(SwiftMtParser_MT566Parser::Seq_D1Context * /*ctx*/) override { }
virtual void enterSeq_D1a(SwiftMtParser_MT566Parser::Seq_D1aContext * /*ctx*/) override { }
virtual void exitSeq_D1a(SwiftMtParser_MT566Parser::Seq_D1aContext * /*ctx*/) override { }
virtual void enterSeq_D1b(SwiftMtParser_MT566Parser::Seq_D1bContext * /*ctx*/) override { }
virtual void exitSeq_D1b(SwiftMtParser_MT566Parser::Seq_D1bContext * /*ctx*/) override { }
virtual void enterSeq_D2(SwiftMtParser_MT566Parser::Seq_D2Context * /*ctx*/) override { }
virtual void exitSeq_D2(SwiftMtParser_MT566Parser::Seq_D2Context * /*ctx*/) override { }
virtual void enterSeq_D2a(SwiftMtParser_MT566Parser::Seq_D2aContext * /*ctx*/) override { }
virtual void exitSeq_D2a(SwiftMtParser_MT566Parser::Seq_D2aContext * /*ctx*/) override { }
virtual void enterSeq_D2b(SwiftMtParser_MT566Parser::Seq_D2bContext * /*ctx*/) override { }
virtual void exitSeq_D2b(SwiftMtParser_MT566Parser::Seq_D2bContext * /*ctx*/) override { }
virtual void enterSeq_E(SwiftMtParser_MT566Parser::Seq_EContext * /*ctx*/) override { }
virtual void exitSeq_E(SwiftMtParser_MT566Parser::Seq_EContext * /*ctx*/) override { }
virtual void enterFld_16R_A(SwiftMtParser_MT566Parser::Fld_16R_AContext * /*ctx*/) override { }
virtual void exitFld_16R_A(SwiftMtParser_MT566Parser::Fld_16R_AContext * /*ctx*/) override { }
virtual void enterFld_20C_A(SwiftMtParser_MT566Parser::Fld_20C_AContext * /*ctx*/) override { }
virtual void exitFld_20C_A(SwiftMtParser_MT566Parser::Fld_20C_AContext * /*ctx*/) override { }
virtual void enterFld_23G_A(SwiftMtParser_MT566Parser::Fld_23G_AContext * /*ctx*/) override { }
virtual void exitFld_23G_A(SwiftMtParser_MT566Parser::Fld_23G_AContext * /*ctx*/) override { }
virtual void enterFld_22F_A(SwiftMtParser_MT566Parser::Fld_22F_AContext * /*ctx*/) override { }
virtual void exitFld_22F_A(SwiftMtParser_MT566Parser::Fld_22F_AContext * /*ctx*/) override { }
virtual void enterFld_98a_A(SwiftMtParser_MT566Parser::Fld_98a_AContext * /*ctx*/) override { }
virtual void exitFld_98a_A(SwiftMtParser_MT566Parser::Fld_98a_AContext * /*ctx*/) override { }
virtual void enterFld_16R_A1(SwiftMtParser_MT566Parser::Fld_16R_A1Context * /*ctx*/) override { }
virtual void exitFld_16R_A1(SwiftMtParser_MT566Parser::Fld_16R_A1Context * /*ctx*/) override { }
virtual void enterFld_22F_A1(SwiftMtParser_MT566Parser::Fld_22F_A1Context * /*ctx*/) override { }
virtual void exitFld_22F_A1(SwiftMtParser_MT566Parser::Fld_22F_A1Context * /*ctx*/) override { }
virtual void enterFld_13a_A1(SwiftMtParser_MT566Parser::Fld_13a_A1Context * /*ctx*/) override { }
virtual void exitFld_13a_A1(SwiftMtParser_MT566Parser::Fld_13a_A1Context * /*ctx*/) override { }
virtual void enterFld_20C_A1(SwiftMtParser_MT566Parser::Fld_20C_A1Context * /*ctx*/) override { }
virtual void exitFld_20C_A1(SwiftMtParser_MT566Parser::Fld_20C_A1Context * /*ctx*/) override { }
virtual void enterFld_16S_A1(SwiftMtParser_MT566Parser::Fld_16S_A1Context * /*ctx*/) override { }
virtual void exitFld_16S_A1(SwiftMtParser_MT566Parser::Fld_16S_A1Context * /*ctx*/) override { }
virtual void enterFld_16S_A(SwiftMtParser_MT566Parser::Fld_16S_AContext * /*ctx*/) override { }
virtual void exitFld_16S_A(SwiftMtParser_MT566Parser::Fld_16S_AContext * /*ctx*/) override { }
virtual void enterFld_16R_B(SwiftMtParser_MT566Parser::Fld_16R_BContext * /*ctx*/) override { }
virtual void exitFld_16R_B(SwiftMtParser_MT566Parser::Fld_16R_BContext * /*ctx*/) override { }
virtual void enterFld_95a_B(SwiftMtParser_MT566Parser::Fld_95a_BContext * /*ctx*/) override { }
virtual void exitFld_95a_B(SwiftMtParser_MT566Parser::Fld_95a_BContext * /*ctx*/) override { }
virtual void enterFld_97A_B(SwiftMtParser_MT566Parser::Fld_97A_BContext * /*ctx*/) override { }
virtual void exitFld_97A_B(SwiftMtParser_MT566Parser::Fld_97A_BContext * /*ctx*/) override { }
virtual void enterFld_94a_B(SwiftMtParser_MT566Parser::Fld_94a_BContext * /*ctx*/) override { }
virtual void exitFld_94a_B(SwiftMtParser_MT566Parser::Fld_94a_BContext * /*ctx*/) override { }
virtual void enterFld_35B_B(SwiftMtParser_MT566Parser::Fld_35B_BContext * /*ctx*/) override { }
virtual void exitFld_35B_B(SwiftMtParser_MT566Parser::Fld_35B_BContext * /*ctx*/) override { }
virtual void enterFld_16R_B1(SwiftMtParser_MT566Parser::Fld_16R_B1Context * /*ctx*/) override { }
virtual void exitFld_16R_B1(SwiftMtParser_MT566Parser::Fld_16R_B1Context * /*ctx*/) override { }
virtual void enterFld_94B_B1(SwiftMtParser_MT566Parser::Fld_94B_B1Context * /*ctx*/) override { }
virtual void exitFld_94B_B1(SwiftMtParser_MT566Parser::Fld_94B_B1Context * /*ctx*/) override { }
virtual void enterFld_22F_B1(SwiftMtParser_MT566Parser::Fld_22F_B1Context * /*ctx*/) override { }
virtual void exitFld_22F_B1(SwiftMtParser_MT566Parser::Fld_22F_B1Context * /*ctx*/) override { }
virtual void enterFld_12a_B1(SwiftMtParser_MT566Parser::Fld_12a_B1Context * /*ctx*/) override { }
virtual void exitFld_12a_B1(SwiftMtParser_MT566Parser::Fld_12a_B1Context * /*ctx*/) override { }
virtual void enterFld_11A_B1(SwiftMtParser_MT566Parser::Fld_11A_B1Context * /*ctx*/) override { }
virtual void exitFld_11A_B1(SwiftMtParser_MT566Parser::Fld_11A_B1Context * /*ctx*/) override { }
virtual void enterFld_98A_B1(SwiftMtParser_MT566Parser::Fld_98A_B1Context * /*ctx*/) override { }
virtual void exitFld_98A_B1(SwiftMtParser_MT566Parser::Fld_98A_B1Context * /*ctx*/) override { }
virtual void enterFld_92a_B1(SwiftMtParser_MT566Parser::Fld_92a_B1Context * /*ctx*/) override { }
virtual void exitFld_92a_B1(SwiftMtParser_MT566Parser::Fld_92a_B1Context * /*ctx*/) override { }
virtual void enterFld_36B_B1(SwiftMtParser_MT566Parser::Fld_36B_B1Context * /*ctx*/) override { }
virtual void exitFld_36B_B1(SwiftMtParser_MT566Parser::Fld_36B_B1Context * /*ctx*/) override { }
virtual void enterFld_16S_B1(SwiftMtParser_MT566Parser::Fld_16S_B1Context * /*ctx*/) override { }
virtual void exitFld_16S_B1(SwiftMtParser_MT566Parser::Fld_16S_B1Context * /*ctx*/) override { }
virtual void enterFld_93a_B(SwiftMtParser_MT566Parser::Fld_93a_BContext * /*ctx*/) override { }
virtual void exitFld_93a_B(SwiftMtParser_MT566Parser::Fld_93a_BContext * /*ctx*/) override { }
virtual void enterFld_16S_B(SwiftMtParser_MT566Parser::Fld_16S_BContext * /*ctx*/) override { }
virtual void exitFld_16S_B(SwiftMtParser_MT566Parser::Fld_16S_BContext * /*ctx*/) override { }
virtual void enterFld_16R_C(SwiftMtParser_MT566Parser::Fld_16R_CContext * /*ctx*/) override { }
virtual void exitFld_16R_C(SwiftMtParser_MT566Parser::Fld_16R_CContext * /*ctx*/) override { }
virtual void enterFld_98a_C(SwiftMtParser_MT566Parser::Fld_98a_CContext * /*ctx*/) override { }
virtual void exitFld_98a_C(SwiftMtParser_MT566Parser::Fld_98a_CContext * /*ctx*/) override { }
virtual void enterFld_69a_C(SwiftMtParser_MT566Parser::Fld_69a_CContext * /*ctx*/) override { }
virtual void exitFld_69a_C(SwiftMtParser_MT566Parser::Fld_69a_CContext * /*ctx*/) override { }
virtual void enterFld_99A_C(SwiftMtParser_MT566Parser::Fld_99A_CContext * /*ctx*/) override { }
virtual void exitFld_99A_C(SwiftMtParser_MT566Parser::Fld_99A_CContext * /*ctx*/) override { }
virtual void enterFld_92a_C(SwiftMtParser_MT566Parser::Fld_92a_CContext * /*ctx*/) override { }
virtual void exitFld_92a_C(SwiftMtParser_MT566Parser::Fld_92a_CContext * /*ctx*/) override { }
virtual void enterFld_90a_C(SwiftMtParser_MT566Parser::Fld_90a_CContext * /*ctx*/) override { }
virtual void exitFld_90a_C(SwiftMtParser_MT566Parser::Fld_90a_CContext * /*ctx*/) override { }
virtual void enterFld_36a_C(SwiftMtParser_MT566Parser::Fld_36a_CContext * /*ctx*/) override { }
virtual void exitFld_36a_C(SwiftMtParser_MT566Parser::Fld_36a_CContext * /*ctx*/) override { }
virtual void enterFld_13a_C(SwiftMtParser_MT566Parser::Fld_13a_CContext * /*ctx*/) override { }
virtual void exitFld_13a_C(SwiftMtParser_MT566Parser::Fld_13a_CContext * /*ctx*/) override { }
virtual void enterFld_17B_C(SwiftMtParser_MT566Parser::Fld_17B_CContext * /*ctx*/) override { }
virtual void exitFld_17B_C(SwiftMtParser_MT566Parser::Fld_17B_CContext * /*ctx*/) override { }
virtual void enterFld_22F_C(SwiftMtParser_MT566Parser::Fld_22F_CContext * /*ctx*/) override { }
virtual void exitFld_22F_C(SwiftMtParser_MT566Parser::Fld_22F_CContext * /*ctx*/) override { }
virtual void enterFld_16S_C(SwiftMtParser_MT566Parser::Fld_16S_CContext * /*ctx*/) override { }
virtual void exitFld_16S_C(SwiftMtParser_MT566Parser::Fld_16S_CContext * /*ctx*/) override { }
virtual void enterFld_16R_D(SwiftMtParser_MT566Parser::Fld_16R_DContext * /*ctx*/) override { }
virtual void exitFld_16R_D(SwiftMtParser_MT566Parser::Fld_16R_DContext * /*ctx*/) override { }
virtual void enterFld_13A_D(SwiftMtParser_MT566Parser::Fld_13A_DContext * /*ctx*/) override { }
virtual void exitFld_13A_D(SwiftMtParser_MT566Parser::Fld_13A_DContext * /*ctx*/) override { }
virtual void enterFld_22a_D(SwiftMtParser_MT566Parser::Fld_22a_DContext * /*ctx*/) override { }
virtual void exitFld_22a_D(SwiftMtParser_MT566Parser::Fld_22a_DContext * /*ctx*/) override { }
virtual void enterFld_11A_D(SwiftMtParser_MT566Parser::Fld_11A_DContext * /*ctx*/) override { }
virtual void exitFld_11A_D(SwiftMtParser_MT566Parser::Fld_11A_DContext * /*ctx*/) override { }
virtual void enterFld_98a_D(SwiftMtParser_MT566Parser::Fld_98a_DContext * /*ctx*/) override { }
virtual void exitFld_98a_D(SwiftMtParser_MT566Parser::Fld_98a_DContext * /*ctx*/) override { }
virtual void enterFld_69a_D(SwiftMtParser_MT566Parser::Fld_69a_DContext * /*ctx*/) override { }
virtual void exitFld_69a_D(SwiftMtParser_MT566Parser::Fld_69a_DContext * /*ctx*/) override { }
virtual void enterFld_92a_D(SwiftMtParser_MT566Parser::Fld_92a_DContext * /*ctx*/) override { }
virtual void exitFld_92a_D(SwiftMtParser_MT566Parser::Fld_92a_DContext * /*ctx*/) override { }
virtual void enterFld_90a_D(SwiftMtParser_MT566Parser::Fld_90a_DContext * /*ctx*/) override { }
virtual void exitFld_90a_D(SwiftMtParser_MT566Parser::Fld_90a_DContext * /*ctx*/) override { }
virtual void enterFld_94B_D(SwiftMtParser_MT566Parser::Fld_94B_DContext * /*ctx*/) override { }
virtual void exitFld_94B_D(SwiftMtParser_MT566Parser::Fld_94B_DContext * /*ctx*/) override { }
virtual void enterFld_16R_D1(SwiftMtParser_MT566Parser::Fld_16R_D1Context * /*ctx*/) override { }
virtual void exitFld_16R_D1(SwiftMtParser_MT566Parser::Fld_16R_D1Context * /*ctx*/) override { }
virtual void enterFld_22a_D1(SwiftMtParser_MT566Parser::Fld_22a_D1Context * /*ctx*/) override { }
virtual void exitFld_22a_D1(SwiftMtParser_MT566Parser::Fld_22a_D1Context * /*ctx*/) override { }
virtual void enterFld_35B_D1(SwiftMtParser_MT566Parser::Fld_35B_D1Context * /*ctx*/) override { }
virtual void exitFld_35B_D1(SwiftMtParser_MT566Parser::Fld_35B_D1Context * /*ctx*/) override { }
virtual void enterFld_16R_D1a(SwiftMtParser_MT566Parser::Fld_16R_D1aContext * /*ctx*/) override { }
virtual void exitFld_16R_D1a(SwiftMtParser_MT566Parser::Fld_16R_D1aContext * /*ctx*/) override { }
virtual void enterFld_94B_D1a(SwiftMtParser_MT566Parser::Fld_94B_D1aContext * /*ctx*/) override { }
virtual void exitFld_94B_D1a(SwiftMtParser_MT566Parser::Fld_94B_D1aContext * /*ctx*/) override { }
virtual void enterFld_22F_D1a(SwiftMtParser_MT566Parser::Fld_22F_D1aContext * /*ctx*/) override { }
virtual void exitFld_22F_D1a(SwiftMtParser_MT566Parser::Fld_22F_D1aContext * /*ctx*/) override { }
virtual void enterFld_12a_D1a(SwiftMtParser_MT566Parser::Fld_12a_D1aContext * /*ctx*/) override { }
virtual void exitFld_12a_D1a(SwiftMtParser_MT566Parser::Fld_12a_D1aContext * /*ctx*/) override { }
virtual void enterFld_11A_D1a(SwiftMtParser_MT566Parser::Fld_11A_D1aContext * /*ctx*/) override { }
virtual void exitFld_11A_D1a(SwiftMtParser_MT566Parser::Fld_11A_D1aContext * /*ctx*/) override { }
virtual void enterFld_98A_D1a(SwiftMtParser_MT566Parser::Fld_98A_D1aContext * /*ctx*/) override { }
virtual void exitFld_98A_D1a(SwiftMtParser_MT566Parser::Fld_98A_D1aContext * /*ctx*/) override { }
virtual void enterFld_90a_D1a(SwiftMtParser_MT566Parser::Fld_90a_D1aContext * /*ctx*/) override { }
virtual void exitFld_90a_D1a(SwiftMtParser_MT566Parser::Fld_90a_D1aContext * /*ctx*/) override { }
virtual void enterFld_92A_D1a(SwiftMtParser_MT566Parser::Fld_92A_D1aContext * /*ctx*/) override { }
virtual void exitFld_92A_D1a(SwiftMtParser_MT566Parser::Fld_92A_D1aContext * /*ctx*/) override { }
virtual void enterFld_36B_D1a(SwiftMtParser_MT566Parser::Fld_36B_D1aContext * /*ctx*/) override { }
virtual void exitFld_36B_D1a(SwiftMtParser_MT566Parser::Fld_36B_D1aContext * /*ctx*/) override { }
virtual void enterFld_16S_D1a(SwiftMtParser_MT566Parser::Fld_16S_D1aContext * /*ctx*/) override { }
virtual void exitFld_16S_D1a(SwiftMtParser_MT566Parser::Fld_16S_D1aContext * /*ctx*/) override { }
virtual void enterFld_36B_D1(SwiftMtParser_MT566Parser::Fld_36B_D1Context * /*ctx*/) override { }
virtual void exitFld_36B_D1(SwiftMtParser_MT566Parser::Fld_36B_D1Context * /*ctx*/) override { }
virtual void enterFld_94a_D1(SwiftMtParser_MT566Parser::Fld_94a_D1Context * /*ctx*/) override { }
virtual void exitFld_94a_D1(SwiftMtParser_MT566Parser::Fld_94a_D1Context * /*ctx*/) override { }
virtual void enterFld_22F_D1(SwiftMtParser_MT566Parser::Fld_22F_D1Context * /*ctx*/) override { }
virtual void exitFld_22F_D1(SwiftMtParser_MT566Parser::Fld_22F_D1Context * /*ctx*/) override { }
virtual void enterFld_11A_D1(SwiftMtParser_MT566Parser::Fld_11A_D1Context * /*ctx*/) override { }
virtual void exitFld_11A_D1(SwiftMtParser_MT566Parser::Fld_11A_D1Context * /*ctx*/) override { }
virtual void enterFld_90a_D1(SwiftMtParser_MT566Parser::Fld_90a_D1Context * /*ctx*/) override { }
virtual void exitFld_90a_D1(SwiftMtParser_MT566Parser::Fld_90a_D1Context * /*ctx*/) override { }
virtual void enterFld_92a_D1(SwiftMtParser_MT566Parser::Fld_92a_D1Context * /*ctx*/) override { }
virtual void exitFld_92a_D1(SwiftMtParser_MT566Parser::Fld_92a_D1Context * /*ctx*/) override { }
virtual void enterFld_98a_D1(SwiftMtParser_MT566Parser::Fld_98a_D1Context * /*ctx*/) override { }
virtual void exitFld_98a_D1(SwiftMtParser_MT566Parser::Fld_98a_D1Context * /*ctx*/) override { }
virtual void enterFld_16R_D1b(SwiftMtParser_MT566Parser::Fld_16R_D1bContext * /*ctx*/) override { }
virtual void exitFld_16R_D1b(SwiftMtParser_MT566Parser::Fld_16R_D1bContext * /*ctx*/) override { }
virtual void enterFld_95a_D1b(SwiftMtParser_MT566Parser::Fld_95a_D1bContext * /*ctx*/) override { }
virtual void exitFld_95a_D1b(SwiftMtParser_MT566Parser::Fld_95a_D1bContext * /*ctx*/) override { }
virtual void enterFld_97A_D1b(SwiftMtParser_MT566Parser::Fld_97A_D1bContext * /*ctx*/) override { }
virtual void exitFld_97A_D1b(SwiftMtParser_MT566Parser::Fld_97A_D1bContext * /*ctx*/) override { }
virtual void enterFld_20C_D1b(SwiftMtParser_MT566Parser::Fld_20C_D1bContext * /*ctx*/) override { }
virtual void exitFld_20C_D1b(SwiftMtParser_MT566Parser::Fld_20C_D1bContext * /*ctx*/) override { }
virtual void enterFld_16S_D1b(SwiftMtParser_MT566Parser::Fld_16S_D1bContext * /*ctx*/) override { }
virtual void exitFld_16S_D1b(SwiftMtParser_MT566Parser::Fld_16S_D1bContext * /*ctx*/) override { }
virtual void enterFld_16S_D1(SwiftMtParser_MT566Parser::Fld_16S_D1Context * /*ctx*/) override { }
virtual void exitFld_16S_D1(SwiftMtParser_MT566Parser::Fld_16S_D1Context * /*ctx*/) override { }
virtual void enterFld_16R_D2(SwiftMtParser_MT566Parser::Fld_16R_D2Context * /*ctx*/) override { }
virtual void exitFld_16R_D2(SwiftMtParser_MT566Parser::Fld_16R_D2Context * /*ctx*/) override { }
virtual void enterFld_22a_D2(SwiftMtParser_MT566Parser::Fld_22a_D2Context * /*ctx*/) override { }
virtual void exitFld_22a_D2(SwiftMtParser_MT566Parser::Fld_22a_D2Context * /*ctx*/) override { }
virtual void enterFld_94C_D2(SwiftMtParser_MT566Parser::Fld_94C_D2Context * /*ctx*/) override { }
virtual void exitFld_94C_D2(SwiftMtParser_MT566Parser::Fld_94C_D2Context * /*ctx*/) override { }
virtual void enterFld_97a_D2(SwiftMtParser_MT566Parser::Fld_97a_D2Context * /*ctx*/) override { }
virtual void exitFld_97a_D2(SwiftMtParser_MT566Parser::Fld_97a_D2Context * /*ctx*/) override { }
virtual void enterFld_16R_D2a(SwiftMtParser_MT566Parser::Fld_16R_D2aContext * /*ctx*/) override { }
virtual void exitFld_16R_D2a(SwiftMtParser_MT566Parser::Fld_16R_D2aContext * /*ctx*/) override { }
virtual void enterFld_95a_D2a(SwiftMtParser_MT566Parser::Fld_95a_D2aContext * /*ctx*/) override { }
virtual void exitFld_95a_D2a(SwiftMtParser_MT566Parser::Fld_95a_D2aContext * /*ctx*/) override { }
virtual void enterFld_97a_D2a(SwiftMtParser_MT566Parser::Fld_97a_D2aContext * /*ctx*/) override { }
virtual void exitFld_97a_D2a(SwiftMtParser_MT566Parser::Fld_97a_D2aContext * /*ctx*/) override { }
virtual void enterFld_20C_D2a(SwiftMtParser_MT566Parser::Fld_20C_D2aContext * /*ctx*/) override { }
virtual void exitFld_20C_D2a(SwiftMtParser_MT566Parser::Fld_20C_D2aContext * /*ctx*/) override { }
virtual void enterFld_16S_D2a(SwiftMtParser_MT566Parser::Fld_16S_D2aContext * /*ctx*/) override { }
virtual void exitFld_16S_D2a(SwiftMtParser_MT566Parser::Fld_16S_D2aContext * /*ctx*/) override { }
virtual void enterFld_19B_D2(SwiftMtParser_MT566Parser::Fld_19B_D2Context * /*ctx*/) override { }
virtual void exitFld_19B_D2(SwiftMtParser_MT566Parser::Fld_19B_D2Context * /*ctx*/) override { }
virtual void enterFld_98a_D2(SwiftMtParser_MT566Parser::Fld_98a_D2Context * /*ctx*/) override { }
virtual void exitFld_98a_D2(SwiftMtParser_MT566Parser::Fld_98a_D2Context * /*ctx*/) override { }
virtual void enterFld_92a_D2(SwiftMtParser_MT566Parser::Fld_92a_D2Context * /*ctx*/) override { }
virtual void exitFld_92a_D2(SwiftMtParser_MT566Parser::Fld_92a_D2Context * /*ctx*/) override { }
virtual void enterFld_90a_D2(SwiftMtParser_MT566Parser::Fld_90a_D2Context * /*ctx*/) override { }
virtual void exitFld_90a_D2(SwiftMtParser_MT566Parser::Fld_90a_D2Context * /*ctx*/) override { }
virtual void enterFld_16R_D2b(SwiftMtParser_MT566Parser::Fld_16R_D2bContext * /*ctx*/) override { }
virtual void exitFld_16R_D2b(SwiftMtParser_MT566Parser::Fld_16R_D2bContext * /*ctx*/) override { }
virtual void enterFld_20C_D2b(SwiftMtParser_MT566Parser::Fld_20C_D2bContext * /*ctx*/) override { }
virtual void exitFld_20C_D2b(SwiftMtParser_MT566Parser::Fld_20C_D2bContext * /*ctx*/) override { }
virtual void enterFld_98a_D2b(SwiftMtParser_MT566Parser::Fld_98a_D2bContext * /*ctx*/) override { }
virtual void exitFld_98a_D2b(SwiftMtParser_MT566Parser::Fld_98a_D2bContext * /*ctx*/) override { }
virtual void enterFld_16S_D2b(SwiftMtParser_MT566Parser::Fld_16S_D2bContext * /*ctx*/) override { }
virtual void exitFld_16S_D2b(SwiftMtParser_MT566Parser::Fld_16S_D2bContext * /*ctx*/) override { }
virtual void enterFld_16S_D2(SwiftMtParser_MT566Parser::Fld_16S_D2Context * /*ctx*/) override { }
virtual void exitFld_16S_D2(SwiftMtParser_MT566Parser::Fld_16S_D2Context * /*ctx*/) override { }
virtual void enterFld_16S_D(SwiftMtParser_MT566Parser::Fld_16S_DContext * /*ctx*/) override { }
virtual void exitFld_16S_D(SwiftMtParser_MT566Parser::Fld_16S_DContext * /*ctx*/) override { }
virtual void enterFld_16R_E(SwiftMtParser_MT566Parser::Fld_16R_EContext * /*ctx*/) override { }
virtual void exitFld_16R_E(SwiftMtParser_MT566Parser::Fld_16R_EContext * /*ctx*/) override { }
virtual void enterFld_70E_E(SwiftMtParser_MT566Parser::Fld_70E_EContext * /*ctx*/) override { }
virtual void exitFld_70E_E(SwiftMtParser_MT566Parser::Fld_70E_EContext * /*ctx*/) override { }
virtual void enterFld_95a_E(SwiftMtParser_MT566Parser::Fld_95a_EContext * /*ctx*/) override { }
virtual void exitFld_95a_E(SwiftMtParser_MT566Parser::Fld_95a_EContext * /*ctx*/) override { }
virtual void enterFld_16S_E(SwiftMtParser_MT566Parser::Fld_16S_EContext * /*ctx*/) override { }
virtual void exitFld_16S_E(SwiftMtParser_MT566Parser::Fld_16S_EContext * /*ctx*/) override { }
virtual void enterFld_20C_A_C(SwiftMtParser_MT566Parser::Fld_20C_A_CContext * /*ctx*/) override { }
virtual void exitFld_20C_A_C(SwiftMtParser_MT566Parser::Fld_20C_A_CContext * /*ctx*/) override { }
virtual void enterFld_23G_A_G(SwiftMtParser_MT566Parser::Fld_23G_A_GContext * /*ctx*/) override { }
virtual void exitFld_23G_A_G(SwiftMtParser_MT566Parser::Fld_23G_A_GContext * /*ctx*/) override { }
virtual void enterFld_22F_A_F(SwiftMtParser_MT566Parser::Fld_22F_A_FContext * /*ctx*/) override { }
virtual void exitFld_22F_A_F(SwiftMtParser_MT566Parser::Fld_22F_A_FContext * /*ctx*/) override { }
virtual void enterFld_98a_A_A(SwiftMtParser_MT566Parser::Fld_98a_A_AContext * /*ctx*/) override { }
virtual void exitFld_98a_A_A(SwiftMtParser_MT566Parser::Fld_98a_A_AContext * /*ctx*/) override { }
virtual void enterFld_98a_A_C(SwiftMtParser_MT566Parser::Fld_98a_A_CContext * /*ctx*/) override { }
virtual void exitFld_98a_A_C(SwiftMtParser_MT566Parser::Fld_98a_A_CContext * /*ctx*/) override { }
virtual void enterFld_22F_A1_F(SwiftMtParser_MT566Parser::Fld_22F_A1_FContext * /*ctx*/) override { }
virtual void exitFld_22F_A1_F(SwiftMtParser_MT566Parser::Fld_22F_A1_FContext * /*ctx*/) override { }
virtual void enterFld_13a_A1_A(SwiftMtParser_MT566Parser::Fld_13a_A1_AContext * /*ctx*/) override { }
virtual void exitFld_13a_A1_A(SwiftMtParser_MT566Parser::Fld_13a_A1_AContext * /*ctx*/) override { }
virtual void enterFld_13a_A1_B(SwiftMtParser_MT566Parser::Fld_13a_A1_BContext * /*ctx*/) override { }
virtual void exitFld_13a_A1_B(SwiftMtParser_MT566Parser::Fld_13a_A1_BContext * /*ctx*/) override { }
virtual void enterFld_20C_A1_C(SwiftMtParser_MT566Parser::Fld_20C_A1_CContext * /*ctx*/) override { }
virtual void exitFld_20C_A1_C(SwiftMtParser_MT566Parser::Fld_20C_A1_CContext * /*ctx*/) override { }
virtual void enterFld_95a_B_P(SwiftMtParser_MT566Parser::Fld_95a_B_PContext * /*ctx*/) override { }
virtual void exitFld_95a_B_P(SwiftMtParser_MT566Parser::Fld_95a_B_PContext * /*ctx*/) override { }
virtual void enterFld_95a_B_R(SwiftMtParser_MT566Parser::Fld_95a_B_RContext * /*ctx*/) override { }
virtual void exitFld_95a_B_R(SwiftMtParser_MT566Parser::Fld_95a_B_RContext * /*ctx*/) override { }
virtual void enterFld_97A_B_A(SwiftMtParser_MT566Parser::Fld_97A_B_AContext * /*ctx*/) override { }
virtual void exitFld_97A_B_A(SwiftMtParser_MT566Parser::Fld_97A_B_AContext * /*ctx*/) override { }
virtual void enterFld_94a_B_B(SwiftMtParser_MT566Parser::Fld_94a_B_BContext * /*ctx*/) override { }
virtual void exitFld_94a_B_B(SwiftMtParser_MT566Parser::Fld_94a_B_BContext * /*ctx*/) override { }
virtual void enterFld_94a_B_C(SwiftMtParser_MT566Parser::Fld_94a_B_CContext * /*ctx*/) override { }
virtual void exitFld_94a_B_C(SwiftMtParser_MT566Parser::Fld_94a_B_CContext * /*ctx*/) override { }
virtual void enterFld_94a_B_F(SwiftMtParser_MT566Parser::Fld_94a_B_FContext * /*ctx*/) override { }
virtual void exitFld_94a_B_F(SwiftMtParser_MT566Parser::Fld_94a_B_FContext * /*ctx*/) override { }
virtual void enterFld_35B_B_B(SwiftMtParser_MT566Parser::Fld_35B_B_BContext * /*ctx*/) override { }
virtual void exitFld_35B_B_B(SwiftMtParser_MT566Parser::Fld_35B_B_BContext * /*ctx*/) override { }
virtual void enterFld_94B_B1_B(SwiftMtParser_MT566Parser::Fld_94B_B1_BContext * /*ctx*/) override { }
virtual void exitFld_94B_B1_B(SwiftMtParser_MT566Parser::Fld_94B_B1_BContext * /*ctx*/) override { }
virtual void enterFld_22F_B1_F(SwiftMtParser_MT566Parser::Fld_22F_B1_FContext * /*ctx*/) override { }
virtual void exitFld_22F_B1_F(SwiftMtParser_MT566Parser::Fld_22F_B1_FContext * /*ctx*/) override { }
virtual void enterFld_12a_B1_A(SwiftMtParser_MT566Parser::Fld_12a_B1_AContext * /*ctx*/) override { }
virtual void exitFld_12a_B1_A(SwiftMtParser_MT566Parser::Fld_12a_B1_AContext * /*ctx*/) override { }
virtual void enterFld_12a_B1_C(SwiftMtParser_MT566Parser::Fld_12a_B1_CContext * /*ctx*/) override { }
virtual void exitFld_12a_B1_C(SwiftMtParser_MT566Parser::Fld_12a_B1_CContext * /*ctx*/) override { }
virtual void enterFld_11A_B1_A(SwiftMtParser_MT566Parser::Fld_11A_B1_AContext * /*ctx*/) override { }
virtual void exitFld_11A_B1_A(SwiftMtParser_MT566Parser::Fld_11A_B1_AContext * /*ctx*/) override { }
virtual void enterFld_98A_B1_A(SwiftMtParser_MT566Parser::Fld_98A_B1_AContext * /*ctx*/) override { }
virtual void exitFld_98A_B1_A(SwiftMtParser_MT566Parser::Fld_98A_B1_AContext * /*ctx*/) override { }
virtual void enterFld_92a_B1_A(SwiftMtParser_MT566Parser::Fld_92a_B1_AContext * /*ctx*/) override { }
virtual void exitFld_92a_B1_A(SwiftMtParser_MT566Parser::Fld_92a_B1_AContext * /*ctx*/) override { }
virtual void enterFld_92a_B1_D(SwiftMtParser_MT566Parser::Fld_92a_B1_DContext * /*ctx*/) override { }
virtual void exitFld_92a_B1_D(SwiftMtParser_MT566Parser::Fld_92a_B1_DContext * /*ctx*/) override { }
virtual void enterFld_36B_B1_B(SwiftMtParser_MT566Parser::Fld_36B_B1_BContext * /*ctx*/) override { }
virtual void exitFld_36B_B1_B(SwiftMtParser_MT566Parser::Fld_36B_B1_BContext * /*ctx*/) override { }
virtual void enterFld_93a_B_B(SwiftMtParser_MT566Parser::Fld_93a_B_BContext * /*ctx*/) override { }
virtual void exitFld_93a_B_B(SwiftMtParser_MT566Parser::Fld_93a_B_BContext * /*ctx*/) override { }
virtual void enterFld_93a_B_C(SwiftMtParser_MT566Parser::Fld_93a_B_CContext * /*ctx*/) override { }
virtual void exitFld_93a_B_C(SwiftMtParser_MT566Parser::Fld_93a_B_CContext * /*ctx*/) override { }
virtual void enterFld_98a_C_A(SwiftMtParser_MT566Parser::Fld_98a_C_AContext * /*ctx*/) override { }
virtual void exitFld_98a_C_A(SwiftMtParser_MT566Parser::Fld_98a_C_AContext * /*ctx*/) override { }
virtual void enterFld_98a_C_B(SwiftMtParser_MT566Parser::Fld_98a_C_BContext * /*ctx*/) override { }
virtual void exitFld_98a_C_B(SwiftMtParser_MT566Parser::Fld_98a_C_BContext * /*ctx*/) override { }
virtual void enterFld_98a_C_C(SwiftMtParser_MT566Parser::Fld_98a_C_CContext * /*ctx*/) override { }
virtual void exitFld_98a_C_C(SwiftMtParser_MT566Parser::Fld_98a_C_CContext * /*ctx*/) override { }
virtual void enterFld_98a_C_E(SwiftMtParser_MT566Parser::Fld_98a_C_EContext * /*ctx*/) override { }
virtual void exitFld_98a_C_E(SwiftMtParser_MT566Parser::Fld_98a_C_EContext * /*ctx*/) override { }
virtual void enterFld_69a_C_A(SwiftMtParser_MT566Parser::Fld_69a_C_AContext * /*ctx*/) override { }
virtual void exitFld_69a_C_A(SwiftMtParser_MT566Parser::Fld_69a_C_AContext * /*ctx*/) override { }
virtual void enterFld_69a_C_B(SwiftMtParser_MT566Parser::Fld_69a_C_BContext * /*ctx*/) override { }
virtual void exitFld_69a_C_B(SwiftMtParser_MT566Parser::Fld_69a_C_BContext * /*ctx*/) override { }
virtual void enterFld_69a_C_C(SwiftMtParser_MT566Parser::Fld_69a_C_CContext * /*ctx*/) override { }
virtual void exitFld_69a_C_C(SwiftMtParser_MT566Parser::Fld_69a_C_CContext * /*ctx*/) override { }
virtual void enterFld_69a_C_D(SwiftMtParser_MT566Parser::Fld_69a_C_DContext * /*ctx*/) override { }
virtual void exitFld_69a_C_D(SwiftMtParser_MT566Parser::Fld_69a_C_DContext * /*ctx*/) override { }
virtual void enterFld_69a_C_E(SwiftMtParser_MT566Parser::Fld_69a_C_EContext * /*ctx*/) override { }
virtual void exitFld_69a_C_E(SwiftMtParser_MT566Parser::Fld_69a_C_EContext * /*ctx*/) override { }
virtual void enterFld_69a_C_F(SwiftMtParser_MT566Parser::Fld_69a_C_FContext * /*ctx*/) override { }
virtual void exitFld_69a_C_F(SwiftMtParser_MT566Parser::Fld_69a_C_FContext * /*ctx*/) override { }
virtual void enterFld_99A_C_A(SwiftMtParser_MT566Parser::Fld_99A_C_AContext * /*ctx*/) override { }
virtual void exitFld_99A_C_A(SwiftMtParser_MT566Parser::Fld_99A_C_AContext * /*ctx*/) override { }
virtual void enterFld_92a_C_A(SwiftMtParser_MT566Parser::Fld_92a_C_AContext * /*ctx*/) override { }
virtual void exitFld_92a_C_A(SwiftMtParser_MT566Parser::Fld_92a_C_AContext * /*ctx*/) override { }
virtual void enterFld_92a_C_F(SwiftMtParser_MT566Parser::Fld_92a_C_FContext * /*ctx*/) override { }
virtual void exitFld_92a_C_F(SwiftMtParser_MT566Parser::Fld_92a_C_FContext * /*ctx*/) override { }
virtual void enterFld_92a_C_K(SwiftMtParser_MT566Parser::Fld_92a_C_KContext * /*ctx*/) override { }
virtual void exitFld_92a_C_K(SwiftMtParser_MT566Parser::Fld_92a_C_KContext * /*ctx*/) override { }
virtual void enterFld_92a_C_P(SwiftMtParser_MT566Parser::Fld_92a_C_PContext * /*ctx*/) override { }
virtual void exitFld_92a_C_P(SwiftMtParser_MT566Parser::Fld_92a_C_PContext * /*ctx*/) override { }
virtual void enterFld_90a_C_A(SwiftMtParser_MT566Parser::Fld_90a_C_AContext * /*ctx*/) override { }
virtual void exitFld_90a_C_A(SwiftMtParser_MT566Parser::Fld_90a_C_AContext * /*ctx*/) override { }
virtual void enterFld_90a_C_B(SwiftMtParser_MT566Parser::Fld_90a_C_BContext * /*ctx*/) override { }
virtual void exitFld_90a_C_B(SwiftMtParser_MT566Parser::Fld_90a_C_BContext * /*ctx*/) override { }
virtual void enterFld_90a_C_L(SwiftMtParser_MT566Parser::Fld_90a_C_LContext * /*ctx*/) override { }
virtual void exitFld_90a_C_L(SwiftMtParser_MT566Parser::Fld_90a_C_LContext * /*ctx*/) override { }
virtual void enterFld_36a_C_B(SwiftMtParser_MT566Parser::Fld_36a_C_BContext * /*ctx*/) override { }
virtual void exitFld_36a_C_B(SwiftMtParser_MT566Parser::Fld_36a_C_BContext * /*ctx*/) override { }
virtual void enterFld_36a_C_C(SwiftMtParser_MT566Parser::Fld_36a_C_CContext * /*ctx*/) override { }
virtual void exitFld_36a_C_C(SwiftMtParser_MT566Parser::Fld_36a_C_CContext * /*ctx*/) override { }
virtual void enterFld_13a_C_A(SwiftMtParser_MT566Parser::Fld_13a_C_AContext * /*ctx*/) override { }
virtual void exitFld_13a_C_A(SwiftMtParser_MT566Parser::Fld_13a_C_AContext * /*ctx*/) override { }
virtual void enterFld_13a_C_B(SwiftMtParser_MT566Parser::Fld_13a_C_BContext * /*ctx*/) override { }
virtual void exitFld_13a_C_B(SwiftMtParser_MT566Parser::Fld_13a_C_BContext * /*ctx*/) override { }
virtual void enterFld_17B_C_B(SwiftMtParser_MT566Parser::Fld_17B_C_BContext * /*ctx*/) override { }
virtual void exitFld_17B_C_B(SwiftMtParser_MT566Parser::Fld_17B_C_BContext * /*ctx*/) override { }
virtual void enterFld_22F_C_F(SwiftMtParser_MT566Parser::Fld_22F_C_FContext * /*ctx*/) override { }
virtual void exitFld_22F_C_F(SwiftMtParser_MT566Parser::Fld_22F_C_FContext * /*ctx*/) override { }
virtual void enterFld_13A_D_A(SwiftMtParser_MT566Parser::Fld_13A_D_AContext * /*ctx*/) override { }
virtual void exitFld_13A_D_A(SwiftMtParser_MT566Parser::Fld_13A_D_AContext * /*ctx*/) override { }
virtual void enterFld_22a_D_F(SwiftMtParser_MT566Parser::Fld_22a_D_FContext * /*ctx*/) override { }
virtual void exitFld_22a_D_F(SwiftMtParser_MT566Parser::Fld_22a_D_FContext * /*ctx*/) override { }
virtual void enterFld_22a_D_H(SwiftMtParser_MT566Parser::Fld_22a_D_HContext * /*ctx*/) override { }
virtual void exitFld_22a_D_H(SwiftMtParser_MT566Parser::Fld_22a_D_HContext * /*ctx*/) override { }
virtual void enterFld_11A_D_A(SwiftMtParser_MT566Parser::Fld_11A_D_AContext * /*ctx*/) override { }
virtual void exitFld_11A_D_A(SwiftMtParser_MT566Parser::Fld_11A_D_AContext * /*ctx*/) override { }
virtual void enterFld_98a_D_A(SwiftMtParser_MT566Parser::Fld_98a_D_AContext * /*ctx*/) override { }
virtual void exitFld_98a_D_A(SwiftMtParser_MT566Parser::Fld_98a_D_AContext * /*ctx*/) override { }
virtual void enterFld_98a_D_B(SwiftMtParser_MT566Parser::Fld_98a_D_BContext * /*ctx*/) override { }
virtual void exitFld_98a_D_B(SwiftMtParser_MT566Parser::Fld_98a_D_BContext * /*ctx*/) override { }
virtual void enterFld_98a_D_C(SwiftMtParser_MT566Parser::Fld_98a_D_CContext * /*ctx*/) override { }
virtual void exitFld_98a_D_C(SwiftMtParser_MT566Parser::Fld_98a_D_CContext * /*ctx*/) override { }
virtual void enterFld_98a_D_E(SwiftMtParser_MT566Parser::Fld_98a_D_EContext * /*ctx*/) override { }
virtual void exitFld_98a_D_E(SwiftMtParser_MT566Parser::Fld_98a_D_EContext * /*ctx*/) override { }
virtual void enterFld_69a_D_A(SwiftMtParser_MT566Parser::Fld_69a_D_AContext * /*ctx*/) override { }
virtual void exitFld_69a_D_A(SwiftMtParser_MT566Parser::Fld_69a_D_AContext * /*ctx*/) override { }
virtual void enterFld_69a_D_B(SwiftMtParser_MT566Parser::Fld_69a_D_BContext * /*ctx*/) override { }
virtual void exitFld_69a_D_B(SwiftMtParser_MT566Parser::Fld_69a_D_BContext * /*ctx*/) override { }
virtual void enterFld_69a_D_C(SwiftMtParser_MT566Parser::Fld_69a_D_CContext * /*ctx*/) override { }
virtual void exitFld_69a_D_C(SwiftMtParser_MT566Parser::Fld_69a_D_CContext * /*ctx*/) override { }
virtual void enterFld_69a_D_D(SwiftMtParser_MT566Parser::Fld_69a_D_DContext * /*ctx*/) override { }
virtual void exitFld_69a_D_D(SwiftMtParser_MT566Parser::Fld_69a_D_DContext * /*ctx*/) override { }
virtual void enterFld_69a_D_E(SwiftMtParser_MT566Parser::Fld_69a_D_EContext * /*ctx*/) override { }
virtual void exitFld_69a_D_E(SwiftMtParser_MT566Parser::Fld_69a_D_EContext * /*ctx*/) override { }
virtual void enterFld_69a_D_F(SwiftMtParser_MT566Parser::Fld_69a_D_FContext * /*ctx*/) override { }
virtual void exitFld_69a_D_F(SwiftMtParser_MT566Parser::Fld_69a_D_FContext * /*ctx*/) override { }
virtual void enterFld_92a_D_A(SwiftMtParser_MT566Parser::Fld_92a_D_AContext * /*ctx*/) override { }
virtual void exitFld_92a_D_A(SwiftMtParser_MT566Parser::Fld_92a_D_AContext * /*ctx*/) override { }
virtual void enterFld_92a_D_F(SwiftMtParser_MT566Parser::Fld_92a_D_FContext * /*ctx*/) override { }
virtual void exitFld_92a_D_F(SwiftMtParser_MT566Parser::Fld_92a_D_FContext * /*ctx*/) override { }
virtual void enterFld_92a_D_H(SwiftMtParser_MT566Parser::Fld_92a_D_HContext * /*ctx*/) override { }
virtual void exitFld_92a_D_H(SwiftMtParser_MT566Parser::Fld_92a_D_HContext * /*ctx*/) override { }
virtual void enterFld_92a_D_J(SwiftMtParser_MT566Parser::Fld_92a_D_JContext * /*ctx*/) override { }
virtual void exitFld_92a_D_J(SwiftMtParser_MT566Parser::Fld_92a_D_JContext * /*ctx*/) override { }
virtual void enterFld_92a_D_R(SwiftMtParser_MT566Parser::Fld_92a_D_RContext * /*ctx*/) override { }
virtual void exitFld_92a_D_R(SwiftMtParser_MT566Parser::Fld_92a_D_RContext * /*ctx*/) override { }
virtual void enterFld_90a_D_A(SwiftMtParser_MT566Parser::Fld_90a_D_AContext * /*ctx*/) override { }
virtual void exitFld_90a_D_A(SwiftMtParser_MT566Parser::Fld_90a_D_AContext * /*ctx*/) override { }
virtual void enterFld_90a_D_B(SwiftMtParser_MT566Parser::Fld_90a_D_BContext * /*ctx*/) override { }
virtual void exitFld_90a_D_B(SwiftMtParser_MT566Parser::Fld_90a_D_BContext * /*ctx*/) override { }
virtual void enterFld_94B_D_B(SwiftMtParser_MT566Parser::Fld_94B_D_BContext * /*ctx*/) override { }
virtual void exitFld_94B_D_B(SwiftMtParser_MT566Parser::Fld_94B_D_BContext * /*ctx*/) override { }
virtual void enterFld_22a_D1_F(SwiftMtParser_MT566Parser::Fld_22a_D1_FContext * /*ctx*/) override { }
virtual void exitFld_22a_D1_F(SwiftMtParser_MT566Parser::Fld_22a_D1_FContext * /*ctx*/) override { }
virtual void enterFld_22a_D1_H(SwiftMtParser_MT566Parser::Fld_22a_D1_HContext * /*ctx*/) override { }
virtual void exitFld_22a_D1_H(SwiftMtParser_MT566Parser::Fld_22a_D1_HContext * /*ctx*/) override { }
virtual void enterFld_35B_D1_B(SwiftMtParser_MT566Parser::Fld_35B_D1_BContext * /*ctx*/) override { }
virtual void exitFld_35B_D1_B(SwiftMtParser_MT566Parser::Fld_35B_D1_BContext * /*ctx*/) override { }
virtual void enterFld_94B_D1a_B(SwiftMtParser_MT566Parser::Fld_94B_D1a_BContext * /*ctx*/) override { }
virtual void exitFld_94B_D1a_B(SwiftMtParser_MT566Parser::Fld_94B_D1a_BContext * /*ctx*/) override { }
virtual void enterFld_22F_D1a_F(SwiftMtParser_MT566Parser::Fld_22F_D1a_FContext * /*ctx*/) override { }
virtual void exitFld_22F_D1a_F(SwiftMtParser_MT566Parser::Fld_22F_D1a_FContext * /*ctx*/) override { }
virtual void enterFld_12a_D1a_A(SwiftMtParser_MT566Parser::Fld_12a_D1a_AContext * /*ctx*/) override { }
virtual void exitFld_12a_D1a_A(SwiftMtParser_MT566Parser::Fld_12a_D1a_AContext * /*ctx*/) override { }
virtual void enterFld_12a_D1a_C(SwiftMtParser_MT566Parser::Fld_12a_D1a_CContext * /*ctx*/) override { }
virtual void exitFld_12a_D1a_C(SwiftMtParser_MT566Parser::Fld_12a_D1a_CContext * /*ctx*/) override { }
virtual void enterFld_11A_D1a_A(SwiftMtParser_MT566Parser::Fld_11A_D1a_AContext * /*ctx*/) override { }
virtual void exitFld_11A_D1a_A(SwiftMtParser_MT566Parser::Fld_11A_D1a_AContext * /*ctx*/) override { }
virtual void enterFld_98A_D1a_A(SwiftMtParser_MT566Parser::Fld_98A_D1a_AContext * /*ctx*/) override { }
virtual void exitFld_98A_D1a_A(SwiftMtParser_MT566Parser::Fld_98A_D1a_AContext * /*ctx*/) override { }
virtual void enterFld_90a_D1a_A(SwiftMtParser_MT566Parser::Fld_90a_D1a_AContext * /*ctx*/) override { }
virtual void exitFld_90a_D1a_A(SwiftMtParser_MT566Parser::Fld_90a_D1a_AContext * /*ctx*/) override { }
virtual void enterFld_90a_D1a_B(SwiftMtParser_MT566Parser::Fld_90a_D1a_BContext * /*ctx*/) override { }
virtual void exitFld_90a_D1a_B(SwiftMtParser_MT566Parser::Fld_90a_D1a_BContext * /*ctx*/) override { }
virtual void enterFld_92A_D1a_A(SwiftMtParser_MT566Parser::Fld_92A_D1a_AContext * /*ctx*/) override { }
virtual void exitFld_92A_D1a_A(SwiftMtParser_MT566Parser::Fld_92A_D1a_AContext * /*ctx*/) override { }
virtual void enterFld_36B_D1a_B(SwiftMtParser_MT566Parser::Fld_36B_D1a_BContext * /*ctx*/) override { }
virtual void exitFld_36B_D1a_B(SwiftMtParser_MT566Parser::Fld_36B_D1a_BContext * /*ctx*/) override { }
virtual void enterFld_36B_D1_B(SwiftMtParser_MT566Parser::Fld_36B_D1_BContext * /*ctx*/) override { }
virtual void exitFld_36B_D1_B(SwiftMtParser_MT566Parser::Fld_36B_D1_BContext * /*ctx*/) override { }
virtual void enterFld_94a_D1_B(SwiftMtParser_MT566Parser::Fld_94a_D1_BContext * /*ctx*/) override { }
virtual void exitFld_94a_D1_B(SwiftMtParser_MT566Parser::Fld_94a_D1_BContext * /*ctx*/) override { }
virtual void enterFld_94a_D1_C(SwiftMtParser_MT566Parser::Fld_94a_D1_CContext * /*ctx*/) override { }
virtual void exitFld_94a_D1_C(SwiftMtParser_MT566Parser::Fld_94a_D1_CContext * /*ctx*/) override { }
virtual void enterFld_94a_D1_F(SwiftMtParser_MT566Parser::Fld_94a_D1_FContext * /*ctx*/) override { }
virtual void exitFld_94a_D1_F(SwiftMtParser_MT566Parser::Fld_94a_D1_FContext * /*ctx*/) override { }
virtual void enterFld_22F_D1_F(SwiftMtParser_MT566Parser::Fld_22F_D1_FContext * /*ctx*/) override { }
virtual void exitFld_22F_D1_F(SwiftMtParser_MT566Parser::Fld_22F_D1_FContext * /*ctx*/) override { }
virtual void enterFld_11A_D1_A(SwiftMtParser_MT566Parser::Fld_11A_D1_AContext * /*ctx*/) override { }
virtual void exitFld_11A_D1_A(SwiftMtParser_MT566Parser::Fld_11A_D1_AContext * /*ctx*/) override { }
virtual void enterFld_90a_D1_A(SwiftMtParser_MT566Parser::Fld_90a_D1_AContext * /*ctx*/) override { }
virtual void exitFld_90a_D1_A(SwiftMtParser_MT566Parser::Fld_90a_D1_AContext * /*ctx*/) override { }
virtual void enterFld_90a_D1_B(SwiftMtParser_MT566Parser::Fld_90a_D1_BContext * /*ctx*/) override { }
virtual void exitFld_90a_D1_B(SwiftMtParser_MT566Parser::Fld_90a_D1_BContext * /*ctx*/) override { }
virtual void enterFld_90a_D1_F(SwiftMtParser_MT566Parser::Fld_90a_D1_FContext * /*ctx*/) override { }
virtual void exitFld_90a_D1_F(SwiftMtParser_MT566Parser::Fld_90a_D1_FContext * /*ctx*/) override { }
virtual void enterFld_90a_D1_J(SwiftMtParser_MT566Parser::Fld_90a_D1_JContext * /*ctx*/) override { }
virtual void exitFld_90a_D1_J(SwiftMtParser_MT566Parser::Fld_90a_D1_JContext * /*ctx*/) override { }
virtual void enterFld_90a_D1_K(SwiftMtParser_MT566Parser::Fld_90a_D1_KContext * /*ctx*/) override { }
virtual void exitFld_90a_D1_K(SwiftMtParser_MT566Parser::Fld_90a_D1_KContext * /*ctx*/) override { }
virtual void enterFld_90a_D1_L(SwiftMtParser_MT566Parser::Fld_90a_D1_LContext * /*ctx*/) override { }
virtual void exitFld_90a_D1_L(SwiftMtParser_MT566Parser::Fld_90a_D1_LContext * /*ctx*/) override { }
virtual void enterFld_92a_D1_A(SwiftMtParser_MT566Parser::Fld_92a_D1_AContext * /*ctx*/) override { }
virtual void exitFld_92a_D1_A(SwiftMtParser_MT566Parser::Fld_92a_D1_AContext * /*ctx*/) override { }
virtual void enterFld_92a_D1_D(SwiftMtParser_MT566Parser::Fld_92a_D1_DContext * /*ctx*/) override { }
virtual void exitFld_92a_D1_D(SwiftMtParser_MT566Parser::Fld_92a_D1_DContext * /*ctx*/) override { }
virtual void enterFld_92a_D1_F(SwiftMtParser_MT566Parser::Fld_92a_D1_FContext * /*ctx*/) override { }
virtual void exitFld_92a_D1_F(SwiftMtParser_MT566Parser::Fld_92a_D1_FContext * /*ctx*/) override { }
virtual void enterFld_92a_D1_L(SwiftMtParser_MT566Parser::Fld_92a_D1_LContext * /*ctx*/) override { }
virtual void exitFld_92a_D1_L(SwiftMtParser_MT566Parser::Fld_92a_D1_LContext * /*ctx*/) override { }
virtual void enterFld_92a_D1_M(SwiftMtParser_MT566Parser::Fld_92a_D1_MContext * /*ctx*/) override { }
virtual void exitFld_92a_D1_M(SwiftMtParser_MT566Parser::Fld_92a_D1_MContext * /*ctx*/) override { }
virtual void enterFld_92a_D1_N(SwiftMtParser_MT566Parser::Fld_92a_D1_NContext * /*ctx*/) override { }
virtual void exitFld_92a_D1_N(SwiftMtParser_MT566Parser::Fld_92a_D1_NContext * /*ctx*/) override { }
virtual void enterFld_98a_D1_A(SwiftMtParser_MT566Parser::Fld_98a_D1_AContext * /*ctx*/) override { }
virtual void exitFld_98a_D1_A(SwiftMtParser_MT566Parser::Fld_98a_D1_AContext * /*ctx*/) override { }
virtual void enterFld_98a_D1_B(SwiftMtParser_MT566Parser::Fld_98a_D1_BContext * /*ctx*/) override { }
virtual void exitFld_98a_D1_B(SwiftMtParser_MT566Parser::Fld_98a_D1_BContext * /*ctx*/) override { }
virtual void enterFld_98a_D1_C(SwiftMtParser_MT566Parser::Fld_98a_D1_CContext * /*ctx*/) override { }
virtual void exitFld_98a_D1_C(SwiftMtParser_MT566Parser::Fld_98a_D1_CContext * /*ctx*/) override { }
virtual void enterFld_98a_D1_E(SwiftMtParser_MT566Parser::Fld_98a_D1_EContext * /*ctx*/) override { }
virtual void exitFld_98a_D1_E(SwiftMtParser_MT566Parser::Fld_98a_D1_EContext * /*ctx*/) override { }
virtual void enterFld_95a_D1b_C(SwiftMtParser_MT566Parser::Fld_95a_D1b_CContext * /*ctx*/) override { }
virtual void exitFld_95a_D1b_C(SwiftMtParser_MT566Parser::Fld_95a_D1b_CContext * /*ctx*/) override { }
virtual void enterFld_95a_D1b_P(SwiftMtParser_MT566Parser::Fld_95a_D1b_PContext * /*ctx*/) override { }
virtual void exitFld_95a_D1b_P(SwiftMtParser_MT566Parser::Fld_95a_D1b_PContext * /*ctx*/) override { }
virtual void enterFld_95a_D1b_Q(SwiftMtParser_MT566Parser::Fld_95a_D1b_QContext * /*ctx*/) override { }
virtual void exitFld_95a_D1b_Q(SwiftMtParser_MT566Parser::Fld_95a_D1b_QContext * /*ctx*/) override { }
virtual void enterFld_95a_D1b_R(SwiftMtParser_MT566Parser::Fld_95a_D1b_RContext * /*ctx*/) override { }
virtual void exitFld_95a_D1b_R(SwiftMtParser_MT566Parser::Fld_95a_D1b_RContext * /*ctx*/) override { }
virtual void enterFld_95a_D1b_S(SwiftMtParser_MT566Parser::Fld_95a_D1b_SContext * /*ctx*/) override { }
virtual void exitFld_95a_D1b_S(SwiftMtParser_MT566Parser::Fld_95a_D1b_SContext * /*ctx*/) override { }
virtual void enterFld_97A_D1b_A(SwiftMtParser_MT566Parser::Fld_97A_D1b_AContext * /*ctx*/) override { }
virtual void exitFld_97A_D1b_A(SwiftMtParser_MT566Parser::Fld_97A_D1b_AContext * /*ctx*/) override { }
virtual void enterFld_20C_D1b_C(SwiftMtParser_MT566Parser::Fld_20C_D1b_CContext * /*ctx*/) override { }
virtual void exitFld_20C_D1b_C(SwiftMtParser_MT566Parser::Fld_20C_D1b_CContext * /*ctx*/) override { }
virtual void enterFld_22a_D2_F(SwiftMtParser_MT566Parser::Fld_22a_D2_FContext * /*ctx*/) override { }
virtual void exitFld_22a_D2_F(SwiftMtParser_MT566Parser::Fld_22a_D2_FContext * /*ctx*/) override { }
virtual void enterFld_22a_D2_H(SwiftMtParser_MT566Parser::Fld_22a_D2_HContext * /*ctx*/) override { }
virtual void exitFld_22a_D2_H(SwiftMtParser_MT566Parser::Fld_22a_D2_HContext * /*ctx*/) override { }
virtual void enterFld_94C_D2_C(SwiftMtParser_MT566Parser::Fld_94C_D2_CContext * /*ctx*/) override { }
virtual void exitFld_94C_D2_C(SwiftMtParser_MT566Parser::Fld_94C_D2_CContext * /*ctx*/) override { }
virtual void enterFld_97a_D2_A(SwiftMtParser_MT566Parser::Fld_97a_D2_AContext * /*ctx*/) override { }
virtual void exitFld_97a_D2_A(SwiftMtParser_MT566Parser::Fld_97a_D2_AContext * /*ctx*/) override { }
virtual void enterFld_97a_D2_E(SwiftMtParser_MT566Parser::Fld_97a_D2_EContext * /*ctx*/) override { }
virtual void exitFld_97a_D2_E(SwiftMtParser_MT566Parser::Fld_97a_D2_EContext * /*ctx*/) override { }
virtual void enterFld_95a_D2a_P(SwiftMtParser_MT566Parser::Fld_95a_D2a_PContext * /*ctx*/) override { }
virtual void exitFld_95a_D2a_P(SwiftMtParser_MT566Parser::Fld_95a_D2a_PContext * /*ctx*/) override { }
virtual void enterFld_95a_D2a_Q(SwiftMtParser_MT566Parser::Fld_95a_D2a_QContext * /*ctx*/) override { }
virtual void exitFld_95a_D2a_Q(SwiftMtParser_MT566Parser::Fld_95a_D2a_QContext * /*ctx*/) override { }
virtual void enterFld_95a_D2a_R(SwiftMtParser_MT566Parser::Fld_95a_D2a_RContext * /*ctx*/) override { }
virtual void exitFld_95a_D2a_R(SwiftMtParser_MT566Parser::Fld_95a_D2a_RContext * /*ctx*/) override { }
virtual void enterFld_95a_D2a_S(SwiftMtParser_MT566Parser::Fld_95a_D2a_SContext * /*ctx*/) override { }
virtual void exitFld_95a_D2a_S(SwiftMtParser_MT566Parser::Fld_95a_D2a_SContext * /*ctx*/) override { }
virtual void enterFld_97a_D2a_A(SwiftMtParser_MT566Parser::Fld_97a_D2a_AContext * /*ctx*/) override { }
virtual void exitFld_97a_D2a_A(SwiftMtParser_MT566Parser::Fld_97a_D2a_AContext * /*ctx*/) override { }
virtual void enterFld_97a_D2a_E(SwiftMtParser_MT566Parser::Fld_97a_D2a_EContext * /*ctx*/) override { }
virtual void exitFld_97a_D2a_E(SwiftMtParser_MT566Parser::Fld_97a_D2a_EContext * /*ctx*/) override { }
virtual void enterFld_20C_D2a_C(SwiftMtParser_MT566Parser::Fld_20C_D2a_CContext * /*ctx*/) override { }
virtual void exitFld_20C_D2a_C(SwiftMtParser_MT566Parser::Fld_20C_D2a_CContext * /*ctx*/) override { }
virtual void enterFld_19B_D2_B(SwiftMtParser_MT566Parser::Fld_19B_D2_BContext * /*ctx*/) override { }
virtual void exitFld_19B_D2_B(SwiftMtParser_MT566Parser::Fld_19B_D2_BContext * /*ctx*/) override { }
virtual void enterFld_98a_D2_A(SwiftMtParser_MT566Parser::Fld_98a_D2_AContext * /*ctx*/) override { }
virtual void exitFld_98a_D2_A(SwiftMtParser_MT566Parser::Fld_98a_D2_AContext * /*ctx*/) override { }
virtual void enterFld_98a_D2_C(SwiftMtParser_MT566Parser::Fld_98a_D2_CContext * /*ctx*/) override { }
virtual void exitFld_98a_D2_C(SwiftMtParser_MT566Parser::Fld_98a_D2_CContext * /*ctx*/) override { }
virtual void enterFld_98a_D2_E(SwiftMtParser_MT566Parser::Fld_98a_D2_EContext * /*ctx*/) override { }
virtual void exitFld_98a_D2_E(SwiftMtParser_MT566Parser::Fld_98a_D2_EContext * /*ctx*/) override { }
virtual void enterFld_92a_D2_A(SwiftMtParser_MT566Parser::Fld_92a_D2_AContext * /*ctx*/) override { }
virtual void exitFld_92a_D2_A(SwiftMtParser_MT566Parser::Fld_92a_D2_AContext * /*ctx*/) override { }
virtual void enterFld_92a_D2_B(SwiftMtParser_MT566Parser::Fld_92a_D2_BContext * /*ctx*/) override { }
virtual void exitFld_92a_D2_B(SwiftMtParser_MT566Parser::Fld_92a_D2_BContext * /*ctx*/) override { }
virtual void enterFld_92a_D2_F(SwiftMtParser_MT566Parser::Fld_92a_D2_FContext * /*ctx*/) override { }
virtual void exitFld_92a_D2_F(SwiftMtParser_MT566Parser::Fld_92a_D2_FContext * /*ctx*/) override { }
virtual void enterFld_92a_D2_H(SwiftMtParser_MT566Parser::Fld_92a_D2_HContext * /*ctx*/) override { }
virtual void exitFld_92a_D2_H(SwiftMtParser_MT566Parser::Fld_92a_D2_HContext * /*ctx*/) override { }
virtual void enterFld_92a_D2_J(SwiftMtParser_MT566Parser::Fld_92a_D2_JContext * /*ctx*/) override { }
virtual void exitFld_92a_D2_J(SwiftMtParser_MT566Parser::Fld_92a_D2_JContext * /*ctx*/) override { }
virtual void enterFld_92a_D2_M(SwiftMtParser_MT566Parser::Fld_92a_D2_MContext * /*ctx*/) override { }
virtual void exitFld_92a_D2_M(SwiftMtParser_MT566Parser::Fld_92a_D2_MContext * /*ctx*/) override { }
virtual void enterFld_92a_D2_R(SwiftMtParser_MT566Parser::Fld_92a_D2_RContext * /*ctx*/) override { }
virtual void exitFld_92a_D2_R(SwiftMtParser_MT566Parser::Fld_92a_D2_RContext * /*ctx*/) override { }
virtual void enterFld_90a_D2_A(SwiftMtParser_MT566Parser::Fld_90a_D2_AContext * /*ctx*/) override { }
virtual void exitFld_90a_D2_A(SwiftMtParser_MT566Parser::Fld_90a_D2_AContext * /*ctx*/) override { }
virtual void enterFld_90a_D2_B(SwiftMtParser_MT566Parser::Fld_90a_D2_BContext * /*ctx*/) override { }
virtual void exitFld_90a_D2_B(SwiftMtParser_MT566Parser::Fld_90a_D2_BContext * /*ctx*/) override { }
virtual void enterFld_90a_D2_F(SwiftMtParser_MT566Parser::Fld_90a_D2_FContext * /*ctx*/) override { }
virtual void exitFld_90a_D2_F(SwiftMtParser_MT566Parser::Fld_90a_D2_FContext * /*ctx*/) override { }
virtual void enterFld_90a_D2_J(SwiftMtParser_MT566Parser::Fld_90a_D2_JContext * /*ctx*/) override { }
virtual void exitFld_90a_D2_J(SwiftMtParser_MT566Parser::Fld_90a_D2_JContext * /*ctx*/) override { }
virtual void enterFld_90a_D2_K(SwiftMtParser_MT566Parser::Fld_90a_D2_KContext * /*ctx*/) override { }
virtual void exitFld_90a_D2_K(SwiftMtParser_MT566Parser::Fld_90a_D2_KContext * /*ctx*/) override { }
virtual void enterFld_90a_D2_L(SwiftMtParser_MT566Parser::Fld_90a_D2_LContext * /*ctx*/) override { }
virtual void exitFld_90a_D2_L(SwiftMtParser_MT566Parser::Fld_90a_D2_LContext * /*ctx*/) override { }
virtual void enterFld_20C_D2b_C(SwiftMtParser_MT566Parser::Fld_20C_D2b_CContext * /*ctx*/) override { }
virtual void exitFld_20C_D2b_C(SwiftMtParser_MT566Parser::Fld_20C_D2b_CContext * /*ctx*/) override { }
virtual void enterFld_98a_D2b_A(SwiftMtParser_MT566Parser::Fld_98a_D2b_AContext * /*ctx*/) override { }
virtual void exitFld_98a_D2b_A(SwiftMtParser_MT566Parser::Fld_98a_D2b_AContext * /*ctx*/) override { }
virtual void enterFld_98a_D2b_C(SwiftMtParser_MT566Parser::Fld_98a_D2b_CContext * /*ctx*/) override { }
virtual void exitFld_98a_D2b_C(SwiftMtParser_MT566Parser::Fld_98a_D2b_CContext * /*ctx*/) override { }
virtual void enterFld_70E_E_E(SwiftMtParser_MT566Parser::Fld_70E_E_EContext * /*ctx*/) override { }
virtual void exitFld_70E_E_E(SwiftMtParser_MT566Parser::Fld_70E_E_EContext * /*ctx*/) override { }
virtual void enterFld_95a_E_P(SwiftMtParser_MT566Parser::Fld_95a_E_PContext * /*ctx*/) override { }
virtual void exitFld_95a_E_P(SwiftMtParser_MT566Parser::Fld_95a_E_PContext * /*ctx*/) override { }
virtual void enterFld_95a_E_Q(SwiftMtParser_MT566Parser::Fld_95a_E_QContext * /*ctx*/) override { }
virtual void exitFld_95a_E_Q(SwiftMtParser_MT566Parser::Fld_95a_E_QContext * /*ctx*/) override { }
virtual void enterFld_95a_E_R(SwiftMtParser_MT566Parser::Fld_95a_E_RContext * /*ctx*/) override { }
virtual void exitFld_95a_E_R(SwiftMtParser_MT566Parser::Fld_95a_E_RContext * /*ctx*/) override { }
virtual void enterEveryRule(antlr4::ParserRuleContext * /*ctx*/) override { }
virtual void exitEveryRule(antlr4::ParserRuleContext * /*ctx*/) override { }
virtual void visitTerminal(antlr4::tree::TerminalNode * /*node*/) override { }
virtual void visitErrorNode(antlr4::tree::ErrorNode * /*node*/) override { }
};
} // namespace message::definition::swift::mt::parsers::sr2018
| 65.846604 | 156 | 0.787189 | [
"vector"
] |
4fc57c9872a59717098584606da3f5aab8bf02e2 | 789 | h | C | DKPlugins/DKSFMLRml/DKSFMLRml.h | aquawicket/DigitalKnob | 9e5997a1f0314ede80cf66a9bf28dc6373cb5987 | [
"MIT"
] | 29 | 2015-05-03T06:23:22.000Z | 2022-02-10T15:16:26.000Z | DKPlugins/DKSFMLRml/DKSFMLRml.h | aquawicket/DigitalKnob | 9e5997a1f0314ede80cf66a9bf28dc6373cb5987 | [
"MIT"
] | 125 | 2016-02-28T06:13:49.000Z | 2022-01-04T11:50:08.000Z | DKPlugins/DKSFMLRml/DKSFMLRml.h | aquawicket/DigitalKnob | 9e5997a1f0314ede80cf66a9bf28dc6373cb5987 | [
"MIT"
] | 8 | 2016-12-04T02:29:34.000Z | 2022-01-04T01:11:25.000Z | #pragma once
#ifndef DKSDLRml_H
#define DKSDLRml_H
#include <RmlUi/Core.h>
#include "DK/DK.h"
#include "DKSDLWindow/DKSDLWindow.h"
#include "DKRml/DKRml.h"
#include "DKSDLRml/DKSDLRmlSystem.h"
#include "DKSDLRml/DKSDLRmlRenderer.h"
//#include "ShellRenderInterfaceOpenGL.h"
//#define RML_SHELL_RENDER 1
///////////////////////////////////////////
class DKSDLRml : public DKObjectT<DKSDLRml>
{
public:
bool Init();
bool End();
bool Handle(SDL_Event *event);
void Render();
void Update();
//void ProcessEvent(Rml::Core::Event& event);
DKSDLWindow* dkSdlWindow;
DKRml* dkRml;
#ifdef RML_SHELL_RENDER
ShellRenderInterfaceOpenGL* Renderer;
#else
RmlSDL2Renderer* Renderer;
#endif
RmlSDL2SystemInterface* SystemInterface;
};
REGISTER_OBJECT(DKSDLRml, true)
#endif //DKSDLRml_H | 20.230769 | 46 | 0.722433 | [
"render"
] |
4fcdebb6a79cf0b6907500eec97390ae70812f33 | 2,440 | h | C | experiments/PolicyManager_c++_jni/crypto/crypto.h | hansmy/Webinos-Platform | 43950daebc41cd985adba4efc5670b61336aca7f | [
"Apache-2.0"
] | 1 | 2015-08-06T20:08:14.000Z | 2015-08-06T20:08:14.000Z | experiments/PolicyManager_c++_jni/crypto/crypto.h | krishnabangalore/Webinos-Platform | 2ab4779112483a0213ae440118b1c2a3cf80c7bd | [
"Apache-2.0"
] | null | null | null | experiments/PolicyManager_c++_jni/crypto/crypto.h | krishnabangalore/Webinos-Platform | 2ab4779112483a0213ae440118b1c2a3cf80c7bd | [
"Apache-2.0"
] | null | null | null | /*******************************************************************************
* Copyright 2010 Telecom Italia SpA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
#ifndef CRYPTO_H
#define CRYPTO_H
#include "core/Environment.h"
#ifdef SYMBIAN
#include "sha2.h"
#endif
#include <openssl/bio.h>
#include "sys/uio.h"
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <string>
#include <vector>
#include "core/BondiDebug.h"
using namespace std;
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/rsa.h>
#define KEY_PRIVKEY 1
#define KEY_PUBKEY 2
#define KEY_CERT 3
#define IN_FILE 0
#define IN_MEM 1
#define BUFLEN 8192
string hex2str(unsigned long hexnum);
bool compareHashes(const char* paddedhash, int paddedhashlen, const char* hash, int hashlen);
int X509_PEM_decorator(const char * cert, int certlen, char* output);
//int X509_info(char *cert, int certlen)
vector<string> X509_info(char *cert, int certlen);
int sha1(const char *in, int len, char *dgst);
int sha256(const char *in, int len, char *dgst);
int toBase64 (unsigned char* input, int inputlen, char* output);
unsigned char b64conv(char chr);
int fromBase64 (unsigned char* input, int inputlen, char* output);
EVP_PKEY * load_key(const char* inkey, int keylen, char keytype);
int dsa_sign(const char* inkey, int keylen, char keytype, const char* data, int datalen, char* signature, const char* signaturefile);
int dsa_verify(const char* inkey, int keylen, char keytype, const char* signature, int signaturelen, const char* data, int datalen);
int rsa_sign(const char* inkey, int keylen, char keytype, const char* data, int datalen, char* signature, const char* signaturefile);
int rsa_verify(const char* inkey, int keylen, char keytype, const char* signature, int signaturelen, const char* data, int datalen);
#endif
| 31.282051 | 133 | 0.695902 | [
"vector"
] |
4fd1fbfdb7cb84098a8bae7301b814cf2ee564e3 | 667 | h | C | benchmark/large_random/simdjson_ondemand.h | mkleshchenok/simdjson | 79879802f9fa9cec17720b8412519f6cbbab5047 | [
"Apache-2.0"
] | 9,541 | 2019-02-21T00:32:22.000Z | 2020-03-20T00:06:57.000Z | benchmark/large_random/simdjson_ondemand.h | mkleshchenok/simdjson | 79879802f9fa9cec17720b8412519f6cbbab5047 | [
"Apache-2.0"
] | 1,084 | 2020-03-20T15:06:02.000Z | 2022-03-29T13:47:35.000Z | benchmark/large_random/simdjson_ondemand.h | mkleshchenok/simdjson | 79879802f9fa9cec17720b8412519f6cbbab5047 | [
"Apache-2.0"
] | 546 | 2019-02-21T03:19:22.000Z | 2020-03-19T11:56:58.000Z | #pragma once
#if SIMDJSON_EXCEPTIONS
#include "large_random.h"
namespace large_random {
using namespace simdjson;
struct simdjson_ondemand {
static constexpr diff_flags DiffFlags = diff_flags::NONE;
ondemand::parser parser{};
bool run(simdjson::padded_string &json, std::vector<point> &result) {
auto doc = parser.iterate(json);
for (ondemand::object coord : doc) {
result.emplace_back(json_benchmark::point{coord.find_field("x"), coord.find_field("y"), coord.find_field("z")});
}
return true;
}
};
BENCHMARK_TEMPLATE(large_random, simdjson_ondemand)->UseManualTime();
} // namespace large_random
#endif // SIMDJSON_EXCEPTIONS
| 22.233333 | 118 | 0.728636 | [
"object",
"vector"
] |
4fee5c71a814daa15b972298e4a24add85cac519 | 2,870 | h | C | System/Library/PrivateFrameworks/CoreSuggestionsInternals.framework/SGModel.h | lechium/iOS1351Headers | 6bed3dada5ffc20366b27f7f2300a24a48a6284e | [
"MIT"
] | 2 | 2021-11-02T09:23:27.000Z | 2022-03-28T08:21:57.000Z | System/Library/PrivateFrameworks/CoreSuggestionsInternals.framework/SGModel.h | lechium/iOS1351Headers | 6bed3dada5ffc20366b27f7f2300a24a48a6284e | [
"MIT"
] | null | null | null | System/Library/PrivateFrameworks/CoreSuggestionsInternals.framework/SGModel.h | lechium/iOS1351Headers | 6bed3dada5ffc20366b27f7f2300a24a48a6284e | [
"MIT"
] | 1 | 2022-03-28T08:21:59.000Z | 2022-03-28T08:21:59.000Z | /*
* This header is generated by classdump-dyld 1.5
* on Wednesday, October 27, 2021 at 3:16:38 PM Mountain Standard Time
* Operating System: Version 13.5.1 (Build 17F80)
* Image Source: /System/Library/PrivateFrameworks/CoreSuggestionsInternals.framework/CoreSuggestionsInternals
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley.
*/
#import <CoreSuggestionsInternals/CoreSuggestionsInternals-Structs.h>
#import <libobjc.A.dylib/PMLPlistAndChunksSerializableProtocol.h>
@protocol PMLTransformerProtocol, PMLRegressionModelProtocolPMLPlistAndChunksSerializableProtocol;
@class SGModelSource, NSString;
@interface SGModel : NSObject <PMLPlistAndChunksSerializableProtocol> {
id<PMLTransformerProtocol> _featurizer;
SGModelSource* _modelSource;
id<PMLRegressionModelProtocol><PMLPlistAndChunksSerializableProtocol> _model;
double _threshold;
NSString* _locale;
}
@property (readonly) id<PMLRegressionModelProtocol><PMLPlistAndChunksSerializableProtocol> model; //@synthesize model=_model - In the implementation block
@property (readonly) double threshold; //@synthesize threshold=_threshold - In the implementation block
@property (copy,readonly) NSString * locale; //@synthesize locale=_locale - In the implementation block
@property (readonly) unsigned long long hash;
@property (readonly) Class superclass;
@property (copy,readonly) NSString * description;
@property (copy,readonly) NSString * debugDescription;
+(id)trainingFeaturesOf:(id)arg1 inLanguage:(id)arg2 ;
+(id)transformerInstanceForLanguage:(id)arg1 ;
+(id)transformerInstanceForLanguage:(id)arg1 withObjective:(unsigned long long)arg2 ;
+(Class)modelClassForObjective:(unsigned long long)arg1 ;
+(id)trainingFeaturesOf:(id)arg1 inLanguage:(id)arg2 withObjective:(unsigned long long)arg3 ;
+(id)newTransformerInstanceForLanguage:(id)arg1 ;
+(id)modelForEntity:(id)arg1 type:(id)arg2 language:(id)arg3 class:(Class)arg4 ;
+(id)modelForName:(id)arg1 language:(id)arg2 ;
+(id)featurize:(id)arg1 ;
-(NSString *)locale;
-(id<PMLRegressionModelProtocol><PMLPlistAndChunksSerializableProtocol>)model;
-(double)threshold;
-(id)serialize;
-(id)toPlistWithChunks:(id)arg1 ;
-(id)initWithPlist:(id)arg1 chunks:(id)arg2 context:(id)arg3 ;
-(id)initWithModel:(id)arg1 decisionThreshold:(double)arg2 locale:(id)arg3 featurizer:(id)arg4 modelSource:(id)arg5 ;
-(id)_predict:(id)arg1 ;
-(id)predictForInput:(id)arg1 ;
-(id)trainingFeaturesOf:(id)arg1 ;
-(SGMFoundInMailModelType_)metricsFoundInMailModelType;
-(SGMSelfIdModelType_)metricsSelfIdModelType;
@end
| 52.181818 | 175 | 0.723345 | [
"model"
] |
4ff5834e8fb411ac69c65b2c39b18f57f9f01a72 | 1,652 | h | C | lonestar/experimental/ordered/avi/util/util.h | lineagech/Galois | 5c7c0abaf7253cb354e35a3836147a960a37ad5b | [
"BSD-3-Clause"
] | null | null | null | lonestar/experimental/ordered/avi/util/util.h | lineagech/Galois | 5c7c0abaf7253cb354e35a3836147a960a37ad5b | [
"BSD-3-Clause"
] | null | null | null | lonestar/experimental/ordered/avi/util/util.h | lineagech/Galois | 5c7c0abaf7253cb354e35a3836147a960a37ad5b | [
"BSD-3-Clause"
] | null | null | null | /*
* This file belongs to the Galois project, a C++ library for exploiting
* parallelism. The code is being released under the terms of the 3-Clause BSD
* License (a copy is located in LICENSE.txt at the top-level directory).
*
* Copyright (C) 2018, The University of Texas at Austin. All rights reserved.
* UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS
* SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF
* PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF
* DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH
* RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances
* shall University be liable for incidental, special, indirect, direct or
* consequential damages or loss of profits, interruption of business, or
* related expenses which may arise from use of Software or Documentation,
* including but not limited to those resulting from defects in Software and/or
* Documentation, or loss or inaccuracy of data of any kind.
*/
#ifndef UTIL_H
#define UTIL_H
#include <iostream>
#include <vector>
template <typename T>
std::ostream& operator<<(std::ostream& out, const std::vector<T>& v) {
out << "{ ";
for (typename std::vector<T>::const_iterator i = v.begin(); i != v.end();
++i) {
out << *i << ", ";
}
out << "}";
return out;
}
template <typename I>
void printIter(std::ostream& out, I begin, I end) {
out << "{ ";
for (I i = begin; i != end; ++i) {
out << *i << ", ";
}
out << "}" << std::endl;
}
#endif
| 34.416667 | 79 | 0.700363 | [
"vector"
] |
4ff747eeecfb2e9bdb33a6f10dae7b37ad778f42 | 9,846 | c | C | LUPFactLinSys.c | m-pikalov/mpi | 99e967d670e03ff5ecd5f2c3eedbb28b2a42f6fc | [
"MIT"
] | null | null | null | LUPFactLinSys.c | m-pikalov/mpi | 99e967d670e03ff5ecd5f2c3eedbb28b2a42f6fc | [
"MIT"
] | null | null | null | LUPFactLinSys.c | m-pikalov/mpi | 99e967d670e03ff5ecd5f2c3eedbb28b2a42f6fc | [
"MIT"
] | null | null | null | #include "mpi.h"
#include "stdlib.h"
#include "time.h"
#include "stdio.h"
#include "math.h"
int main(int argc, char *argv[]){
int size = 2500;
srand(time(NULL));
int procRank = 0, procNum = 0, nameLen = 0, i = 0, j = 0, k = 0;
char procName[MPI_MAX_PROCESSOR_NAME];
double startTime = 0, endTime = 0;
double* matrix;
double* vector;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &procNum);
MPI_Comm_rank(MPI_COMM_WORLD, &procRank);
MPI_Get_processor_name(procName, &nameLen);
MPI_Status Status;
fprintf(stderr, "Process %d on %s\n", procRank, procName);
if(procRank == 0){
matrix = (double*)malloc(size * size * sizeof(double));
vector = (double*)malloc(size * sizeof(double));
for(i = 0; i < size; ++i){
for(j = 0; j < size; ++j){
matrix[i * size + j] = rand() % 100000;
}
vector[i] = rand() % 100000;
}
/*for(i = 0; i < size; ++i){
for(j = 0; j < size; ++j){
printf("%.9f ", matrix[i * size + j]);
}
printf("\n");
}
printf("\n");
for(i = 0; i < size; ++i){
printf("%.9f ", vector[i]);
}
printf("\n\n");*/
}
startTime = MPI_Wtime();
if((size < procNum) && (procRank == 0)){
//TODO write sequential algorithm
free(matrix);
} else if(size >= procNum){
double* pivotRow;
int* sendCount = (int*)malloc(procNum * sizeof(int));
int* sendInd = (int*)malloc(size * sizeof(int));
int* localInd;
int* localTransposInd;
for(i = 0; i < procNum; ++i){
sendCount[i] = 0;
}
for(i = 0; i < size; ++i){
++(sendCount[i % procNum]);
sendInd[i] = i % procNum;
}
int numberOfRows = sendCount[procRank];
free(sendCount);
localInd = (int*)malloc(numberOfRows * sizeof(int));
localTransposInd = (int*)malloc(numberOfRows * sizeof(int));
int ind = 0;
for(i = 0; i < size; ++i){
if(sendInd[i] == procRank){
localInd[ind] = i;
localTransposInd[ind] = i;
++ind;
}
}
double* subMatrix = (double*)malloc(numberOfRows * size * sizeof(double));
if(procRank == 0){
for(i = 0; i < numberOfRows; ++i){
for(j = 0; j < size; ++j){
subMatrix[i * size + j] = matrix[localInd[i] * size + j];
}
}
for(i = 0; i < size; ++i){
if(sendInd[i] != 0){
MPI_Send(matrix + i * size, size, MPI_DOUBLE, sendInd[i], i, MPI_COMM_WORLD);
}
}
} else {
for(i = 0; i < numberOfRows; ++i){
MPI_Recv(subMatrix + i * size, size, MPI_DOUBLE, 0, localInd[i], MPI_COMM_WORLD, &Status);
}
}
if(procRank == 0){
free(matrix);
}
for(i = 0; i < size; ++i){
int pivotRank = 0;
double pivotVal = 0;
int pivotInd = -1;
double pivot[3];
double bufPivot[2];
if(procRank == 0){
for(j = 0; j < numberOfRows; ++j){
if((localInd[j] >= i) && (fabs(subMatrix[j * size + i]) > pivotVal)){
pivotVal = fabs(subMatrix[j * size + i]);
pivotInd = localInd[j];
}
}
for(j = 1; j < procNum; ++j){
MPI_Recv(&bufPivot, 2, MPI_DOUBLE, j, i, MPI_COMM_WORLD, &Status);
if((int)(round(bufPivot[1]) >= 0) && (bufPivot[0] > pivotVal)){
pivotRank = j;
pivotVal = bufPivot[0];
pivotInd = round(bufPivot[1]);
}
}
pivot[0] = pivotVal;
pivot[1] = (double)pivotInd;
pivot[2] = (double)pivotRank;
} else {
for(j = 0; j < numberOfRows; ++j){
if((localInd[j] >= i ) && (fabs(subMatrix[j * size + i]) > pivotVal)){
pivotVal = fabs(subMatrix[j * size + i]);
pivotInd = localInd[j];
}
}
bufPivot[0] = pivotVal;
bufPivot[1] = (double)pivotInd;
MPI_Send(&bufPivot, 2, MPI_DOUBLE, 0, i, MPI_COMM_WORLD);
}
MPI_Bcast(&pivot, 3, MPI_DOUBLE, 0, MPI_COMM_WORLD);
if((int)round(pivot[2]) != sendInd[i]){
if(procRank == (int)round(pivot[2])){
for(j = 0; j < numberOfRows; ++j){
if(localInd[j] == (int)round(pivot[1])){
localInd[j] = i;
break;
}
}
}
if(procRank == sendInd[i]){
for(j = 0; j < numberOfRows; ++j){
if(localInd[j] == i){
localInd[j] = (int)round(pivot[1]);
break;
}
}
}
} else {
if(procRank == sendInd[i]){
int bufIndexOne = 0;
int bufIndexTwo = 0;
for(j = 0; j < numberOfRows; ++j){
if(localInd[j] == i){
bufIndexOne = j;
}
if(localInd[j] == (int)round(pivot[1])){
bufIndexTwo = j;
}
}
localInd[bufIndexOne] = (int)round(pivot[1]);
localInd[bufIndexTwo] = i;
}
}
sendInd[(int)round(pivot[1])] = sendInd[i];
sendInd[i] = (int)round(pivot[2]);
pivotRow = (double*)malloc(size * sizeof(double));
if(procRank == (int)round(pivot[2])){
for(j = 0; j < numberOfRows; ++j){
if(localInd[j] == i){
for(k = 0; k < size; ++k){
pivotRow[k] = subMatrix[j * size + k];
}
break;
}
}
}
MPI_Bcast(pivotRow, size, MPI_DOUBLE, (int)round(pivot[2]), MPI_COMM_WORLD);
for(j = 0; j < numberOfRows; ++j){
if(localInd[j] > i){
subMatrix[j * size + i] = subMatrix[j * size + i] / pivotRow[i];
for(k = i + 1; k < size; ++k){
subMatrix[j * size + k] -= subMatrix[j * size + i] * pivotRow[k];
}
}
}
MPI_Barrier(MPI_COMM_WORLD);
free(pivotRow);
}
if(procRank != 0){
vector = (double*)malloc(size * sizeof(double));
}
MPI_Bcast(vector, size, MPI_DOUBLE, 0, MPI_COMM_WORLD);
double* yVector = (double*)malloc(size * sizeof(double));
for(i = 0; i < size; ++i){
if(procRank == sendInd[i]){
for(j = 0; j < numberOfRows; ++j){
if(localInd[j] == i){
double buf = vector[localTransposInd[j]];
for(k = 0; k < i; ++k){
buf -= subMatrix[j * size + k] * yVector[k];
}
yVector[i] = buf;
if((i < size - 1) && (sendInd[i + 1] != sendInd[i])){
MPI_Ssend(yVector, i + 1, MPI_DOUBLE, sendInd[i + 1], 0, MPI_COMM_WORLD);
}
break;
}
}
}
if((procRank == sendInd[i + 1]) && (sendInd[i + 1] != sendInd[i]) && (i < size - 1)){
MPI_Recv(yVector, i + 1, MPI_DOUBLE, sendInd[i], 0, MPI_COMM_WORLD, &Status);
}
MPI_Barrier(MPI_COMM_WORLD);
}
free(vector);
MPI_Bcast(yVector, size, MPI_DOUBLE, sendInd[size - 1], MPI_COMM_WORLD);
double* xVector = (double*)malloc(size * sizeof(double));
for(i = size - 1; i >= 0; --i){
if(procRank == sendInd[i]){
for(j = 0; j < numberOfRows; ++j){
if(localInd[j] == i){
double buf = yVector[i];
for(k = i + 1; k < size; ++k){
buf -= subMatrix[j * size + k] * xVector[k];
}
buf /= subMatrix[j * size + i];
xVector[i] = buf;
if((i > 0) && (sendInd[i - 1] != sendInd[i])){
MPI_Ssend(xVector + i, size - i, MPI_DOUBLE, sendInd[i - 1], 0, MPI_COMM_WORLD);
}
}
}
}
if ((procRank == sendInd[i - 1]) && (sendInd[i - 1] != sendInd[i]) && (i > 0)){
MPI_Recv(xVector + i, size - i, MPI_DOUBLE, sendInd[i], 0, MPI_COMM_WORLD, &Status);
}
MPI_Barrier(MPI_COMM_WORLD);
}
if((procRank == sendInd[0]) && (sendInd[0] != 0)){
MPI_Ssend(xVector, size, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD);
}
if((procRank == 0) && (sendInd[0] != 0)){
MPI_Recv(xVector, size, MPI_DOUBLE, sendInd[0], 0, MPI_COMM_WORLD, &Status);
}
if(procRank == 0){
vector = xVector;
}
free(subMatrix);
free(sendInd);
free(localInd);
free(localTransposInd);
free(yVector);
if(procRank != 0){
free(xVector);
}
}
endTime = MPI_Wtime();
if(procRank == 0){
/*for(i = 0; i < size; ++i){
printf("%.9f ", vector[i]);
}
printf("\n");*/
printf("\nTime = %f\n", (endTime - startTime));
free(vector);
}
MPI_Finalize();
return 0;
} | 30.672897 | 106 | 0.419561 | [
"vector"
] |
4ff9b35e1ad3b1fd2b36fe0eab8dcdf9e36b83f9 | 88,661 | c | C | openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/mtd-utils/2.1.0+AUTOINC+b5027be5f4-r0/git/ubifs-utils/mkfs.ubifs/mkfs.ubifs.c | sotaoverride/backup | ca53a10b72295387ef4948a9289cb78ab70bc449 | [
"Apache-2.0"
] | null | null | null | openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/mtd-utils/2.1.0+AUTOINC+b5027be5f4-r0/git/ubifs-utils/mkfs.ubifs/mkfs.ubifs.c | sotaoverride/backup | ca53a10b72295387ef4948a9289cb78ab70bc449 | [
"Apache-2.0"
] | null | null | null | openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/mtd-utils/2.1.0+AUTOINC+b5027be5f4-r0/git/ubifs-utils/mkfs.ubifs/mkfs.ubifs.c | sotaoverride/backup | ca53a10b72295387ef4948a9289cb78ab70bc449 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2008 Nokia Corporation.
* Copyright (C) 2008 University of Szeged, Hungary
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Authors: Adrian Hunter
* Artem Bityutskiy
* Zoltan Sogor
*/
#define _XOPEN_SOURCE 500 /* For realpath() */
#include "mkfs.ubifs.h"
#include <crc32.h>
#include <sys/types.h>
#include "common.h"
#ifndef WITHOUT_XATTR
#include <sys/xattr.h>
#endif
#ifdef WITH_SELINUX
#include <selinux/label.h>
#include <selinux/selinux.h>
#endif
#include "crypto.h"
#include "fscrypt.h"
/* Size (prime number) of hash table for link counting */
#define HASH_TABLE_SIZE 10099
/* The node buffer must allow for worst case compression */
#define NODE_BUFFER_SIZE \
(UBIFS_DATA_NODE_SZ + UBIFS_BLOCK_SIZE * WORST_COMPR_FACTOR)
/* Default time granularity in nanoseconds */
#define DEFAULT_TIME_GRAN 1000000000
#ifdef WITH_SELINUX
#define XATTR_NAME_SELINUX "security.selinux"
static struct selabel_handle* sehnd;
static char* secontext;
#endif
/**
* struct idx_entry - index entry.
* @next: next index entry (NULL at end of list)
* @prev: previous index entry (NULL at beginning of list)
* @key: key
* @name: directory entry name used for sorting colliding keys by name
* @lnum: LEB number
* @offs: offset
* @len: length
*
* The index is recorded as a linked list which is sorted and used to create
* the bottom level of the on-flash index tree. The remaining levels of the
* index tree are each built from the level below.
*/
struct idx_entry
{
struct idx_entry* next;
struct idx_entry* prev;
union ubifs_key key;
char* name;
int name_len;
int lnum;
int offs;
int len;
};
/**
* struct inum_mapping - inode number mapping for link counting.
* @next: next inum_mapping (NULL at end of list)
* @prev: previous inum_mapping (NULL at beginning of list)
* @dev: source device on which the source inode number resides
* @inum: source inode number of the file
* @use_inum: target inode number of the file
* @use_nlink: number of links
* @path_name: a path name of the file
* @st: struct stat object containing inode attributes which have to be used
* when the inode is being created (actually only UID, GID, access
* mode, major and minor device numbers)
*
* If a file has more than one hard link, then the number of hard links that
* exist in the source directory hierarchy must be counted to exclude the
* possibility that the file is linked from outside the source directory
* hierarchy.
*
* The inum_mappings are stored in a hash_table of linked lists.
*/
struct inum_mapping
{
struct inum_mapping* next;
struct inum_mapping* prev;
dev_t dev;
ino_t inum;
ino_t use_inum;
unsigned int use_nlink;
char* path_name;
struct stat st;
};
/*
* Because we copy functions from the kernel, we use a subset of the UBIFS
* file-system description object struct ubifs_info.
*/
struct ubifs_info info_;
static struct ubifs_info* c = &info_;
static libubi_t ubi;
/* Debug levels are: 0 (none), 1 (statistics), 2 (files) ,3 (more details) */
int debug_level;
int verbose;
int yes;
static char* root;
static int root_len;
static struct fscrypt_context* root_fctx;
static struct stat root_st;
static char* output;
static int out_fd;
static int out_ubi;
static int squash_owner;
static int do_create_inum_attr;
static char* context;
static int context_len;
static struct stat context_st;
/* The 'head' (position) which nodes are written */
static int head_lnum;
static int head_offs;
static int head_flags;
/* The index list */
static struct idx_entry* idx_list_first;
static struct idx_entry* idx_list_last;
static size_t idx_cnt;
/* Global buffers */
static void* leb_buf;
static void* node_buf;
static void* block_buf;
/* Hash table for inode link counting */
static struct inum_mapping** hash_table;
/* Inode creation sequence number */
static unsigned long long creat_sqnum;
static const char* optstring =
"d:r:m:o:D:yh?vVe:c:g:f:Fp:k:x:X:j:R:l:j:UQqaK:b:P:C:";
static const struct option longopts[] = {{"root", 1, NULL, 'r'},
{"min-io-size", 1, NULL, 'm'},
{"leb-size", 1, NULL, 'e'},
{"max-leb-cnt", 1, NULL, 'c'},
{"output", 1, NULL, 'o'},
{"devtable", 1, NULL, 'D'},
{"yes", 0, NULL, 'y'},
{"help", 0, NULL, 'h'},
{"verbose", 0, NULL, 'v'},
{"version", 0, NULL, 'V'},
{"debug-level", 1, NULL, 'g'},
{"jrn-size", 1, NULL, 'j'},
{"reserved", 1, NULL, 'R'},
{"compr", 1, NULL, 'x'},
{"favor-percent", 1, NULL, 'X'},
{"fanout", 1, NULL, 'f'},
{"space-fixup", 0, NULL, 'F'},
{"keyhash", 1, NULL, 'k'},
{"log-lebs", 1, NULL, 'l'},
{"orph-lebs", 1, NULL, 'p'},
{"squash-uids", 0, NULL, 'U'},
{"set-inode-attr", 0, NULL, 'a'},
{"selinux", 1, NULL, 's'},
{"key", 1, NULL, 'K'},
{"key-descriptor", 1, NULL, 'b'},
{"padding", 1, NULL, 'P'},
{"cipher", 1, NULL, 'C'},
{NULL, 0, NULL, 0}};
static const char* helptext =
"Usage: mkfs.ubifs [OPTIONS] target\n"
"Make a UBIFS file system image from an existing directory tree\n\n"
"Examples:\n"
"Build file system from directory /opt/img, writting the result in the "
"ubifs.img file\n"
"\tmkfs.ubifs -m 512 -e 128KiB -c 100 -r /opt/img ubifs.img\n"
"The same, but writting directly to an UBI volume\n"
"\tmkfs.ubifs -r /opt/img /dev/ubi0_0\n"
"Creating an empty UBIFS filesystem on an UBI volume\n"
"\tmkfs.ubifs /dev/ubi0_0\n\n"
"Options:\n"
"-r, -d, --root=DIR build file system from directory DIR\n"
"-m, --min-io-size=SIZE minimum I/O unit size\n"
"-e, --leb-size=SIZE logical erase block size\n"
"-c, --max-leb-cnt=COUNT maximum logical erase block count\n"
"-o, --output=FILE output to FILE\n"
"-j, --jrn-size=SIZE journal size\n"
"-R, --reserved=SIZE how much space should be reserved for the "
"super-user\n"
"-x, --compr=TYPE compression type - \"lzo\", \"favor_lzo\", "
"\"zlib\" or\n"
" \"none\" (default: \"lzo\")\n"
"-X, --favor-percent may only be used with favor LZO compression and "
"defines\n"
" how many percent better zlib should compress to "
"make\n"
" mkfs.ubifs use zlib instead of LZO (default "
"20%)\n"
"-f, --fanout=NUM fanout NUM (default: 8)\n"
"-F, --space-fixup file-system free space has to be fixed up on "
"first mount\n"
" (requires kernel version 3.0 or greater)\n"
"-k, --keyhash=TYPE key hash type - \"r5\" or \"test\" (default: "
"\"r5\")\n"
"-p, --orph-lebs=COUNT count of erase blocks for orphans (default: 1)\n"
"-D, --devtable=FILE use device table FILE\n"
"-U, --squash-uids squash owners making all files owned by root\n"
"-l, --log-lebs=COUNT count of erase blocks for the log (used only "
"for\n"
" debugging)\n"
"-y, --yes assume the answer is \"yes\" for all questions\n"
"-v, --verbose verbose operation\n"
"-V, --version display version information\n"
"-g, --debug=LEVEL display debug information (0 - none, 1 - "
"statistics,\n"
" 2 - files, 3 - more details)\n"
"-a, --set-inum-attr create user.image-inode-number extended "
"attribute on files\n"
" added to the image. The attribute will contain "
"the inode\n"
" number the file has in the generated image.\n"
"-s, --selinux=FILE Selinux context file\n"
"-K, --key=FILE load an encryption key from a specified file.\n"
"-b, --key-descriptor=HEX specify the key descriptor as a hex string.\n"
"-P, --padding=NUM specify padding policy for encrypting filenames\n"
" (default = 4).\n"
"-C, --cipher=NAME Specify cipher to use for file level encryption\n"
" (default is \"AES-256-XTS\").\n"
"-h, --help display this help text\n\n"
"Note, SIZE is specified in bytes, but it may also be specified in "
"Kilobytes,\n"
"Megabytes, and Gigabytes if a KiB, MiB, or GiB suffix is used.\n\n"
"If you specify \"lzo\" or \"zlib\" compressors, mkfs.ubifs will use this "
"compressor\n"
"for all data. The \"none\" disables any data compression. The "
"\"favor_lzo\" is not\n"
"really a separate compressor. It is just a method of combining \"lzo\" "
"and \"zlib\"\n"
"compressors. Namely, mkfs.ubifs tries to compress data with both \"lzo\" "
"and \"zlib\"\n"
"compressors, then it compares which compressor is better. If \"zlib\" "
"compresses 20\n"
"or more percent better than \"lzo\", mkfs.ubifs chooses \"lzo\", "
"otherwise it chooses\n"
"\"zlib\". The \"--favor-percent\" may specify arbitrary threshold instead "
"of the\n"
"default 20%.\n\n"
"The -F parameter is used to set the \"fix up free space\" flag in the "
"superblock,\n"
"which forces UBIFS to \"fixup\" all the free space which it is going to "
"use. This\n"
"option is useful to work-around the problem of double free space "
"programming: if the\n"
"flasher program which flashes the UBI image is unable to skip NAND pages "
"containing\n"
"only 0xFF bytes, the effect is that some NAND pages are written to twice "
"- first time\n"
"when flashing the image and the second time when UBIFS is mounted and "
"writes useful\n"
"data there. A proper UBI-aware flasher should skip such NAND pages, "
"though. Note, this\n"
"flag may make the first mount very slow, because the \"free space fixup\" "
"procedure\n"
"takes time. This feature is supported by the Linux kernel starting from "
"version 3.0.\n";
/**
* make_path - make a path name from a directory and a name.
* @dir: directory path name
* @name: name
*/
static char* make_path(const char* dir, const char* name)
{
char* s;
xasprintf(&s, "%s%s%s", dir, dir[strlen(dir) - 1] == '/' ? "" : "/", name);
return s;
}
/**
* is_contained - determine if a file is beneath a directory.
* @file: file path name
* @dir: directory path name
*
* This function returns %1 if @file is accessible from the @dir directory and
* %0 otherwise. In case of error, returns %-1.
*/
static int is_contained(const char* file, const char* dir)
{
char* real_file = NULL;
char* real_dir = NULL;
char *file_base, *copy;
int ret = -1;
/* Make a copy of the file path because 'dirname()' can modify it */
copy = strdup(file);
if (!copy)
return -1;
file_base = dirname(copy);
/* Turn the paths into the canonical form */
real_file = xmalloc(PATH_MAX);
real_dir = xmalloc(PATH_MAX);
if (!realpath(file_base, real_file))
{
perror("Could not canonicalize file path");
goto out_free;
}
if (!realpath(dir, real_dir))
{
perror("Could not canonicalize directory");
goto out_free;
}
ret = !!strstr(real_file, real_dir);
out_free:
free(copy);
free(real_file);
free(real_dir);
return ret;
}
/**
* calc_min_log_lebs - calculate the minimum number of log LEBs needed.
* @max_bud_bytes: journal size (buds only)
*/
static int calc_min_log_lebs(unsigned long long max_bud_bytes)
{
int buds, log_lebs;
unsigned long long log_size;
buds = (max_bud_bytes + c->leb_size - 1) / c->leb_size;
log_size = ALIGN(UBIFS_REF_NODE_SZ, c->min_io_size);
log_size *= buds;
log_size += ALIGN(UBIFS_CS_NODE_SZ + UBIFS_REF_NODE_SZ * (c->jhead_cnt + 2),
c->min_io_size);
log_lebs = (log_size + c->leb_size - 1) / c->leb_size;
log_lebs += 1;
return log_lebs;
}
/**
* add_space_overhead - add UBIFS overhead.
* @size: flash space which should be visible to the user
*
* UBIFS has overhead, and if we need to reserve @size bytes for the user data,
* we have to reserve more flash space, to compensate the overhead. This
* function calculates and returns the amount of physical flash space which
* should be reserved to provide @size bytes for the user.
*/
static long long add_space_overhead(long long size)
{
int divisor, factor, f, max_idx_node_sz;
/*
* Do the opposite to what the 'ubifs_reported_space()' kernel UBIFS
* function does.
*/
max_idx_node_sz = ubifs_idx_node_sz(c, c->fanout);
f = c->fanout > 3 ? c->fanout >> 1 : 2;
divisor = UBIFS_BLOCK_SIZE;
factor = UBIFS_MAX_DATA_NODE_SZ;
factor += (max_idx_node_sz * 3) / (f - 1);
size *= factor;
return size / divisor;
}
static int validate_options(void)
{
int tmp;
if (!output)
return err_msg("no output file or UBI volume specified");
if (root)
{
tmp = is_contained(output, root);
if (tmp < 0)
return err_msg("failed to perform output file root check");
else if (tmp)
return err_msg("output file cannot be in the UBIFS root "
"directory");
}
if (!is_power_of_2(c->min_io_size))
return err_msg("min. I/O unit size should be power of 2");
if (c->leb_size < c->min_io_size)
return err_msg("min. I/O unit cannot be larger than LEB size");
if (c->leb_size < UBIFS_MIN_LEB_SZ)
return err_msg("too small LEB size %d, minimum is %d", c->leb_size,
UBIFS_MIN_LEB_SZ);
if (c->leb_size % c->min_io_size)
return err_msg("LEB should be multiple of min. I/O units");
if (c->leb_size % 8)
return err_msg("LEB size has to be multiple of 8");
if (c->leb_size > UBIFS_MAX_LEB_SZ)
return err_msg("too large LEB size %d, maximum is %d", c->leb_size,
UBIFS_MAX_LEB_SZ);
if (c->max_leb_cnt < UBIFS_MIN_LEB_CNT)
return err_msg("too low max. count of LEBs, minimum is %d",
UBIFS_MIN_LEB_CNT);
if (c->fanout < UBIFS_MIN_FANOUT)
return err_msg("too low fanout, minimum is %d", UBIFS_MIN_FANOUT);
tmp = c->leb_size - UBIFS_IDX_NODE_SZ;
tmp /= UBIFS_BRANCH_SZ + UBIFS_MAX_KEY_LEN;
if (c->fanout > tmp)
return err_msg("too high fanout, maximum is %d", tmp);
if (c->log_lebs < UBIFS_MIN_LOG_LEBS)
return err_msg("too few log LEBs, minimum is %d", UBIFS_MIN_LOG_LEBS);
if (c->log_lebs >= c->max_leb_cnt - UBIFS_MIN_LEB_CNT)
return err_msg("too many log LEBs, maximum is %d",
c->max_leb_cnt - UBIFS_MIN_LEB_CNT);
if (c->orph_lebs < UBIFS_MIN_ORPH_LEBS)
return err_msg("too few orphan LEBs, minimum is %d",
UBIFS_MIN_ORPH_LEBS);
if (c->orph_lebs >= c->max_leb_cnt - UBIFS_MIN_LEB_CNT)
return err_msg("too many orphan LEBs, maximum is %d",
c->max_leb_cnt - UBIFS_MIN_LEB_CNT);
tmp = UBIFS_SB_LEBS + UBIFS_MST_LEBS + c->log_lebs + c->lpt_lebs;
tmp += c->orph_lebs + 4;
if (tmp > c->max_leb_cnt)
return err_msg("too low max. count of LEBs, expected at "
"least %d",
tmp);
tmp = calc_min_log_lebs(c->max_bud_bytes);
if (c->log_lebs < calc_min_log_lebs(c->max_bud_bytes))
return err_msg("too few log LEBs, expected at least %d", tmp);
if (c->rp_size >= ((long long)c->leb_size * c->max_leb_cnt) / 2)
return err_msg("too much reserved space %lld", c->rp_size);
return 0;
}
/**
* get_multiplier - convert size specifier to an integer multiplier.
* @str: the size specifier string
*
* This function parses the @str size specifier, which may be one of
* 'KiB', 'MiB', or 'GiB' into an integer multiplier. Returns positive
* size multiplier in case of success and %-1 in case of failure.
*/
static int get_multiplier(const char* str)
{
if (!str)
return 1;
/* Remove spaces before the specifier */
while (*str == ' ' || *str == '\t')
str += 1;
if (!strcmp(str, "KiB"))
return 1024;
if (!strcmp(str, "MiB"))
return 1024 * 1024;
if (!strcmp(str, "GiB"))
return 1024 * 1024 * 1024;
return -1;
}
/**
* get_bytes - convert a string containing amount of bytes into an
* integer.
* @str: string to convert
*
* This function parses @str which may have one of 'KiB', 'MiB', or 'GiB' size
* specifiers. Returns positive amount of bytes in case of success and %-1 in
* case of failure.
*/
static long long get_bytes(const char* str)
{
char* endp;
long long bytes = strtoull(str, &endp, 0);
if (endp == str || bytes < 0)
return err_msg("incorrect amount of bytes: \"%s\"", str);
if (*endp != '\0')
{
int mult = get_multiplier(endp);
if (mult == -1)
return err_msg("bad size specifier: \"%s\" - "
"should be 'KiB', 'MiB' or 'GiB'",
endp);
bytes *= mult;
}
return bytes;
}
/**
* open_ubi - open the UBI volume.
* @node: name of the UBI volume character device to fetch information about
*
* Returns %0 in case of success and %-1 in case of failure
*/
static int open_ubi(const char* node)
{
struct stat st;
if (stat(node, &st) || !S_ISCHR(st.st_mode))
return -1;
ubi = libubi_open();
if (!ubi)
return -1;
if (ubi_get_vol_info(ubi, node, &c->vi))
return -1;
if (ubi_get_dev_info1(ubi, c->vi.dev_num, &c->di))
return -1;
return 0;
}
static void select_default_compr(void)
{
if (c->encrypted)
{
c->default_compr = UBIFS_COMPR_NONE;
return;
}
#ifdef WITHOUT_LZO
c->default_compr = UBIFS_COMPR_ZLIB;
#else
c->default_compr = UBIFS_COMPR_LZO;
#endif
}
static int get_options(int argc, char** argv)
{
int opt, i, fscrypt_flags = FS_POLICY_FLAGS_PAD_4;
const char *key_file = NULL, *key_desc = NULL;
const char* tbl_file = NULL;
struct stat st;
char* endp;
#ifdef WITH_CRYPTO
const char* cipher_name;
#endif
c->fanout = 8;
c->orph_lebs = 1;
c->key_hash = key_r5_hash;
c->key_len = UBIFS_SK_LEN;
c->favor_percent = 20;
c->lsave_cnt = 256;
c->leb_size = -1;
c->min_io_size = -1;
c->max_leb_cnt = -1;
c->max_bud_bytes = -1;
c->log_lebs = -1;
c->double_hash = 0;
c->encrypted = 0;
c->default_compr = -1;
while (1)
{
opt = getopt_long(argc, argv, optstring, longopts, &i);
if (opt == -1)
break;
switch (opt)
{
case 'r':
case 'd':
root_len = strlen(optarg);
root = xmalloc(root_len + 2);
/*
* The further code expects '/' at the end of the root
* UBIFS directory on the host.
*/
memcpy(root, optarg, root_len);
if (root[root_len - 1] != '/')
root[root_len++] = '/';
root[root_len] = 0;
/* Make sure the root directory exists */
if (stat(root, &st))
return sys_err_msg("bad root directory '%s'", root);
break;
case 'm':
c->min_io_size = get_bytes(optarg);
if (c->min_io_size <= 0)
return err_msg("bad min. I/O size");
break;
case 'e':
c->leb_size = get_bytes(optarg);
if (c->leb_size <= 0)
return err_msg("bad LEB size");
break;
case 'c':
c->max_leb_cnt = get_bytes(optarg);
if (c->max_leb_cnt <= 0)
return err_msg("bad maximum LEB count");
break;
case 'o':
output = xstrdup(optarg);
break;
case 'D':
tbl_file = optarg;
if (stat(tbl_file, &st) < 0)
return sys_err_msg("bad device table file '%s'", tbl_file);
break;
case 'y':
yes = 1;
break;
case 'h':
printf("%s", helptext);
exit(EXIT_SUCCESS);
case '?':
printf("%s", helptext);
#ifdef WITH_CRYPTO
printf("\n\nSupported ciphers:\n");
list_ciphers(stdout);
#endif
exit(-1);
case 'v':
verbose = 1;
break;
case 'V':
common_print_version();
exit(EXIT_SUCCESS);
case 'g':
debug_level = strtol(optarg, &endp, 0);
if (*endp != '\0' || endp == optarg || debug_level < 0 ||
debug_level > 3)
return err_msg("bad debugging level '%s'", optarg);
break;
case 'f':
c->fanout = strtol(optarg, &endp, 0);
if (*endp != '\0' || endp == optarg || c->fanout <= 0)
return err_msg("bad fanout %s", optarg);
break;
case 'F':
c->space_fixup = 1;
break;
case 'l':
c->log_lebs = strtol(optarg, &endp, 0);
if (*endp != '\0' || endp == optarg || c->log_lebs <= 0)
return err_msg("bad count of log LEBs '%s'", optarg);
break;
case 'p':
c->orph_lebs = strtol(optarg, &endp, 0);
if (*endp != '\0' || endp == optarg || c->orph_lebs <= 0)
return err_msg("bad orphan LEB count '%s'", optarg);
break;
case 'k':
if (strcmp(optarg, "r5") == 0)
{
c->key_hash = key_r5_hash;
c->key_hash_type = UBIFS_KEY_HASH_R5;
}
else if (strcmp(optarg, "test") == 0)
{
c->key_hash = key_test_hash;
c->key_hash_type = UBIFS_KEY_HASH_TEST;
}
else
return err_msg("bad key hash");
break;
case 'x':
if (strcmp(optarg, "none") == 0)
c->default_compr = UBIFS_COMPR_NONE;
else if (strcmp(optarg, "zlib") == 0)
c->default_compr = UBIFS_COMPR_ZLIB;
#ifndef WITHOUT_LZO
else if (strcmp(optarg, "favor_lzo") == 0)
{
c->default_compr = UBIFS_COMPR_LZO;
c->favor_lzo = 1;
}
else if (strcmp(optarg, "lzo") == 0)
{
c->default_compr = UBIFS_COMPR_LZO;
}
#endif
else
return err_msg("bad compressor name");
break;
case 'X':
#ifdef WITHOUT_LZO
return err_msg("built without LZO support");
#else
c->favor_percent = strtol(optarg, &endp, 0);
if (*endp != '\0' || endp == optarg || c->favor_percent <= 0 ||
c->favor_percent >= 100)
return err_msg("bad favor LZO percent '%s'", optarg);
#endif
break;
case 'j':
c->max_bud_bytes = get_bytes(optarg);
if (c->max_bud_bytes <= 0)
return err_msg("bad maximum amount of buds");
break;
case 'R':
c->rp_size = get_bytes(optarg);
if (c->rp_size < 0)
return err_msg("bad reserved bytes count");
break;
case 'U':
squash_owner = 1;
break;
case 'a':
do_create_inum_attr = 1;
break;
case 's':
context_len = strlen(optarg);
context = (char*)xmalloc(context_len + 1);
if (!context)
return err_msg("xmalloc failed\n");
memcpy(context, optarg, context_len);
/* Make sure root directory exists */
if (stat(context, &context_st))
return sys_err_msg("bad file context %s\n", context);
break;
case 'K':
if (key_file)
{
return err_msg("key file specified more than once");
}
key_file = optarg;
break;
case 'b':
if (key_desc)
{
return err_msg("key descriptor specified more than once");
}
key_desc = optarg;
break;
case 'P':
{
int error = 0;
unsigned long num;
num = simple_strtoul(optarg, &error);
if (error)
num = -1;
fscrypt_flags &= ~FS_POLICY_FLAGS_PAD_MASK;
switch (num)
{
case 4:
fscrypt_flags |= FS_POLICY_FLAGS_PAD_4;
break;
case 8:
fscrypt_flags |= FS_POLICY_FLAGS_PAD_8;
break;
case 16:
fscrypt_flags |= FS_POLICY_FLAGS_PAD_16;
break;
case 32:
fscrypt_flags |= FS_POLICY_FLAGS_PAD_32;
break;
default:
return errmsg("invalid padding policy '%s'", optarg);
}
break;
}
case 'C':
#ifdef WITH_CRYPTO
cipher_name = optarg;
#else
return err_msg("mkfs.ubifs was built without crypto support.");
#endif
break;
}
}
if (optind != argc && !output)
output = xstrdup(argv[optind]);
if (!output)
return err_msg("not output device or file specified");
out_ubi = !open_ubi(output);
if (out_ubi)
{
c->min_io_size = c->di.min_io_size;
c->leb_size = c->vi.leb_size;
if (c->max_leb_cnt == -1)
c->max_leb_cnt = c->vi.rsvd_lebs;
}
if (key_file || key_desc)
{
#ifdef WITH_CRYPTO
if (!key_file)
return err_msg("no key file specified");
c->double_hash = 1;
c->encrypted = 1;
if (cipher_name == NULL)
cipher_name = "AES-256-XTS";
root_fctx = init_fscrypt_context(cipher_name, fscrypt_flags, key_file,
key_desc);
if (!root_fctx)
return -1;
#else
return err_msg("mkfs.ubifs was built without crypto support.");
#endif
}
if (c->default_compr == -1)
select_default_compr();
if (c->min_io_size == -1)
return err_msg("min. I/O unit was not specified "
"(use -h for help)");
if (c->leb_size == -1)
return err_msg("LEB size was not specified (use -h for help)");
if (c->max_leb_cnt == -1)
return err_msg("Maximum count of LEBs was not specified "
"(use -h for help)");
if (c->max_bud_bytes == -1)
{
int lebs;
lebs = c->max_leb_cnt - UBIFS_SB_LEBS - UBIFS_MST_LEBS;
lebs -= c->orph_lebs;
if (c->log_lebs != -1)
lebs -= c->log_lebs;
else
lebs -= UBIFS_MIN_LOG_LEBS;
/*
* We do not know lprops geometry so far, so assume minimum
* count of lprops LEBs.
*/
lebs -= UBIFS_MIN_LPT_LEBS;
/* Make the journal about 12.5% of main area lebs */
c->max_bud_bytes = (lebs / 8) * (long long)c->leb_size;
/* Make the max journal size 8MiB */
if (c->max_bud_bytes > 8 * 1024 * 1024)
c->max_bud_bytes = 8 * 1024 * 1024;
if (c->max_bud_bytes < 4 * c->leb_size)
c->max_bud_bytes = 4 * c->leb_size;
}
if (c->log_lebs == -1)
{
c->log_lebs = calc_min_log_lebs(c->max_bud_bytes);
c->log_lebs += 2;
}
if (c->min_io_size < 8)
c->min_io_size = 8;
c->rp_size = add_space_overhead(c->rp_size);
if (verbose)
{
printf("mkfs.ubifs\n");
printf("\troot: %s\n", root);
printf("\tmin_io_size: %d\n", c->min_io_size);
printf("\tleb_size: %d\n", c->leb_size);
printf("\tmax_leb_cnt: %d\n", c->max_leb_cnt);
printf("\toutput: %s\n", output);
printf("\tjrn_size: %llu\n", c->max_bud_bytes);
printf("\treserved: %llu\n", c->rp_size);
switch (c->default_compr)
{
case UBIFS_COMPR_LZO:
printf("\tcompr: lzo\n");
break;
case UBIFS_COMPR_ZLIB:
printf("\tcompr: zlib\n");
break;
case UBIFS_COMPR_NONE:
printf("\tcompr: none\n");
break;
}
printf("\tkeyhash: %s\n",
(c->key_hash == key_r5_hash) ? "r5" : "test");
printf("\tfanout: %d\n", c->fanout);
printf("\torph_lebs: %d\n", c->orph_lebs);
printf("\tspace_fixup: %d\n", c->space_fixup);
printf("\tselinux file: %s\n", context);
}
if (validate_options())
return -1;
if (tbl_file && parse_devtable(tbl_file))
return err_msg("cannot parse device table file '%s'", tbl_file);
return 0;
}
/**
* prepare_node - fill in the common header.
* @node: node
* @len: node length
*/
static void prepare_node(void* node, int len)
{
uint32_t crc;
struct ubifs_ch* ch = node;
ch->magic = cpu_to_le32(UBIFS_NODE_MAGIC);
ch->len = cpu_to_le32(len);
ch->group_type = UBIFS_NO_NODE_GROUP;
ch->sqnum = cpu_to_le64(++c->max_sqnum);
ch->padding[0] = ch->padding[1] = 0;
crc = mtd_crc32(UBIFS_CRC32_INIT, node + 8, len - 8);
ch->crc = cpu_to_le32(crc);
}
/**
* write_leb - copy the image of a LEB to the output target.
* @lnum: LEB number
* @len: length of data in the buffer
* @buf: buffer (must be at least c->leb_size bytes)
*/
int write_leb(int lnum, int len, void* buf)
{
off_t pos = (off_t)lnum * c->leb_size;
dbg_msg(3, "LEB %d len %d", lnum, len);
memset(buf + len, 0xff, c->leb_size - len);
if (out_ubi)
if (ubi_leb_change_start(ubi, out_fd, lnum, c->leb_size))
return sys_err_msg("ubi_leb_change_start failed");
if (lseek(out_fd, pos, SEEK_SET) != pos)
return sys_err_msg("lseek failed seeking %lld", (long long)pos);
if (write(out_fd, buf, c->leb_size) != c->leb_size)
return sys_err_msg("write failed writing %d bytes at pos %lld",
c->leb_size, (long long)pos);
return 0;
}
/**
* write_empty_leb - copy the image of an empty LEB to the output target.
* @lnum: LEB number
*/
static int write_empty_leb(int lnum)
{
return write_leb(lnum, 0, leb_buf);
}
/**
* do_pad - pad a buffer to the minimum I/O size.
* @buf: buffer
* @len: buffer length
*/
static int do_pad(void* buf, int len)
{
int pad_len, alen = ALIGN(len, 8), wlen = ALIGN(alen, c->min_io_size);
uint32_t crc;
memset(buf + len, 0xff, alen - len);
pad_len = wlen - alen;
dbg_msg(3, "len %d pad_len %d", len, pad_len);
buf += alen;
if (pad_len >= (int)UBIFS_PAD_NODE_SZ)
{
struct ubifs_ch* ch = buf;
struct ubifs_pad_node* pad_node = buf;
ch->magic = cpu_to_le32(UBIFS_NODE_MAGIC);
ch->node_type = UBIFS_PAD_NODE;
ch->group_type = UBIFS_NO_NODE_GROUP;
ch->padding[0] = ch->padding[1] = 0;
ch->sqnum = cpu_to_le64(0);
ch->len = cpu_to_le32(UBIFS_PAD_NODE_SZ);
pad_len -= UBIFS_PAD_NODE_SZ;
pad_node->pad_len = cpu_to_le32(pad_len);
crc = mtd_crc32(UBIFS_CRC32_INIT, buf + 8, UBIFS_PAD_NODE_SZ - 8);
ch->crc = cpu_to_le32(crc);
memset(buf + UBIFS_PAD_NODE_SZ, 0, pad_len);
}
else if (pad_len > 0)
memset(buf, UBIFS_PADDING_BYTE, pad_len);
return wlen;
}
/**
* write_node - write a node to a LEB.
* @node: node
* @len: node length
* @lnum: LEB number
*/
static int write_node(void* node, int len, int lnum)
{
prepare_node(node, len);
memcpy(leb_buf, node, len);
len = do_pad(leb_buf, len);
return write_leb(lnum, len, leb_buf);
}
/**
* calc_dark - calculate LEB dark space size.
* @c: the UBIFS file-system description object
* @spc: amount of free and dirty space in the LEB
*
* This function calculates amount of dark space in an LEB which has @spc bytes
* of free and dirty space. Returns the calculations result.
*
* Dark space is the space which is not always usable - it depends on which
* nodes are written in which order. E.g., if an LEB has only 512 free bytes,
* it is dark space, because it cannot fit a large data node. So UBIFS cannot
* count on this LEB and treat these 512 bytes as usable because it is not true
* if, for example, only big chunks of uncompressible data will be written to
* the FS.
*/
static int calc_dark(struct ubifs_info* c, int spc)
{
if (spc < c->dark_wm)
return spc;
/*
* If we have slightly more space then the dark space watermark, we can
* anyway safely assume it we'll be able to write a node of the
* smallest size there.
*/
if (spc - c->dark_wm < (int)MIN_WRITE_SZ)
return spc - MIN_WRITE_SZ;
return c->dark_wm;
}
/**
* set_lprops - set the LEB property values for a LEB.
* @lnum: LEB number
* @offs: end offset of data in the LEB
* @flags: LEB property flags
*/
static void set_lprops(int lnum, int offs, int flags)
{
int i = lnum - c->main_first, free, dirty;
int a = max_t(int, c->min_io_size, 8);
free = c->leb_size - ALIGN(offs, a);
dirty = c->leb_size - free - ALIGN(offs, 8);
dbg_msg(3, "LEB %d free %d dirty %d flags %d", lnum, free, dirty, flags);
if (i < c->main_lebs)
{
c->lpt[i].free = free;
c->lpt[i].dirty = dirty;
c->lpt[i].flags = flags;
}
c->lst.total_free += free;
c->lst.total_dirty += dirty;
if (flags & LPROPS_INDEX)
c->lst.idx_lebs += 1;
else
{
int spc;
spc = free + dirty;
if (spc < c->dead_wm)
c->lst.total_dead += spc;
else
c->lst.total_dark += calc_dark(c, spc);
c->lst.total_used += c->leb_size - spc;
}
}
/**
* add_to_index - add a node key and position to the index.
* @key: node key
* @lnum: node LEB number
* @offs: node offset
* @len: node length
*/
static int add_to_index(union ubifs_key* key, char* name, int name_len,
int lnum, int offs, int len)
{
struct idx_entry* e;
dbg_msg(3, "LEB %d offs %d len %d", lnum, offs, len);
e = xmalloc(sizeof(struct idx_entry));
e->next = NULL;
e->prev = idx_list_last;
e->key = *key;
e->name = name;
e->name_len = name_len;
e->lnum = lnum;
e->offs = offs;
e->len = len;
if (!idx_list_first)
idx_list_first = e;
if (idx_list_last)
idx_list_last->next = e;
idx_list_last = e;
idx_cnt += 1;
return 0;
}
/**
* flush_nodes - write the current head and move the head to the next LEB.
*/
static int flush_nodes(void)
{
int len, err;
if (!head_offs)
return 0;
len = do_pad(leb_buf, head_offs);
err = write_leb(head_lnum, len, leb_buf);
if (err)
return err;
set_lprops(head_lnum, head_offs, head_flags);
head_lnum += 1;
head_offs = 0;
return 0;
}
/**
* reserve_space - reserve space for a node on the head.
* @len: node length
* @lnum: LEB number is returned here
* @offs: offset is returned here
*/
static int reserve_space(int len, int* lnum, int* offs)
{
int err;
if (len > c->leb_size - head_offs)
{
err = flush_nodes();
if (err)
return err;
}
*lnum = head_lnum;
*offs = head_offs;
head_offs += ALIGN(len, 8);
return 0;
}
/**
* add_node - write a node to the head.
* @key: node key
* @node: node
* @len: node length
*/
static int add_node(union ubifs_key* key, char* name, int name_len, void* node,
int len)
{
int err, lnum, offs, type = key_type(key);
if (type == UBIFS_DENT_KEY || type == UBIFS_XENT_KEY)
{
if (!name)
return err_msg("Directory entry or xattr "
"without name!");
}
else
{
if (name)
return err_msg("Name given for non dir/xattr node!");
}
prepare_node(node, len);
err = reserve_space(len, &lnum, &offs);
if (err)
return err;
memcpy(leb_buf + offs, node, len);
memset(leb_buf + offs + len, 0xff, ALIGN(len, 8) - len);
add_to_index(key, name, name_len, lnum, offs, len);
return 0;
}
static int add_xattr(struct ubifs_ino_node* host_ino, struct stat* st,
ino_t inum, char* name, const void* data,
unsigned int data_len)
{
struct ubifs_ino_node* ino;
struct ubifs_dent_node* xent;
struct qstr nm;
union ubifs_key xkey, nkey;
int len, ret;
nm.len = strlen(name);
nm.name = xmalloc(nm.len + 1);
memcpy(nm.name, name, nm.len + 1);
host_ino->xattr_cnt++;
host_ino->xattr_size += CALC_DENT_SIZE(nm.len);
host_ino->xattr_size += CALC_XATTR_BYTES(data_len);
host_ino->xattr_names += nm.len;
xent = xzalloc(sizeof(*xent) + nm.len + 1);
ino = xzalloc(sizeof(*ino) + data_len);
xent_key_init(c, &xkey, inum, &nm);
xent->ch.node_type = UBIFS_XENT_NODE;
key_write(&xkey, &xent->key);
len = UBIFS_XENT_NODE_SZ + nm.len + 1;
xent->ch.len = len;
xent->padding1 = 0;
xent->type = UBIFS_ITYPE_DIR;
xent->nlen = cpu_to_le16(nm.len);
memcpy(xent->name, nm.name, nm.len + 1);
inum = ++c->highest_inum;
creat_sqnum = ++c->max_sqnum;
xent->inum = cpu_to_le64(inum);
ret = add_node(&xkey, nm.name, nm.len, xent, len);
if (ret)
goto out;
ino->creat_sqnum = cpu_to_le64(creat_sqnum);
ino->nlink = cpu_to_le32(1);
/*
* The time fields are updated assuming the default time granularity
* of 1 second. To support finer granularities, utime() would be needed.
*/
ino->atime_sec = cpu_to_le64(st->st_atime);
ino->ctime_sec = cpu_to_le64(st->st_ctime);
ino->mtime_sec = cpu_to_le64(st->st_mtime);
ino->atime_nsec = 0;
ino->ctime_nsec = 0;
ino->mtime_nsec = 0;
ino->uid = cpu_to_le32(st->st_uid);
ino->gid = cpu_to_le32(st->st_gid);
ino->compr_type = cpu_to_le16(c->default_compr);
ino->ch.node_type = UBIFS_INO_NODE;
ino_key_init(&nkey, inum);
key_write(&nkey, &ino->key);
ino->size = cpu_to_le64(data_len);
ino->mode = cpu_to_le32(S_IFREG);
ino->data_len = cpu_to_le32(data_len);
ino->flags = cpu_to_le32(UBIFS_XATTR_FL);
if (data_len)
memcpy(&ino->data, data, data_len);
ret = add_node(&nkey, NULL, 0, ino, UBIFS_INO_NODE_SZ + data_len);
out:
free(xent);
free(ino);
return ret;
}
#ifdef WITHOUT_XATTR
static inline int create_inum_attr(ino_t inum, const char* name)
{
(void)inum;
(void)name;
return 0;
}
static inline int inode_add_xattr(struct ubifs_ino_node* host_ino,
const char* path_name, struct stat* st,
ino_t inum)
{
(void)host_ino;
(void)path_name;
(void)st;
(void)inum;
return 0;
}
#else
static int create_inum_attr(ino_t inum, const char* name)
{
char* str;
int ret;
if (!do_create_inum_attr)
return 0;
ret = asprintf(&str, "%llu", (unsigned long long)inum);
if (ret < 0)
return ret;
ret = lsetxattr(name, "user.image-inode-number", str, ret, 0);
free(str);
return ret;
}
static int inode_add_xattr(struct ubifs_ino_node* host_ino,
const char* path_name, struct stat* st, ino_t inum)
{
int ret;
void* buf = NULL;
ssize_t len;
ssize_t pos = 0;
len = llistxattr(path_name, NULL, 0);
if (len < 0)
{
if (errno == ENOENT || errno == EOPNOTSUPP)
return 0;
sys_err_msg("llistxattr failed on %s", path_name);
return len;
}
if (len == 0)
goto noxattr;
buf = xmalloc(len);
len = llistxattr(path_name, buf, len);
if (len < 0)
{
sys_err_msg("llistxattr failed on %s", path_name);
goto out_free;
}
while (pos < len)
{
char attrbuf[1024] = {};
char* name;
ssize_t attrsize;
name = buf + pos;
pos += strlen(name) + 1;
attrsize = lgetxattr(path_name, name, attrbuf, sizeof(attrbuf) - 1);
if (attrsize < 0)
{
sys_err_msg("lgetxattr failed on %s", path_name);
goto out_free;
}
if (!strcmp(name, "user.image-inode-number"))
{
ino_t inum_from_xattr;
inum_from_xattr = strtoull(attrbuf, NULL, 10);
if (inum != inum_from_xattr)
{
errno = EINVAL;
sys_err_msg("calculated inum (%llu) doesn't match inum from "
"xattr (%llu) size (%zd) on %s",
(unsigned long long)inum,
(unsigned long long)inum_from_xattr, attrsize,
path_name);
goto out_free;
}
continue;
}
ret = add_xattr(host_ino, st, inum, name, attrbuf, attrsize);
if (ret < 0)
goto out_free;
}
noxattr:
free(buf);
return 0;
out_free:
free(buf);
return -1;
}
#endif
#ifdef WITH_SELINUX
static int inode_add_selinux_xattr(struct ubifs_ino_node* host_ino,
const char* path_name, struct stat* st,
ino_t inum)
{
int ret;
char* sepath = NULL;
char* name;
struct qstr nm;
unsigned int con_size;
if (!context || !sehnd)
{
secontext = NULL;
con_size = 0;
return 0;
}
if (path_name[strlen(root)] == '/')
sepath = strdup(&path_name[strlen(root)]);
else if (asprintf(&sepath, "/%s", &path_name[strlen(root)]) < 0)
sepath = NULL;
if (!sepath)
return sys_err_msg("could not get sepath\n");
if (selabel_lookup(sehnd, &secontext, sepath, st->st_mode) < 0)
{
/* Failed to lookup context, assume unlabeled */
secontext = strdup("system_u:object_r:unlabeled_t:s0");
dbg_msg(2, "missing context: %s\t%s\t%d\n", secontext, sepath,
st->st_mode);
}
dbg_msg(2, "appling selinux context on sepath=%s, secontext=%s\n", sepath,
secontext);
free(sepath);
con_size = strlen(secontext) + 1;
name = strdup(XATTR_NAME_SELINUX);
nm.name = name;
nm.len = strlen(name);
host_ino->xattr_cnt++;
host_ino->xattr_size += CALC_DENT_SIZE(nm.len);
host_ino->xattr_size += CALC_XATTR_BYTES(con_size);
host_ino->xattr_names += nm.len;
ret = add_xattr(st, inum, secontext, con_size, &nm);
if (ret < 0)
dbg_msg(2, "add_xattr failed %d\n", ret);
return ret;
}
#else
static inline int inode_add_selinux_xattr(struct ubifs_ino_node* host_ino,
const char* path_name,
struct stat* st, ino_t inum)
{
(void)host_ino;
(void)path_name;
(void)st;
(void)inum;
return 0;
}
#endif
#ifdef WITH_CRYPTO
static int set_fscrypt_context(struct ubifs_ino_node* host_ino, ino_t inum,
struct stat* host_st,
struct fscrypt_context* fctx)
{
return add_xattr(host_ino, host_st, inum,
xstrdup(UBIFS_XATTR_NAME_ENCRYPTION_CONTEXT), fctx,
sizeof(*fctx));
}
static int encrypt_symlink(void* dst, void* data, unsigned int data_len,
struct fscrypt_context* fctx)
{
struct fscrypt_symlink_data* sd;
void* outbuf;
unsigned int link_disk_len;
unsigned int cryptlen;
int ret;
link_disk_len = sizeof(struct fscrypt_symlink_data);
link_disk_len += fscrypt_fname_encrypted_size(fctx, data_len);
ret = encrypt_path(&outbuf, data, data_len, UBIFS_MAX_INO_DATA, fctx);
if (ret < 0)
return ret;
cryptlen = ret;
sd = xzalloc(link_disk_len);
memcpy(sd->encrypted_path, outbuf, cryptlen);
sd->len = cpu_to_le16(cryptlen);
memcpy(dst, sd, link_disk_len);
((char*)dst)[link_disk_len - 1] = '\0';
free(outbuf);
free(sd);
return link_disk_len;
}
#else
static int set_fscrypt_context(struct ubifs_ino_node* host_ino, ino_t inum,
struct stat* host_st,
struct fscrypt_context* fctx)
{
(void)host_ino;
(void)inum;
(void)host_st;
(void)fctx;
assert(0);
return -1;
}
static int encrypt_symlink(void* dst, void* data, unsigned int data_len,
struct fscrypt_context* fctx)
{
(void)dst;
(void)data;
(void)data_len;
(void)fctx;
assert(0);
return -1;
}
#endif
/**
* add_inode - write an inode.
* @st: stat information of source inode
* @inum: target inode number
* @data: inode data (for special inodes e.g. symlink path etc)
* @data_len: inode data length
* @flags: source inode flags
*/
static int add_inode(struct stat* st, ino_t inum, void* data,
unsigned int data_len, int flags, const char* xattr_path,
struct fscrypt_context* fctx)
{
struct ubifs_ino_node* ino = node_buf;
union ubifs_key key;
int len, use_flags = 0, ret;
if (c->default_compr != UBIFS_COMPR_NONE)
use_flags |= UBIFS_COMPR_FL;
if (flags & FS_COMPR_FL)
use_flags |= UBIFS_COMPR_FL;
if (flags & FS_SYNC_FL)
use_flags |= UBIFS_SYNC_FL;
if (flags & FS_IMMUTABLE_FL)
use_flags |= UBIFS_IMMUTABLE_FL;
if (flags & FS_APPEND_FL)
use_flags |= UBIFS_APPEND_FL;
if (flags & FS_DIRSYNC_FL && S_ISDIR(st->st_mode))
use_flags |= UBIFS_DIRSYNC_FL;
if (fctx)
use_flags |= UBIFS_CRYPT_FL;
memset(ino, 0, UBIFS_INO_NODE_SZ);
ino_key_init(&key, inum);
ino->ch.node_type = UBIFS_INO_NODE;
key_write(&key, &ino->key);
ino->creat_sqnum = cpu_to_le64(creat_sqnum);
ino->size = cpu_to_le64(st->st_size);
ino->nlink = cpu_to_le32(st->st_nlink);
/*
* The time fields are updated assuming the default time granularity
* of 1 second. To support finer granularities, utime() would be needed.
*/
ino->atime_sec = cpu_to_le64(st->st_atime);
ino->ctime_sec = cpu_to_le64(st->st_ctime);
ino->mtime_sec = cpu_to_le64(st->st_mtime);
ino->atime_nsec = 0;
ino->ctime_nsec = 0;
ino->mtime_nsec = 0;
ino->uid = cpu_to_le32(st->st_uid);
ino->gid = cpu_to_le32(st->st_gid);
ino->mode = cpu_to_le32(st->st_mode);
ino->flags = cpu_to_le32(use_flags);
ino->compr_type = cpu_to_le16(c->default_compr);
if (data_len)
{
if (!S_ISLNK(st->st_mode))
return err_msg("Expected symlink");
if (!fctx)
{
memcpy(&ino->data, data, data_len);
}
else
{
ret = encrypt_symlink(&ino->data, data, data_len, fctx);
if (ret < 0)
return ret;
data_len = ret;
}
}
ino->data_len = cpu_to_le32(data_len);
len = UBIFS_INO_NODE_SZ + data_len;
if (xattr_path)
{
#ifdef WITH_SELINUX
ret = inode_add_selinux_xattr(ino, xattr_path, st, inum);
#else
ret = inode_add_xattr(ino, xattr_path, st, inum);
#endif
if (ret < 0)
return ret;
}
if (fctx)
{
ret = set_fscrypt_context(ino, inum, st, fctx);
if (ret < 0)
return ret;
}
return add_node(&key, NULL, 0, ino, len);
}
/**
* add_dir_inode - write an inode for a directory.
* @dir: source directory
* @inum: target inode number
* @size: target directory size
* @nlink: target directory link count
* @st: struct stat object describing attributes (except size and nlink) of the
* target inode to create
*
* Note, this function may be called with %NULL @dir, when the directory which
* is being created does not exist at the host file system, but is defined by
* the device table.
*/
static int add_dir_inode(const char* path_name, DIR* dir, ino_t inum,
loff_t size, unsigned int nlink, struct stat* st,
struct fscrypt_context* fctx)
{
int fd, flags = 0;
st->st_size = size;
st->st_nlink = nlink;
if (dir)
{
fd = dirfd(dir);
if (fd == -1)
return sys_err_msg("dirfd failed");
if (ioctl(fd, FS_IOC_GETFLAGS, &flags) == -1)
flags = 0;
}
return add_inode(st, inum, NULL, 0, flags, path_name, fctx);
}
/**
* add_dev_inode - write an inode for a character or block device.
* @st: stat information of source inode
* @inum: target inode number
* @flags: source inode flags
*/
static int add_dev_inode(const char* path_name, struct stat* st, ino_t inum,
int flags)
{
union ubifs_dev_desc dev;
dev.huge = cpu_to_le64(makedev(major(st->st_rdev), minor(st->st_rdev)));
return add_inode(st, inum, &dev, 8, flags, path_name, NULL);
}
/**
* add_symlink_inode - write an inode for a symbolic link.
* @path_name: path name of symbolic link inode itself (not the link target)
* @st: stat information of source inode
* @inum: target inode number
* @flags: source inode flags
*/
static int add_symlink_inode(const char* path_name, struct stat* st, ino_t inum,
int flags, struct fscrypt_context* fctx)
{
char buf[UBIFS_MAX_INO_DATA + 2];
ssize_t len;
/* Take the symlink as is */
len = readlink(path_name, buf, UBIFS_MAX_INO_DATA + 1);
if (len <= 0)
return sys_err_msg("readlink failed for %s", path_name);
if (len > UBIFS_MAX_INO_DATA)
return err_msg("symlink too long for %s", path_name);
return add_inode(st, inum, buf, len, flags, path_name, fctx);
}
static void set_dent_cookie(struct ubifs_dent_node* dent)
{
#ifdef WITH_CRYPTO
if (c->double_hash)
RAND_bytes((void*)&dent->cookie, sizeof(dent->cookie));
else
#endif
dent->cookie = 0;
}
/**
* add_dent_node - write a directory entry node.
* @dir_inum: target inode number of directory
* @name: directory entry name
* @inum: target inode number of the directory entry
* @type: type of the target inode
*/
static int add_dent_node(ino_t dir_inum, const char* name, ino_t inum,
unsigned char type, struct fscrypt_context* fctx)
{
struct ubifs_dent_node* dent = node_buf;
union ubifs_key key;
struct qstr dname;
char* kname;
int kname_len;
int len;
dbg_msg(3, "%s ino %lu type %u dir ino %lu", name, (unsigned long)inum,
(unsigned int)type, (unsigned long)dir_inum);
memset(dent, 0, UBIFS_DENT_NODE_SZ);
dname.name = (void*)name;
dname.len = strlen(name);
dent->ch.node_type = UBIFS_DENT_NODE;
dent->inum = cpu_to_le64(inum);
dent->padding1 = 0;
dent->type = type;
set_dent_cookie(dent);
if (!fctx)
{
kname_len = dname.len;
kname = strdup(name);
if (!kname)
return err_msg("cannot allocate memory");
}
else
{
unsigned int max_namelen = UBIFS_MAX_NLEN;
int ret;
if (type == UBIFS_ITYPE_LNK)
max_namelen = UBIFS_MAX_INO_DATA;
ret = encrypt_path((void**)&kname, dname.name, dname.len, max_namelen,
fctx);
if (ret < 0)
return ret;
kname_len = ret;
}
dent_key_init(c, &key, dir_inum, kname, kname_len);
dent->nlen = cpu_to_le16(kname_len);
memcpy(dent->name, kname, kname_len);
dent->name[kname_len] = '\0';
len = UBIFS_DENT_NODE_SZ + kname_len + 1;
key_write(&key, dent->key);
return add_node(&key, kname, kname_len, dent, len);
}
/**
* lookup_inum_mapping - add an inode mapping for link counting.
* @dev: source device on which source inode number resides
* @inum: source inode number
*/
static struct inum_mapping* lookup_inum_mapping(dev_t dev, ino_t inum)
{
struct inum_mapping* im;
unsigned int k;
k = inum % HASH_TABLE_SIZE;
im = hash_table[k];
while (im)
{
if (im->dev == dev && im->inum == inum)
return im;
im = im->next;
}
im = xmalloc(sizeof(struct inum_mapping));
im->next = hash_table[k];
im->prev = NULL;
im->dev = dev;
im->inum = inum;
im->use_inum = 0;
im->use_nlink = 0;
if (hash_table[k])
hash_table[k]->prev = im;
hash_table[k] = im;
return im;
}
/**
* all_zero - does a buffer contain only zero bytes.
* @buf: buffer
* @len: buffer length
*/
static int all_zero(void* buf, int len)
{
unsigned char* p = buf;
while (len--)
if (*p++ != 0)
return 0;
return 1;
}
/**
* add_file - write the data of a file and its inode to the output file.
* @path_name: source path name
* @st: source inode stat information
* @inum: target inode number
* @flags: source inode flags
*/
static int add_file(const char* path_name, struct stat* st, ino_t inum,
int flags, struct fscrypt_context* fctx)
{
struct ubifs_data_node* dn = node_buf;
void* buf = block_buf;
loff_t file_size = 0;
ssize_t ret, bytes_read;
union ubifs_key key;
int fd, dn_len, err, compr_type, use_compr;
unsigned int block_no = 0;
size_t out_len;
fd = open(path_name, O_RDONLY | O_LARGEFILE);
if (fd == -1)
return sys_err_msg("failed to open file '%s'", path_name);
do
{
/* Read next block */
bytes_read = 0;
do
{
ret = read(fd, buf + bytes_read, UBIFS_BLOCK_SIZE - bytes_read);
if (ret == -1)
{
sys_err_msg("failed to read file '%s'", path_name);
close(fd);
return 1;
}
bytes_read += ret;
} while (ret != 0 && bytes_read != UBIFS_BLOCK_SIZE);
if (bytes_read == 0)
break;
file_size += bytes_read;
/* Skip holes */
if (all_zero(buf, bytes_read))
{
block_no += 1;
continue;
}
/* Make data node */
memset(dn, 0, UBIFS_DATA_NODE_SZ);
data_key_init(&key, inum, block_no);
dn->ch.node_type = UBIFS_DATA_NODE;
key_write(&key, &dn->key);
out_len = NODE_BUFFER_SIZE - UBIFS_DATA_NODE_SZ;
if (c->default_compr == UBIFS_COMPR_NONE && !c->encrypted &&
(flags & FS_COMPR_FL))
#ifdef WITHOUT_LZO
use_compr = UBIFS_COMPR_ZLIB;
#else
use_compr = UBIFS_COMPR_LZO;
#endif
else
use_compr = c->default_compr;
compr_type =
compress_data(buf, bytes_read, &dn->data, &out_len, use_compr);
dn->compr_type = cpu_to_le16(compr_type);
dn->size = cpu_to_le32(bytes_read);
if (!fctx)
{
dn->compr_size = 0;
}
else
{
ret = encrypt_data_node(fctx, block_no, dn, out_len);
if (ret < 0)
return ret;
out_len = ret;
}
dn_len = UBIFS_DATA_NODE_SZ + out_len;
/* Add data node to file system */
err = add_node(&key, NULL, 0, dn, dn_len);
if (err)
{
close(fd);
return err;
}
block_no++;
} while (ret != 0);
if (close(fd) == -1)
return sys_err_msg("failed to close file '%s'", path_name);
if (file_size != st->st_size)
return err_msg("file size changed during writing file '%s'", path_name);
return add_inode(st, inum, NULL, 0, flags, path_name, fctx);
}
/**
* add_non_dir - write a non-directory to the output file.
* @path_name: source path name
* @inum: target inode number is passed and returned here (due to link counting)
* @nlink: number of links if known otherwise zero
* @type: UBIFS inode type is returned here
* @st: struct stat object containing inode attributes which should be use when
* creating the UBIFS inode
*/
static int add_non_dir(const char* path_name, ino_t* inum, unsigned int nlink,
unsigned char* type, struct stat* st,
struct fscrypt_context* fctx)
{
int fd, flags = 0;
dbg_msg(2, "%s", path_name);
if (S_ISREG(st->st_mode))
{
fd = open(path_name, O_RDONLY);
if (fd == -1)
return sys_err_msg("failed to open file '%s'", path_name);
if (ioctl(fd, FS_IOC_GETFLAGS, &flags) == -1)
flags = 0;
if (close(fd) == -1)
return sys_err_msg("failed to close file '%s'", path_name);
*type = UBIFS_ITYPE_REG;
}
else if (S_ISCHR(st->st_mode))
*type = UBIFS_ITYPE_CHR;
else if (S_ISBLK(st->st_mode))
*type = UBIFS_ITYPE_BLK;
else if (S_ISLNK(st->st_mode))
*type = UBIFS_ITYPE_LNK;
else if (S_ISSOCK(st->st_mode))
*type = UBIFS_ITYPE_SOCK;
else if (S_ISFIFO(st->st_mode))
*type = UBIFS_ITYPE_FIFO;
else
return err_msg("file '%s' has unknown inode type", path_name);
if (nlink)
st->st_nlink = nlink;
else if (st->st_nlink > 1)
{
/*
* If the number of links is greater than 1, then add this file
* later when we know the number of links that we actually have.
* For now, we just put the inode mapping in the hash table.
*/
struct inum_mapping* im;
im = lookup_inum_mapping(st->st_dev, st->st_ino);
if (!im)
return err_msg("out of memory");
if (im->use_nlink == 0)
{
/* New entry */
im->use_inum = *inum;
im->use_nlink = 1;
im->path_name = xmalloc(strlen(path_name) + 1);
strcpy(im->path_name, path_name);
}
else
{
/* Existing entry */
*inum = im->use_inum;
im->use_nlink += 1;
/* Return unused inode number */
c->highest_inum -= 1;
}
memcpy(&im->st, st, sizeof(struct stat));
return 0;
}
else
st->st_nlink = 1;
creat_sqnum = ++c->max_sqnum;
if (S_ISREG(st->st_mode))
return add_file(path_name, st, *inum, flags, fctx);
if (S_ISCHR(st->st_mode))
return add_dev_inode(path_name, st, *inum, flags);
if (S_ISBLK(st->st_mode))
return add_dev_inode(path_name, st, *inum, flags);
if (S_ISLNK(st->st_mode))
return add_symlink_inode(path_name, st, *inum, flags, fctx);
if (S_ISSOCK(st->st_mode))
return add_inode(st, *inum, NULL, 0, flags, NULL, NULL);
if (S_ISFIFO(st->st_mode))
return add_inode(st, *inum, NULL, 0, flags, NULL, NULL);
return err_msg("file '%s' has unknown inode type", path_name);
}
/**
* add_directory - write a directory tree to the output file.
* @dir_name: directory path name
* @dir_inum: UBIFS inode number of directory
* @st: directory inode statistics
* @existing: zero if this function is called for a directory which
* does not exist on the host file-system and it is being
* created because it is defined in the device table file.
*/
static int add_directory(const char* dir_name, ino_t dir_inum, struct stat* st,
int existing, struct fscrypt_context* fctx)
{
struct dirent* entry;
DIR* dir = NULL;
int err = 0;
loff_t size = UBIFS_INO_NODE_SZ;
char* name = NULL;
unsigned int nlink = 2;
struct path_htbl_element* ph_elt;
struct name_htbl_element* nh_elt = NULL;
struct hashtable_itr* itr;
ino_t inum;
unsigned char type;
unsigned long long dir_creat_sqnum = ++c->max_sqnum;
dbg_msg(2, "%s", dir_name);
if (existing)
{
dir = opendir(dir_name);
if (dir == NULL)
return sys_err_msg("cannot open directory '%s'", dir_name);
}
/*
* Check whether this directory contains files which should be
* added/changed because they were specified in the device table.
* @ph_elt will be non-zero if yes.
*/
ph_elt = devtbl_find_path(dir_name + root_len - 1);
/*
* Before adding the directory itself, we have to iterate over all the
* entries the device table adds to this directory and create them.
*/
for (; existing;)
{
struct stat dent_st;
struct fscrypt_context* new_fctx = NULL;
errno = 0;
entry = readdir(dir);
if (!entry)
{
if (errno == 0)
break;
sys_err_msg("error reading directory '%s'", dir_name);
err = -1;
break;
}
if (strcmp(".", entry->d_name) == 0)
continue;
if (strcmp("..", entry->d_name) == 0)
continue;
if (ph_elt)
/*
* This directory was referred to at the device table
* file. Check if this directory entry is referred at
* too.
*/
nh_elt = devtbl_find_name(ph_elt, entry->d_name);
/*
* We are going to create the file corresponding to this
* directory entry (@entry->d_name). We use 'struct stat'
* object to pass information about file attributes (actually
* only about UID, GID, mode, major, and minor). Get attributes
* for this file from the UBIFS rootfs on the host.
*/
free(name);
name = make_path(dir_name, entry->d_name);
if (lstat(name, &dent_st) == -1)
{
sys_err_msg("lstat failed for file '%s'", name);
goto out_free;
}
if (squash_owner)
/*
* Squash UID/GID. But the device table may override
* this.
*/
dent_st.st_uid = dent_st.st_gid = 0;
/*
* And if the device table describes the same file, override
* the attributes. However, this is not allowed for device node
* files.
*/
if (nh_elt && override_attributes(&dent_st, ph_elt, nh_elt))
goto out_free;
inum = ++c->highest_inum;
if (fctx)
new_fctx = inherit_fscrypt_context(fctx);
if (S_ISDIR(dent_st.st_mode))
{
err = add_directory(name, inum, &dent_st, 1, new_fctx);
if (err)
goto out_free;
nlink += 1;
type = UBIFS_ITYPE_DIR;
}
else
{
err = add_non_dir(name, &inum, 0, &type, &dent_st, new_fctx);
if (err)
goto out_free;
}
err = create_inum_attr(inum, name);
if (err)
goto out_free;
err = add_dent_node(dir_inum, entry->d_name, inum, type, fctx);
if (err)
goto out_free;
size += ALIGN(UBIFS_DENT_NODE_SZ + strlen(entry->d_name) + 1, 8);
if (new_fctx)
free_fscrypt_context(new_fctx);
}
/*
* OK, we have created all files in this directory (recursively), let's
* also create all files described in the device table. All t
*/
nh_elt = first_name_htbl_element(ph_elt, &itr);
while (nh_elt)
{
struct stat fake_st;
struct fscrypt_context* new_fctx = NULL;
/*
* We prohibit creating regular files using the device table,
* the device table may only re-define attributes of regular
* files.
*/
if (S_ISREG(nh_elt->mode))
{
err_msg("Bad device table entry %s/%s - it is "
"prohibited to create regular files "
"via device table",
strcmp(ph_elt->path, "/") ? ph_elt->path : "",
nh_elt->name);
goto out_free;
}
memcpy(&fake_st, &root_st, sizeof(struct stat));
fake_st.st_uid = nh_elt->uid;
fake_st.st_gid = nh_elt->gid;
fake_st.st_mode = nh_elt->mode;
fake_st.st_rdev = nh_elt->dev;
fake_st.st_nlink = 1;
free(name);
name = make_path(dir_name, nh_elt->name);
inum = ++c->highest_inum;
new_fctx = inherit_fscrypt_context(fctx);
if (S_ISDIR(nh_elt->mode))
{
err = add_directory(name, inum, &fake_st, 0, new_fctx);
if (err)
goto out_free;
nlink += 1;
type = UBIFS_ITYPE_DIR;
}
else
{
err = add_non_dir(name, &inum, 0, &type, &fake_st, new_fctx);
if (err)
goto out_free;
}
err = create_inum_attr(inum, name);
if (err)
goto out_free;
err = add_dent_node(dir_inum, nh_elt->name, inum, type, fctx);
if (err)
goto out_free;
size += ALIGN(UBIFS_DENT_NODE_SZ + strlen(nh_elt->name) + 1, 8);
nh_elt = next_name_htbl_element(ph_elt, &itr);
if (new_fctx)
free_fscrypt_context(new_fctx);
}
creat_sqnum = dir_creat_sqnum;
err = add_dir_inode(dir ? dir_name : NULL, dir, dir_inum, size, nlink, st,
fctx);
if (err)
goto out_free;
free(name);
if (existing && closedir(dir) == -1)
return sys_err_msg("error closing directory '%s'", dir_name);
return 0;
out_free:
free(name);
if (existing)
closedir(dir);
return -1;
}
/**
* add_multi_linked_files - write all the files for which we counted links.
*/
static int add_multi_linked_files(void)
{
int i, err;
for (i = 0; i < HASH_TABLE_SIZE; i++)
{
struct inum_mapping* im;
unsigned char type = 0;
for (im = hash_table[i]; im; im = im->next)
{
dbg_msg(2, "%s", im->path_name);
err = add_non_dir(im->path_name, &im->use_inum, im->use_nlink,
&type, &im->st, NULL);
if (err)
return err;
}
}
return 0;
}
/**
* write_data - write the files and directories.
*/
static int write_data(void)
{
int err;
mode_t mode = S_IFDIR | S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
struct path_htbl_element* ph_elt;
struct name_htbl_element* nh_elt;
if (root)
{
err = stat(root, &root_st);
if (err)
return sys_err_msg("bad root file-system directory '%s'", root);
if (squash_owner)
root_st.st_uid = root_st.st_gid = 0;
}
else
{
root_st.st_mtime = time(NULL);
root_st.st_atime = root_st.st_ctime = root_st.st_mtime;
root_st.st_mode = mode;
}
/*
* Check for root entry and update permissions if it exists. This will
* also remove the entry from the device table list.
*/
ph_elt = devtbl_find_path("/");
if (ph_elt)
{
nh_elt = devtbl_find_name(ph_elt, "");
if (nh_elt && override_attributes(&root_st, ph_elt, nh_elt))
return -1;
}
head_flags = 0;
err = create_inum_attr(UBIFS_ROOT_INO, root);
if (err)
return err;
err = add_directory(root, UBIFS_ROOT_INO, &root_st, !!root, root_fctx);
if (err)
return err;
err = add_multi_linked_files();
if (err)
return err;
return flush_nodes();
}
static int namecmp(const struct idx_entry* e1, const struct idx_entry* e2)
{
size_t len1 = e1->name_len, len2 = e2->name_len;
size_t clen = (len1 < len2) ? len1 : len2;
int cmp;
cmp = memcmp(e1->name, e2->name, clen);
if (cmp)
return cmp;
return (len1 < len2) ? -1 : 1;
}
static int cmp_idx(const void* a, const void* b)
{
const struct idx_entry* e1 = *(const struct idx_entry**)a;
const struct idx_entry* e2 = *(const struct idx_entry**)b;
int cmp;
cmp = keys_cmp(&e1->key, &e2->key);
if (cmp)
return cmp;
return namecmp(e1, e2);
}
/**
* add_idx_node - write an index node to the head.
* @node: index node
* @child_cnt: number of children of this index node
*/
static int add_idx_node(void* node, int child_cnt)
{
int err, lnum, offs, len;
len = ubifs_idx_node_sz(c, child_cnt);
prepare_node(node, len);
err = reserve_space(len, &lnum, &offs);
if (err)
return err;
memcpy(leb_buf + offs, node, len);
memset(leb_buf + offs + len, 0xff, ALIGN(len, 8) - len);
c->old_idx_sz += ALIGN(len, 8);
dbg_msg(3, "at %d:%d len %d index size %llu", lnum, offs, len,
c->old_idx_sz);
/* The last index node written will be the root */
c->zroot.lnum = lnum;
c->zroot.offs = offs;
c->zroot.len = len;
return 0;
}
/**
* write_index - write out the index.
*/
static int write_index(void)
{
size_t sz, i, cnt, idx_sz, pstep, bcnt;
struct idx_entry **idx_ptr, **p;
struct ubifs_idx_node* idx;
struct ubifs_branch* br;
int child_cnt = 0, j, level, blnum, boffs, blen, blast_len, err;
dbg_msg(1, "leaf node count: %zd", idx_cnt);
/* Reset the head for the index */
head_flags = LPROPS_INDEX;
/* Allocate index node */
idx_sz = ubifs_idx_node_sz(c, c->fanout);
idx = xmalloc(idx_sz);
/* Make an array of pointers to sort the index list */
sz = idx_cnt * sizeof(struct idx_entry*);
if (sz / sizeof(struct idx_entry*) != idx_cnt)
{
free(idx);
return err_msg("index is too big (%zu entries)", idx_cnt);
}
idx_ptr = xmalloc(sz);
idx_ptr[0] = idx_list_first;
for (i = 1; i < idx_cnt; i++)
idx_ptr[i] = idx_ptr[i - 1]->next;
qsort(idx_ptr, idx_cnt, sizeof(struct idx_entry*), cmp_idx);
/* Write level 0 index nodes */
cnt = idx_cnt / c->fanout;
if (idx_cnt % c->fanout)
cnt += 1;
p = idx_ptr;
blnum = head_lnum;
boffs = head_offs;
for (i = 0; i < cnt; i++)
{
/*
* Calculate the child count. All index nodes are created full
* except for the last index node on each row.
*/
if (i == cnt - 1)
{
child_cnt = idx_cnt % c->fanout;
if (child_cnt == 0)
child_cnt = c->fanout;
}
else
child_cnt = c->fanout;
memset(idx, 0, idx_sz);
idx->ch.node_type = UBIFS_IDX_NODE;
idx->child_cnt = cpu_to_le16(child_cnt);
idx->level = cpu_to_le16(0);
for (j = 0; j < child_cnt; j++, p++)
{
br = ubifs_idx_branch(c, idx, j);
key_write_idx(&(*p)->key, &br->key);
br->lnum = cpu_to_le32((*p)->lnum);
br->offs = cpu_to_le32((*p)->offs);
br->len = cpu_to_le32((*p)->len);
}
add_idx_node(idx, child_cnt);
}
/* Write level 1 index nodes and above */
level = 0;
pstep = 1;
while (cnt > 1)
{
/*
* 'blast_len' is the length of the last index node in the level
* below.
*/
blast_len = ubifs_idx_node_sz(c, child_cnt);
/* 'bcnt' is the number of index nodes in the level below */
bcnt = cnt;
/* 'cnt' is the number of index nodes in this level */
cnt = (cnt + c->fanout - 1) / c->fanout;
if (cnt == 0)
cnt = 1;
level += 1;
/*
* The key of an index node is the same as the key of its first
* child. Thus we can get the key by stepping along the bottom
* level 'p' with an increasing large step 'pstep'.
*/
p = idx_ptr;
pstep *= c->fanout;
for (i = 0; i < cnt; i++)
{
/*
* Calculate the child count. All index nodes are
* created full except for the last index node on each
* row.
*/
if (i == cnt - 1)
{
child_cnt = bcnt % c->fanout;
if (child_cnt == 0)
child_cnt = c->fanout;
}
else
child_cnt = c->fanout;
memset(idx, 0, idx_sz);
idx->ch.node_type = UBIFS_IDX_NODE;
idx->child_cnt = cpu_to_le16(child_cnt);
idx->level = cpu_to_le16(level);
for (j = 0; j < child_cnt; j++)
{
size_t bn = i * c->fanout + j;
/*
* The length of the index node in the level
* below is 'idx_sz' except when it is the last
* node on the row. i.e. all the others on the
* row are full.
*/
if (bn == bcnt - 1)
blen = blast_len;
else
blen = idx_sz;
/*
* 'blnum' and 'boffs' hold the position of the
* index node on the level below.
*/
if (boffs + blen > c->leb_size)
{
blnum += 1;
boffs = 0;
}
/*
* Fill in the branch with the key and position
* of the index node from the level below.
*/
br = ubifs_idx_branch(c, idx, j);
key_write_idx(&(*p)->key, &br->key);
br->lnum = cpu_to_le32(blnum);
br->offs = cpu_to_le32(boffs);
br->len = cpu_to_le32(blen);
/*
* Step to the next index node on the level
* below.
*/
boffs += ALIGN(blen, 8);
p += pstep;
}
add_idx_node(idx, child_cnt);
}
}
/* Free stuff */
for (i = 0; i < idx_cnt; i++)
{
free(idx_ptr[i]->name);
free(idx_ptr[i]);
}
free(idx_ptr);
free(idx);
dbg_msg(1, "zroot is at %d:%d len %d", c->zroot.lnum, c->zroot.offs,
c->zroot.len);
/* Set the index head */
c->ihead_lnum = head_lnum;
c->ihead_offs = ALIGN(head_offs, c->min_io_size);
dbg_msg(1, "ihead is at %d:%d", c->ihead_lnum, c->ihead_offs);
/* Flush the last index LEB */
err = flush_nodes();
if (err)
return err;
return 0;
}
/**
* set_gc_lnum - set the LEB number reserved for the garbage collector.
*/
static int set_gc_lnum(void)
{
int err;
c->gc_lnum = head_lnum++;
err = write_empty_leb(c->gc_lnum);
if (err)
return err;
set_lprops(c->gc_lnum, 0, 0);
c->lst.empty_lebs += 1;
return 0;
}
/**
* finalize_leb_cnt - now that we know how many LEBs we used.
*/
static int finalize_leb_cnt(void)
{
c->leb_cnt = head_lnum;
if (c->leb_cnt > c->max_leb_cnt)
return err_msg("max_leb_cnt too low (%d needed)", c->leb_cnt);
c->main_lebs = c->leb_cnt - c->main_first;
if (verbose)
{
printf("\tsuper lebs: %d\n", UBIFS_SB_LEBS);
printf("\tmaster lebs: %d\n", UBIFS_MST_LEBS);
printf("\tlog_lebs: %d\n", c->log_lebs);
printf("\tlpt_lebs: %d\n", c->lpt_lebs);
printf("\torph_lebs: %d\n", c->orph_lebs);
printf("\tmain_lebs: %d\n", c->main_lebs);
printf("\tgc lebs: %d\n", 1);
printf("\tindex lebs: %d\n", c->lst.idx_lebs);
printf("\tleb_cnt: %d\n", c->leb_cnt);
}
dbg_msg(1, "total_free: %llu", c->lst.total_free);
dbg_msg(1, "total_dirty: %llu", c->lst.total_dirty);
dbg_msg(1, "total_used: %llu", c->lst.total_used);
dbg_msg(1, "total_dead: %llu", c->lst.total_dead);
dbg_msg(1, "total_dark: %llu", c->lst.total_dark);
dbg_msg(1, "index size: %llu", c->old_idx_sz);
dbg_msg(1, "empty_lebs: %d", c->lst.empty_lebs);
return 0;
}
static int ubifs_format_version(void)
{
if (c->double_hash || c->encrypted)
return 5;
/* Default */
return 4;
}
/**
* write_super - write the super block.
*/
static int write_super(void)
{
struct ubifs_sb_node sup;
memset(&sup, 0, UBIFS_SB_NODE_SZ);
sup.ch.node_type = UBIFS_SB_NODE;
sup.key_hash = c->key_hash_type;
sup.min_io_size = cpu_to_le32(c->min_io_size);
sup.leb_size = cpu_to_le32(c->leb_size);
sup.leb_cnt = cpu_to_le32(c->leb_cnt);
sup.max_leb_cnt = cpu_to_le32(c->max_leb_cnt);
sup.max_bud_bytes = cpu_to_le64(c->max_bud_bytes);
sup.log_lebs = cpu_to_le32(c->log_lebs);
sup.lpt_lebs = cpu_to_le32(c->lpt_lebs);
sup.orph_lebs = cpu_to_le32(c->orph_lebs);
sup.jhead_cnt = cpu_to_le32(c->jhead_cnt);
sup.fanout = cpu_to_le32(c->fanout);
sup.lsave_cnt = cpu_to_le32(c->lsave_cnt);
sup.fmt_version = cpu_to_le32(ubifs_format_version());
sup.default_compr = cpu_to_le16(c->default_compr);
sup.rp_size = cpu_to_le64(c->rp_size);
sup.time_gran = cpu_to_le32(DEFAULT_TIME_GRAN);
uuid_generate_random(sup.uuid);
if (verbose)
{
char s[40];
uuid_unparse_upper(sup.uuid, s);
printf("\tUUID: %s\n", s);
}
if (c->big_lpt)
sup.flags |= cpu_to_le32(UBIFS_FLG_BIGLPT);
if (c->space_fixup)
sup.flags |= cpu_to_le32(UBIFS_FLG_SPACE_FIXUP);
if (c->double_hash)
sup.flags |= cpu_to_le32(UBIFS_FLG_DOUBLE_HASH);
if (c->encrypted)
sup.flags |= cpu_to_le32(UBIFS_FLG_ENCRYPTION);
return write_node(&sup, UBIFS_SB_NODE_SZ, UBIFS_SB_LNUM);
}
/**
* write_master - write the master node.
*/
static int write_master(void)
{
struct ubifs_mst_node mst;
int err;
memset(&mst, 0, UBIFS_MST_NODE_SZ);
mst.ch.node_type = UBIFS_MST_NODE;
mst.log_lnum = cpu_to_le32(UBIFS_LOG_LNUM);
mst.highest_inum = cpu_to_le64(c->highest_inum);
mst.cmt_no = cpu_to_le64(0);
mst.flags = cpu_to_le32(UBIFS_MST_NO_ORPHS);
mst.root_lnum = cpu_to_le32(c->zroot.lnum);
mst.root_offs = cpu_to_le32(c->zroot.offs);
mst.root_len = cpu_to_le32(c->zroot.len);
mst.gc_lnum = cpu_to_le32(c->gc_lnum);
mst.ihead_lnum = cpu_to_le32(c->ihead_lnum);
mst.ihead_offs = cpu_to_le32(c->ihead_offs);
mst.index_size = cpu_to_le64(c->old_idx_sz);
mst.lpt_lnum = cpu_to_le32(c->lpt_lnum);
mst.lpt_offs = cpu_to_le32(c->lpt_offs);
mst.nhead_lnum = cpu_to_le32(c->nhead_lnum);
mst.nhead_offs = cpu_to_le32(c->nhead_offs);
mst.ltab_lnum = cpu_to_le32(c->ltab_lnum);
mst.ltab_offs = cpu_to_le32(c->ltab_offs);
mst.lsave_lnum = cpu_to_le32(c->lsave_lnum);
mst.lsave_offs = cpu_to_le32(c->lsave_offs);
mst.lscan_lnum = cpu_to_le32(c->lscan_lnum);
mst.empty_lebs = cpu_to_le32(c->lst.empty_lebs);
mst.idx_lebs = cpu_to_le32(c->lst.idx_lebs);
mst.total_free = cpu_to_le64(c->lst.total_free);
mst.total_dirty = cpu_to_le64(c->lst.total_dirty);
mst.total_used = cpu_to_le64(c->lst.total_used);
mst.total_dead = cpu_to_le64(c->lst.total_dead);
mst.total_dark = cpu_to_le64(c->lst.total_dark);
mst.leb_cnt = cpu_to_le32(c->leb_cnt);
err = write_node(&mst, UBIFS_MST_NODE_SZ, UBIFS_MST_LNUM);
if (err)
return err;
err = write_node(&mst, UBIFS_MST_NODE_SZ, UBIFS_MST_LNUM + 1);
if (err)
return err;
return 0;
}
/**
* write_log - write an empty log.
*/
static int write_log(void)
{
struct ubifs_cs_node cs;
int err, i, lnum;
lnum = UBIFS_LOG_LNUM;
cs.ch.node_type = UBIFS_CS_NODE;
cs.cmt_no = cpu_to_le64(0);
err = write_node(&cs, UBIFS_CS_NODE_SZ, lnum);
if (err)
return err;
lnum += 1;
for (i = 1; i < c->log_lebs; i++, lnum++)
{
err = write_empty_leb(lnum);
if (err)
return err;
}
return 0;
}
/**
* write_lpt - write the LEB properties tree.
*/
static int write_lpt(void)
{
int err, lnum;
err = create_lpt(c);
if (err)
return err;
lnum = c->nhead_lnum + 1;
while (lnum <= c->lpt_last)
{
err = write_empty_leb(lnum++);
if (err)
return err;
}
return 0;
}
/**
* write_orphan_area - write an empty orphan area.
*/
static int write_orphan_area(void)
{
int err, i, lnum;
lnum = UBIFS_LOG_LNUM + c->log_lebs + c->lpt_lebs;
for (i = 0; i < c->orph_lebs; i++, lnum++)
{
err = write_empty_leb(lnum);
if (err)
return err;
}
return 0;
}
/**
* check_volume_empty - check if the UBI volume is empty.
*
* This function checks if the UBI volume is empty by looking if its LEBs are
* mapped or not.
*
* Returns %0 in case of success, %1 is the volume is not empty,
* and a negative error code in case of failure.
*/
static int check_volume_empty(void)
{
int lnum, err;
for (lnum = 0; lnum < c->vi.rsvd_lebs; lnum++)
{
err = ubi_is_mapped(out_fd, lnum);
if (err < 0)
return err;
if (err == 1)
return 1;
}
return 0;
}
/**
* open_target - open the output target.
*
* Open the output target. The target can be an UBI volume
* or a file.
*
* Returns %0 in case of success and %-1 in case of failure.
*/
static int open_target(void)
{
if (out_ubi)
{
out_fd = open(output, O_RDWR | O_EXCL);
if (out_fd == -1)
return sys_err_msg("cannot open the UBI volume '%s'", output);
if (ubi_set_property(out_fd, UBI_VOL_PROP_DIRECT_WRITE, 1))
return sys_err_msg("ubi_set_property failed");
if (!yes && check_volume_empty())
{
if (!prompt("UBI volume is not empty. Format anyways?", false))
return err_msg("UBI volume is not empty");
}
}
else
{
out_fd = open(output, O_CREAT | O_RDWR | O_TRUNC,
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);
if (out_fd == -1)
return sys_err_msg("cannot create output file '%s'", output);
}
return 0;
}
/**
* close_target - close the output target.
*
* Close the output target. If the target was an UBI
* volume, also close libubi.
*
* Returns %0 in case of success and %-1 in case of failure.
*/
static int close_target(void)
{
if (ubi)
libubi_close(ubi);
if (out_fd >= 0 && close(out_fd) == -1)
return sys_err_msg("cannot close the target '%s'", output);
if (output)
free(output);
return 0;
}
/**
* init - initialize things.
*/
static int init(void)
{
int err, i, main_lebs, big_lpt = 0, sz;
c->highest_inum = UBIFS_FIRST_INO;
c->jhead_cnt = 1;
main_lebs = c->max_leb_cnt - UBIFS_SB_LEBS - UBIFS_MST_LEBS;
main_lebs -= c->log_lebs + c->orph_lebs;
err = calc_dflt_lpt_geom(c, &main_lebs, &big_lpt);
if (err)
return err;
c->main_first = UBIFS_LOG_LNUM + c->log_lebs + c->lpt_lebs + c->orph_lebs;
head_lnum = c->main_first;
head_offs = 0;
c->lpt_first = UBIFS_LOG_LNUM + c->log_lebs;
c->lpt_last = c->lpt_first + c->lpt_lebs - 1;
c->lpt = xmalloc(c->main_lebs * sizeof(struct ubifs_lprops));
c->ltab = xmalloc(c->lpt_lebs * sizeof(struct ubifs_lprops));
/* Initialize LPT's own lprops */
for (i = 0; i < c->lpt_lebs; i++)
{
c->ltab[i].free = c->leb_size;
c->ltab[i].dirty = 0;
}
c->dead_wm = ALIGN(MIN_WRITE_SZ, c->min_io_size);
c->dark_wm = ALIGN(UBIFS_MAX_NODE_SZ, c->min_io_size);
dbg_msg(1, "dead_wm %d dark_wm %d", c->dead_wm, c->dark_wm);
leb_buf = xmalloc(c->leb_size);
node_buf = xmalloc(NODE_BUFFER_SIZE);
block_buf = xmalloc(UBIFS_BLOCK_SIZE);
sz = sizeof(struct inum_mapping*) * HASH_TABLE_SIZE;
hash_table = xzalloc(sz);
err = init_compression();
if (err)
return err;
#ifdef WITH_SELINUX
if (context)
{
struct selinux_opt seopts[] = {{SELABEL_OPT_PATH, context}};
sehnd = selabel_open(SELABEL_CTX_FILE, seopts, 1);
if (!sehnd)
return err_msg("could not open selinux context\n");
}
#endif
return 0;
}
static void destroy_hash_table(void)
{
int i;
for (i = 0; i < HASH_TABLE_SIZE; i++)
{
struct inum_mapping *im, *q;
for (im = hash_table[i]; im;)
{
q = im;
im = im->next;
free(q->path_name);
free(q);
}
}
}
/**
* deinit - deinitialize things.
*/
static void deinit(void)
{
#ifdef WITH_SELINUX
if (sehnd)
selabel_close(sehnd);
#endif
free(c->lpt);
free(c->ltab);
free(leb_buf);
free(node_buf);
free(block_buf);
destroy_hash_table();
free(hash_table);
destroy_compression();
free_devtable_info();
}
/**
* mkfs - make the file system.
*
* Each on-flash area has a corresponding function to create it. The order of
* the functions reflects what information must be known to complete each stage.
* As a consequence the output file is not written sequentially. No effort has
* been made to make efficient use of memory or to allow for the possibility of
* incremental updates to the output file.
*/
static int mkfs(void)
{
int err = 0;
err = init();
if (err)
goto out;
err = write_data();
if (err)
goto out;
err = set_gc_lnum();
if (err)
goto out;
err = write_index();
if (err)
goto out;
err = finalize_leb_cnt();
if (err)
goto out;
err = write_lpt();
if (err)
goto out;
err = write_super();
if (err)
goto out;
err = write_master();
if (err)
goto out;
err = write_log();
if (err)
goto out;
err = write_orphan_area();
out:
deinit();
return err;
}
int main(int argc, char* argv[])
{
int err;
if (crypto_init())
return -1;
err = get_options(argc, argv);
if (err)
return err;
err = open_target();
if (err)
return err;
err = mkfs();
if (err)
{
close_target();
return err;
}
err = close_target();
if (err)
return err;
if (verbose)
printf("Success!\n");
crypto_cleanup();
return 0;
}
| 29.116913 | 80 | 0.559976 | [
"geometry",
"object"
] |
4ffbedff5426dae8d7c4753ca951ba7562e8b4e1 | 2,794 | h | C | DQM/EcalCommon/interface/MESetEcal.h | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 1 | 2019-08-09T08:42:11.000Z | 2019-08-09T08:42:11.000Z | DQM/EcalCommon/interface/MESetEcal.h | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | null | null | null | DQM/EcalCommon/interface/MESetEcal.h | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 1 | 2019-03-19T13:44:54.000Z | 2019-03-19T13:44:54.000Z | #ifndef MESetEcal_H
#define MESetEcal_H
#include "MESet.h"
namespace ecaldqm
{
/* class MESetEcal
implements plot <-> detector part relationship
base class for channel-binned histograms
MESetEcal is only filled given an object identifier and a bin (channel id does not give a bin)
*/
class MESetEcal : public MESet
{
public :
MESetEcal(std::string const&, binning::ObjectType, binning::BinningType, MonitorElement::Kind, unsigned, binning::AxisSpecs const* = nullptr, binning::AxisSpecs const* = nullptr, binning::AxisSpecs const* = nullptr);
MESetEcal(MESetEcal const&);
~MESetEcal() override;
MESet& operator=(MESet const&) override;
MESet* clone(std::string const& = "") const override;
void book(DQMStore::IBooker&) override;
bool retrieve(DQMStore::IGetter&, std::string* = nullptr) const override;
void fill(DetId const&, double = 1., double = 1., double = 1.) override;
void fill(EcalElectronicsId const&, double = 1., double = 1., double = 1.) override;
void fill(int, double = 1., double = 1., double = 1.) override;
void fill(double, double = 1., double = 1.) override;
void setBinContent(DetId const&, int, double) override;
void setBinContent(EcalElectronicsId const&, int, double) override;
void setBinContent(int, int, double) override;
void setBinError(DetId const&, int, double) override;
void setBinError(EcalElectronicsId const&, int, double) override;
void setBinError(int, int, double) override;
void setBinEntries(DetId const&, int, double) override;
void setBinEntries(EcalElectronicsId const&, int, double) override;
void setBinEntries(int, int, double) override;
double getBinContent(DetId const&, int) const override;
double getBinContent(EcalElectronicsId const&, int) const override;
double getBinContent(int, int) const override;
double getBinError(DetId const&, int) const override;
double getBinError(EcalElectronicsId const&, int) const override;
double getBinError(int, int) const override;
double getBinEntries(DetId const&, int) const override;
double getBinEntries(EcalElectronicsId const&, int) const override;
double getBinEntries(int, int) const override;
virtual int findBin(DetId const&, double, double = 0.) const;
virtual int findBin(EcalElectronicsId const&, double, double = 0.) const;
virtual int findBin(int, double, double = 0.) const;
bool isVariableBinning() const override;
std::vector<std::string> generatePaths() const;
protected :
unsigned logicalDimensions_;
binning::AxisSpecs const* xaxis_;
binning::AxisSpecs const* yaxis_;
binning::AxisSpecs const* zaxis_;
private:
template<class Bookable> void doBook_(Bookable&);
};
}
#endif
| 35.367089 | 220 | 0.715104 | [
"object",
"vector"
] |
4ffd15cf621b29de4b42e73b0842f7dc00472966 | 10,905 | h | C | ios/Pods/Headers/Public/ABI40_0_0ReactCommon/ABI40_0_0ReactCommon/ABI40_0_0RCTTurboModule.h | coreplane/expo | e25a063e2f355983ee3db5a1068da4d41a599722 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-06-06T23:56:04.000Z | 2021-06-06T23:56:04.000Z | ios/Pods/Headers/Public/ABI40_0_0ReactCommon/ABI40_0_0ReactCommon/ABI40_0_0RCTTurboModule.h | coreplane/expo | e25a063e2f355983ee3db5a1068da4d41a599722 | [
"Apache-2.0",
"MIT"
] | null | null | null | ios/Pods/Headers/Public/ABI40_0_0ReactCommon/ABI40_0_0ReactCommon/ABI40_0_0RCTTurboModule.h | coreplane/expo | e25a063e2f355983ee3db5a1068da4d41a599722 | [
"Apache-2.0",
"MIT"
] | null | null | null | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#import <memory>
#import <Foundation/Foundation.h>
#import <ABI40_0_0React/ABI40_0_0RCTBridge.h>
#import <ABI40_0_0React/ABI40_0_0RCTBridgeModule.h>
#import <ABI40_0_0React/ABI40_0_0RCTModuleMethod.h>
#import <ABI40_0_0ReactCommon/ABI40_0_0CallInvoker.h>
#import <ABI40_0_0ReactCommon/ABI40_0_0TurboModule.h>
#import <ABI40_0_0ReactCommon/ABI40_0_0TurboModuleUtils.h>
#import <string>
#import <unordered_map>
#define ABI40_0_0RCT_IS_TURBO_MODULE_CLASS(klass) \
((ABI40_0_0RCTTurboModuleEnabled() && [(klass) conformsToProtocol:@protocol(ABI40_0_0RCTTurboModule)]))
#define ABI40_0_0RCT_IS_TURBO_MODULE_INSTANCE(module) ABI40_0_0RCT_IS_TURBO_MODULE_CLASS([(module) class])
typedef int MethodCallId;
/**
* This interface exists to allow the application to collect performance
* metrics of the TurboModule system. By implementing each function, you can
* hook into various stages of TurboModule creation and method dispatch (both async and sync).
*
* Note:
* - TurboModule async method invocations can interleave, so methodCallId should be used as a unique id for a method
* call.
*/
@protocol ABI40_0_0RCTTurboModulePerformanceLogger
// Create TurboModule JS Object
- (void)createTurboModuleStart:(const char *)moduleName;
- (void)createTurboModuleEnd:(const char *)moduleName;
- (void)createTurboModuleCacheHit:(const char *)moduleName;
- (void)getCppTurboModuleFromTMMDelegateStart:(const char *)moduleName;
- (void)getCppTurboModuleFromTMMDelegateEnd:(const char *)moduleName;
- (void)getTurboModuleFromABI40_0_0RCTTurboModuleStart:(const char *)moduleName;
- (void)getTurboModuleFromABI40_0_0RCTTurboModuleEnd:(const char *)moduleName;
- (void)getTurboModuleFromABI40_0_0RCTCxxModuleStart:(const char *)moduleName;
- (void)getTurboModuleFromABI40_0_0RCTCxxModuleEnd:(const char *)moduleName;
- (void)getTurboModuleFromTMMDelegateStart:(const char *)moduleName;
- (void)getTurboModuleFromTMMDelegateEnd:(const char *)moduleName;
// Create ABI40_0_0RCTTurboModule object
- (void)createABI40_0_0RCTTurboModuleStart:(const char *)moduleName;
- (void)createABI40_0_0RCTTurboModuleEnd:(const char *)moduleName;
- (void)createABI40_0_0RCTTurboModuleCacheHit:(const char *)moduleName;
- (void)getABI40_0_0RCTTurboModuleClassStart:(const char *)moduleName;
- (void)getABI40_0_0RCTTurboModuleClassEnd:(const char *)moduleName;
- (void)getABI40_0_0RCTTurboModuleInstanceStart:(const char *)moduleName;
- (void)getABI40_0_0RCTTurboModuleInstanceEnd:(const char *)moduleName;
- (void)setupABI40_0_0RCTTurboModuleDispatch:(const char *)moduleName;
- (void)setupABI40_0_0RCTTurboModuleStart:(const char *)moduleName;
- (void)setupABI40_0_0RCTTurboModuleEnd:(const char *)moduleName;
- (void)attachABI40_0_0RCTBridgeToABI40_0_0RCTTurboModuleStart:(const char *)moduleName;
- (void)attachABI40_0_0RCTBridgeToABI40_0_0RCTTurboModuleEnd:(const char *)moduleName;
- (void)attachMethodQueueToABI40_0_0RCTTurboModuleStart:(const char *)moduleName;
- (void)attachMethodQueueToABI40_0_0RCTTurboModuleEnd:(const char *)moduleName;
- (void)registerABI40_0_0RCTTurboModuleForFrameUpdatesStart:(const char *)moduleName;
- (void)registerABI40_0_0RCTTurboModuleForFrameUpdatesEnd:(const char *)moduleName;
- (void)dispatchDidInitializeModuleNotificationForABI40_0_0RCTTurboModuleStart:(const char *)moduleName;
- (void)dispatchDidInitializeModuleNotificationForABI40_0_0RCTTurboModuleEnd:(const char *)moduleName;
// Sync method invocation
- (void)syncMethodCallStart:(const char *)moduleName
methodName:(const char *)methodName
methodCallId:(MethodCallId)methodCallId;
- (void)syncMethodCallEnd:(const char *)moduleName
methodName:(const char *)methodName
methodCallId:(MethodCallId)methodCallId;
- (void)syncMethodCallArgumentConversionStart:(const char *)moduleName
methodName:(const char *)methodName
methodCallId:(MethodCallId)methodCallId;
- (void)syncMethodCallArgumentConversionEnd:(const char *)moduleName
methodName:(const char *)methodName
methodCallId:(MethodCallId)methodCallId;
- (void)syncABI40_0_0RCTTurboModuleMethodCallStart:(const char *)moduleName
methodName:(const char *)methodName
methodCallId:(MethodCallId)methodCallId;
- (void)syncABI40_0_0RCTTurboModuleMethodCallEnd:(const char *)moduleName
methodName:(const char *)methodName
methodCallId:(MethodCallId)methodCallId;
- (void)syncMethodCallReturnConversionStart:(const char *)moduleName
methodName:(const char *)methodName
methodCallId:(MethodCallId)methodCallId;
- (void)syncMethodCallReturnConversionEnd:(const char *)moduleName
methodName:(const char *)methodName
methodCallId:(MethodCallId)methodCallId;
// Async method invocation
- (void)asyncMethodCallStart:(const char *)moduleName
methodName:(const char *)methodName
methodCallId:(MethodCallId)methodCallId;
- (void)asyncMethodCallEnd:(const char *)moduleName
methodName:(const char *)methodName
methodCallId:(MethodCallId)methodCallId;
- (void)asyncMethodCallArgumentConversionStart:(const char *)moduleName
methodName:(const char *)methodName
methodCallId:(MethodCallId)methodCallId;
- (void)asyncMethodCallArgumentConversionEnd:(const char *)moduleName
methodName:(const char *)methodName
methodCallId:(MethodCallId)methodCallId;
- (void)asyncABI40_0_0RCTTurboModuleMethodCallDispatch:(const char *)moduleName
methodName:(const char *)methodName
methodCallId:(MethodCallId)methodCallId;
- (void)asyncABI40_0_0RCTTurboModuleMethodCallStart:(const char *)moduleName
methodName:(const char *)methodName
methodCallId:(MethodCallId)methodCallId;
- (void)asyncABI40_0_0RCTTurboModuleMethodCallEnd:(const char *)moduleName
methodName:(const char *)methodName
methodCallId:(MethodCallId)methodCallId;
@end
namespace ABI40_0_0facebook {
namespace ABI40_0_0React {
class Instance;
/**
* ObjC++ specific TurboModule base class.
*/
class JSI_EXPORT ObjCTurboModule : public TurboModule {
public:
ObjCTurboModule(
const std::string &name,
id<ABI40_0_0RCTTurboModule> instance,
std::shared_ptr<CallInvoker> jsInvoker,
std::shared_ptr<CallInvoker> nativeInvoker,
id<ABI40_0_0RCTTurboModulePerformanceLogger> perfLogger);
jsi::Value invokeObjCMethod(
jsi::Runtime &runtime,
TurboModuleMethodValueKind valueKind,
const std::string &methodName,
SEL selector,
const jsi::Value *args,
size_t count);
id<ABI40_0_0RCTTurboModule> instance_;
std::shared_ptr<CallInvoker> nativeInvoker_;
protected:
void setMethodArgConversionSelector(NSString *methodName, int argIndex, NSString *fnName);
private:
/**
* TODO(ramanpreet):
* Investigate an optimization that'll let us get rid of this NSMutableDictionary.
*/
NSMutableDictionary<NSString *, NSMutableArray *> *methodArgConversionSelectors_;
NSDictionary<NSString *, NSArray<NSString *> *> *methodArgumentTypeNames_;
NSString *getArgumentTypeName(NSString *methodName, int argIndex);
id<ABI40_0_0RCTTurboModulePerformanceLogger> performanceLogger_;
/**
* Required for performance logging async method invocations.
* This field is static because two nth async method calls from different
* TurboModules can interleave, and should therefore be treated as two distinct calls.
*/
static MethodCallId methodCallId_;
static MethodCallId getNewMethodCallId();
NSInvocation *getMethodInvocation(
jsi::Runtime &runtime,
TurboModuleMethodValueKind returnType,
const char *methodName,
SEL selector,
const jsi::Value *args,
size_t count,
NSMutableArray *retainedObjectsForInvocation,
MethodCallId methodCallId);
jsi::Value performMethodInvocation(
jsi::Runtime &runtime,
TurboModuleMethodValueKind returnType,
const char *methodName,
NSInvocation *inv,
NSMutableArray *retainedObjectsForInvocation,
MethodCallId methodCallId);
BOOL hasMethodArgConversionSelector(NSString *methodName, int argIndex);
SEL getMethodArgConversionSelector(NSString *methodName, int argIndex);
using PromiseInvocationBlock = void (^)(ABI40_0_0RCTPromiseResolveBlock resolveWrapper, ABI40_0_0RCTPromiseRejectBlock rejectWrapper);
jsi::Value
createPromise(jsi::Runtime &runtime, std::shared_ptr<ABI40_0_0React::CallInvoker> jsInvoker, PromiseInvocationBlock invoke);
};
} // namespace ABI40_0_0React
} // namespace ABI40_0_0facebook
@protocol ABI40_0_0RCTTurboModule <NSObject>
@optional
/**
* Used by TurboModules to get access to other TurboModules.
*
* Usage:
* Place `@synthesize turboModuleLookupDelegate = _turboModuleLookupDelegate`
* in the @implementation section of your TurboModule.
*/
@property (nonatomic, weak) id<ABI40_0_0RCTTurboModuleLookupDelegate> turboModuleLookupDelegate;
@optional
// This should be required, after migration is done.
- (std::shared_ptr<ABI40_0_0facebook::ABI40_0_0React::TurboModule>)
getTurboModuleWithJsInvoker:(std::shared_ptr<ABI40_0_0facebook::ABI40_0_0React::CallInvoker>)jsInvoker
nativeInvoker:(std::shared_ptr<ABI40_0_0facebook::ABI40_0_0React::CallInvoker>)nativeInvoker
perfLogger:(id<ABI40_0_0RCTTurboModulePerformanceLogger>)perfLogger;
@end
/**
* These methods are all implemented by ABI40_0_0RCTCxxBridge, which subclasses ABI40_0_0RCTBridge. Hence, they must only be used in
* contexts where the concrete class of an ABI40_0_0RCTBridge instance is ABI40_0_0RCTCxxBridge. This happens, for example, when
* [ABI40_0_0RCTCxxBridgeDelegate jsExecutorFactoryForBridge:(ABI40_0_0RCTBridge *)] is invoked by ABI40_0_0RCTCxxBridge.
*
* TODO: Consolidate this extension with the one in ABI40_0_0RCTSurfacePresenter.
*/
@interface ABI40_0_0RCTBridge (ABI40_0_0RCTTurboModule)
- (std::shared_ptr<ABI40_0_0facebook::ABI40_0_0React::CallInvoker>)jsCallInvoker;
- (std::shared_ptr<ABI40_0_0facebook::ABI40_0_0React::CallInvoker>)decorateNativeCallInvoker:
(std::shared_ptr<ABI40_0_0facebook::ABI40_0_0React::CallInvoker>)nativeInvoker;
@end
| 47.413043 | 136 | 0.745438 | [
"object"
] |
8b122f13f442bbd8513ea3c4a68bc1674f4b7bc9 | 687 | h | C | aws-cpp-sdk-codeguru-reviewer/include/aws/codeguru-reviewer/model/Severity.h | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-codeguru-reviewer/include/aws/codeguru-reviewer/model/Severity.h | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2021-10-14T16:57:00.000Z | 2021-10-18T10:47:24.000Z | aws-cpp-sdk-codeguru-reviewer/include/aws/codeguru-reviewer/model/Severity.h | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/codeguru-reviewer/CodeGuruReviewer_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
namespace Aws
{
namespace CodeGuruReviewer
{
namespace Model
{
enum class Severity
{
NOT_SET,
Info,
Low,
Medium,
High,
Critical
};
namespace SeverityMapper
{
AWS_CODEGURUREVIEWER_API Severity GetSeverityForName(const Aws::String& name);
AWS_CODEGURUREVIEWER_API Aws::String GetNameForSeverity(Severity value);
} // namespace SeverityMapper
} // namespace Model
} // namespace CodeGuruReviewer
} // namespace Aws
| 19.628571 | 78 | 0.742358 | [
"model"
] |
8b1d55aa6017217c1bcf2753c973a010127c970d | 1,225 | h | C | runtime/cpp/src/external/dynamic/string.h | DaMSL/K3 | 51749157844e76ae79dba619116fc5ad9d685643 | [
"Apache-2.0"
] | 17 | 2015-05-27T17:36:33.000Z | 2020-06-07T07:21:29.000Z | runtime/cpp/src/external/dynamic/string.h | DaMSL/K3 | 51749157844e76ae79dba619116fc5ad9d685643 | [
"Apache-2.0"
] | 3 | 2015-10-02T19:37:58.000Z | 2016-01-05T18:26:48.000Z | runtime/cpp/src/external/dynamic/string.h | DaMSL/K3 | 51749157844e76ae79dba619116fc5ad9d685643 | [
"Apache-2.0"
] | 6 | 2015-03-18T20:05:24.000Z | 2020-02-06T21:35:09.000Z | #ifndef STRING_H_INCLUDED
#define STRING_H_INCLUDED
typedef struct string string;
struct string
{
buffer buffer;
};
/* allocators */
string *string_new(char *);
void string_free(string *);
void string_init(string *, char *);
char *string_deconstruct(string *);
/* capacity */
size_t string_length(string *);
size_t string_capacity(string *);
int string_reserve(string *, size_t);
void string_clear(string *);
int string_empty(string *);
int string_shrink_to_fit(string *);
/* modifiers */
int string_prepend(string *, char *);
int string_append(string *, char *);
int string_insert(string *, size_t, char *);
int string_erase(string *, size_t, size_t);
int string_replace(string *, size_t, size_t, char *);
int string_replace_all(string *, char *, char *);
/* string operations */
char *string_data(string *);
int string_copy(string *, char *, size_t, size_t, size_t *);
size_t string_find(string *, char *, size_t);
string *string_substr(string *, size_t, size_t);
int string_compare(string *, string *);
vector *string_split(string *, char *);
/* internals */
void string_split_release(void *);
#endif /* STRING_H_INLCUDED */
| 24.5 | 65 | 0.674286 | [
"vector"
] |
8b1f3245f83cb927a2708e248d2516fc0a08b549 | 6,776 | h | C | source/r_lvd_rx/r_lvd_rx_vx.xx/r_lvd_rx/r_lvd_rx_if.h | HirokiIshiguro/rx-driver-package | 4af73486ecdd07ad58258625e9e8410db2fdaaba | [
"MIT"
] | 6 | 2020-09-13T10:33:02.000Z | 2022-01-06T03:38:34.000Z | source/r_lvd_rx/r_lvd_rx_vx.xx/r_lvd_rx/r_lvd_rx_if.h | HirokiIshiguro/rx-driver-package | 4af73486ecdd07ad58258625e9e8410db2fdaaba | [
"MIT"
] | 20 | 2020-10-08T06:10:28.000Z | 2022-03-16T09:24:31.000Z | source/r_lvd_rx/r_lvd_rx_vx.xx/r_lvd_rx/r_lvd_rx_if.h | HirokiIshiguro/rx-driver-package | 4af73486ecdd07ad58258625e9e8410db2fdaaba | [
"MIT"
] | 2 | 2020-10-10T05:04:51.000Z | 2021-02-24T14:27:19.000Z | /***********************************************************************************************************************
* DISCLAIMER
* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No
* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all
* applicable laws, including copyright laws.
* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING
* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM
* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES
* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS
* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of
* this software. By using this software, you agree to the additional terms and conditions found by accessing the
* following link:
* http://www.renesas.com/disclaimer
*
* Copyright (C) 2016-2019 Renesas Electronics Corporation. All rights reserved.
***********************************************************************************************************************/
/***********************************************************************************************************************
* File Name : r_lvd_rx_if.h
* Description : Functions for using LVD on RX devices.
***********************************************************************************************************************/
/***********************************************************************************************************************
* History : DD.MM.YYYY Version Description
* : 15.06.2016 2.00 First Release
* : 01.10.2016 2.10 Deleted Tool-Chain version.
* : 19.12.2016 2.20 Added support for RX24U, RX24T(512KB).
* : Deleted unnecessary header information.
* : 09.06.2017 2.30 Added support for RX130-512K, RX65N-2M.
* : 28.09.2018 2.40 Added support for RX66T.
* : 01.02.2019 2.50 Added support for RX72T, RX65N-64pin.
* : 20.05.2019 3.00 Added support for GNUC and ICCRX.
***********************************************************************************************************************/
#ifndef LVD_INTERFACE_HEADER_FILE
#define LVD_INTERFACE_HEADER_FILE
/***********************************************************************************************************************
Includes <System Includes> , "Project Includes"
***********************************************************************************************************************/
/* Includes board and MCU related header files. */
#include "platform.h"
/***********************************************************************************************************************
Macro definitions
***********************************************************************************************************************/
#if R_BSP_VERSION_MAJOR < 5
#error "This module must use BSP module of Rev.5.00 or higher. Please use the BSP module of Rev.5.00 or higher."
#endif
/***********************************************************************************************************************
Typedef definitions
***********************************************************************************************************************/
/* This section describes return values which can be used with the LVD FIT module. */
typedef enum
{
LVD_SUCCESS = 0,
LVD_ERR_INVALID_PTR,
LVD_ERR_INVALID_FUNC,
LVD_ERR_INVALID_DATA,
LVD_ERR_INVALID_CHAN,
LVD_ERR_INVALID_ARG,
LVD_ERR_UNSUPPORTED,
LVD_ERR_ALREADY_OPEN,
LVD_ERR_NOT_OPENED,
LVD_ERR_LOCO_STOPPED
} lvd_err_t;
/* This enum defines channels that can be used with the MCU. */
typedef enum
{
LVD_CHANNEL_1 = 0,
LVD_CHANNEL_2,
LVD_CHANNEL_INVALID
} lvd_channel_t;
/* This enum defines voltage detection conditions and influences interrupt conditions and the LVD status. A reset */
/* occurs when the monitored voltage is below the voltage detection level, thus it is not influenced by this enum. */
typedef enum
{
LVD_TRIGGER_RISE = 0,
LVD_TRIGGER_FALL,
LVD_TRIGGER_BOTH,
LVD_TRIGGER_INVALID
}lvd_trigger_t;
/* This enum defines the status whether the monitored voltage is above or below the voltage detection level. */
typedef enum
{
LVD_STATUS_POSITION_ABOVE = 0,
LVD_STATUS_POSITION_BELOW,
LVD_STATUS_POSITION_INVALID
}lvd_status_position_t;
/* This enum defines whether the voltage crossed the voltage detection level. */
typedef enum
{
LVD_STATUS_CROSS_NONE = 0,
LVD_STATUS_CROSS_OVER,
LVD_STATUS_CROSS_INVALID
}lvd_status_cross_t;
/* This data structure defines the structure which is sent to the R_LVD_Open() function. */
typedef struct
{
lvd_trigger_t trigger;
}lvd_config_t;
/* This data structure defines the structure which is sent to the callback function. */
typedef struct
{
bsp_int_src_t vector;
} lvd_int_cb_args_t;
/***********************************************************************************************************************
Imported global variables and functions (from other files)
***********************************************************************************************************************/
extern lvd_err_t R_LVD_Open(lvd_channel_t channel, lvd_config_t const *p_cfg, void (*p_callback)(void *));
extern lvd_err_t R_LVD_Close(lvd_channel_t channel);
extern lvd_err_t R_LVD_GetStatus(lvd_channel_t channel,
lvd_status_position_t *p_status_position,
lvd_status_cross_t *p_status_cross);
extern lvd_err_t R_LVD_ClearStatus(lvd_channel_t channel);
extern uint32_t R_LVD_GetVersion(void);
/***********************************************************************************************************************
Exported global variables and functions (to be accessed by other files)
***********************************************************************************************************************/
#endif /* LVD_INTERFACE_HEADER_FILE */
/* End of File */
| 50.192593 | 121 | 0.512544 | [
"vector"
] |
8b3378c10a6bf56bc43c7e59208ec6866af8a337 | 3,746 | h | C | build/linux-build/Sources/include/hxinc/kha/audio2/ogg/vorbis/VorbisTools.h | 5Mixer/GGJ20 | a12a14d596ab150e8d96dda5a21defcd176f251f | [
"MIT"
] | null | null | null | build/linux-build/Sources/include/hxinc/kha/audio2/ogg/vorbis/VorbisTools.h | 5Mixer/GGJ20 | a12a14d596ab150e8d96dda5a21defcd176f251f | [
"MIT"
] | null | null | null | build/linux-build/Sources/include/hxinc/kha/audio2/ogg/vorbis/VorbisTools.h | 5Mixer/GGJ20 | a12a14d596ab150e8d96dda5a21defcd176f251f | [
"MIT"
] | null | null | null | // Generated by Haxe 4.0.5
#ifndef INCLUDED_kha_audio2_ogg_vorbis_VorbisTools
#define INCLUDED_kha_audio2_ogg_vorbis_VorbisTools
#ifndef HXCPP_H
#include <hxcpp.h>
#endif
HX_DECLARE_CLASS4(kha,audio2,ogg,vorbis,VorbisTools)
HX_DECLARE_CLASS5(kha,audio2,ogg,vorbis,data,IntPoint)
namespace kha{
namespace audio2{
namespace ogg{
namespace vorbis{
class HXCPP_CLASS_ATTRIBUTES VorbisTools_obj : public hx::Object
{
public:
typedef hx::Object super;
typedef VorbisTools_obj OBJ_;
VorbisTools_obj();
public:
enum { _hx_ClassId = 0x2cc82abe };
void __construct();
inline void *operator new(size_t inSize, bool inContainer=false,const char *inName="kha.audio2.ogg.vorbis.VorbisTools")
{ return hx::Object::operator new(inSize,inContainer,inName); }
inline void *operator new(size_t inSize, int extra)
{ return hx::Object::operator new(inSize+extra,false,"kha.audio2.ogg.vorbis.VorbisTools"); }
inline static hx::ObjectPtr< VorbisTools_obj > __new() {
hx::ObjectPtr< VorbisTools_obj > __this = new VorbisTools_obj();
__this->__construct();
return __this;
}
inline static hx::ObjectPtr< VorbisTools_obj > __alloc(hx::Ctx *_hx_ctx) {
VorbisTools_obj *__this = (VorbisTools_obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(VorbisTools_obj), false, "kha.audio2.ogg.vorbis.VorbisTools"));
*(void **)__this = VorbisTools_obj::_hx_vtable;
return __this;
}
static void * _hx_vtable;
static Dynamic __CreateEmpty();
static Dynamic __Create(hx::DynamicArray inArgs);
//~VorbisTools_obj();
HX_DO_RTTI_ALL;
static bool __GetStatic(const ::String &inString, Dynamic &outValue, hx::PropertyAccess inCallProp);
static bool __SetStatic(const ::String &inString, Dynamic &ioValue, hx::PropertyAccess inCallProp);
static void __register();
bool _hx_isInstanceOf(int inClassId);
::String __ToString() const { return HX_("VorbisTools",a8,a9,86,30); }
static void __boot();
static int EOP;
static ::Array< ::Dynamic> integerDivideTable;
static Float M__PI;
static int DIVTAB_NUMER;
static int DIVTAB_DENOM;
static ::Array< Float > INVERSE_DB_TABLE;
static void _hx_assert(bool b, ::Dynamic p);
static ::Dynamic _hx_assert_dyn();
static ::Dynamic neighbors(::Array< int > x,int n);
static ::Dynamic neighbors_dyn();
static Float floatUnpack(int x);
static ::Dynamic floatUnpack_dyn();
static int bitReverse(int n);
static ::Dynamic bitReverse_dyn();
static int pointCompare( ::kha::audio2::ogg::vorbis::data::IntPoint a, ::kha::audio2::ogg::vorbis::data::IntPoint b);
static ::Dynamic pointCompare_dyn();
static int uintAsc(int a,int b);
static ::Dynamic uintAsc_dyn();
static int lookup1Values(int entries,int dim);
static ::Dynamic lookup1Values_dyn();
static void computeWindow(int n,::Array< Float > window);
static ::Dynamic computeWindow_dyn();
static Float square(Float f);
static ::Dynamic square_dyn();
static void computeBitReverse(int n,::Array< int > rev);
static ::Dynamic computeBitReverse_dyn();
static void computeTwiddleFactors(int n,::Array< Float > af,::Array< Float > bf,::Array< Float > cf);
static ::Dynamic computeTwiddleFactors_dyn();
static void drawLine(::Array< Float > output,int x0,int y0,int x1,int y1,int n);
static ::Dynamic drawLine_dyn();
static int predictPoint(int x,int x0,int x1,int y0,int y1);
static ::Dynamic predictPoint_dyn();
static ::Array< Float > emptyFloatVector(int len);
static ::Dynamic emptyFloatVector_dyn();
static ::Array< Float > copyVector(::Array< Float > source);
static ::Dynamic copyVector_dyn();
};
} // end namespace kha
} // end namespace audio2
} // end namespace ogg
} // end namespace vorbis
#endif /* INCLUDED_kha_audio2_ogg_vorbis_VorbisTools */
| 31.745763 | 142 | 0.734116 | [
"object"
] |
8b47f9c04b7ddfabafcfa22fa903796f68f15fc9 | 3,038 | h | C | api/filtering/method_name_filters.h | Project-ARTist/artist | 69e3cb556b50244852e72b1f5c39e60773bdb925 | [
"Apache-2.0"
] | 105 | 2017-04-28T10:31:21.000Z | 2022-03-10T12:05:15.000Z | api/filtering/method_name_filters.h | Project-ARTist/artist | 69e3cb556b50244852e72b1f5c39e60773bdb925 | [
"Apache-2.0"
] | 19 | 2017-07-07T12:02:08.000Z | 2019-01-18T23:30:23.000Z | api/filtering/method_name_filters.h | Project-ARTist/artist | 69e3cb556b50244852e72b1f5c39e60773bdb925 | [
"Apache-2.0"
] | 28 | 2017-05-03T03:33:11.000Z | 2022-02-28T13:26:26.000Z | /**
* The ARTist Project (https://artist.cispa.saarland)
*
* Copyright (C) 2017 CISPA (https://cispa.saarland), Saarland University
*
* 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.
*
* @author "Oliver Schranz <oliver.schranz@cispa.saarland>"
*
*/
#include "filter.h"
#include <vector>
#include <string>
#ifndef ART_API_FILTERING_METHOD_NAME_FILTERS_H_
#define ART_API_FILTERING_METHOD_NAME_FILTERS_H_
using std::vector;
using std::string;
using std::unique_ptr;
namespace art {
/**
* A filter implementation based on a list of method names.
*/
class MethodNameFilter : public Filter {
public:
MethodNameFilter(const vector<const string>& method_names, bool accept_or_deny, bool exact = false,
bool signature = false)
: _names(method_names), _accept(accept_or_deny), _exact(exact), _signature(signature) {}
MethodNameFilter(const MethodNameFilter& other) = default;
MethodNameFilter(MethodNameFilter&& other) = default;
~MethodNameFilter() = default;
MethodNameFilter& operator= (const MethodNameFilter& other) = default;
MethodNameFilter& operator= (MethodNameFilter&& other) = default;
bool accept(const MethodInfo &info) OVERRIDE;
private:
const vector<const string> _names;
const bool _accept;
const bool _exact;
const bool _signature;
};
/**
* A filter implementation that checks candidate method names against a whitelist.
*/
class MethodNameWhitelist : public MethodNameFilter {
public:
MethodNameWhitelist(const vector<const string>& method_names, bool exact = false, bool signature = false) :
MethodNameFilter(method_names, true, exact, signature) {}
};
/**
* A filter implementation that checks candidate method names against a blacklist.
*/
class MethodNameBlacklist : public MethodNameFilter {
public:
MethodNameBlacklist(const vector<const string>& method_names, bool exact = false, bool signature = false) :
MethodNameFilter(method_names, false, exact, signature) {}
};
/**
* A filter implementation that checks method names against two filter,
* which enables one to create a WhiteList with blacklisted exceptions.
*/
class DualFilter : public Filter {
const unique_ptr<Filter> filter1;
const unique_ptr<Filter> filter2;
public:
DualFilter(unique_ptr<Filter>& _filter1,
unique_ptr<Filter>& _filter2)
: filter1(std::move(_filter1))
, filter2(std::move(_filter2)) { }
bool accept(const MethodInfo& info) OVERRIDE;
};
} // namespace art
#endif // ART_API_FILTERING_METHOD_NAME_FILTERS_H_
| 30.38 | 109 | 0.740948 | [
"vector"
] |
8b4aad317ca4394c53c33f537b21d98294ba22b1 | 1,622 | h | C | Source/block.h | Borisas/Old-School-Tetris | 6bd7ea740cc43d9e1b343efe66d6c9ad16b22f70 | [
"MIT"
] | null | null | null | Source/block.h | Borisas/Old-School-Tetris | 6bd7ea740cc43d9e1b343efe66d6c9ad16b22f70 | [
"MIT"
] | null | null | null | Source/block.h | Borisas/Old-School-Tetris | 6bd7ea740cc43d9e1b343efe66d6c9ad16b22f70 | [
"MIT"
] | null | null | null | #ifndef BLOCK_H
#define BLOCK_H
#include "SDL2/SDL.h"
#include "SDL2/SDL_image.h"
#include "SDL2/SDL_opengl.h"
#include <vector>
#include <vector>
#include <iostream>
#include "core.h"
#include <fstream>
#include <stdlib.h>
#include <time.h>
#include <cmath>
using namespace std;
class block
{
public:
block(const char* img, const char* fallimg);
virtual ~block();
void draw();
void set_pos(double x, double y, double w, double h);
void set_speed(int speed);
void drop();
void forceDrop();
void update(int *score);
void loadBlockSetup(const char* file);
void newBlock(int id);
void move(int amount);
void rotate();
void hold();
void collision();
void stopMoving();
void changePos(int x, int y, int id);
int checkClear();
void clear(int line);
void clean();
bool loseCheck();
void newGame();
void modPos(int id, int x, int y);
void instaDrop();
protected:
private:
GLuint texture;
GLuint fall_texture;
box startPos;
box position;
unsigned int current;
int speed;
int rotation;
int tickA;
int tickB;
int tickC;
int tickD;
int tickE;
int tickF;
bool holding;
int c_hold;
bool c_drop;
unsigned int next;
vector<bool> moving;
vector<box> held;
vector<box> temporary;
vector<vector<box> > b_db;
vector<vector<box> > currentBlocks;
};
#endif // BLOCK_H
| 22.84507 | 61 | 0.562885 | [
"vector"
] |
8b523ec149179ee8d73ee9fecbe63a49ac7724a8 | 2,493 | h | C | ThirdParties/SQLite/Examples/sqlite_examples/extract.h | TotteKarlsson/dsl | 3807cbe5f90a3cd495979eafa8cf5485367b634c | [
"BSD-2-Clause"
] | null | null | null | ThirdParties/SQLite/Examples/sqlite_examples/extract.h | TotteKarlsson/dsl | 3807cbe5f90a3cd495979eafa8cf5485367b634c | [
"BSD-2-Clause"
] | null | null | null | ThirdParties/SQLite/Examples/sqlite_examples/extract.h | TotteKarlsson/dsl | 3807cbe5f90a3cd495979eafa8cf5485367b634c | [
"BSD-2-Clause"
] | null | null | null | /* Copyright (C) GPL 2004 Mike Chirico mchirico@users.sourceforge.net mchirico@comcast.net
*
*/
class extract {
public:
extract(std::string d=" \n")
{
delims=d;
}
void setdelims(std::string d)
{
delims=d;
}
void setterm(std::string t="")
{
terminator=t;
}
void strip(std::string s ) {
v.clear();
bidx=s.find_first_not_of(delims);
while(bidx != std::string::npos) {
eidx=s.find_first_of(delims,bidx);
if (eidx == std::string::npos) {
eidx = s.length();
}
v.push_back(s.substr(bidx,(eidx-bidx)));
bidx=s.find_first_not_of(delims,eidx);
}
index();
}
std::vector<std::string>::iterator BEGIN()
{
return indexv.begin();
}
std::vector<std::string>::iterator END()
{
return indexv.end();
}
std::string I(unsigned int i)
{
if ( i < indexv.size() && indexv.size() > 0 )
return indexv[i];
else
if ( indexv.size() > 0 )
return indexv[ indexv.size()-1];
else
return "";
}
std::string F()
{
std::string s="";
std::string d="";
for(std::vector<std::string>::iterator i = indexv.begin(); i < indexv.end(); ++i)
{
s=s + d + *i;
d=",";
}
return s;
}
std::string NF()
{
std::string s="(";
std::string d="";
for(std::vector<std::string>::iterator i = indexv.begin(); i < indexv.end(); ++i)
{
s=s + d + *i;
d=",";
}
s+=")";
return s;
}
int TL()
{
return tree_level;
}
private:
void index()
{
int rcount=0;
tree_level=0;
std::string t="";
indexv.clear();
for(std::vector<std::string>::iterator i = v.begin(); i < v.end(); ++i)
{
for(std::string::iterator j = i->begin(); j < i->end(); ++j)
{
while( *j == '(' && j < i->end() )
{
rcount++;
if(rcount > tree_level)
tree_level=rcount;
if ( rcount > 1)
t+=*j;
j++;
}
while( *j != ')' && j < i->end() ) {
t+=*j;
j++;
}
while( *j == ')' && j < i->end() ) {
if ( rcount > 1)
t+=*j;
rcount--;
j++;
}
if ( rcount <= 1)
{
indexv.push_back(t);
t="";
} else { t+=","; }
}
}
}
std::string::size_type bidx,eidx;
std::string delims,terminator;
std::vector<std::string> indexv;
std::vector<std::string> v;
int tree_level;
};
| 17.556338 | 90 | 0.46771 | [
"vector"
] |
8b54e29ac4cff79905de0dc5682fc5e10aa0d3b3 | 3,825 | h | C | cartographer/mapping/internal/optimization/cost_functions/cost_helpers.h | laotie/cartographer | b8228ee6564f5a7ad0d6d0b9a30516521cff2ee9 | [
"Apache-2.0"
] | 5,196 | 2016-08-04T14:52:31.000Z | 2020-04-02T18:30:00.000Z | cartographer/mapping/internal/optimization/cost_functions/cost_helpers.h | laotie/cartographer | b8228ee6564f5a7ad0d6d0b9a30516521cff2ee9 | [
"Apache-2.0"
] | 1,206 | 2016-08-03T14:27:00.000Z | 2020-03-31T21:14:18.000Z | cartographer/mapping/internal/optimization/cost_functions/cost_helpers.h | laotie/cartographer | b8228ee6564f5a7ad0d6d0b9a30516521cff2ee9 | [
"Apache-2.0"
] | 1,810 | 2016-08-03T05:45:02.000Z | 2020-04-02T03:44:18.000Z | /*
* Copyright 2018 The Cartographer 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.
*/
#ifndef CARTOGRAPHER_MAPPING_INTERNAL_OPTIMIZATION_COST_FUNCTIONS_COST_HELPERS_H_
#define CARTOGRAPHER_MAPPING_INTERNAL_OPTIMIZATION_COST_FUNCTIONS_COST_HELPERS_H_
#include "Eigen/Core"
#include "Eigen/Geometry"
#include "cartographer/transform/rigid_transform.h"
#include "cartographer/transform/transform.h"
namespace cartographer {
namespace mapping {
namespace optimization {
// Computes the error between the given relative pose and the difference of
// poses 'start' and 'end' which are both in an arbitrary common frame.
//
// 'start' and 'end' poses have the format [x, y, rotation].
template <typename T>
static std::array<T, 3> ComputeUnscaledError(
const transform::Rigid2d& relative_pose, const T* const start,
const T* const end);
template <typename T>
std::array<T, 3> ScaleError(const std::array<T, 3>& error,
double translation_weight, double rotation_weight);
// Computes the error between the given relative pose and the difference of
// poses 'start' and 'end' which are both in an arbitrary common frame.
//
// 'start' and 'end' translation has the format [x, y, z].
// 'start' and 'end' rotation are quaternions in the format [w, n_1, n_2, n_3].
template <typename T>
static std::array<T, 6> ComputeUnscaledError(
const transform::Rigid3d& relative_pose, const T* const start_rotation,
const T* const start_translation, const T* const end_rotation,
const T* const end_translation);
template <typename T>
std::array<T, 6> ScaleError(const std::array<T, 6>& error,
double translation_weight, double rotation_weight);
// Computes spherical linear interpolation of unit quaternions.
//
// 'start' and 'end' are quaternions in the format [w, n_1, n_2, n_3].
template <typename T>
std::array<T, 4> SlerpQuaternions(const T* const start, const T* const end,
double factor);
// Interpolates 3D poses. Linear interpolation is performed for translation and
// spherical-linear one for rotation.
template <typename T>
std::tuple<std::array<T, 4> /* rotation */, std::array<T, 3> /* translation */>
InterpolateNodes3D(const T* const prev_node_rotation,
const T* const prev_node_translation,
const T* const next_node_rotation,
const T* const next_node_translation,
const double interpolation_parameter);
// Embeds 2D poses into 3D and interpolates them. Linear interpolation is
// performed for translation and spherical-linear one for rotation.
template <typename T>
std::tuple<std::array<T, 4> /* rotation */, std::array<T, 3> /* translation */>
InterpolateNodes2D(const T* const prev_node_pose,
const Eigen::Quaterniond& prev_node_gravity_alignment,
const T* const next_node_pose,
const Eigen::Quaterniond& next_node_gravity_alignment,
const double interpolation_parameter);
} // namespace optimization
} // namespace mapping
} // namespace cartographer
#include "cartographer/mapping/internal/optimization/cost_functions/cost_helpers_impl.h"
#endif // CARTOGRAPHER_MAPPING_INTERNAL_OPTIMIZATION_COST_FUNCTIONS_COST_HELPERS_H_
| 42.5 | 88 | 0.721046 | [
"geometry",
"transform",
"3d"
] |
a00fbbfd3826ee1f8b3412d4e34a5b202a44de85 | 6,446 | h | C | packages/@lse/core/addon/lse-core/lse/Style.h | lightsourceengine/LightSourceEngine | bc2d0cc08907f65a900d924d1a0ab19164171cb5 | [
"Apache-2.0"
] | null | null | null | packages/@lse/core/addon/lse-core/lse/Style.h | lightsourceengine/LightSourceEngine | bc2d0cc08907f65a900d924d1a0ab19164171cb5 | [
"Apache-2.0"
] | 5 | 2020-07-23T01:09:07.000Z | 2020-09-09T05:32:29.000Z | packages/@lse/core/addon/lse-core/lse/Style.h | lightsourceengine/LightSourceEngine | bc2d0cc08907f65a900d924d1a0ab19164171cb5 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2021 Light Source Software, LLC. 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.
*/
#pragma once
#include <lse/Reference.h>
#include <lse/StyleEnums.h>
#include <lse/Color.h>
#include <lse/math-ext.h>
#include <Yoga.h>
#include <phmap.h>
#include <phmap_utils.h>
#include <std17/optional>
namespace lse {
/**
* Number Style property value. Wraps a float value with a unit type.
*/
struct StyleValue {
float value{ kUndefined };
StyleNumberUnit unit{ StyleNumberUnitUndefined };
StyleValue() = default;
StyleValue(float value, StyleNumberUnit unit) : value(value), unit(unit) {
if (std::isnan(value)) {
this->value = kUndefined;
this->unit = StyleNumberUnitUndefined;
}
}
StyleValue(float value, int32_t unit) : value(value) {
if (!IsEnum<StyleNumberUnit>(unit) || std::isnan(value)) {
this->value = kUndefined;
this->unit = StyleNumberUnitUndefined;
}
this->unit = static_cast<StyleNumberUnit>(unit);
}
bool IsUndefined() const noexcept {
return this->unit == StyleNumberUnitUndefined;
}
bool IsAuto() const noexcept {
return this->unit == StyleNumberUnitAuto;
}
static StyleValue OfAuto() noexcept {
return { 0, StyleNumberUnitAuto };
}
static StyleValue OfUndefined() noexcept {
return {};
}
static StyleValue OfPoint(float value) noexcept {
return { value, StyleNumberUnitPoint };
}
static StyleValue OfAnchor(StyleAnchor anchor) noexcept {
return { static_cast<float>(anchor), StyleNumberUnitAnchor };
}
};
bool operator==(const StyleValue& a, const StyleValue& b) noexcept;
bool operator!=(const StyleValue& a, const StyleValue& b) noexcept;
/**
* Entry in transform Style property array representing specific transforms of identity, rotate, scale and translate.
*/
struct StyleTransformSpec {
StyleTransform transform{};
StyleValue x{};
StyleValue y{};
StyleValue angle{};
static StyleTransformSpec OfIdentity() {
return { StyleTransformIdentity, {}, {}, {}};
}
static StyleTransformSpec OfScale(const StyleValue& x, const StyleValue& y) {
return { StyleTransformScale, x, y, {}};
}
static StyleTransformSpec OfTranslate(const StyleValue& x, const StyleValue& y) {
return { StyleTransformTranslate, x, y, {}};
}
static StyleTransformSpec OfRotate(const StyleValue& angle) {
return { StyleTransformRotate, {}, {}, angle };
}
};
bool operator==(const StyleTransformSpec& a, const StyleTransformSpec& b) noexcept;
bool operator!=(const StyleTransformSpec& a, const StyleTransformSpec& b) noexcept;
struct StyleFilterFunction {
StyleFilter filter{};
color_t color{};
};
bool operator==(const StyleFilterFunction& a, const StyleFilterFunction& b) noexcept;
bool operator!=(const StyleFilterFunction& a, const StyleFilterFunction& b) noexcept;
class Style : public Reference {
public:
~Style() override;
// enum based properties
void SetEnum(StyleProperty property, const char* value);
const char* GetEnumString(StyleProperty property);
int32_t GetEnum(StyleProperty property);
template<typename T>
T GetEnum(StyleProperty property) {
return static_cast<T>(this->GetEnum(property));
}
// color based properties
void SetColor(StyleProperty property, color_t color);
std17::optional<color_t> GetColor(StyleProperty property);
// string based properties
void SetString(StyleProperty property, std::string&& value);
const std::string& GetString(StyleProperty property);
// number or StyleValue based properties
void SetNumber(StyleProperty property, const StyleValue& value);
const StyleValue& GetNumber(StyleProperty property);
// integer based properties
std17::optional<int32_t> GetInteger(StyleProperty property);
void SetInteger(StyleProperty property, int32_t value);
// transform property
void SetTransform(std::vector<StyleTransformSpec>&& transform);
const std::vector<StyleTransformSpec>& GetTransform();
// filter property
void SetFilter(std::vector<StyleFilterFunction>&& filter);
const std::vector<StyleFilterFunction>& GetFilter();
// property existence: these function will check the parent!
bool IsEmpty(StyleProperty property) const noexcept;
bool Exists(StyleProperty property) const noexcept { return !this->IsEmpty(property); }
// Clear a property.
void SetUndefined(StyleProperty property);
// Change listener. Called when a property value changes (set undefined or set to new value)
void SetChangeListener(std::function<void(StyleProperty)>&& changeListener) noexcept;
void ClearChangeListener() noexcept;
// Set the parent. If a value in this style is undefined, the parent will be queried.
void SetParent(Style* parent) noexcept;
// Handle root font size and viewport changes. The method will force a change on properties that use rem, vw, vmin,
// etc units.
void OnMediaChange(bool remChange, bool viewportChange) noexcept;
void Reset();
void Lock() noexcept { this->locked = true; }
bool IsLocked() const noexcept { return this->locked; }
static void Init();
static Style* Or(Style* style) noexcept;
private:
using StylePropertySet = phmap::flat_hash_set<StyleProperty>;
void GatherDefinedProperties(StylePropertySet& properties);
bool IsEmpty(StyleProperty property, bool includeParent) const noexcept;
private:
// Style state
bool locked{false};
Style* parent{};
std::function<void(StyleProperty)> onChange;
// Property buckets
phmap::flat_hash_map<StyleProperty, color_t> colorMap;
phmap::flat_hash_map<StyleProperty, std::string> stringMap;
phmap::flat_hash_map<StyleProperty, StyleValue> numberMap;
phmap::flat_hash_map<StyleProperty, int32_t> enumMap;
std::vector<StyleTransformSpec> transform;
std::vector<StyleFilterFunction> filter;
// Static helpers
static StylePropertySet tempDefinedProperties;
static Style empty;
};
} // namespace lse
| 30.842105 | 118 | 0.736426 | [
"vector",
"transform"
] |
a015c23071febdb50879cf4886924a8156bc9511 | 29,766 | h | C | VirtualBox-5.0.0/src/VBox/Frontends/VirtualBox/src/extradata/UIExtraDataManager.h | egraba/vbox_openbsd | 6cb82f2eed1fa697d088cecc91722b55b19713c2 | [
"MIT"
] | 1 | 2015-04-30T14:18:45.000Z | 2015-04-30T14:18:45.000Z | VirtualBox-5.0.0/src/VBox/Frontends/VirtualBox/src/extradata/UIExtraDataManager.h | egraba/vbox_openbsd | 6cb82f2eed1fa697d088cecc91722b55b19713c2 | [
"MIT"
] | null | null | null | VirtualBox-5.0.0/src/VBox/Frontends/VirtualBox/src/extradata/UIExtraDataManager.h | egraba/vbox_openbsd | 6cb82f2eed1fa697d088cecc91722b55b19713c2 | [
"MIT"
] | null | null | null | /* $Id: UIExtraDataManager.h $ */
/** @file
* VBox Qt GUI - UIExtraDataManager class declaration.
*/
/*
* Copyright (C) 2010-2014 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
#ifndef ___UIExtraDataManager_h___
#define ___UIExtraDataManager_h___
/* Qt includes: */
#include <QObject>
#include <QMap>
#ifdef DEBUG
# include <QPointer>
#endif /* DEBUG */
/* GUI includes: */
#include "UIExtraDataDefs.h"
/* COM includes: */
#include "CEventListener.h"
/* Forward declarations: */
class UIExtraDataEventHandler;
#ifdef DEBUG
class UIExtraDataManagerWindow;
#endif /* DEBUG */
/* Type definitions: */
typedef QMap<QString, QString> ExtraDataMap;
/** Singleton QObject extension
* providing GUI with corresponding extra-data values,
* and notifying it whenever any of those values changed. */
class UIExtraDataManager : public QObject
{
Q_OBJECT;
/** Extra-data Manager constructor. */
UIExtraDataManager();
/** Extra-data Manager destructor. */
~UIExtraDataManager();
signals:
/** Notifies about extra-data map acknowledging. */
void sigExtraDataMapAcknowledging(QString strID);
/** Notifies about extra-data change. */
void sigExtraDataChange(QString strID, QString strKey, QString strValue);
/** Notifies about GUI language change. */
void sigLanguageChange(QString strLanguage);
/** Notifies about Selector UI keyboard shortcut change. */
void sigSelectorUIShortcutChange();
/** Notifies about Runtime UI keyboard shortcut change. */
void sigRuntimeUIShortcutChange();
/** Notifies about menu-bar configuration change. */
void sigMenuBarConfigurationChange(const QString &strMachineID);
/** Notifies about status-bar configuration change. */
void sigStatusBarConfigurationChange(const QString &strMachineID);
/** Notifies about HID LEDs synchronization state change. */
void sigHidLedsSyncStateChange(bool fEnabled);
/** Notifies about the scale-factor change. */
void sigScaleFactorChange(const QString &strMachineID);
/** Notifies about the scaling optimization type change. */
void sigScalingOptimizationTypeChange(const QString &strMachineID);
/** Notifies about the HiDPI optimization type change. */
void sigHiDPIOptimizationTypeChange(const QString &strMachineID);
/** Notifies about unscaled HiDPI output mode change. */
void sigUnscaledHiDPIOutputModeChange(const QString &strMachineID);
#ifdef RT_OS_DARWIN
/** Mac OS X: Notifies about 'dock icon' appearance change. */
void sigDockIconAppearanceChange(bool fEnabled);
#endif /* RT_OS_DARWIN */
public:
/** Global extra-data ID. */
static const QString GlobalID;
/** Static Extra-data Manager instance/constructor. */
static UIExtraDataManager* instance();
/** Static Extra-data Manager destructor. */
static void destroy();
#ifdef DEBUG
/** Static show and raise API. */
static void openWindow(QWidget *pCenterWidget);
#endif /* DEBUG */
/** @name General
* @{ */
/** Returns whether Extra-data Manager cached the map with passed @a strID. */
bool contains(const QString &strID) const { return m_data.contains(strID); }
/** Returns read-only extra-data map for passed @a strID. */
const ExtraDataMap map(const QString &strID) const { return m_data.value(strID); }
/** Hot-load machine extra-data map. */
void hotloadMachineExtraDataMap(const QString &strID);
/** Returns extra-data value corresponding to passed @a strKey as QString.
* If valid @a strID is set => applies to machine extra-data, otherwise => to global one. */
QString extraDataString(const QString &strKey, const QString &strID = GlobalID);
/** Defines extra-data value corresponding to passed @a strKey as strValue.
* If valid @a strID is set => applies to machine extra-data, otherwise => to global one. */
void setExtraDataString(const QString &strKey, const QString &strValue, const QString &strID = GlobalID);
/** Returns extra-data value corresponding to passed @a strKey as QStringList.
* If valid @a strID is set => applies to machine extra-data, otherwise => to global one. */
QStringList extraDataStringList(const QString &strKey, const QString &strID = GlobalID);
/** Defines extra-data value corresponding to passed @a strKey as value.
* If valid @a strID is set => applies to machine extra-data, otherwise => to global one. */
void setExtraDataStringList(const QString &strKey, const QStringList &value, const QString &strID = GlobalID);
/** @} */
/** @name Messaging
* @{ */
/** Returns the list of supressed messages for the Message/Popup center frameworks. */
QStringList suppressedMessages();
/** Defines the @a list of supressed messages for the Message/Popup center frameworks. */
void setSuppressedMessages(const QStringList &list);
/** Returns the list of messages for the Message/Popup center frameworks with inverted check-box state. */
QStringList messagesWithInvertedOption();
#if !defined(VBOX_BLEEDING_EDGE) && !defined(DEBUG)
/** Returns version for which user wants to prevent BETA build warning. */
QString preventBetaBuildWarningForVersion();
#endif /* !defined(VBOX_BLEEDING_EDGE) && !defined(DEBUG) */
/** @} */
#ifdef VBOX_GUI_WITH_NETWORK_MANAGER
/** @name Application Update
* @{ */
/** Returns whether Application Update functionality enabled. */
bool applicationUpdateEnabled();
/** Returns Application Update data. */
QString applicationUpdateData();
/** Defines Application Update data as @a strValue. */
void setApplicationUpdateData(const QString &strValue);
/** Returns Application Update check counter. */
qulonglong applicationUpdateCheckCounter();
/** Increments Application Update check counter. */
void incrementApplicationUpdateCheckCounter();
/** @} */
#endif /* VBOX_GUI_WITH_NETWORK_MANAGER */
/** @name Settings
* @{ */
/** Returns restricted global settings pages. */
QList<GlobalSettingsPageType> restrictedGlobalSettingsPages();
/** Returns restricted machine settings pages. */
QList<MachineSettingsPageType> restrictedMachineSettingsPages(const QString &strID);
/** @} */
/** @name Settings: Display
* @{ */
/** Returns whether hovered machine-window should be activated. */
bool activateHoveredMachineWindow();
/** Defines whether hovered machine-window should be @a fActivated. */
void setActivateHoveredMachineWindow(bool fActivate);
/** @} */
/** @name Settings: Keyboard
* @{ */
/** Returns shortcut overrides for shortcut-pool with @a strPoolExtraDataID. */
QStringList shortcutOverrides(const QString &strPoolExtraDataID);
/** @} */
/** @name Settings: Storage
* @{ */
/** Returns recent folder for hard-drives. */
QString recentFolderForHardDrives();
/** Returns recent folder for optical-disks. */
QString recentFolderForOpticalDisks();
/** Returns recent folder for floppy-disks. */
QString recentFolderForFloppyDisks();
/** Defines recent folder for hard-drives as @a strValue. */
void setRecentFolderForHardDrives(const QString &strValue);
/** Defines recent folder for optical-disk as @a strValue. */
void setRecentFolderForOpticalDisks(const QString &strValue);
/** Defines recent folder for floppy-disk as @a strValue. */
void setRecentFolderForFloppyDisks(const QString &strValue);
/** Returns the list of recently used hard-drives. */
QStringList recentListOfHardDrives();
/** Returns the list of recently used optical-disk. */
QStringList recentListOfOpticalDisks();
/** Returns the list of recently used floppy-disk. */
QStringList recentListOfFloppyDisks();
/** Defines the list of recently used hard-drives as @a value. */
void setRecentListOfHardDrives(const QStringList &value);
/** Defines the list of recently used optical-disks as @a value. */
void setRecentListOfOpticalDisks(const QStringList &value);
/** Defines the list of recently used floppy-disks as @a value. */
void setRecentListOfFloppyDisks(const QStringList &value);
/** @} */
/** @name VirtualBox Manager
* @{ */
/** Returns selector-window geometry using @a pWidget as the hint. */
QRect selectorWindowGeometry(QWidget *pWidget);
/** Returns whether selector-window should be maximized. */
bool selectorWindowShouldBeMaximized();
/** Defines selector-window @a geometry and @a fMaximized state. */
void setSelectorWindowGeometry(const QRect &geometry, bool fMaximized);
/** Returns selector-window splitter hints. */
QList<int> selectorWindowSplitterHints();
/** Defines selector-window splitter @a hints. */
void setSelectorWindowSplitterHints(const QList<int> &hints);
/** Returns whether selector-window tool-bar visible. */
bool selectorWindowToolBarVisible();
/** Defines whether selector-window tool-bar @a fVisible. */
void setSelectorWindowToolBarVisible(bool fVisible);
/** Returns whether selector-window status-bar visible. */
bool selectorWindowStatusBarVisible();
/** Defines whether selector-window status-bar @a fVisible. */
void setSelectorWindowStatusBarVisible(bool fVisible);
/** Clears all the existing selector-window chooser-pane' group definitions. */
void clearSelectorWindowGroupsDefinitions();
/** Returns selector-window chooser-pane' groups definitions for passed @a strGroupID. */
QStringList selectorWindowGroupsDefinitions(const QString &strGroupID);
/** Defines selector-window chooser-pane' groups @a definitions for passed @a strGroupID. */
void setSelectorWindowGroupsDefinitions(const QString &strGroupID, const QStringList &definitions);
/** Returns last-item ID of the item chosen in selector-window chooser-pane. */
QString selectorWindowLastItemChosen();
/** Defines @a lastItemID of the item chosen in selector-window chooser-pane. */
void setSelectorWindowLastItemChosen(const QString &strItemID);
/** Returns selector-window details-pane' elements. */
QMap<DetailsElementType, bool> selectorWindowDetailsElements();
/** Defines selector-window details-pane' @a elements. */
void setSelectorWindowDetailsElements(const QMap<DetailsElementType, bool> &elements);
/** Returns selector-window details-pane' preview update interval. */
PreviewUpdateIntervalType selectorWindowPreviewUpdateInterval();
/** Defines selector-window details-pane' preview update @a interval. */
void setSelectorWindowPreviewUpdateInterval(PreviewUpdateIntervalType interval);
/** @} */
/** @name Wizards
* @{ */
/** Returns mode for wizard of passed @a type. */
WizardMode modeForWizardType(WizardType type);
/** Defines @a mode for wizard of passed @a type. */
void setModeForWizardType(WizardType type, WizardMode mode);
/** @} */
/** @name Virtual Machine
* @{ */
/** Returns whether machine should be shown in selector-window chooser-pane. */
bool showMachineInSelectorChooser(const QString &strID);
/** Returns whether machine should be shown in selector-window details-pane. */
bool showMachineInSelectorDetails(const QString &strID);
/** Returns whether machine reconfiguration enabled. */
bool machineReconfigurationEnabled(const QString &strID);
/** Returns whether machine snapshot operations enabled. */
bool machineSnapshotOperationsEnabled(const QString &strID);
/** Returns whether this machine is first time started. */
bool machineFirstTimeStarted(const QString &strID);
/** Returns whether this machine is fFirstTimeStarted. */
void setMachineFirstTimeStarted(bool fFirstTimeStarted, const QString &strID);
#ifndef Q_WS_MAC
/** Except Mac OS X: Returns redefined machine-window icon names. */
QStringList machineWindowIconNames(const QString &strID);
/** Except Mac OS X: Returns redefined machine-window name postfix. */
QString machineWindowNamePostfix(const QString &strID);
#endif /* !Q_WS_MAC */
/** Returns geometry for machine-window with @a uScreenIndex in @a visualStateType. */
QRect machineWindowGeometry(UIVisualStateType visualStateType, ulong uScreenIndex, const QString &strID);
/** Returns whether machine-window with @a uScreenIndex in @a visualStateType should be maximized. */
bool machineWindowShouldBeMaximized(UIVisualStateType visualStateType, ulong uScreenIndex, const QString &strID);
/** Defines @a geometry and @a fMaximized state for machine-window with @a uScreenIndex in @a visualStateType. */
void setMachineWindowGeometry(UIVisualStateType visualStateType, ulong uScreenIndex, const QRect &geometry, bool fMaximized, const QString &strID);
#ifndef Q_WS_MAC
/** Returns whether Runtime UI menu-bar is enabled. */
bool menuBarEnabled(const QString &strID);
/** Defines whether Runtime UI menu-bar is @a fEnabled. */
void setMenuBarEnabled(bool fEnabled, const QString &strID);
#endif /* !Q_WS_MAC */
/** Returns restricted Runtime UI menu types. */
UIExtraDataMetaDefs::MenuType restrictedRuntimeMenuTypes(const QString &strID);
/** Defines restricted Runtime UI menu types. */
void setRestrictedRuntimeMenuTypes(UIExtraDataMetaDefs::MenuType types, const QString &strID);
/** Returns restricted Runtime UI action types for Application menu. */
UIExtraDataMetaDefs::MenuApplicationActionType restrictedRuntimeMenuApplicationActionTypes(const QString &strID);
/** Defines restricted Runtime UI action types for Application menu. */
void setRestrictedRuntimeMenuApplicationActionTypes(UIExtraDataMetaDefs::MenuApplicationActionType types, const QString &strID);
/** Returns restricted Runtime UI action types for Machine menu. */
UIExtraDataMetaDefs::RuntimeMenuMachineActionType restrictedRuntimeMenuMachineActionTypes(const QString &strID);
/** Defines restricted Runtime UI action types for Machine menu. */
void setRestrictedRuntimeMenuMachineActionTypes(UIExtraDataMetaDefs::RuntimeMenuMachineActionType types, const QString &strID);
/** Returns restricted Runtime UI action types for View menu. */
UIExtraDataMetaDefs::RuntimeMenuViewActionType restrictedRuntimeMenuViewActionTypes(const QString &strID);
/** Defines restricted Runtime UI action types for View menu. */
void setRestrictedRuntimeMenuViewActionTypes(UIExtraDataMetaDefs::RuntimeMenuViewActionType types, const QString &strID);
/** Returns restricted Runtime UI action types for Input menu. */
UIExtraDataMetaDefs::RuntimeMenuInputActionType restrictedRuntimeMenuInputActionTypes(const QString &strID);
/** Defines restricted Runtime UI action types for Input menu. */
void setRestrictedRuntimeMenuInputActionTypes(UIExtraDataMetaDefs::RuntimeMenuInputActionType types, const QString &strID);
/** Returns restricted Runtime UI action types for Devices menu. */
UIExtraDataMetaDefs::RuntimeMenuDevicesActionType restrictedRuntimeMenuDevicesActionTypes(const QString &strID);
/** Defines restricted Runtime UI action types for Devices menu. */
void setRestrictedRuntimeMenuDevicesActionTypes(UIExtraDataMetaDefs::RuntimeMenuDevicesActionType types, const QString &strID);
#ifdef VBOX_WITH_DEBUGGER_GUI
/** Returns restricted Runtime UI action types for Debugger menu. */
UIExtraDataMetaDefs::RuntimeMenuDebuggerActionType restrictedRuntimeMenuDebuggerActionTypes(const QString &strID);
/** Defines restricted Runtime UI action types for Debugger menu. */
void setRestrictedRuntimeMenuDebuggerActionTypes(UIExtraDataMetaDefs::RuntimeMenuDebuggerActionType types, const QString &strID);
#endif /* VBOX_WITH_DEBUGGER_GUI */
#ifdef Q_WS_MAC
/** Mac OS X: Returns restricted Runtime UI action types for Window menu. */
UIExtraDataMetaDefs::MenuWindowActionType restrictedRuntimeMenuWindowActionTypes(const QString &strID);
/** Mac OS X: Defines restricted Runtime UI action types for Window menu. */
void setRestrictedRuntimeMenuWindowActionTypes(UIExtraDataMetaDefs::MenuWindowActionType types, const QString &strID);
#endif /* Q_WS_MAC */
/** Returns restricted Runtime UI action types for Help menu. */
UIExtraDataMetaDefs::MenuHelpActionType restrictedRuntimeMenuHelpActionTypes(const QString &strID);
/** Defines restricted Runtime UI action types for Help menu. */
void setRestrictedRuntimeMenuHelpActionTypes(UIExtraDataMetaDefs::MenuHelpActionType types, const QString &strID);
/** Returns restricted Runtime UI visual-states. */
UIVisualStateType restrictedVisualStates(const QString &strID);
/** Returns requested Runtime UI visual-state. */
UIVisualStateType requestedVisualState(const QString &strID);
/** Defines requested Runtime UI visual-state as @a visualState. */
void setRequestedVisualState(UIVisualStateType visualState, const QString &strID);
#ifdef Q_WS_X11
/** Returns whether legacy full-screen mode is requested. */
bool legacyFullscreenModeRequested();
#endif /* Q_WS_X11 */
/** Returns whether guest-screen auto-resize according machine-window size is enabled. */
bool guestScreenAutoResizeEnabled(const QString &strID);
/** Defines whether guest-screen auto-resize according machine-window size is @a fEnabled. */
void setGuestScreenAutoResizeEnabled(bool fEnabled, const QString &strID);
/** Returns last guest-screen visibility status for screen with @a uScreenIndex. */
bool lastGuestScreenVisibilityStatus(ulong uScreenIndex, const QString &strID);
/** Defines whether last guest-screen visibility status was @a fEnabled for screen with @a uScreenIndex. */
void setLastGuestScreenVisibilityStatus(ulong uScreenIndex, bool fEnabled, const QString &strID);
/** Returns last guest-screen size-hint for screen with @a uScreenIndex. */
QSize lastGuestScreenSizeHint(ulong uScreenIndex, const QString &strID);
/** Defines last guest-screen @a sizeHint for screen with @a uScreenIndex. */
void setLastGuestScreenSizeHint(ulong uScreenIndex, const QSize &sizeHint, const QString &strID);
/** Returns host-screen index corresponding to passed guest-screen @a iGuestScreenIndex. */
int hostScreenForPassedGuestScreen(int iGuestScreenIndex, const QString &strID);
/** Defines @a iHostScreenIndex corresponding to passed guest-screen @a iGuestScreenIndex. */
void setHostScreenForPassedGuestScreen(int iGuestScreenIndex, int iHostScreenIndex, const QString &strID);
/** Returns whether automatic mounting/unmounting of guest-screens enabled. */
bool autoMountGuestScreensEnabled(const QString &strID);
#ifdef VBOX_WITH_VIDEOHWACCEL
/** Returns whether 2D acceleration should use linear sretch. */
bool useLinearStretch(const QString &strID);
/** Returns whether 2D acceleration should use YV12 pixel format. */
bool usePixelFormatYV12(const QString &strID);
/** Returns whether 2D acceleration should use UYVY pixel format. */
bool usePixelFormatUYVY(const QString &strID);
/** Returns whether 2D acceleration should use YUY2 pixel format. */
bool usePixelFormatYUY2(const QString &strID);
/** Returns whether 2D acceleration should use AYUV pixel format. */
bool usePixelFormatAYUV(const QString &strID);
#endif /* VBOX_WITH_VIDEOHWACCEL */
/** Returns whether Runtime UI should use unscaled HiDPI output. */
bool useUnscaledHiDPIOutput(const QString &strID);
/** Defines whether Runtime UI should @a fUseUnscaledHiDPIOutput. */
void setUseUnscaledHiDPIOutput(bool fUseUnscaledHiDPIOutput, const QString &strID);
/** Returns Runtime UI HiDPI optimization type. */
HiDPIOptimizationType hiDPIOptimizationType(const QString &strID);
#ifndef Q_WS_MAC
/** Returns whether mini-toolbar is enabled for full and seamless screens. */
bool miniToolbarEnabled(const QString &strID);
/** Defines whether mini-toolbar is @a fEnabled for full and seamless screens. */
void setMiniToolbarEnabled(bool fEnabled, const QString &strID);
/** Returns whether mini-toolbar should auto-hide itself. */
bool autoHideMiniToolbar(const QString &strID);
/** Defines whether mini-toolbar should @a fAutoHide itself. */
void setAutoHideMiniToolbar(bool fAutoHide, const QString &strID);
/** Returns mini-toolbar alignment. */
Qt::AlignmentFlag miniToolbarAlignment(const QString &strID);
/** Returns mini-toolbar @a alignment. */
void setMiniToolbarAlignment(Qt::AlignmentFlag alignment, const QString &strID);
#endif /* Q_WS_MAC */
/** Returns whether Runtime UI status-bar is enabled. */
bool statusBarEnabled(const QString &strID);
/** Defines whether Runtime UI status-bar is @a fEnabled. */
void setStatusBarEnabled(bool fEnabled, const QString &strID);
/** Returns restricted Runtime UI status-bar indicator list. */
QList<IndicatorType> restrictedStatusBarIndicators(const QString &strID);
/** Defines restricted Runtime UI status-bar indicator @a list. */
void setRestrictedStatusBarIndicators(const QList<IndicatorType> &list, const QString &strID);
/** Returns Runtime UI status-bar indicator order list. */
QList<IndicatorType> statusBarIndicatorOrder(const QString &strID);
/** Defines Runtime UI status-bar indicator order @a list. */
void setStatusBarIndicatorOrder(const QList<IndicatorType> &list, const QString &strID);
#ifdef Q_WS_MAC
/** Mac OS X: Returns whether Dock icon should be updated at runtime. */
bool realtimeDockIconUpdateEnabled(const QString &strID);
/** Mac OS X: Defines whether Dock icon update should be fEnabled at runtime. */
void setRealtimeDockIconUpdateEnabled(bool fEnabled, const QString &strID);
/** Mac OS X: Returns guest-screen which Dock icon should reflect at runtime. */
int realtimeDockIconUpdateMonitor(const QString &strID);
/** Mac OS X: Defines guest-screen @a iIndex which Dock icon should reflect at runtime. */
void setRealtimeDockIconUpdateMonitor(int iIndex, const QString &strID);
#endif /* Q_WS_MAC */
/** Returns whether machine should pass CAD to guest. */
bool passCADtoGuest(const QString &strID);
/** Returns the mouse-capture policy. */
MouseCapturePolicy mouseCapturePolicy(const QString &strID);
/** Returns redefined guru-meditation handler type. */
GuruMeditationHandlerType guruMeditationHandlerType(const QString &strID);
/** Returns whether machine should perform HID LEDs synchronization. */
bool hidLedsSyncState(const QString &strID);
/** Returns the scale-factor. */
double scaleFactor(const QString &strID);
/** Defines the @a dScaleFactor. */
void setScaleFactor(double dScaleFactor, const QString &strID);
/** Returns the scaling optimization type. */
ScalingOptimizationType scalingOptimizationType(const QString &strID);
/** @} */
/** @name Virtual Machine: Information dialog
* @{ */
/** Returns information-window geometry using @a pWidget and @a pParentWidget as hints. */
QRect informationWindowGeometry(QWidget *pWidget, QWidget *pParentWidget, const QString &strID);
/** Returns whether information-window should be maximized or not. */
bool informationWindowShouldBeMaximized(const QString &strID);
/** Defines information-window @a geometry and @a fMaximized state. */
void setInformationWindowGeometry(const QRect &geometry, bool fMaximized, const QString &strID);
/** @} */
/** @name Virtual Machine: Close dialog
* @{ */
/** Returns default machine close action. */
MachineCloseAction defaultMachineCloseAction(const QString &strID);
/** Returns restricted machine close actions. */
MachineCloseAction restrictedMachineCloseActions(const QString &strID);
/** Returns last machine close action. */
MachineCloseAction lastMachineCloseAction(const QString &strID);
/** Defines last @a machineCloseAction. */
void setLastMachineCloseAction(MachineCloseAction machineCloseAction, const QString &strID);
/** Returns machine close hook script name as simple string. */
QString machineCloseHookScript(const QString &strID);
/** @} */
#ifdef VBOX_WITH_DEBUGGER_GUI
/** @name Virtual Machine: Debug UI
* @{ */
/** Returns debug flag value for passed @a strDebugFlagKey. */
QString debugFlagValue(const QString &strDebugFlagKey);
/** @} */
#endif /* VBOX_WITH_DEBUGGER_GUI */
#ifdef DEBUG
/** @name VirtualBox: Extra-data Manager window
* @{ */
/** Returns Extra-data Manager geometry using @a pWidget as hint. */
QRect extraDataManagerGeometry(QWidget *pWidget);
/** Returns whether Extra-data Manager should be maximized or not. */
bool extraDataManagerShouldBeMaximized();
/** Defines Extra-data Manager @a geometry and @a fMaximized state. */
void setExtraDataManagerGeometry(const QRect &geometry, bool fMaximized);
/** Returns Extra-data Manager splitter hints using @a pWidget as hint. */
QList<int> extraDataManagerSplitterHints(QWidget *pWidget);
/** Defines Extra-data Manager splitter @a hints. */
void setExtraDataManagerSplitterHints(const QList<int> &hints);
/** @} */
#endif /* DEBUG */
private slots:
/** Handles 'extra-data change' event: */
void sltExtraDataChange(QString strMachineID, QString strKey, QString strValue);
private:
/** Prepare Extra-data Manager. */
void prepare();
/** Prepare global extra-data map. */
void prepareGlobalExtraDataMap();
/** Prepare extra-data event-handler. */
void prepareExtraDataEventHandler();
/** Prepare Main event-listener. */
void prepareMainEventListener();
#ifdef DEBUG
// /** Prepare window. */
// void prepareWindow();
/** Cleanup window. */
void cleanupWindow();
#endif /* DEBUG */
/** Cleanup Main event-listener. */
void cleanupMainEventListener();
// /** Cleanup extra-data event-handler. */
// void cleanupExtraDataEventHandler();
// /** Cleanup extra-data map. */
// void cleanupExtraDataMap();
/** Cleanup Extra-data Manager. */
void cleanup();
#ifdef DEBUG
/** Open window. */
void open(QWidget *pCenterWidget);
#endif /* DEBUG */
/** Determines whether feature corresponding to passed @a strKey is allowed.
* If valid @a strID is set => applies to machine extra-data, otherwise => to global one. */
bool isFeatureAllowed(const QString &strKey, const QString &strID = GlobalID);
/** Determines whether feature corresponding to passed @a strKey is restricted.
* If valid @a strID is set => applies to machine extra-data, otherwise => to global one. */
bool isFeatureRestricted(const QString &strKey, const QString &strID = GlobalID);
/** Translates bool flag into 'allowed' value. */
QString toFeatureAllowed(bool fAllowed);
/** Translates bool flag into 'restricted' value. */
QString toFeatureRestricted(bool fRestricted);
/** Returns string consisting of @a strBase appended with @a uScreenIndex for the *non-primary* screen-index.
* If @a fSameRuleForPrimary is 'true' same rule will be used for *primary* screen-index. Used for storing per-screen extra-data. */
static QString extraDataKeyPerScreen(const QString &strBase, ulong uScreenIndex, bool fSameRuleForPrimary = false);
/** Singleton Extra-data Manager instance. */
static UIExtraDataManager *m_spInstance;
/** Holds main event-listener instance. */
CEventListener m_listener;
/** Holds extra-data event-handler instance. */
UIExtraDataEventHandler *m_pHandler;
/** Holds extra-data map instance. */
QMap<QString, ExtraDataMap> m_data;
#ifdef DEBUG
/** Holds Extra-data Manager window instance. */
QPointer<UIExtraDataManagerWindow> m_pWindow;
#endif /* DEBUG */
};
/** Singleton Extra-data Manager 'official' name. */
#define gEDataManager UIExtraDataManager::instance()
#endif /* !___UIExtraDataManager_h___ */
| 48.876847 | 155 | 0.703386 | [
"cad",
"geometry"
] |
a018defb7621fd2e1c91e45f271485bebd9b17c5 | 13,926 | c | C | linsched-linsched-alpha/drivers/gpu/drm/nouveau/nouveau_channel.c | usenixatc2021/SoftRefresh_Scheduling | 589ba06c8ae59538973c22edf28f74a59d63aa14 | [
"MIT"
] | null | null | null | linsched-linsched-alpha/drivers/gpu/drm/nouveau/nouveau_channel.c | usenixatc2021/SoftRefresh_Scheduling | 589ba06c8ae59538973c22edf28f74a59d63aa14 | [
"MIT"
] | null | null | null | linsched-linsched-alpha/drivers/gpu/drm/nouveau/nouveau_channel.c | usenixatc2021/SoftRefresh_Scheduling | 589ba06c8ae59538973c22edf28f74a59d63aa14 | [
"MIT"
] | null | null | null | /*
* Copyright 2005-2006 Stephane Marchesin
* All Rights Reserved.
*
* 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 (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "drmP.h"
#include "drm.h"
#include "nouveau_drv.h"
#include "nouveau_drm.h"
#include "nouveau_dma.h"
#include "nouveau_ramht.h"
static int
nouveau_channel_pushbuf_init(struct nouveau_channel *chan)
{
u32 mem = nouveau_vram_pushbuf ? TTM_PL_FLAG_VRAM : TTM_PL_FLAG_TT;
struct drm_device *dev = chan->dev;
struct drm_nouveau_private *dev_priv = dev->dev_private;
int ret;
/* allocate buffer object */
ret = nouveau_bo_new(dev, 65536, 0, mem, 0, 0, &chan->pushbuf_bo);
if (ret)
goto out;
ret = nouveau_bo_pin(chan->pushbuf_bo, mem);
if (ret)
goto out;
ret = nouveau_bo_map(chan->pushbuf_bo);
if (ret)
goto out;
/* create DMA object covering the entire memtype where the push
* buffer resides, userspace can submit its own push buffers from
* anywhere within the same memtype.
*/
chan->pushbuf_base = chan->pushbuf_bo->bo.offset;
if (dev_priv->card_type >= NV_50) {
ret = nouveau_bo_vma_add(chan->pushbuf_bo, chan->vm,
&chan->pushbuf_vma);
if (ret)
goto out;
if (dev_priv->card_type < NV_C0) {
ret = nouveau_gpuobj_dma_new(chan,
NV_CLASS_DMA_IN_MEMORY, 0,
(1ULL << 40),
NV_MEM_ACCESS_RO,
NV_MEM_TARGET_VM,
&chan->pushbuf);
}
chan->pushbuf_base = chan->pushbuf_vma.offset;
} else
if (chan->pushbuf_bo->bo.mem.mem_type == TTM_PL_TT) {
ret = nouveau_gpuobj_dma_new(chan, NV_CLASS_DMA_IN_MEMORY, 0,
dev_priv->gart_info.aper_size,
NV_MEM_ACCESS_RO,
NV_MEM_TARGET_GART,
&chan->pushbuf);
} else
if (dev_priv->card_type != NV_04) {
ret = nouveau_gpuobj_dma_new(chan, NV_CLASS_DMA_IN_MEMORY, 0,
dev_priv->fb_available_size,
NV_MEM_ACCESS_RO,
NV_MEM_TARGET_VRAM,
&chan->pushbuf);
} else {
/* NV04 cmdbuf hack, from original ddx.. not sure of it's
* exact reason for existing :) PCI access to cmdbuf in
* VRAM.
*/
ret = nouveau_gpuobj_dma_new(chan, NV_CLASS_DMA_IN_MEMORY,
pci_resource_start(dev->pdev, 1),
dev_priv->fb_available_size,
NV_MEM_ACCESS_RO,
NV_MEM_TARGET_PCI,
&chan->pushbuf);
}
out:
if (ret) {
NV_ERROR(dev, "error initialising pushbuf: %d\n", ret);
nouveau_bo_vma_del(chan->pushbuf_bo, &chan->pushbuf_vma);
nouveau_gpuobj_ref(NULL, &chan->pushbuf);
if (chan->pushbuf_bo) {
nouveau_bo_unmap(chan->pushbuf_bo);
nouveau_bo_ref(NULL, &chan->pushbuf_bo);
}
}
return 0;
}
/* allocates and initializes a fifo for user space consumption */
int
nouveau_channel_alloc(struct drm_device *dev, struct nouveau_channel **chan_ret,
struct drm_file *file_priv,
uint32_t vram_handle, uint32_t gart_handle)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nouveau_fifo_engine *pfifo = &dev_priv->engine.fifo;
struct nouveau_fpriv *fpriv = nouveau_fpriv(file_priv);
struct nouveau_channel *chan;
unsigned long flags;
int ret;
/* allocate and lock channel structure */
chan = kzalloc(sizeof(*chan), GFP_KERNEL);
if (!chan)
return -ENOMEM;
chan->dev = dev;
chan->file_priv = file_priv;
chan->vram_handle = vram_handle;
chan->gart_handle = gart_handle;
kref_init(&chan->ref);
atomic_set(&chan->users, 1);
mutex_init(&chan->mutex);
mutex_lock(&chan->mutex);
/* allocate hw channel id */
spin_lock_irqsave(&dev_priv->channels.lock, flags);
for (chan->id = 0; chan->id < pfifo->channels; chan->id++) {
if (!dev_priv->channels.ptr[chan->id]) {
nouveau_channel_ref(chan, &dev_priv->channels.ptr[chan->id]);
break;
}
}
spin_unlock_irqrestore(&dev_priv->channels.lock, flags);
if (chan->id == pfifo->channels) {
mutex_unlock(&chan->mutex);
kfree(chan);
return -ENODEV;
}
NV_DEBUG(dev, "initialising channel %d\n", chan->id);
INIT_LIST_HEAD(&chan->nvsw.vbl_wait);
INIT_LIST_HEAD(&chan->nvsw.flip);
INIT_LIST_HEAD(&chan->fence.pending);
spin_lock_init(&chan->fence.lock);
/* setup channel's memory and vm */
ret = nouveau_gpuobj_channel_init(chan, vram_handle, gart_handle);
if (ret) {
NV_ERROR(dev, "gpuobj %d\n", ret);
nouveau_channel_put(&chan);
return ret;
}
/* Allocate space for per-channel fixed notifier memory */
ret = nouveau_notifier_init_channel(chan);
if (ret) {
NV_ERROR(dev, "ntfy %d\n", ret);
nouveau_channel_put(&chan);
return ret;
}
/* Allocate DMA push buffer */
ret = nouveau_channel_pushbuf_init(chan);
if (ret) {
NV_ERROR(dev, "pushbuf %d\n", ret);
nouveau_channel_put(&chan);
return ret;
}
nouveau_dma_pre_init(chan);
chan->user_put = 0x40;
chan->user_get = 0x44;
if (dev_priv->card_type >= NV_50)
chan->user_get_hi = 0x60;
/* disable the fifo caches */
pfifo->reassign(dev, false);
/* Construct initial RAMFC for new channel */
ret = pfifo->create_context(chan);
if (ret) {
nouveau_channel_put(&chan);
return ret;
}
pfifo->reassign(dev, true);
ret = nouveau_dma_init(chan);
if (!ret)
ret = nouveau_fence_channel_init(chan);
if (ret) {
nouveau_channel_put(&chan);
return ret;
}
nouveau_debugfs_channel_init(chan);
NV_DEBUG(dev, "channel %d initialised\n", chan->id);
if (fpriv) {
spin_lock(&fpriv->lock);
list_add(&chan->list, &fpriv->channels);
spin_unlock(&fpriv->lock);
}
*chan_ret = chan;
return 0;
}
struct nouveau_channel *
nouveau_channel_get_unlocked(struct nouveau_channel *ref)
{
struct nouveau_channel *chan = NULL;
if (likely(ref && atomic_inc_not_zero(&ref->users)))
nouveau_channel_ref(ref, &chan);
return chan;
}
struct nouveau_channel *
nouveau_channel_get(struct drm_file *file_priv, int id)
{
struct nouveau_fpriv *fpriv = nouveau_fpriv(file_priv);
struct nouveau_channel *chan;
spin_lock(&fpriv->lock);
list_for_each_entry(chan, &fpriv->channels, list) {
if (chan->id == id) {
chan = nouveau_channel_get_unlocked(chan);
spin_unlock(&fpriv->lock);
mutex_lock(&chan->mutex);
return chan;
}
}
spin_unlock(&fpriv->lock);
return ERR_PTR(-EINVAL);
}
void
nouveau_channel_put_unlocked(struct nouveau_channel **pchan)
{
struct nouveau_channel *chan = *pchan;
struct drm_device *dev = chan->dev;
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nouveau_fifo_engine *pfifo = &dev_priv->engine.fifo;
unsigned long flags;
int i;
/* decrement the refcount, and we're done if there's still refs */
if (likely(!atomic_dec_and_test(&chan->users))) {
nouveau_channel_ref(NULL, pchan);
return;
}
/* no one wants the channel anymore */
NV_DEBUG(dev, "freeing channel %d\n", chan->id);
nouveau_debugfs_channel_fini(chan);
/* give it chance to idle */
nouveau_channel_idle(chan);
/* ensure all outstanding fences are signaled. they should be if the
* above attempts at idling were OK, but if we failed this'll tell TTM
* we're done with the buffers.
*/
nouveau_fence_channel_fini(chan);
/* boot it off the hardware */
pfifo->reassign(dev, false);
/* destroy the engine specific contexts */
pfifo->destroy_context(chan);
for (i = 0; i < NVOBJ_ENGINE_NR; i++) {
if (chan->engctx[i])
dev_priv->eng[i]->context_del(chan, i);
}
pfifo->reassign(dev, true);
/* aside from its resources, the channel should now be dead,
* remove it from the channel list
*/
spin_lock_irqsave(&dev_priv->channels.lock, flags);
nouveau_channel_ref(NULL, &dev_priv->channels.ptr[chan->id]);
spin_unlock_irqrestore(&dev_priv->channels.lock, flags);
/* destroy any resources the channel owned */
nouveau_gpuobj_ref(NULL, &chan->pushbuf);
if (chan->pushbuf_bo) {
nouveau_bo_vma_del(chan->pushbuf_bo, &chan->pushbuf_vma);
nouveau_bo_unmap(chan->pushbuf_bo);
nouveau_bo_unpin(chan->pushbuf_bo);
nouveau_bo_ref(NULL, &chan->pushbuf_bo);
}
nouveau_ramht_ref(NULL, &chan->ramht, chan);
nouveau_notifier_takedown_channel(chan);
nouveau_gpuobj_channel_takedown(chan);
nouveau_channel_ref(NULL, pchan);
}
void
nouveau_channel_put(struct nouveau_channel **pchan)
{
mutex_unlock(&(*pchan)->mutex);
nouveau_channel_put_unlocked(pchan);
}
static void
nouveau_channel_del(struct kref *ref)
{
struct nouveau_channel *chan =
container_of(ref, struct nouveau_channel, ref);
kfree(chan);
}
void
nouveau_channel_ref(struct nouveau_channel *chan,
struct nouveau_channel **pchan)
{
if (chan)
kref_get(&chan->ref);
if (*pchan)
kref_put(&(*pchan)->ref, nouveau_channel_del);
*pchan = chan;
}
void
nouveau_channel_idle(struct nouveau_channel *chan)
{
struct drm_device *dev = chan->dev;
struct nouveau_fence *fence = NULL;
int ret;
nouveau_fence_update(chan);
if (chan->fence.sequence != chan->fence.sequence_ack) {
ret = nouveau_fence_new(chan, &fence, true);
if (!ret) {
ret = nouveau_fence_wait(fence, false, false);
nouveau_fence_unref(&fence);
}
if (ret)
NV_ERROR(dev, "Failed to idle channel %d.\n", chan->id);
}
}
/* cleans up all the fifos from file_priv */
void
nouveau_channel_cleanup(struct drm_device *dev, struct drm_file *file_priv)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nouveau_engine *engine = &dev_priv->engine;
struct nouveau_channel *chan;
int i;
NV_DEBUG(dev, "clearing FIFO enables from file_priv\n");
for (i = 0; i < engine->fifo.channels; i++) {
chan = nouveau_channel_get(file_priv, i);
if (IS_ERR(chan))
continue;
list_del(&chan->list);
atomic_dec(&chan->users);
nouveau_channel_put(&chan);
}
}
/***********************************
* ioctls wrapping the functions
***********************************/
static int
nouveau_ioctl_fifo_alloc(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct drm_nouveau_channel_alloc *init = data;
struct nouveau_channel *chan;
int ret;
if (!dev_priv->eng[NVOBJ_ENGINE_GR])
return -ENODEV;
if (init->fb_ctxdma_handle == ~0 || init->tt_ctxdma_handle == ~0)
return -EINVAL;
ret = nouveau_channel_alloc(dev, &chan, file_priv,
init->fb_ctxdma_handle,
init->tt_ctxdma_handle);
if (ret)
return ret;
init->channel = chan->id;
if (nouveau_vram_pushbuf == 0) {
if (chan->dma.ib_max)
init->pushbuf_domains = NOUVEAU_GEM_DOMAIN_VRAM |
NOUVEAU_GEM_DOMAIN_GART;
else if (chan->pushbuf_bo->bo.mem.mem_type == TTM_PL_VRAM)
init->pushbuf_domains = NOUVEAU_GEM_DOMAIN_VRAM;
else
init->pushbuf_domains = NOUVEAU_GEM_DOMAIN_GART;
} else {
init->pushbuf_domains = NOUVEAU_GEM_DOMAIN_VRAM;
}
if (dev_priv->card_type < NV_C0) {
init->subchan[0].handle = NvM2MF;
if (dev_priv->card_type < NV_50)
init->subchan[0].grclass = 0x0039;
else
init->subchan[0].grclass = 0x5039;
init->subchan[1].handle = NvSw;
init->subchan[1].grclass = NV_SW;
init->nr_subchan = 2;
} else {
init->subchan[0].handle = 0x9039;
init->subchan[0].grclass = 0x9039;
init->nr_subchan = 1;
}
/* Named memory object area */
ret = drm_gem_handle_create(file_priv, chan->notifier_bo->gem,
&init->notifier_handle);
if (ret == 0)
atomic_inc(&chan->users); /* userspace reference */
nouveau_channel_put(&chan);
return ret;
}
static int
nouveau_ioctl_fifo_free(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct drm_nouveau_channel_free *req = data;
struct nouveau_channel *chan;
chan = nouveau_channel_get(file_priv, req->channel);
if (IS_ERR(chan))
return PTR_ERR(chan);
list_del(&chan->list);
atomic_dec(&chan->users);
nouveau_channel_put(&chan);
return 0;
}
/***********************************
* finally, the ioctl table
***********************************/
struct drm_ioctl_desc nouveau_ioctls[] = {
DRM_IOCTL_DEF_DRV(NOUVEAU_GETPARAM, nouveau_ioctl_getparam, DRM_UNLOCKED|DRM_AUTH),
DRM_IOCTL_DEF_DRV(NOUVEAU_SETPARAM, nouveau_ioctl_setparam, DRM_UNLOCKED|DRM_AUTH|DRM_MASTER|DRM_ROOT_ONLY),
DRM_IOCTL_DEF_DRV(NOUVEAU_CHANNEL_ALLOC, nouveau_ioctl_fifo_alloc, DRM_UNLOCKED|DRM_AUTH),
DRM_IOCTL_DEF_DRV(NOUVEAU_CHANNEL_FREE, nouveau_ioctl_fifo_free, DRM_UNLOCKED|DRM_AUTH),
DRM_IOCTL_DEF_DRV(NOUVEAU_GROBJ_ALLOC, nouveau_ioctl_grobj_alloc, DRM_UNLOCKED|DRM_AUTH),
DRM_IOCTL_DEF_DRV(NOUVEAU_NOTIFIEROBJ_ALLOC, nouveau_ioctl_notifier_alloc, DRM_UNLOCKED|DRM_AUTH),
DRM_IOCTL_DEF_DRV(NOUVEAU_GPUOBJ_FREE, nouveau_ioctl_gpuobj_free, DRM_UNLOCKED|DRM_AUTH),
DRM_IOCTL_DEF_DRV(NOUVEAU_GEM_NEW, nouveau_gem_ioctl_new, DRM_UNLOCKED|DRM_AUTH),
DRM_IOCTL_DEF_DRV(NOUVEAU_GEM_PUSHBUF, nouveau_gem_ioctl_pushbuf, DRM_UNLOCKED|DRM_AUTH),
DRM_IOCTL_DEF_DRV(NOUVEAU_GEM_CPU_PREP, nouveau_gem_ioctl_cpu_prep, DRM_UNLOCKED|DRM_AUTH),
DRM_IOCTL_DEF_DRV(NOUVEAU_GEM_CPU_FINI, nouveau_gem_ioctl_cpu_fini, DRM_UNLOCKED|DRM_AUTH),
DRM_IOCTL_DEF_DRV(NOUVEAU_GEM_INFO, nouveau_gem_ioctl_info, DRM_UNLOCKED|DRM_AUTH),
};
int nouveau_max_ioctl = DRM_ARRAY_SIZE(nouveau_ioctls);
| 28.362525 | 109 | 0.716932 | [
"object"
] |
a01cfcc45167a9feabba719eb90e74d20277be1f | 21,481 | c | C | parasail_c/src/sg_stats_striped_avx2_256_64.c | dikaiosune/parasail-sys | bcaf089eaec5de7147a421bea8b4811d1720ef5d | [
"MIT"
] | 1 | 2021-05-28T01:51:57.000Z | 2021-05-28T01:51:57.000Z | parasail_c/src/sg_stats_striped_avx2_256_64.c | dikaiosune/parasail-sys | bcaf089eaec5de7147a421bea8b4811d1720ef5d | [
"MIT"
] | null | null | null | parasail_c/src/sg_stats_striped_avx2_256_64.c | dikaiosune/parasail-sys | bcaf089eaec5de7147a421bea8b4811d1720ef5d | [
"MIT"
] | 2 | 2021-05-28T01:55:07.000Z | 2021-05-28T18:34:18.000Z | /**
* @file
*
* @author jeff.daily@pnnl.gov
*
* Copyright (c) 2015 Battelle Memorial Institute.
*/
#include "config.h"
#include <stdint.h>
#include <stdlib.h>
#include <immintrin.h>
#include "parasail.h"
#include "parasail/memory.h"
#include "parasail/internal_avx.h"
#define FASTSTATS
#define NEG_INF (INT64_MIN/(int64_t)(2))
#if HAVE_AVX2_MM256_INSERT_EPI64
#define _mm256_insert_epi64_rpl _mm256_insert_epi64
#else
static inline __m256i _mm256_insert_epi64_rpl(__m256i a, int64_t i, int imm) {
__m256i_64_t A;
A.m = a;
A.v[imm] = i;
return A.m;
}
#endif
static inline __m256i _mm256_max_epi64_rpl(__m256i a, __m256i b) {
__m256i_64_t A;
__m256i_64_t B;
A.m = a;
B.m = b;
A.v[0] = (A.v[0]>B.v[0]) ? A.v[0] : B.v[0];
A.v[1] = (A.v[1]>B.v[1]) ? A.v[1] : B.v[1];
A.v[2] = (A.v[2]>B.v[2]) ? A.v[2] : B.v[2];
A.v[3] = (A.v[3]>B.v[3]) ? A.v[3] : B.v[3];
return A.m;
}
#if HAVE_AVX2_MM256_EXTRACT_EPI64
#define _mm256_extract_epi64_rpl _mm256_extract_epi64
#else
static inline int64_t _mm256_extract_epi64_rpl(__m256i a, int imm) {
__m256i_64_t A;
A.m = a;
return A.v[imm];
}
#endif
#define _mm256_cmplt_epi64_rpl(a,b) _mm256_cmpgt_epi64(b,a)
#define _mm256_slli_si256_rpl(a,imm) _mm256_alignr_epi8(a, _mm256_permute2x128_si256(a, a, _MM_SHUFFLE(0,0,3,0)), 16-imm)
static inline int64_t _mm256_hmax_epi64_rpl(__m256i a) {
a = _mm256_max_epi64_rpl(a, _mm256_permute2x128_si256(a, a, _MM_SHUFFLE(0,0,0,0)));
a = _mm256_max_epi64_rpl(a, _mm256_slli_si256(a, 8));
return _mm256_extract_epi64_rpl(a, 3);
}
#ifdef PARASAIL_TABLE
static inline void arr_store_si256(
int *array,
__m256i vH,
int32_t t,
int32_t seglen,
int32_t d,
int32_t dlen)
{
array[(0*seglen+t)*dlen + d] = (int64_t)_mm256_extract_epi64_rpl(vH, 0);
array[(1*seglen+t)*dlen + d] = (int64_t)_mm256_extract_epi64_rpl(vH, 1);
array[(2*seglen+t)*dlen + d] = (int64_t)_mm256_extract_epi64_rpl(vH, 2);
array[(3*seglen+t)*dlen + d] = (int64_t)_mm256_extract_epi64_rpl(vH, 3);
}
#endif
#ifdef PARASAIL_ROWCOL
static inline void arr_store_col(
int *col,
__m256i vH,
int32_t t,
int32_t seglen)
{
col[0*seglen+t] = (int64_t)_mm256_extract_epi64_rpl(vH, 0);
col[1*seglen+t] = (int64_t)_mm256_extract_epi64_rpl(vH, 1);
col[2*seglen+t] = (int64_t)_mm256_extract_epi64_rpl(vH, 2);
col[3*seglen+t] = (int64_t)_mm256_extract_epi64_rpl(vH, 3);
}
#endif
#ifdef PARASAIL_TABLE
#define FNAME parasail_sg_stats_table_striped_avx2_256_64
#define PNAME parasail_sg_stats_table_striped_profile_avx2_256_64
#define INAME PNAME
#define STATIC
#else
#ifdef PARASAIL_ROWCOL
#define FNAME parasail_sg_stats_rowcol_striped_avx2_256_64
#define PNAME parasail_sg_stats_rowcol_striped_profile_avx2_256_64
#define INAME PNAME
#define STATIC
#else
#define FNAME parasail_sg_stats_striped_avx2_256_64
#ifdef FASTSTATS
#define PNAME parasail_sg_stats_striped_profile_avx2_256_64_internal
#define INAME parasail_sg_stats_striped_profile_avx2_256_64
#define STATIC static
#else
#define PNAME parasail_sg_stats_striped_profile_avx2_256_64
#define INAME PNAME
#define STATIC
#endif
#endif
#endif
parasail_result_t* FNAME(
const char * const restrict s1, const int s1Len,
const char * const restrict s2, const int s2Len,
const int open, const int gap, const parasail_matrix_t *matrix)
{
parasail_profile_t *profile = parasail_profile_create_stats_avx_256_64(s1, s1Len, matrix);
parasail_result_t *result = INAME(profile, s2, s2Len, open, gap);
parasail_profile_free(profile);
return result;
}
STATIC parasail_result_t* PNAME(
const parasail_profile_t * const restrict profile,
const char * const restrict s2, const int s2Len,
const int open, const int gap)
{
int32_t i = 0;
int32_t j = 0;
int32_t k = 0;
int32_t end_query = 0;
int32_t end_ref = 0;
const int s1Len = profile->s1Len;
const parasail_matrix_t *matrix = profile->matrix;
const int32_t segWidth = 4; /* number of values in vector unit */
const int32_t segLen = (s1Len + segWidth - 1) / segWidth;
const int32_t offset = (s1Len - 1) % segLen;
const int32_t position = (segWidth - 1) - (s1Len - 1) / segLen;
__m256i* const restrict vProfile = (__m256i*)profile->profile64.score;
__m256i* const restrict vProfileM = (__m256i*)profile->profile64.matches;
__m256i* const restrict vProfileS = (__m256i*)profile->profile64.similar;
__m256i* restrict pvHStore = parasail_memalign___m256i(32, segLen);
__m256i* restrict pvHLoad = parasail_memalign___m256i(32, segLen);
__m256i* restrict pvHMStore = parasail_memalign___m256i(32, segLen);
__m256i* restrict pvHMLoad = parasail_memalign___m256i(32, segLen);
__m256i* restrict pvHSStore = parasail_memalign___m256i(32, segLen);
__m256i* restrict pvHSLoad = parasail_memalign___m256i(32, segLen);
__m256i* restrict pvHLStore = parasail_memalign___m256i(32, segLen);
__m256i* restrict pvHLLoad = parasail_memalign___m256i(32, segLen);
__m256i* restrict pvEStore = parasail_memalign___m256i(32, segLen);
__m256i* restrict pvELoad = parasail_memalign___m256i(32, segLen);
__m256i* const restrict pvEM = parasail_memalign___m256i(32, segLen);
__m256i* const restrict pvES = parasail_memalign___m256i(32, segLen);
__m256i* const restrict pvEL = parasail_memalign___m256i(32, segLen);
__m256i vGapO = _mm256_set1_epi64x(open);
__m256i vGapE = _mm256_set1_epi64x(gap);
__m256i vNegInf = _mm256_set1_epi64x(NEG_INF);
__m256i vZero = _mm256_setzero_si256();
__m256i vOne = _mm256_set1_epi64x(1);
int64_t score = NEG_INF;
int64_t matches = NEG_INF;
int64_t similar = NEG_INF;
int64_t length = NEG_INF;
__m256i vMaxH = vNegInf;
__m256i vMaxHM = vNegInf;
__m256i vMaxHS = vNegInf;
__m256i vMaxHL = vNegInf;
__m256i vPosMask = _mm256_cmpeq_epi64(_mm256_set1_epi64x(position),
_mm256_set_epi64x(0,1,2,3));
#ifdef PARASAIL_TABLE
parasail_result_t *result = parasail_result_new_table3(segLen*segWidth, s2Len);
#else
#ifdef PARASAIL_ROWCOL
parasail_result_t *result = parasail_result_new_rowcol3(segLen*segWidth, s2Len);
#else
parasail_result_t *result = parasail_result_new();
#endif
#endif
parasail_memset___m256i(pvHMStore, vZero, segLen);
parasail_memset___m256i(pvHSStore, vZero, segLen);
parasail_memset___m256i(pvHLStore, vZero, segLen);
parasail_memset___m256i(pvEM, vZero, segLen);
parasail_memset___m256i(pvES, vZero, segLen);
parasail_memset___m256i(pvEL, vZero, segLen);
parasail_memset___m256i(pvHStore, vZero, segLen);
parasail_memset___m256i(pvEStore, _mm256_set1_epi64x(-open), segLen);
/* outer loop over database sequence */
for (j=0; j<s2Len; ++j) {
__m256i vE;
__m256i vEM;
__m256i vES;
__m256i vEL;
__m256i vF;
__m256i vFM;
__m256i vFS;
__m256i vFL;
__m256i vH;
__m256i vHM;
__m256i vHS;
__m256i vHL;
const __m256i* vP = NULL;
const __m256i* vPM = NULL;
const __m256i* vPS = NULL;
__m256i* pv = NULL;
/* Initialize F value to neg inf. Any errors to vH values will
* be corrected in the Lazy_F loop. */
vF = vNegInf;
vFM = vZero;
vFS = vZero;
vFL = vZero;
/* load final segment of pvHStore and shift left by 2 bytes */
vH = _mm256_slli_si256_rpl(pvHStore[segLen - 1], 8);
vHM = _mm256_slli_si256_rpl(pvHMStore[segLen - 1], 8);
vHS = _mm256_slli_si256_rpl(pvHSStore[segLen - 1], 8);
vHL = _mm256_slli_si256_rpl(pvHLStore[segLen - 1], 8);
/* Correct part of the vProfile */
vP = vProfile + matrix->mapper[(unsigned char)s2[j]] * segLen;
vPM = vProfileM + matrix->mapper[(unsigned char)s2[j]] * segLen;
vPS = vProfileS + matrix->mapper[(unsigned char)s2[j]] * segLen;
/* Swap the 2 H buffers. */
pv = pvHLoad;
pvHLoad = pvHStore;
pvHStore = pv;
pv = pvHMLoad;
pvHMLoad = pvHMStore;
pvHMStore = pv;
pv = pvHSLoad;
pvHSLoad = pvHSStore;
pvHSStore = pv;
pv = pvHLLoad;
pvHLLoad = pvHLStore;
pvHLStore = pv;
pv = pvELoad;
pvELoad = pvEStore;
pvEStore = pv;
/* inner loop to process the query sequence */
for (i=0; i<segLen; ++i) {
__m256i case1not;
__m256i case2not;
__m256i case2;
__m256i case3;
vH = _mm256_add_epi64(vH, _mm256_load_si256(vP + i));
vE = _mm256_load_si256(pvELoad + i);
/* determine which direction of length and match to
* propagate, before vH is finished calculating */
case1not = _mm256_or_si256(
_mm256_cmplt_epi64_rpl(vH,vF),_mm256_cmplt_epi64_rpl(vH,vE));
case2not = _mm256_cmplt_epi64_rpl(vF,vE);
case2 = _mm256_andnot_si256(case2not,case1not);
case3 = _mm256_and_si256(case1not,case2not);
/* Get max from vH, vE and vF. */
vH = _mm256_max_epi64_rpl(vH, vE);
vH = _mm256_max_epi64_rpl(vH, vF);
/* Save vH values. */
_mm256_store_si256(pvHStore + i, vH);
/* calculate vM */
vEM = _mm256_load_si256(pvEM + i);
vHM = _mm256_blendv_epi8(
_mm256_add_epi64(vHM, _mm256_load_si256(vPM + i)),
_mm256_or_si256(
_mm256_and_si256(case2, vFM),
_mm256_and_si256(case3, vEM)),
case1not);
_mm256_store_si256(pvHMStore + i, vHM);
/* calculate vS */
vES = _mm256_load_si256(pvES + i);
vHS = _mm256_blendv_epi8(
_mm256_add_epi64(vHS, _mm256_load_si256(vPS + i)),
_mm256_or_si256(
_mm256_and_si256(case2, vFS),
_mm256_and_si256(case3, vES)),
case1not);
_mm256_store_si256(pvHSStore + i, vHS);
/* calculate vL */
vEL = _mm256_load_si256(pvEL + i);
vHL = _mm256_blendv_epi8(
_mm256_add_epi64(vHL, vOne),
_mm256_or_si256(
_mm256_and_si256(case2, _mm256_add_epi64(vFL, vOne)),
_mm256_and_si256(case3, _mm256_add_epi64(vEL, vOne))),
case1not);
_mm256_store_si256(pvHLStore + i, vHL);
#ifdef PARASAIL_TABLE
arr_store_si256(result->matches_table, vHM, i, segLen, j, s2Len);
arr_store_si256(result->similar_table, vHS, i, segLen, j, s2Len);
arr_store_si256(result->length_table, vHL, i, segLen, j, s2Len);
arr_store_si256(result->score_table, vH, i, segLen, j, s2Len);
#endif
/* Update vE value. */
vH = _mm256_sub_epi64(vH, vGapO);
vE = _mm256_sub_epi64(vE, vGapE);
vE = _mm256_max_epi64_rpl(vE, vH);
_mm256_store_si256(pvEStore + i, vE);
_mm256_store_si256(pvEM + i, vHM);
_mm256_store_si256(pvES + i, vHS);
_mm256_store_si256(pvEL + i, vHL);
/* Update vF value. */
vF = _mm256_sub_epi64(vF, vGapE);
vF = _mm256_max_epi64_rpl(vF, vH);
vFM = vHM;
vFS = vHS;
vFL = vHL;
/* Load the next vH. */
vH = _mm256_load_si256(pvHLoad + i);
vHM = _mm256_load_si256(pvHMLoad + i);
vHS = _mm256_load_si256(pvHSLoad + i);
vHL = _mm256_load_si256(pvHLLoad + i);
}
/* Lazy_F loop: has been revised to disallow adjecent insertion and
* then deletion, so don't update E(i, i), learn from SWPS3 */
for (k=0; k<segWidth; ++k) {
__m256i vHp = _mm256_slli_si256_rpl(pvHLoad[segLen - 1], 8);
vF = _mm256_slli_si256_rpl(vF, 8);
vF = _mm256_insert_epi64_rpl(vF, -open, 0);
vFM = _mm256_slli_si256_rpl(vFM, 8);
vFS = _mm256_slli_si256_rpl(vFS, 8);
vFL = _mm256_slli_si256_rpl(vFL, 8);
for (i=0; i<segLen; ++i) {
__m256i case1not;
__m256i case2not;
__m256i case2;
/* need to know where match and length come from so
* recompute the cases as in the main loop */
vHp = _mm256_add_epi64(vHp, _mm256_load_si256(vP + i));
vE = _mm256_load_si256(pvELoad + i);
case1not = _mm256_or_si256(
_mm256_cmplt_epi64_rpl(vHp,vF),_mm256_cmplt_epi64_rpl(vHp,vE));
case2not = _mm256_cmplt_epi64_rpl(vF,vE);
case2 = _mm256_andnot_si256(case2not,case1not);
vHM = _mm256_load_si256(pvHMStore + i);
vHM = _mm256_blendv_epi8(vHM, vFM, case2);
_mm256_store_si256(pvHMStore + i, vHM);
_mm256_store_si256(pvEM + i, vHM);
vHS = _mm256_load_si256(pvHSStore + i);
vHS = _mm256_blendv_epi8(vHS, vFS, case2);
_mm256_store_si256(pvHSStore + i, vHS);
_mm256_store_si256(pvES + i, vHS);
vHL = _mm256_load_si256(pvHLStore + i);
vHL = _mm256_blendv_epi8(vHL, _mm256_add_epi64(vFL,vOne), case2);
_mm256_store_si256(pvHLStore + i, vHL);
_mm256_store_si256(pvEL + i, vHL);
vH = _mm256_load_si256(pvHStore + i);
vH = _mm256_max_epi64_rpl(vH,vF);
_mm256_store_si256(pvHStore + i, vH);
#ifdef PARASAIL_TABLE
arr_store_si256(result->matches_table, vHM, i, segLen, j, s2Len);
arr_store_si256(result->similar_table, vHS, i, segLen, j, s2Len);
arr_store_si256(result->length_table, vHL, i, segLen, j, s2Len);
arr_store_si256(result->score_table, vH, i, segLen, j, s2Len);
#endif
vH = _mm256_sub_epi64(vH, vGapO);
vF = _mm256_sub_epi64(vF, vGapE);
if (! _mm256_movemask_epi8(_mm256_cmpgt_epi64(vF, vH))) goto end;
/*vF = _mm256_max_epi64_rpl(vF, vH);*/
vFM = vHM;
vFS = vHS;
vFL = vHL;
vHp = _mm256_load_si256(pvHLoad + i);
}
}
end:
{
/* extract vector containing last value from the column */
__m256i cond_max;
vH = _mm256_load_si256(pvHStore + offset);
vHM = _mm256_load_si256(pvHMStore + offset);
vHS = _mm256_load_si256(pvHSStore + offset);
vHL = _mm256_load_si256(pvHLStore + offset);
cond_max = _mm256_cmpgt_epi64(vH, vMaxH);
vMaxH = _mm256_blendv_epi8(vMaxH, vH, cond_max);
vMaxHM = _mm256_blendv_epi8(vMaxHM, vHM, cond_max);
vMaxHS = _mm256_blendv_epi8(vMaxHS, vHS, cond_max);
vMaxHL = _mm256_blendv_epi8(vMaxHL, vHL, cond_max);
if (_mm256_movemask_epi8(_mm256_and_si256(vPosMask, cond_max))) {
end_ref = j;
end_query = s1Len - 1;
}
#ifdef PARASAIL_ROWCOL
for (k=0; k<position; ++k) {
vH = _mm256_slli_si256_rpl(vH, 8);
vHM = _mm256_slli_si256_rpl(vHM, 8);
vHS = _mm256_slli_si256_rpl(vHS, 8);
vHL = _mm256_slli_si256_rpl(vHL, 8);
}
result->score_row[j] = (int64_t) _mm256_extract_epi64_rpl (vH, 3);
result->matches_row[j] = (int64_t) _mm256_extract_epi64_rpl (vHM, 3);
result->similar_row[j] = (int64_t) _mm256_extract_epi64_rpl (vHS, 3);
result->length_row[j] = (int64_t) _mm256_extract_epi64_rpl (vHL, 3);
#endif
}
}
{
/* extract last value from the column */
for (k=0; k<position; ++k) {
vMaxH = _mm256_slli_si256_rpl (vMaxH, 8);
vMaxHM = _mm256_slli_si256_rpl (vMaxHM, 8);
vMaxHS = _mm256_slli_si256_rpl (vMaxHS, 8);
vMaxHL = _mm256_slli_si256_rpl (vMaxHL, 8);
}
score = (int64_t) _mm256_extract_epi64_rpl (vMaxH, 3);
matches = (int64_t)_mm256_extract_epi64_rpl(vMaxHM, 3);
similar = (int64_t)_mm256_extract_epi64_rpl(vMaxHS, 3);
length = (int64_t)_mm256_extract_epi64_rpl(vMaxHL, 3);
}
/* max of last column */
if (INT32_MAX == profile->stop || 0 == profile->stop)
{
int64_t score_last;
vMaxH = vNegInf;
if (0 == profile->stop) {
/* ignore last row contributions */
score = NEG_INF;
matches = NEG_INF;
similar = NEG_INF;
length = NEG_INF;
end_query = s1Len;
end_ref = s2Len - 1;
}
for (i=0; i<segLen; ++i) {
/* load the last stored values */
__m256i vH = _mm256_load_si256(pvHStore + i);
#ifdef PARASAIL_ROWCOL
__m256i vHM = _mm256_load_si256(pvHMStore + i);
__m256i vHS = _mm256_load_si256(pvHSStore + i);
__m256i vHL = _mm256_load_si256(pvHLStore + i);
arr_store_col(result->score_col, vH, i, segLen);
arr_store_col(result->matches_col, vHM, i, segLen);
arr_store_col(result->similar_col, vHS, i, segLen);
arr_store_col(result->length_col, vHL, i, segLen);
#endif
vMaxH = _mm256_max_epi64_rpl(vH, vMaxH);
}
/* max in vec */
score_last = _mm256_hmax_epi64_rpl(vMaxH);
if (score_last > score) {
end_query = s1Len;
end_ref = s2Len - 1;
/* Trace the alignment ending position on read. */
{
int64_t *t = (int64_t*)pvHStore;
int64_t *m = (int64_t*)pvHMStore;
int64_t *s = (int64_t*)pvHSStore;
int64_t *l = (int64_t*)pvHLStore;
int32_t column_len = segLen * segWidth;
for (i = 0; i<column_len; ++i, ++t, ++m, ++s, ++l) {
int32_t temp = i / segWidth + i % segWidth * segLen;
if (temp < s1Len) {
if (*t > score || (*t == score && temp < end_query)) {
score = *t;
end_query = temp;
matches = *m;
similar = *s;
length = *l;
}
}
}
}
}
}
result->score = score;
result->end_query = end_query;
result->end_ref = end_ref;
result->matches = matches;
result->similar = similar;
result->length = length;
parasail_free(pvEL);
parasail_free(pvES);
parasail_free(pvEM);
parasail_free(pvELoad);
parasail_free(pvEStore);
parasail_free(pvHLLoad);
parasail_free(pvHLStore);
parasail_free(pvHSLoad);
parasail_free(pvHSStore);
parasail_free(pvHMLoad);
parasail_free(pvHMStore);
parasail_free(pvHLoad);
parasail_free(pvHStore);
return result;
}
#ifdef FASTSTATS
#ifdef PARASAIL_TABLE
#else
#ifdef PARASAIL_ROWCOL
#else
#include <assert.h>
parasail_result_t* INAME(
const parasail_profile_t * const restrict profile,
const char * const restrict s2, const int s2Len,
const int open, const int gap)
{
const char *s1 = profile->s1;
const parasail_matrix_t *matrix = profile->matrix;
/* find the end loc first with the faster implementation */
parasail_result_t *result = parasail_sg_striped_profile_avx2_256_64(profile, s2, s2Len, open, gap);
if (!result->saturated) {
int s1Len_new = 0;
int s2Len_new = 0;
parasail_result_t *result_final = NULL;
/* using the end loc, call the original stats function */
s1Len_new = result->end_query+1;
s2Len_new = result->end_ref+1;
if (s1Len_new == profile->s1Len) {
/* special 'stop' value tells stats function not to
* consider last column results */
int stop_save = profile->stop;
((parasail_profile_t*)profile)->stop = 1;
result_final = PNAME(
profile, s2, s2Len_new, open, gap);
((parasail_profile_t*)profile)->stop = stop_save;
}
else {
parasail_profile_t *profile_final = NULL;
profile_final = parasail_profile_create_stats_avx_256_64(
s1, s1Len_new, matrix);
/* special 'stop' value tells stats function not to
* consider last row results */
profile_final->stop = 0;
result_final = PNAME(
profile_final, s2, s2Len_new, open, gap);
parasail_profile_free(profile_final);
}
parasail_result_free(result);
/* correct the end locations before returning */
result_final->end_query = s1Len_new-1;
result_final->end_ref = s2Len_new-1;
return result_final;
}
else {
return result;
}
}
#endif
#endif
#endif
| 36.470289 | 121 | 0.599879 | [
"vector"
] |
a027abb6382071e7d06cb1e351cc96d951f7c59e | 1,879 | h | C | ash/assistant/ui/dialog_plate/dialog_plate.h | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | ash/assistant/ui/dialog_plate/dialog_plate.h | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | ash/assistant/ui/dialog_plate/dialog_plate.h | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ASH_ASSISTANT_UI_DIALOG_PLATE_DIALOG_PLATE_H_
#define ASH_ASSISTANT_UI_DIALOG_PLATE_DIALOG_PLATE_H_
#include "ash/assistant/model/assistant_interaction_model_observer.h"
#include "ash/assistant/ui/dialog_plate/action_view.h"
#include "base/macros.h"
#include "ui/views/controls/textfield/textfield_controller.h"
#include "ui/views/view.h"
namespace ash {
class AssistantController;
class DialogPlate : public views::View,
public views::TextfieldController,
public ActionViewListener,
public AssistantInteractionModelObserver {
public:
explicit DialogPlate(AssistantController* assistant_controller);
~DialogPlate() override;
// views::View:
gfx::Size CalculatePreferredSize() const override;
int GetHeightForWidth(int width) const override;
void RequestFocus() override;
// views::TextfieldController:
void ContentsChanged(views::Textfield* sender,
const base::string16& new_contents) override;
bool HandleKeyEvent(views::Textfield* sender,
const ui::KeyEvent& key_event) override;
// ActionViewListener:
void OnActionPressed() override;
// AssistantInteractionModelObserver:
void OnInteractionStateChanged(InteractionState interaction_state) override;
private:
void InitLayout();
void UpdateIcon();
AssistantController* const assistant_controller_; // Owned by Shell.
views::Textfield* textfield_; // Owned by view hierarchy.
ActionView* action_view_; // Owned by view hierarchy.
DISALLOW_COPY_AND_ASSIGN(DialogPlate);
};
} // namespace ash
#endif // ASH_ASSISTANT_UI_DIALOG_PLATE_DIALOG_PLATE_H_
| 32.964912 | 80 | 0.73124 | [
"model"
] |
a0286b65a175e2fba223726a0e8b5a3d1d584840 | 2,916 | h | C | Src/include/vector_utils.h | cosocaf/Pick | e21a3ff204e8cf60a40985ebda73d90f087205a9 | [
"MIT"
] | 6 | 2021-05-17T14:03:18.000Z | 2021-08-06T11:43:12.000Z | Src/include/vector_utils.h | cosocaf/Pick | e21a3ff204e8cf60a40985ebda73d90f087205a9 | [
"MIT"
] | null | null | null | Src/include/vector_utils.h | cosocaf/Pick | e21a3ff204e8cf60a40985ebda73d90f087205a9 | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include <string>
#include <cassert>
namespace pick
{
template<typename T>
std::vector<T>& operator+=(std::vector<T>& a, const std::vector<T>& b)
{
a.reserve(a.size() + b.size());
a.insert(a.end(), b.begin(), b.end());
return a;
}
template<typename T>
std::vector<T>& operator+=(std::vector<T>& a, std::vector<T>&& b)
{
a.reserve(a.size() + b.size());
a.insert(a.end(), std::make_move_iterator(b.begin()), std::make_move_iterator(b.end()));
return a;
}
template<typename T>
std::vector<T>& operator+=(std::vector<T>& a, std::vector<T>& b)
{
a.reserve(a.size() + b.size());
a.insert(a.end(), b.begin(), b.end());
return a;
}
template<typename A, typename B>
std::vector<A>& operator+=(std::vector<A>& a, const B& b)
{
a.push_back(b);
return a;
}
template<typename A, typename B>
std::vector<A>& operator+=(std::vector<A>& a, B&& b)
{
a.emplace_back(std::move(b));
return a;
}
/*template<typename T>
std::vector<T> operator+(const std::vector<T>& a, const std::vector<T>& b)
{
std::vector<T> res(a.size() + b.size());
res.insert(res.end(), a.begin(), a.end());
res.insert(res.end(), b.begin(), b.end());
return res;
}
template<typename T>
std::vector<T> operator+(std::vector<T>&& a, std::vector<T>&& b)
{
std::vector<T> res(a.size() + b.size());
res.insert(res.end(), std::make_move_iterator(a.begin()), std::make_move_iterator(a.end()));
res.insert(res.end(), std::make_move_iterator(b.begin()), std::make_move_iterator(b.end()));
return res;
}*/
std::vector<uint8_t>& operator<<(std::vector<uint8_t>& vec, uint8_t val);
std::vector<uint8_t>& operator<<(std::vector<uint8_t>& vec, uint16_t val);
std::vector<uint8_t>& operator<<(std::vector<uint8_t>& vec, uint32_t val);
std::vector<uint8_t>& operator<<(std::vector<uint8_t>& vec, uint64_t val);
template<typename T>
std::vector<uint8_t>& operator<<(std::vector<uint8_t>& vec, const T& val)
{
for (int i = 0; i < sizeof(T); ++i) {
vec.push_back(((char*)&val)[i]);
}
return vec;
}
std::vector<uint8_t> toList(uint8_t u8);
std::vector<uint8_t> toList(uint16_t u16);
std::vector<uint8_t> toList(uint32_t u32);
std::vector<uint8_t> toList(uint64_t u64);
std::vector<std::string> charVecToStrVec(const std::vector<const char*> vec);
std::vector<std::string> charToStrVec(const char* vec);
inline void pushError(std::vector<std::string>& error, const std::string& message)
{
#ifdef _DEBUG
assert(false);
#else
error.push_back(message);
#endif
}
} | 32.764045 | 101 | 0.559671 | [
"vector"
] |
a037901f3f319b832ab640357a28ff219a1a4924 | 1,312 | c | C | cmds/bard/_story.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 13 | 2019-07-19T05:24:44.000Z | 2021-11-18T04:08:19.000Z | cmds/bard/_story.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 4 | 2021-03-15T18:56:39.000Z | 2021-08-17T17:08:22.000Z | cmds/bard/_story.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 13 | 2019-09-12T06:22:38.000Z | 2022-01-31T01:15:12.000Z | #include <std.h>
#include <objects.h>
inherit DAEMON;
int help();
int cmd_story(string str) {
object ob;
if(!str) return help();
ob = new("/cmds/bard/storyobj");
ob->set_name(str);
ob->move(this_player());
return 1;
}
int help() {
write(
@OLI
story:
Usage: story <name>
This opens an editor area for you to input a new story.
The name is the name of the story <one word> and will be
used to reference it later. Emoteat can now be used
with stories and songs, the target of the emoteat is
always assumed to be yourself.
Syntax:
The commands song recognizes are say, speech and emote.
you can write the following:
say come to me my love
come see my joy
emote drops his voice to a whisper
speech whisper
say come closer my love...
emoteat A woman from the audience blows a kiss to $M
and your audience will see:
Joe says come to me my love
Joe says come see my joy.
Joe drops his voice to a whisper.
Joe whispers come closer my love...
A woman from the audience blows a kiss to Joe
OLI
);
return 1;
}
| 25.72549 | 68 | 0.564024 | [
"object"
] |
a03b99c9d46c53bd0a03c87fc6e5c50958adb010 | 23,435 | h | C | Ring0/KTL/KTL.Functional.Function.h | MeeSong/mbox | 05295cef7933d802718b5bfcc27d979f87873971 | [
"MIT"
] | 52 | 2017-07-03T14:34:53.000Z | 2021-12-13T08:00:50.000Z | Ring0/KTL/KTL.Functional.Function.h | marcosd4h/MBox | 05295cef7933d802718b5bfcc27d979f87873971 | [
"MIT"
] | 1 | 2020-12-23T07:13:31.000Z | 2020-12-31T16:25:17.000Z | Ring0/KTL/KTL.Functional.Function.h | marcosd4h/MBox | 05295cef7933d802718b5bfcc27d979f87873971 | [
"MIT"
] | 40 | 2017-08-30T13:12:19.000Z | 2022-03-23T13:22:31.000Z | #pragma once
#ifndef Function_$196042EF_9259_402B_9606_932D5BA69C2B
#define Function_$196042EF_9259_402B_9606_932D5BA69C2B 1
#include "KTL.Memory.New.h"
#include "KTL.Functional.h"
namespace ktl
{
inline namespace functional
{
/// TEMPLATE CLASS function
template<typename _ReturnType, typename... _ArgTypes>
struct _Arguments_types
{ };
template<typename _ReturnType, typename _ArgTypes>
struct _Arguments_types<_ReturnType, _ArgTypes>
: unary_function<_ArgTypes, _ReturnType>
{ };
template<typename _ReturnType, typename _ArgTypes1, typename _ArgTypes2>
struct _Arguments_types<_ReturnType, _ArgTypes1, _ArgTypes2>
: binary_function<_ArgTypes1, _ArgTypes2, _ReturnType>
{ };
// Simple type wrapper that helps avoid annoying const problems
// when casting between void pointers and pointers-to-pointers.
template<typename _Type>
struct _Simple_type_wrapper
{
_Simple_type_wrapper(_Type aValue)
: value(aValue)
{ }
_Type value;
};
template<typename _Type>
struct __is_location_invariant
: is_trivially_copyable<_Type>::type
{ };
template<typename _Type>
struct __is_location_invariant<_Simple_type_wrapper<_Type>>
: __is_location_invariant<_Type>
{ };
#ifdef _M_X64
#pragma pack(push, 8)
#else
#pragma pack(push, 4)
#endif
union _Nocopy_types
{
void *object;
const void *const_object;
void(*function_pointer)();
void(_undefined::*member_pointer)();
};
#pragma pack(pop)
union _Any_data
{
void* access() { return &m_PodData[0]; }
const void* access() const { return &m_PodData[0]; }
template<typename _Functor>
_Functor& access()
{
return *static_cast<_Functor*>(access());
}
template<typename _Functor>
const _Functor& access() const
{
return *static_cast<const _Functor*>(access());
}
_Nocopy_types m_Unused;
char m_PodData[sizeof(_Nocopy_types)] = { 0 };
};
enum class _Manager_operation
{
get_functor_ptr,
clone_functor,
destroy_functor
};
// Converts a reference to a function object into a callable
// function object.
template<typename _Functor>
inline _Functor&
_Convert_function_reference_to_callable(_Functor& aFunctor)
{
return aFunctor;
}
template<typename _Member, typename _Class>
inline __mem_fn<_Member _Class::*>
_Convert_function_reference_to_callable(
_Member _Class::* &aMemberPointer)
{
return mem_fn(aMemberPointer);
}
template<typename _Member, typename _Class>
inline __mem_fn<_Member _Class::*>
_Convert_function_reference_to_callable(
_Member _Class::* const &aMemberPointer)
{
return mem_fn(aMemberPointer);
}
template<typename _Member, typename _Class>
inline __mem_fn<_Member _Class::*>
_Convert_function_reference_to_callable(
_Member _Class::* volatile &aMemberPointer)
{
return mem_fn(aMemberPointer);
}
template<typename _Member, typename _Class>
inline __mem_fn<_Member _Class::*>
_Convert_function_reference_to_callable(
_Member _Class::* const volatile &aMemberPointer)
{
return mem_fn(aMemberPointer);
}
// TEMPLATE class function_base
template<typename _FuncType>
class function;
class _Function_base
{
public:
static constexpr usize m_MaxSize = sizeof(_Nocopy_types);
static constexpr usize m_MaxAlign = alignof(_Nocopy_types);
template<typename _Functor>
class base_manager
{
protected:
static constexpr bool m_stored_locally =
(__is_location_invariant<_Functor>::value
&& sizeof(_Functor) <= m_MaxSize
&& alignof(_Functor) <= m_MaxAlign
&& (m_MaxAlign % alignof(_Functor) == 0));
using _Local_storage = bool_constant<m_stored_locally>;
// Retrieve a pointer to the function object
static _Functor* get_pointer(const _Any_data& aSource)
{
const _Functor *vPtr = m_stored_locally ?
addressof(aSource.access<_Functor>())
: aSource.access<_Functor*>(); /* have stored a pointer */
return const_cast<_Functor*>(vPtr);
}
// Clone a location-invariant function object that fits within
// an _Any_data structure.
static bool clone(_Any_data& aDest, const _Any_data& aSource, true_type)
{
new (aDest.access()) _Functor(aSource.access<_Functor>());
return true;
}
// Clone a function object that is not location-invariant or
// that cannot fit into an _Any_data structure.
static bool clone(_Any_data& aDest, const _Any_data& aSource, false_type)
{
aDest.access<_Functor*>() = new _Functor(*aSource.access<_Functor*>());
if (nullptr == aDest.access<_Functor*>())
{
return false;
}
return true;
}
// Destroying a location-invariant object may still require
// destruction.
static void destroy(_Any_data& aObject, true_type)
{
aObject.access<_Functor>().~_Functor();
aObject.m_Unused.function_pointer = nullptr;
}
// Destroying an object located on the heap.
static void destroy(_Any_data& aObject, false_type)
{
delete aObject.access<_Functor*>();
aObject.m_Unused.function_pointer = nullptr;
}
public:
static bool manager(_Any_data& aDest, const _Any_data& aSource,
_Manager_operation aOperation)
{
bool vSuccess = false;
switch (aOperation)
{
case _Manager_operation::get_functor_ptr:
aDest.access<_Functor*>() = get_pointer(aSource);
vSuccess = true;
break;
case _Manager_operation::clone_functor:
vSuccess = clone(aDest, aSource, _Local_storage());
break;
case _Manager_operation::destroy_functor:
destroy(aDest, _Local_storage());
vSuccess = true;
break;
}
return vSuccess;
}
static bool init_functor(_Any_data& aFunctor, _Functor&& aPrimitiveFunctor)
{
return init_functor(aFunctor, move(aPrimitiveFunctor), _Local_storage());
}
template<typename _FuncType>
static bool not_empty_function(const function<_FuncType>& aFunctor)
{
return static_cast<bool>(aFunctor);
}
template<typename _FuncType>
static bool not_empty_function(_FuncType *aFunctionPointer)
{
return aFunctionPointer != nullptr;
}
template<typename _Class, typename _FuncType>
static bool not_empty_function(_FuncType _Class::* aMemberPointer)
{
return aMemberPointer != nullptr;
}
template<typename _FuncType>
static bool not_empty_function(const _FuncType&)
{
return true;
}
private:
static bool init_functor(_Any_data& aFunctor, _Functor&& aPrimitiveFunctor, true_type)
{
new (aFunctor.access()) _Functor(move(aPrimitiveFunctor));
return true;
}
static bool init_functor(_Any_data& aFunctor, _Functor&& aPrimitiveFunctor, false_type)
{
aFunctor.access<_Functor*>() = new _Functor(move(aPrimitiveFunctor));
if (nullptr == aFunctor.access<_Functor*>())
{
return false;
}
return true;
}
};
template<typename _Functor>
class _Reference_manager
: public base_manager<_Functor*>
{
using _Base = _Function_base::base_manager<_Functor*>;
public:
static bool manager(_Any_data& aDest, const _Any_data& aSource, _Manager_operation aOperation)
{
bool vSuccess = false;
switch (aOperation)
{
case _Manager_operation::get_functor_ptr:
aDest.access<_Functor*>() = *_Base::get_pointer(aSource);
return is_const<_Functor>::value;
default:
vSuccess = _Base::manager(aDest, aSource, aOperation);
}
return vSuccess;
}
static bool init_functor(_Any_data& aFunctor, reference_wrapper<_Functor> aPrimitiveFunctor)
{
return _Base::init_functor(aFunctor, addressof(aPrimitiveFunctor.get()));
}
};
_Function_base()
: m_Manager(nullptr)
{
}
~_Function_base()
{
if (m_Manager)
{
m_Manager(m_Functor, m_Functor, _Manager_operation::destroy_functor);
}
}
bool is_empty() const
{
return !m_Manager;
}
using _ManagerType = bool(*)(_Any_data&, const _Any_data&, _Manager_operation);
_Any_data m_Functor;
_ManagerType m_Manager = nullptr;
};
// TEMPLATE class function_handler
template<typename _FunctorType, typename _Functor>
class _Function_handler;
template<typename _ReturnType, typename _Functor, typename... _ArgTypes>
class _Function_handler<_ReturnType(_ArgTypes...), _Functor>
: public _Function_base::base_manager<_Functor>
{
using _Base = _Function_base::base_manager<_Functor>;
public:
static _ReturnType invoke(const _Any_data& aFunctor, _ArgTypes&&... aArguments)
{
return (*_Base::get_pointer(aFunctor))(forward<_ArgTypes>(aArguments)...);
}
};
template<typename _Functor, typename... _ArgTypes>
class _Function_handler<void(_ArgTypes...), _Functor>
: public _Function_base::base_manager<_Functor>
{
using _Base = _Function_base::base_manager<_Functor>;
public:
static void invoke(const _Any_data& aFunctor, _ArgTypes&&... aArguments)
{
(*_Base::get_pointer(aFunctor))(forward<_ArgTypes>(aArguments)...);
}
};
template<typename _ReturnType, typename _Functor, typename... _ArgTypes>
class _Function_handler<_ReturnType(_ArgTypes...), reference_wrapper<_Functor>>
: public _Function_base::_Reference_manager<_Functor>
{
using _Base = _Function_base::_Reference_manager<_Functor>;
public:
static _ReturnType invoke(const _Any_data& aFunctor, _ArgTypes&&... aArguments)
{
return _Convert_function_reference_to_callable(
**_Base::get_pointer(aFunctor))(
forward<_ArgTypes>(aArguments)...);
}
};
template<typename _Functor, typename... _ArgTypes>
class _Function_handler<void(_ArgTypes...), reference_wrapper<_Functor>>
: public _Function_base::_Reference_manager<_Functor>
{
using _Base = _Function_base::_Reference_manager<_Functor>;
public:
static void invoke(const _Any_data& aFunctor, _ArgTypes&&... aArguments)
{
_Convert_function_reference_to_callable(
**_Base::get_pointer(aFunctor))(
forward<_ArgTypes>(aArguments)...);
}
};
template<typename _Class, typename _Member, typename... _ArgTypes>
class _Function_handler<void(_ArgTypes...), _Member _Class::*>
: public _Function_base::base_manager<_Simple_type_wrapper<_Member _Class::*>>
{
using _Functor = _Member _Class::*;
using _Wrapper = _Simple_type_wrapper<_Functor>;
using _Base = _Function_base::base_manager<_Wrapper>;
public:
static bool mamager(_Any_data& aDest, const _Any_data& aSource, _Manager_operation aOperation)
{
bool vSuccess = false;
switch (aOperation)
{
case _Manager_operation::get_functor_ptr:
aDest.access<_Functor*>() = &_Base::get_pointer(aSource)->value;
vSuccess = true;
break;
default:
vSuccess = _Base::manager(aDest, aSource, aOperation);
break;
}
return vSuccess;
}
static void invoke(const _Any_data& aFunctor, _ArgTypes&&... aArguments)
{
mem_fn(_Base::get_pointer(aFunctor)->value)(forward<_ArgTypes>(aArguments)...);
}
};
template<typename _Class, typename _Member, typename _ReturnType, typename... _ArgTypes>
class _Function_handler<_ReturnType(_ArgTypes...), _Member _Class::*>
: public _Function_handler<void(_ArgTypes...), _Member _Class::*>
{
using _Base = _Function_handler<void(_ArgTypes...), _Member _Class::*>;
public:
static _ReturnType invoke(const _Any_data& aFunctor, _ArgTypes&&... aArguments)
{
return mem_fn(_Base::get_pointer(aFunctor)->value)(forward<_ArgTypes>(aArguments)...);
}
};
template<typename _From, typename _To>
using __check_func_return_type = disjunction< // or
is_void<_To>,
is_same<_From, _To>,
is_convertible<_From, _To>>;
// TEMPLATE class function
template<typename _ReturnType, typename... _ArgTypes>
class function<_ReturnType(_ArgTypes...)>
: public _Arguments_types<_ReturnType, _ArgTypes...>,
private _Function_base
{
using _FunctorType = _ReturnType(_ArgTypes...);
template<
typename _Functor,
typename _ReturnType2 = typename result_of<_Functor&(_ArgTypes...)>::type>
struct _Callable : __check_func_return_type<_ReturnType2, _ReturnType> {};
// Used so the return type convertibility checks aren't done when
// performing overload resolution for copy construction/assignment.
template<typename _Type>
struct _Callable<function, _Type> : false_type
{ };
template<typename _Cond, typename _Type>
using _Requires = typename enable_if<_Cond::value, _Type>::type;
public:
using return_type = _ReturnType;
function() NOEXCEPT$TYPE
: _Function_base()
{ }
function(nullptr_t) NOEXCEPT$TYPE
: _Function_base()
{ }
function(const function&) = delete;
function& operator= (const function&) = delete;
/*function(const function& aSource)
{
if (static_cast<bool>(aSource))
{
if (aSource.m_Manager(m_Functor, aSource.m_Functor,
_Manager_operation::clone_functor))
{
m_Invoker = aSource.m_Invoker;
m_Manager = aSource.m_Manager;
}
}
}
function(function&& aSource)
{
aSource.swap(*this);
}
template<typename _Functor,
typename = _Requires<negation<is_same<_Functor, function>>, void>,
typename = _Requires<_Callable<_Functor>, void>
>
function(_Functor aFunctor)
{
using _Handler = _Function_handler<_FunctorType, _Functor>;
if (_Handler::not_empty_function(aFunctor))
{
if (_Handler::init_functor(m_Functor, move(aFunctor)))
{
m_Invoker = &_Handler::invoke;
m_Manager = &_Handler::manager;
}
}
}
function& operator=(const function& aSource)
{
function(aSource).swap(*this);
return *this;
}
function& operator=(function&& aSource)
{
function(move(aSource)).swap(*this);
return *this;
}
function& operator=(nullptr_t) NOEXCEPT$TYPE
{
reset();
return *this;
}
template<typename _Functor>
_Requires<_Callable<typename decay<_Functor>::type>, function&>
operator=(_Functor&& aSource)
{
function(forward<_Functor>(aSource)).swap(*this);
return *this;
}
template<typename _Functor>
function& operator=(reference_wrapper<_Functor> aSource) NOEXCEPT$TYPE
{
function(aSource.get()).swap(*this);
return *this;
}*/
bool attach(const function& aSource)
{
function vTemp;
if (static_cast<bool>(aSource))
{
if (aSource.m_Manager(vTemp.m_Functor, aSource.m_Functor,
_Manager_operation::clone_functor))
{
vTemp.m_Invoker = aSource.m_Invoker;
vTemp.m_Manager = aSource.m_Manager;
vTemp.swap(*this);
return true;
}
}
return false;
}
bool attach(function&& aSource)
{
reset();
aSource.swap(*this);
return true;
}
template<typename _Functor,
typename = _Requires<negation<is_same<_Functor, function>>, void>,
typename = _Requires<_Callable<_Functor>, void>
>
bool attach(_Functor aFunctor) NOEXCEPT$TYPE
{
function vTemp;
using _Handler = _Function_handler<_FunctorType, _Functor>;
if (_Handler::not_empty_function(aFunctor))
{
if (_Handler::init_functor(vTemp.m_Functor, move(aFunctor)))
{
vTemp.m_Invoker = &_Handler::invoke;
vTemp.m_Manager = &_Handler::manager;
vTemp.swap(*this);
return true;
}
}
return false;
}
template<typename _Functor>
bool attach(reference_wrapper<_Functor> aSource) NOEXCEPT$TYPE
{
return attach(aSource.get());
}
void reset()
{
if (!is_empty())
{
m_Manager(m_Functor, m_Functor, _Manager_operation::destroy_functor);
m_Manager = nullptr;
m_Invoker = nullptr;
}
}
void swap(function& aFunctor)
{
swap_adl(m_Functor, aFunctor.m_Functor);
swap_adl(m_Manager, aFunctor.m_Manager);
swap_adl(m_Invoker, aFunctor.m_Invoker);
}
bool is_empty() const
{
return (!m_Manager || !m_Invoker);
}
explicit operator bool() const NOEXCEPT$TYPE
{
return !is_empty();
}
inline bool operator==(nullptr_t) const NOEXCEPT$TYPE
{
return !(static_cast<bool>(*this));
}
inline bool operator!=(nullptr_t) const NOEXCEPT$TYPE
{
return (static_cast<bool>(*this));
}
_ReturnType operator()(_ArgTypes... aArguments) const
{
if (!is_empty())
{
return m_Invoker(m_Functor, forward<_ArgTypes>(aArguments)...);
}
return static_cast<_ReturnType>(0);
}
template<typename _Functor>
_Functor *target() NOEXCEPT$TYPE
{
if (m_Manager)
{
_Any_data vPtr;
m_Manager(vPtr, m_Functor, _Manager_operation::get_functor_ptr);
return vPtr.access<_Functor*>();
}
return nullptr;
}
template<typename _Functor>
const _Functor *target() const NOEXCEPT$TYPE
{
if (m_Manager)
{
_Any_data vPtr;
m_Manager(vPtr, m_Functor, _Manager_operation::get_functor_ptr);
return vPtr.access<_Functor*>();
}
return nullptr;
}
private:
using _InvokerType = _ReturnType(*)(const _Any_data& aFunctor, _ArgTypes&&...);
_InvokerType m_Invoker = nullptr;
};
/// function function's swap
template<typename _ReturnType, typename... _ArgTypes>
inline void swap(function<_ReturnType(_ArgTypes...)>& aLeft,
function<_ReturnType(_ArgTypes...)>& aRight)
{
aLeft.swap(aRight);
}
}
}
#endif
| 33.478571 | 110 | 0.513804 | [
"object"
] |
a03fb4bd86dbff29ce0402c5cd88d353cdbe2534 | 4,540 | h | C | src/Engine/InternalProductOnTheFly.h | g1257/LanczosPlusPlus | ce0b9ad9969014c013e81d3072ea8418dead3c8f | [
"Unlicense"
] | 9 | 2018-03-09T04:26:23.000Z | 2022-03-10T15:42:14.000Z | src/Engine/InternalProductOnTheFly.h | g1257/LanczosPlusPlus | ce0b9ad9969014c013e81d3072ea8418dead3c8f | [
"Unlicense"
] | 2 | 2016-06-23T14:59:36.000Z | 2016-09-09T15:17:16.000Z | src/Engine/InternalProductOnTheFly.h | g1257/LanczosPlusPlus | ce0b9ad9969014c013e81d3072ea8418dead3c8f | [
"Unlicense"
] | 2 | 2015-11-23T17:09:05.000Z | 2016-08-12T17:00:42.000Z | /*
Copyright (c) 2009-2016, 2017, UT-Battelle, LLC
All rights reserved
[Lanczos, Version 2.]
[by G.A., Oak Ridge National Laboratory]
UT Battelle Open Source Software License 11242008
OPEN SOURCE LICENSE
Subject to the conditions of this License, each
contributor to this software hereby grants, free of
charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), a
perpetual, worldwide, non-exclusive, no-charge,
royalty-free, irrevocable copyright license to use, copy,
modify, merge, publish, distribute, and/or sublicense
copies of the Software.
1. Redistributions of Software must retain the above
copyright and license notices, this list of conditions,
and the following disclaimer. Changes or modifications
to, or derivative works of, the Software should be noted
with comments and the contributor and organization's
name.
2. Neither the names of UT-Battelle, LLC or the
Department of Energy nor the names of the Software
contributors may be used to endorse or promote products
derived from this software without specific prior written
permission of UT-Battelle.
3. The software and the end-user documentation included
with the redistribution, with or without modification,
must include the following acknowledgment:
"This product includes software produced by UT-Battelle,
LLC under Contract No. DE-AC05-00OR22725 with the
Department of Energy."
*********************************************************
DISCLAIMER
THE SOFTWARE IS SUPPLIED 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, CONTRIBUTORS, UNITED STATES GOVERNMENT,
OR THE UNITED STATES DEPARTMENT OF ENERGY 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.
NEITHER THE UNITED STATES GOVERNMENT, NOR THE UNITED
STATES DEPARTMENT OF ENERGY, NOR THE COPYRIGHT OWNER, NOR
ANY OF THEIR EMPLOYEES, REPRESENTS THAT THE USE OF ANY
INFORMATION, DATA, APPARATUS, PRODUCT, OR PROCESS
DISCLOSED WOULD NOT INFRINGE PRIVATELY OWNED RIGHTS.
*********************************************************
*/
/** \ingroup LanczosPlusPlus */
/*@{*/
/*! \file InternalProductOnTheFly.h
*
* A class to encapsulate the product x+=Hy, where x and y are vectors and H is the Hamiltonian matrix
*
*/
#ifndef INTERNALPRODUCT_OTF_H
#define INTERNALPRODUCT_OTF_H
#include <vector>
#include <cassert>
#include "Vector.h"
#include "Matrix.h"
namespace LanczosPlusPlus {
template<typename ModelType_, typename SpecialSymmetryType_>
class InternalProductOnTheFly {
public:
typedef ModelType_ ModelType;
typedef SpecialSymmetryType_ SpecialSymmetryType;
typedef typename ModelType::BasisBaseType BasisType;
typedef typename SpecialSymmetryType::SparseMatrixType SparseMatrixType;
typedef typename ModelType::RealType RealType;
typedef typename ModelType::GeometryType GeometryType;
typedef typename GeometryType::ComplexOrRealType ComplexOrRealType;
typedef PsimagLite::Matrix<ComplexOrRealType> MatrixType;
typedef typename PsimagLite::Vector<RealType>::Type VectorRealType;
typedef typename PsimagLite::Vector<ComplexOrRealType>::Type VectorType;
InternalProductOnTheFly(const ModelType& model,
const BasisType& basis,
SpecialSymmetryType&)
: model_(model),basis_(basis)
{}
InternalProductOnTheFly(const ModelType& model,
SpecialSymmetryType&)
: model_(model),basis_(model.basis())
{}
SizeType rows() const
{
return basis_.size();
}
void matrixVectorProduct(VectorType &x, const VectorType& y) const
{
model_.matrixVectorProduct(x, y, basis_);
}
SizeType reflectionSector() const { return 0; }
void specialSymmetrySector(SizeType) { }
void fullDiag(VectorRealType&,
MatrixType&)
{
err("no fullDiag possible when on the fly\n");
}
private:
const ModelType& model_;
const BasisType& basis_;
}; // class InternalProductOnTheFly
} // namespace LanczosPlusPlus
/*@}*/
#endif
| 31.310345 | 103 | 0.757269 | [
"vector",
"model"
] |
a048cc578b02bf2a1f4fee5a9811fab7dfac6389 | 2,587 | h | C | enduser/netmeeting/t120/h/memmgr.h | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | enduser/netmeeting/t120/h/memmgr.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | enduser/netmeeting/t120/h/memmgr.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*
* memmgr.h
*
* Copyright (c) 1998 by Microsoft Corporation, Redmond, WA
*
* Abstract:
* This is the header file for the T.120 memory allocation mechanism. This
* file contains the declarations necessary to allocate and distribute memory
* in the form of Memory objects within T.120.
*
* This implementation defines priorities of memory allocations. A lower
* priority number implies higher priority. Priority-0 allocations will be
* satisfied, unless the system is out of memory. Priorities 1 and 2
* limit the amount of total memory that can be allocated, but priority 1 (recv priority)
* has higher water mark limits than priority 2 (send priority).
*
* Protected Member Functions:
* None.
*
* Caveats:
* None.
*
* Author:
* Christos Tsollis
*/
/*
* We define the following 3 memory priorities:
* TOP_PRIORITY (0): The allocation will succeed unless the system is out of memory
* RECV_PRIORITY (1): Allocation will succeed only if less than 1 MB has been allocated
* SEND_PRIORITY (2): Allocation will succeed only if less than 0xE0000 bytes have been allocated so far.
*/
#ifndef _T120_MEMORY_MANAGER
#define _T120_MEMORY_MANAGER
#include "memory.h"
// This is the main T.120 allocation routine
PMemory AllocateMemory (
PUChar reference_ptr,
UINT length,
MemoryPriority priority = HIGHEST_PRIORITY);
// Routine to ReAlloc memory allocated by AllocateMemory().
BOOL ReAllocateMemory (
PMemory *pmemory,
UINT length);
// Routine to free the memory allocated by AllocateMemory().
void FreeMemory (PMemory memory);
// To discover how much space is available at a non-TOP priority...
unsigned int GetFreeMemory (MemoryPriority priority);
// Macro to get to the Memory object from app-requested buffer space
#define GetMemoryObject(p) ((PMemory) ((PUChar) p - (sizeof(Memory) + MAXIMUM_PROTOCOL_OVERHEAD)))
// Macro to get to the Memory object from the coder-alloced buffer space
#define GetMemoryObjectFromEncData(p) ((PMemory) ((PUChar) p - sizeof(Memory)))
// Routines to lock/unlock (AddRef/Release) memory allocated by AllocateMemory()
#define LockMemory(memory) ((memory)->Lock())
#define UnlockMemory(memory) (FreeMemory(memory))
// Routines to allocate, realloc and free space without an associated Memory object
#ifdef DEBUG
PUChar Allocate (UINT length);
#else
# define Allocate(length) ((PUChar) new BYTE[length])
#endif // DEBUG
#define Free(p) (delete [] (BYTE *) (p))
#endif // _T120_MEMORY_MANAGER
| 36.43662 | 107 | 0.715501 | [
"object"
] |
a049179022991675c52b0dec9e89de5fabe6a2b8 | 1,400 | h | C | SampleCode/Dependencies/inc/Extern/IDrive.h | virtium/vtStor | 069d3e1ddb1c5589826dfe59714a1479c4af8f51 | [
"Apache-2.0"
] | 3 | 2015-04-27T07:53:57.000Z | 2017-12-26T08:55:24.000Z | SampleCode/Dependencies/inc/Extern/IDrive.h | virtium/vtStor | 069d3e1ddb1c5589826dfe59714a1479c4af8f51 | [
"Apache-2.0"
] | 18 | 2015-04-08T21:44:45.000Z | 2016-03-09T23:44:51.000Z | SampleCode/Dependencies/inc/Extern/IDrive.h | virtium/vtStor | 069d3e1ddb1c5589826dfe59714a1479c4af8f51 | [
"Apache-2.0"
] | 19 | 2015-05-15T07:48:05.000Z | 2019-09-16T09:12:05.000Z | /*
<License>
Copyright 2016 Virtium Technology
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.
</License>
*/
#ifndef __vtStorIDrive_h__
#define __vtStorIDrive_h__
#include <memory>
#include <vector>
#include "BusType.h"
#include "DriveProperties.h"
#include "IBuffer.h"
#include "ICommandHandler.h"
#include "IDevice.h"
namespace vtStor
{
class VTSTOR_API IDrive : public IDevice
{
public:
virtual ~IDrive() {}
virtual void RegisterCommandHandler(U32 CommandType, std::shared_ptr<ICommandHandler> CommandHandler) = 0;
virtual eErrorCode IssueCommand(U32 CommandType, std::shared_ptr<const IBuffer> CommandDescriptor, std::shared_ptr<IBuffer> Data) = 0;
virtual eBusType GetBusType() = 0;
virtual std::shared_ptr<vtStor::sDriveProperties> GetDriveProperties() = 0;
};
using Vector_Drives = std::vector<std::shared_ptr<IDrive>>;
}
#endif // end __vtStorIDrive_h__ | 31.111111 | 142 | 0.751429 | [
"vector"
] |
a04b9c6121cc0aed56b193d05a4962537ffb9236 | 7,581 | h | C | src/sparki/core/rnd_base.h | ref2401/SPARKi | 4ee899420a425a1c7aec6a01bf58b257c27d9b70 | [
"MIT"
] | null | null | null | src/sparki/core/rnd_base.h | ref2401/SPARKi | 4ee899420a425a1c7aec6a01bf58b257c27d9b70 | [
"MIT"
] | 1 | 2017-09-06T09:18:37.000Z | 2017-09-06T09:30:54.000Z | src/sparki/core/rnd_base.h | ref2401/SPARKi | 4ee899420a425a1c7aec6a01bf58b257c27d9b70 | [
"MIT"
] | null | null | null | #pragma once
#include "sparki/core/asset.h"
#include <windows.h>
#include <d3d11.h>
#include <d3dcommon.h>
#include <d3dcompiler.h>
#include <dxgi.h>
using namespace math;
namespace sparki {
namespace core {
// Unique_com_ptr is a smart pointer that owns and manages a COM object through a pointer
// and disposes of that object when the Unique_com_ptr goes out of scope.
template<typename T>
struct com_ptr final {
static_assert(std::is_base_of<IUnknown, T>::value, "T must be derived from IUnknown.");
com_ptr() noexcept = default;
explicit com_ptr(T* ptr) noexcept
: ptr(ptr)
{}
com_ptr(nullptr_t) noexcept {}
com_ptr(com_ptr&& com_ptr) noexcept
: ptr(com_ptr.ptr)
{
com_ptr.ptr = nullptr;
}
com_ptr& operator=(com_ptr&& com_ptr) noexcept
{
if (this == &com_ptr) return *this;
dispose();
ptr = com_ptr.ptr;
com_ptr.ptr = nullptr;
return *this;
}
~com_ptr() noexcept
{
dispose();
}
com_ptr& operator=(T* ptr) noexcept
{
dispose();
this->ptr = ptr;
return *this;
}
com_ptr& operator=(nullptr_t) noexcept
{
dispose();
return *this;
}
T& operator*() const noexcept
{
return *ptr;
}
T* operator->() const noexcept
{
return ptr;
}
operator bool() const noexcept
{
return (ptr != nullptr);
}
operator T*() const noexcept
{
return ptr;
}
// Releases the managed COM object if such is present.
void dispose() noexcept
{
T* temp = ptr;
if (temp == nullptr) return;
ptr = nullptr;
temp->Release();
}
// Releases the ownership of the managed COM object and returns a pointer to it.
// Does not call ptr->Release(). ptr == nullptr after that.
T* release_ownership() noexcept
{
T* tmp = ptr;
ptr = nullptr;
return tmp;
}
// Pointer to the managed COM object.
T* ptr = nullptr;
};
struct hlsl_compute final {
hlsl_compute() noexcept = default;
hlsl_compute(ID3D11Device* p_device, const hlsl_compute_desc& desc);
hlsl_compute(hlsl_compute&& s) noexcept = default;
hlsl_compute& operator=(hlsl_compute&& s) noexcept = default;
com_ptr<ID3D11ComputeShader> p_compute_shader;
com_ptr<ID3DBlob> p_compute_shader_bytecode;
};
struct hlsl_shader final {
hlsl_shader() noexcept = default;
hlsl_shader(ID3D11Device* p_device, const hlsl_shader_desc& desc);
hlsl_shader(hlsl_shader&& s) noexcept = default;
hlsl_shader& operator=(hlsl_shader&& s) noexcept = default;
com_ptr<ID3D11VertexShader> p_vertex_shader;
com_ptr<ID3DBlob> p_vertex_shader_bytecode;
com_ptr<ID3D11HullShader> p_hull_shader;
com_ptr<ID3DBlob> p_hull_shader_bytecode;
com_ptr<ID3D11DomainShader> p_domain_shader;
com_ptr<ID3DBlob> p_domain_shader_bytecode;
com_ptr<ID3D11PixelShader> p_pixel_shader;
com_ptr<ID3DBlob> p_pixel_shader_bytecode;
private:
void init_vertex_shader(ID3D11Device* p_device, const hlsl_shader_desc& desc);
void init_hull_shader(ID3D11Device* p_device, const hlsl_shader_desc& desc);
void init_domain_shader(ID3D11Device* p_device, const hlsl_shader_desc& desc);
void init_pixel_shader(ID3D11Device* p_device, const hlsl_shader_desc& desc);
};
struct material final {
ID3D11ShaderResourceView* p_tex_base_color_srv = nullptr;
ID3D11ShaderResourceView* p_tex_reflect_color_srv = nullptr;
ID3D11ShaderResourceView* p_tex_normal_map_srv = nullptr;
ID3D11ShaderResourceView* p_tex_properties_srv = nullptr;
};
struct gbuffer final {
static constexpr float viewport_factor = 1.333f;
explicit gbuffer(ID3D11Device* p_device);
gbuffer(gbuffer&&) = delete;
gbuffer& operator=(gbuffer&&) = delete;
void resize(ID3D11Device* p_device, const uint2 size);
// color texture
com_ptr<ID3D11Texture2D> p_tex_color;
com_ptr<ID3D11ShaderResourceView> p_tex_color_srv;
com_ptr<ID3D11RenderTargetView> p_tex_color_rtv;
// post processing
com_ptr<ID3D11Texture2D> p_tex_tone_mapping;
com_ptr<ID3D11ShaderResourceView> p_tex_tone_mapping_srv;
com_ptr<ID3D11UnorderedAccessView> p_tex_tone_mapping_uav;
com_ptr<ID3D11Texture2D> p_tex_aa;
com_ptr<ID3D11ShaderResourceView> p_tex_aa_srv;
com_ptr<ID3D11UnorderedAccessView> p_tex_aa_uav;
// depth texture
com_ptr<ID3D11Texture2D> p_tex_depth;
com_ptr<ID3D11DepthStencilView> p_tex_depth_dsv;
// other stuff:
com_ptr<ID3D11BlendState> p_blend_state_no_blend;
// Common rasterizer state. FrontCounterClockwise, CULL_BACK
com_ptr<ID3D11RasterizerState> p_rasterizer_state;
// Sampler: MIN_MAG_MIP_LINEAR, ADDRESS_CLAMP, LOD in [0, D3D11_FLOAT32_MAX]
com_ptr<ID3D11SamplerState> p_sampler_linear;
// Sampler: MIN_MAG_MIP_POINT, ADDRESS_CLAMP, LOD in [0, D3D11_FLOAT32_MAX]
com_ptr<ID3D11SamplerState> p_sampler_point;
D3D11_VIEWPORT rnd_viewport = { 0, 0, 0, 0, 0, 1 };
D3D11_VIEWPORT window_viewport = { 0, 0, 0, 0, 0, 1 };
};
template<typename T>
inline bool operator==(const com_ptr<T>& l, const com_ptr<T>& r) noexcept
{
return l.ptr == r.ptr;
}
template<typename T>
inline bool operator==(const com_ptr<T>& com_ptr, nullptr_t) noexcept
{
return com_ptr.ptr == nullptr;
}
template<typename T>
inline bool operator==(nullptr_t, const com_ptr<T>& com_ptr) noexcept
{
return com_ptr.ptr == nullptr;
}
template<typename T>
inline bool operator!=(const com_ptr<T>& l, const com_ptr<T>& r) noexcept
{
return l.ptr != r.ptr;
}
template<typename T>
inline bool operator!=(const com_ptr<T>& com_ptr, nullptr_t) noexcept
{
return com_ptr.ptr != nullptr;
}
template<typename T>
inline bool operator!=(nullptr_t, const com_ptr<T>& com_ptr) noexcept
{
return com_ptr.ptr != nullptr;
}
com_ptr<ID3DBlob> compile_shader(const std::string& source_code, const std::string& source_filename,
uint32_t compile_flags, const char* p_entry_point_name, const char* p_shader_model);
// Returns true is the given material object is valid (may be used during rendering).
inline bool is_valid_material(const material& m) noexcept
{
return (m.p_tex_base_color_srv != nullptr)
&& (m.p_tex_reflect_color_srv != nullptr);
}
// Creates a standard buffer resource.
com_ptr<ID3D11Buffer> make_buffer(ID3D11Device* p_device, UINT byte_count,
D3D11_USAGE usage, UINT bing_flags, UINT cpu_access_flags = 0);
// Creates an unitialized a constant buffer object.
com_ptr<ID3D11Buffer> make_constant_buffer(ID3D11Device* p_device, UINT byte_count);
// Creates a structured buffer resource.
com_ptr<ID3D11Buffer> make_structured_buffer(ID3D11Device* p_device, UINT item_byte_count, UINT item_count,
D3D11_USAGE usage, UINT bing_flags);
DXGI_FORMAT make_dxgi_format(pixel_format fmt) noexcept;
pixel_format make_pixel_format(DXGI_FORMAT fmt) noexcept;
com_ptr<ID3D11Texture2D> make_texture_2d(ID3D11Device* p_device, const texture_data& td,
D3D11_USAGE usage, UINT bind_flags);
com_ptr<ID3D11Texture2D> make_texture_cube(ID3D11Device* p_device, const texture_data& td,
D3D11_USAGE usage, UINT bind_flags, UINT misc_flags = 0);
com_ptr<ID3D11Texture2D> make_texture_cube(ID3D11Device* p_device, UINT side_size, UINT mipmap_count,
DXGI_FORMAT format, D3D11_USAGE usage, UINT bing_flags, UINT misc_flags = 0);
// Returns texture_data object which stores all the array slices of the specified texture.
texture_data make_texture_data(ID3D11Device* p_device, ID3D11DeviceContext* p_ctx,
texture_type type, ID3D11Texture2D* p_tex);
} // namespace core
} // namespace sparki
| 26.978648 | 108 | 0.733676 | [
"object"
] |
a059737e8bc77b657d2dbbbbc9917b8a779d4348 | 15,287 | h | C | Classes/gframe/game.h | oldwang504/YGOMobile | daa6eb2c7a93e09776686c6c81d11ccb779cde39 | [
"MIT"
] | 41 | 2015-05-03T03:15:39.000Z | 2020-11-26T04:05:25.000Z | Classes/gframe/game.h | oldwang504/YGOMobile | daa6eb2c7a93e09776686c6c81d11ccb779cde39 | [
"MIT"
] | 5 | 2015-06-27T01:26:04.000Z | 2018-01-21T06:01:30.000Z | Classes/gframe/game.h | oldwang504/YGOMobile | daa6eb2c7a93e09776686c6c81d11ccb779cde39 | [
"MIT"
] | 28 | 2015-02-28T06:22:22.000Z | 2021-02-22T12:15:28.000Z | #ifndef GAME_H
#define GAME_H
#include "config.h"
#include "client_field.h"
#include "deck_con.h"
#include "menu_handler.h"
#include <unordered_map>
#include <vector>
#include <list>
#include "IYGOSoundEffectPlayer.h"
namespace ygo {
struct Config {
bool use_d3d;
unsigned short antialias;
unsigned short serverport;
unsigned char textfontsize;
wchar_t lastip[20];
wchar_t lastport[10];
wchar_t nickname[20];
wchar_t gamename[20];
wchar_t lastdeck[64];
wchar_t textfont[256];
wchar_t numfont[256];
wchar_t roompass[20];
//settings
int chkAutoPos;
int chkRandomPos;
int chkAutoChain;
int chkWaitChain;
int chkIgnore1;
int chkIgnore2;
int chkHideSetname;
int control_mode;
};
struct DuelInfo {
bool isStarted;
bool isReplay;
bool isReplaySkiping;
bool isFirst;
bool isTag;
bool isSingleMode;
bool is_shuffling;
bool tag_player[2];
int lp[2];
int turn;
short curMsg;
wchar_t hostname[20];
wchar_t clientname[20];
wchar_t hostname_tag[20];
wchar_t clientname_tag[20];
wchar_t strLP[2][16];
wchar_t strTurn[8];
wchar_t* vic_string;
unsigned char player_type;
unsigned char time_player;
unsigned short time_limit;
unsigned short time_left[2];
};
struct FadingUnit {
bool signalAction;
bool isFadein;
int fadingFrame;
int autoFadeoutFrame;
irr::gui::IGUIElement* guiFading;
irr::core::recti fadingSize;
irr::core::vector2di fadingUL;
irr::core::vector2di fadingLR;
irr::core::vector2di fadingDiff;
};
class Game {
public:
#ifdef _IRR_ANDROID_PLATFORM_
bool Initialize(android_app* app);
#else
bool Initialize();
#endif
void MainLoop();
void BuildProjectionMatrix(irr::core::matrix4& mProjection, f32 left,
f32 right, f32 bottom, f32 top, f32 znear, f32 zfar);
void InitStaticText(irr::gui::IGUIStaticText* pControl, u32 cWidth,
u32 cHeight, irr::gui::CGUITTFont* font, const wchar_t* text);
void SetStaticText(irr::gui::IGUIStaticText* pControl, u32 cWidth,
irr::gui::CGUITTFont* font, const wchar_t* text, u32 pos = 0);
void RefreshDeck(irr::gui::IGUIComboBox* cbDeck);
void RefreshReplay();
void RefreshSingleplay();
void DrawSelectionLine(irr::video::S3DVertex* vec, bool strip, int width,
float* cv);
void DrawBackGround();
void DrawCards();
void DrawCard(ClientCard* pcard);
void DrawMisc();
void DrawGUI();
void DrawSpec();
void ShowElement(irr::gui::IGUIElement* element, int autoframe = 0);
void HideElement(irr::gui::IGUIElement* element, bool set_action = false);
void PopupElement(irr::gui::IGUIElement* element, int hideframe = 0);
void WaitFrameSignal(int frame);
void DrawThumb(code_pointer cp, position2di pos,
std::unordered_map<int, int>* lflist);
void DrawDeckBd();
void LoadConfig();
void SaveConfig();
void ShowCardInfo(int code);
void AddChatMsg(wchar_t* msg, int player);
void ClearTextures();
void CloseDuelWindow();
int LocalPlayer(int player);
const wchar_t* LocalName(int local_player);
bool HasFocus(EGUI_ELEMENT_TYPE type) const {
irr::gui::IGUIElement* focus = env->getFocus();
return focus && focus->hasType(type);
}
Mutex gMutex;
Mutex gBuffer;
Signal frameSignal;
Signal actionSignal;
Signal replaySignal;
Signal singleSignal;
Signal closeSignal;
Signal closeDoneSignal;
Config gameConf;
DuelInfo dInfo;
std::list<FadingUnit> fadingList;
std::vector<int> logParam;
std::wstring chatMsg[8];
int hideChatTimer;
bool hideChat;
int chatTiming[8];
int chatType[8];
unsigned short linePattern;
int waitFrame;
int signalFrame;
int actionParam;
const wchar_t* showingtext;
int showcard;
int showcardcode;
int showcarddif;
int showcardp;
int is_attacking;
int attack_sv;
irr::core::vector3df atk_r;
irr::core::vector3df atk_t;
float atkdy;
int lpframe;
int lpd;
int lpplayer;
int lpccolor;
wchar_t* lpcstring;
bool always_chain;
bool ignore_chain;
bool is_building;
bool is_siding;
ClientField dField;
DeckBuilder deckBuilder;
MenuHandler menuHandler;
irr::IrrlichtDevice* device;
irr::video::IVideoDriver* driver;
irr::scene::ISceneManager* smgr;
irr::scene::ICameraSceneNode* camera;
//GUI
irr::gui::IGUIEnvironment* env;
irr::gui::CGUITTFont* guiFont;
irr::gui::CGUITTFont* textFont;
irr::gui::CGUITTFont* numFont;
irr::gui::CGUITTFont* adFont;
irr::gui::CGUITTFont* lpcFont;
std::map<irr::gui::CGUIImageButton*, int> imageLoading;
//card image
irr::gui::IGUIStaticText* wCardImg;
irr::gui::IGUIImage* imgCard;
//hint text
irr::gui::IGUIStaticText* stHintMsg;
irr::gui::IGUIStaticText* stTip;
//infos
irr::gui::IGUITabControl* wInfos;
irr::gui::IGUIStaticText* stName;
irr::gui::IGUIStaticText* stInfo;
irr::gui::IGUIStaticText* stDataInfo;
irr::gui::IGUIStaticText* stSetName;
irr::gui::IGUIStaticText* stText;
irr::gui::IGUIScrollBar *scrCardText;
irr::gui::IGUICheckBox* chkAutoPos;
irr::gui::IGUICheckBox* chkRandomPos;
irr::gui::IGUICheckBox* chkAutoChain;
irr::gui::IGUICheckBox* chkWaitChain;
irr::gui::IGUICheckBox* chkHideSetname;
irr::gui::IGUIListBox* lstLog;
irr::gui::IGUIButton* btnClearLog;
irr::gui::IGUIButton* btnSaveLog;
//main menu
irr::gui::IGUIWindow* wMainMenu;
irr::gui::IGUIButton* btnLanMode;
irr::gui::IGUIButton* btnServerMode;
irr::gui::IGUIButton* btnReplayMode;
irr::gui::IGUIButton* btnTestMode;
irr::gui::IGUIButton* btnDeckEdit;
irr::gui::IGUIButton* btnModeExit;
//lan
irr::gui::IGUIWindow* wLanWindow;
irr::gui::IGUIEditBox* ebNickName;
irr::gui::IGUIListBox* lstHostList;
irr::gui::IGUIButton* btnLanRefresh;
irr::gui::IGUIEditBox* ebJoinIP;
irr::gui::IGUIEditBox* ebJoinPort;
irr::gui::IGUIEditBox* ebJoinPass;
irr::gui::IGUIButton* btnJoinHost;
irr::gui::IGUIButton* btnJoinCancel;
irr::gui::IGUIButton* btnCreateHost;
//create host
irr::gui::IGUIWindow* wCreateHost;
irr::gui::IGUIComboBox* cbLFlist;
irr::gui::IGUIComboBox* cbMatchMode;
irr::gui::IGUIComboBox* cbRule;
irr::gui::IGUIEditBox* ebTimeLimit;
irr::gui::IGUIEditBox* ebStartLP;
irr::gui::IGUIEditBox* ebStartHand;
irr::gui::IGUIEditBox* ebDrawCount;
irr::gui::IGUIEditBox* ebServerName;
irr::gui::IGUIEditBox* ebServerPass;
irr::gui::IGUICheckBox* chkEnablePriority;
irr::gui::IGUICheckBox* chkNoCheckDeck;
irr::gui::IGUICheckBox* chkNoShuffleDeck;
irr::gui::IGUIButton* btnHostConfirm;
irr::gui::IGUIButton* btnHostCancel;
//host panel
irr::gui::IGUIWindow* wHostPrepare;
irr::gui::IGUIButton* btnHostPrepDuelist;
irr::gui::IGUIButton* btnHostPrepOB;
irr::gui::IGUIStaticText* stHostPrepDuelist[4];
irr::gui::IGUICheckBox* chkHostPrepReady[4];
irr::gui::IGUIButton* btnHostPrepKick[4];
irr::gui::IGUIComboBox* cbDeckSelect;
irr::gui::IGUIStaticText* stHostPrepRule;
irr::gui::IGUIStaticText* stHostPrepOB;
irr::gui::IGUIButton* btnHostPrepStart;
irr::gui::IGUIButton* btnHostPrepCancel;
//replay
irr::gui::IGUIWindow* wReplay;
irr::gui::IGUIListBox* lstReplayList;
irr::gui::IGUIStaticText* stReplayInfo;
irr::gui::IGUIButton* btnLoadReplay;
irr::gui::IGUIButton* btnReplayCancel;
irr::gui::IGUIEditBox* ebRepStartTurn;
//single play
irr::gui::IGUIWindow* wSinglePlay;
irr::gui::IGUIListBox* lstSinglePlayList;
irr::gui::IGUIStaticText* stSinglePlayInfo;
irr::gui::IGUIButton* btnLoadSinglePlay;
irr::gui::IGUIButton* btnSinglePlayCancel;
//hand
irr::gui::IGUIWindow* wHand;
irr::gui::CGUIImageButton* btnHand[3];
//
irr::gui::IGUIWindow* wFTSelect;
irr::gui::IGUIButton* btnFirst;
irr::gui::IGUIButton* btnSecond;
//message
irr::gui::IGUIWindow* wMessage;
irr::gui::IGUIStaticText* stMessage;
irr::gui::IGUIButton* btnMsgOK;
//auto close message
irr::gui::IGUIWindow* wACMessage;
irr::gui::IGUIStaticText* stACMessage;
//yes/no
irr::gui::IGUIWindow* wQuery;
irr::gui::IGUIStaticText* stQMessage;
irr::gui::IGUIButton* btnYes;
irr::gui::IGUIButton* btnNo;
//options
irr::gui::IGUIWindow* wOptions;
irr::gui::IGUIStaticText* stOptions;
irr::gui::IGUIButton* btnOptionp;
irr::gui::IGUIButton* btnOptionn;
irr::gui::IGUIButton* btnOptionOK;
//pos selection
irr::gui::IGUIWindow* wPosSelect;
irr::gui::CGUIImageButton* btnPSAU;
irr::gui::CGUIImageButton* btnPSAD;
irr::gui::CGUIImageButton* btnPSDU;
irr::gui::CGUIImageButton* btnPSDD;
//card selection
irr::gui::IGUIWindow* wCardSelect;
irr::gui::CGUIImageButton* btnCardSelect[5];
irr::gui::IGUIStaticText *stCardPos[5];
irr::gui::IGUIScrollBar *scrCardList;
irr::gui::IGUIButton* btnSelectOK;
//card display
irr::gui::IGUIWindow* wCardDisplay;
irr::gui::CGUIImageButton* btnCardDisplay[5];
irr::gui::IGUIStaticText *stDisplayPos[5];
irr::gui::IGUIScrollBar *scrDisplayList;
irr::gui::IGUIButton* btnDisplayOK;
//announce number
irr::gui::IGUIWindow* wANNumber;
irr::gui::IGUIComboBox* cbANNumber;
irr::gui::IGUIButton* btnANNumberOK;
//announce card
irr::gui::IGUIWindow* wANCard;
irr::gui::IGUIEditBox* ebANCard;
irr::gui::IGUIListBox* lstANCard;
irr::gui::IGUIButton* btnANCardOK;
//announce attribute
irr::gui::IGUIWindow* wANAttribute;
irr::gui::IGUICheckBox* chkAttribute[7];
//announce race
irr::gui::IGUIWindow* wANRace;
//merge 0f2fb4
irr::gui::IGUICheckBox* chkRace[24];
// irr::gui::IGUICheckBox* chkRace[23];
//cmd menu
irr::gui::IGUIWindow* wCmdMenu;
irr::gui::IGUIButton* btnActivate;
irr::gui::IGUIButton* btnSummon;
irr::gui::IGUIButton* btnSPSummon;
irr::gui::IGUIButton* btnMSet;
irr::gui::IGUIButton* btnSSet;
irr::gui::IGUIButton* btnRepos;
irr::gui::IGUIButton* btnAttack;
irr::gui::IGUIButton* btnShowList;
irr::gui::IGUIButton* btnShuffle;
//chat window
irr::gui::IGUIWindow* wChat;
irr::gui::IGUIListBox* lstChatLog;
irr::gui::IGUIEditBox* ebChatInput;
irr::gui::IGUICheckBox* chkIgnore1;
irr::gui::IGUICheckBox* chkIgnore2;
//phase button
irr::gui::IGUIStaticText* wPhase;
irr::gui::IGUIButton* btnDP;
irr::gui::IGUIButton* btnSP;
irr::gui::IGUIButton* btnM1;
irr::gui::IGUIButton* btnBP;
irr::gui::IGUIButton* btnM2;
irr::gui::IGUIButton* btnEP;
//deck edit
irr::gui::IGUIStaticText* wDeckEdit;
irr::gui::IGUIComboBox* cbDBLFList;
irr::gui::IGUIComboBox* cbDBDecks;
irr::gui::IGUIButton* btnClearDeck;
irr::gui::IGUIButton* btnSortDeck;
irr::gui::IGUIButton* btnShuffleDeck;
irr::gui::IGUIButton* btnSaveDeck;
irr::gui::IGUIButton* btnSaveDeckAs;
irr::gui::IGUIButton* btnDBExit;
irr::gui::IGUIButton* btnSideOK;
irr::gui::IGUIEditBox* ebDeckname;
irr::gui::IGUIButton* btnDeleteDeck;
//filter
irr::gui::IGUIStaticText* wFilter;
irr::gui::IGUIScrollBar* scrFilter;
irr::gui::IGUIComboBox* cbCardType;
irr::gui::IGUIComboBox* cbCardType2;
irr::gui::IGUIComboBox* cbRace;
irr::gui::IGUIComboBox* cbAttribute;
irr::gui::IGUIComboBox* cbLimit;
irr::gui::IGUIEditBox* ebStar;
irr::gui::IGUIEditBox* ebAttack;
irr::gui::IGUIEditBox* ebDefence;
irr::gui::IGUIEditBox* ebCardName;
irr::gui::IGUIButton* btnEffectFilter;
irr::gui::IGUIButton* btnStartFilter;
irr::gui::IGUIWindow* wCategories;
irr::gui::IGUICheckBox* chkCategory[32];
irr::gui::IGUIButton* btnCategoryOK;
//replay save
irr::gui::IGUIWindow* wReplaySave;
irr::gui::IGUIEditBox* ebRSName;
irr::gui::IGUIButton* btnRSYes;
irr::gui::IGUIButton* btnRSNo;
//replay control
irr::gui::IGUIStaticText* wReplayControl;
irr::gui::IGUIButton* btnReplayStart;
irr::gui::IGUIButton* btnReplayPause;
irr::gui::IGUIButton* btnReplayStep;
irr::gui::IGUIButton* btnReplayExit;
irr::gui::IGUIButton* btnReplaySwap;
//surrender/leave
irr::gui::IGUIButton* btnLeaveGame;
float xScale;
float yScale;
IYGOSoundEffectPlayer* soundEffectPlayer;
#ifdef _IRR_ANDROID_PLATFORM_
android_app* appMain;
int glversion;
bool isPSEnabled;
bool isNPOTSupported;
s32 ogles2Solid;
s32 ogles2TrasparentAlpha;
s32 ogles2BlendTexture;
irr::android::CustomShaderConstantSetCallBack customShadersCallback;
Signal externalSignal;
#endif
};
extern Game* mainGame;
}
#define UEVENT_EXIT 0x1
#define UEVENT_TOWINDOW 0x2
#define COMMAND_ACTIVATE 0x0001
#define COMMAND_SUMMON 0x0002
#define COMMAND_SPSUMMON 0x0004
#define COMMAND_MSET 0x0008
#define COMMAND_SSET 0x0010
#define COMMAND_REPOS 0x0020
#define COMMAND_ATTACK 0x0040
#define COMMAND_LIST 0x0080
#define BUTTON_LAN_MODE 100
#define BUTTON_SINGLE_MODE 101
#define BUTTON_REPLAY_MODE 102
#define BUTTON_TEST_MODE 103
#define BUTTON_DECK_EDIT 104
#define BUTTON_MODE_EXIT 105
#define LISTBOX_LAN_HOST 110
#define BUTTON_JOIN_HOST 111
#define BUTTON_JOIN_CANCEL 112
#define BUTTON_CREATE_HOST 113
#define BUTTON_HOST_CONFIRM 114
#define BUTTON_HOST_CANCEL 115
#define BUTTON_LAN_REFRESH 116
#define BUTTON_HP_DUELIST 120
#define BUTTON_HP_OBSERVER 121
#define BUTTON_HP_START 122
#define BUTTON_HP_CANCEL 123
#define BUTTON_HP_KICK 124
#define CHECKBOX_HP_READY 125
#define LISTBOX_REPLAY_LIST 130
#define BUTTON_LOAD_REPLAY 131
#define BUTTON_CANCEL_REPLAY 132
#define EDITBOX_CHAT 140
#define BUTTON_MSG_OK 200
#define BUTTON_YES 201
#define BUTTON_NO 202
#define BUTTON_HAND1 205
#define BUTTON_HAND2 206
#define BUTTON_HAND3 207
#define BUTTON_FIRST 208
#define BUTTON_SECOND 209
#define BUTTON_POS_AU 210
#define BUTTON_POS_AD 211
#define BUTTON_POS_DU 212
#define BUTTON_POS_DD 213
#define BUTTON_OPTION_PREV 220
#define BUTTON_OPTION_NEXT 221
#define BUTTON_OPTION_OK 222
#define BUTTON_CARD_0 230
#define BUTTON_CARD_1 231
#define BUTTON_CARD_2 232
#define BUTTON_CARD_3 233
#define BUTTON_CARD_4 234
#define SCROLL_CARD_SELECT 235
#define BUTTON_CARD_SEL_OK 236
#define BUTTON_CMD_ACTIVATE 240
#define BUTTON_CMD_SUMMON 241
#define BUTTON_CMD_SPSUMMON 242
#define BUTTON_CMD_MSET 243
#define BUTTON_CMD_SSET 244
#define BUTTON_CMD_REPOS 245
#define BUTTON_CMD_ATTACK 246
#define BUTTON_CMD_SHOWLIST 247
#define BUTTON_CMD_SHUFFLE 248
#define BUTTON_ANNUMBER_OK 250
#define BUTTON_ANCARD_OK 251
#define EDITBOX_ANCARD 252
#define LISTBOX_ANCARD 253
#define CHECK_ATTRIBUTE 254
#define CHECK_RACE 255
#define BUTTON_BP 260
#define BUTTON_M2 261
#define BUTTON_EP 262
#define BUTTON_LEAVE_GAME 263
#define BUTTON_CLEAR_LOG 270
#define LISTBOX_LOG 271
#define SCROLL_CARDTEXT 280
#define BUTTON_DISPLAY_0 290
#define BUTTON_DISPLAY_1 291
#define BUTTON_DISPLAY_2 292
#define BUTTON_DISPLAY_3 293
#define BUTTON_DISPLAY_4 294
#define SCROLL_CARD_DISPLAY 295
#define BUTTON_CARD_DISP_OK 296
#define BUTTON_CATEGORY_OK 300
#define COMBOBOX_DBLFLIST 301
#define COMBOBOX_DBDECKS 302
#define BUTTON_CLEAR_DECK 303
#define BUTTON_SAVE_DECK 304
#define BUTTON_SAVE_DECK_AS 305
#define BUTTON_DBEXIT 306
#define BUTTON_SORT_DECK 307
#define BUTTON_SIDE_OK 308
#define BUTTON_SHUFFLE_DECK 309
#define COMBOBOX_MAINTYPE 310
#define BUTTON_EFFECT_FILTER 311
#define BUTTON_START_FILTER 312
#define SCROLL_FILTER 314
#define EDITBOX_KEYWORD 315
#define BUTTON_REPLAY_START 320
#define BUTTON_REPLAY_PAUSE 321
#define BUTTON_REPLAY_STEP 322
#define BUTTON_REPLAY_EXIT 323
#define BUTTON_REPLAY_SWAP 324
#define BUTTON_REPLAY_SAVE 330
#define BUTTON_REPLAY_CANCEL 331
#define LISTBOX_SINGLEPLAY_LIST 350
#define BUTTON_LOAD_SINGLEPLAY 351
#define BUTTON_CANCEL_SINGLEPLAY 352
#ifdef _IRR_ANDROID_PLATFORM_
#define GUI_INFO_FPS 1000
#define BUTTON_DELETE_DECK 1001
#endif
#endif // GAME_H
| 28.789077 | 75 | 0.76117 | [
"vector"
] |
a05fd5798bdac9e42ea9a2595af4979bce1b30b7 | 6,956 | h | C | open-source/amazon-kinesis-video-streams-producer-c/open-source/amazon-kinesis-video-streams-pic/src/utils/src/Include_i.h | vinoth-rigpa/amazon-kinesis-video-streams-producer-sdk-cpp | 2b364c4e3e0b533dec863d9a7bfb23b9ad456d07 | [
"Apache-2.0"
] | null | null | null | open-source/amazon-kinesis-video-streams-producer-c/open-source/amazon-kinesis-video-streams-pic/src/utils/src/Include_i.h | vinoth-rigpa/amazon-kinesis-video-streams-producer-sdk-cpp | 2b364c4e3e0b533dec863d9a7bfb23b9ad456d07 | [
"Apache-2.0"
] | null | null | null | open-source/amazon-kinesis-video-streams-producer-c/open-source/amazon-kinesis-video-streams-pic/src/utils/src/Include_i.h | vinoth-rigpa/amazon-kinesis-video-streams-producer-sdk-cpp | 2b364c4e3e0b533dec863d9a7bfb23b9ad456d07 | [
"Apache-2.0"
] | null | null | null | /**
* Internal functionality
*/
#ifndef __UTILS_I_H__
#define __UTILS_I_H__
#ifdef __cplusplus
extern "C" {
#endif
#pragma once
#include "com/amazonaws/kinesis/video/utils/Include.h"
/**
* Thread wrapper for Windows
*/
typedef struct {
// Stored routine
startRoutine storedStartRoutine;
// Original arguments
PVOID storedArgs;
} WindowsThreadRoutineWrapper, *PWindowsThreadRoutineWrapper;
/**
* Internal String operations
*/
STATUS strtoint(PCHAR, PCHAR, UINT32, PUINT64, PBOOL);
/**
* Internal safe multiplication
*/
STATUS unsignedSafeMultiplyAdd(UINT64, UINT64, UINT64, PUINT64);
/**
* Internal Double Linked List operations
*/
STATUS doubleListAllocNode(UINT64, PDoubleListNode*);
STATUS doubleListInsertNodeHeadInternal(PDoubleList, PDoubleListNode);
STATUS doubleListInsertNodeTailInternal(PDoubleList, PDoubleListNode);
STATUS doubleListInsertNodeBeforeInternal(PDoubleList, PDoubleListNode, PDoubleListNode);
STATUS doubleListInsertNodeAfterInternal(PDoubleList, PDoubleListNode, PDoubleListNode);
STATUS doubleListRemoveNodeInternal(PDoubleList, PDoubleListNode);
STATUS doubleListGetNodeAtInternal(PDoubleList, UINT32, PDoubleListNode*);
/**
* Internal Single Linked List operations
*/
STATUS singleListAllocNode(UINT64, PSingleListNode*);
STATUS singleListInsertNodeHeadInternal(PSingleList, PSingleListNode);
STATUS singleListInsertNodeTailInternal(PSingleList, PSingleListNode);
STATUS singleListInsertNodeAfterInternal(PSingleList, PSingleListNode, PSingleListNode);
STATUS singleListGetNodeAtInternal(PSingleList, UINT32, PSingleListNode*);
/**
* Internal Hash Table operations
*/
#define DEFAULT_HASH_TABLE_BUCKET_LENGTH 2
#define DEFAULT_HASH_TABLE_BUCKET_COUNT 10000
#define MIN_HASH_TABLE_ENTRIES_ALLOC_LENGTH 8
/**
* Bucket declaration
* NOTE: Variable size structure - the buckets can follow directly after the main structure
* or in case of allocated array it's a separate allocation
*/
typedef struct {
UINT32 count;
UINT32 length;
PHashEntry entries;
} HashBucket, *PHashBucket;
UINT64 getKeyHash(UINT64);
PHashBucket getHashBucket(PHashTable, UINT64);
/**
* Internal Directory functionality
*/
STATUS removeFileDir(UINT64, DIR_ENTRY_TYPES, PCHAR, PCHAR);
STATUS getFileDirSize(UINT64, DIR_ENTRY_TYPES, PCHAR, PCHAR);
/**
* Endianness functionality
*/
INLINE INT16 getInt16Swap(INT16);
INLINE INT16 getInt16NoSwap(INT16);
INLINE INT32 getInt32Swap(INT32);
INLINE INT32 getInt32NoSwap(INT32);
INLINE INT64 getInt64Swap(INT64);
INLINE INT64 getInt64NoSwap(INT64);
INLINE VOID putInt16Swap(PINT16, INT16);
INLINE VOID putInt16NoSwap(PINT16, INT16);
INLINE VOID putInt32Swap(PINT32, INT32);
INLINE VOID putInt32NoSwap(PINT32, INT32);
INLINE VOID putInt64Swap(PINT64, INT64);
INLINE VOID putInt64NoSwap(PINT64, INT64);
/**
* Unaligned access functionality
*/
INLINE INT16 getUnalignedInt16Be(PVOID);
INLINE INT16 getUnalignedInt16Le(PVOID);
INLINE INT32 getUnalignedInt32Be(PVOID);
INLINE INT32 getUnalignedInt32Le(PVOID);
INLINE INT64 getUnalignedInt64Be(PVOID);
INLINE INT64 getUnalignedInt64Le(PVOID);
INLINE VOID putUnalignedInt16Be(PVOID, INT16);
INLINE VOID putUnalignedInt16Le(PVOID, INT16);
INLINE VOID putUnalignedInt32Be(PVOID, INT32);
INLINE VOID putUnalignedInt32Le(PVOID, INT32);
INLINE VOID putUnalignedInt64Be(PVOID, INT64);
INLINE VOID putUnalignedInt64Le(PVOID, INT64);
//////////////////////////////////////////////////////////////////////////////////////////////
// TimerQueue functionality
//////////////////////////////////////////////////////////////////////////////////////////////
/**
* Startup and shutdown timeout value
*/
#define TIMER_QUEUE_SHUTDOWN_TIMEOUT (200 * HUNDREDS_OF_NANOS_IN_A_MILLISECOND)
/**
* Timer entry structure definition
*/
typedef struct {
UINT64 period;
UINT64 invokeTime;
UINT64 customData;
TimerCallbackFunc timerCallbackFn;
} TimerEntry, *PTimerEntry;
/**
* Internal timer queue definition
*/
typedef struct {
volatile TID executorTid;
volatile ATOMIC_BOOL shutdown;
volatile ATOMIC_BOOL terminated;
volatile ATOMIC_BOOL started;
UINT32 maxTimerCount;
UINT32 activeTimerCount;
UINT64 invokeTime;
MUTEX executorLock;
CVAR executorCvar;
MUTEX startLock;
CVAR startCvar;
MUTEX exitLock;
CVAR exitCvar;
PTimerEntry pTimers;
} TimerQueue, *PTimerQueue;
// Public handle to and from object converters
#define TO_TIMER_QUEUE_HANDLE(p) ((TIMER_QUEUE_HANDLE) (p))
#define FROM_TIMER_QUEUE_HANDLE(h) (IS_VALID_TIMER_QUEUE_HANDLE(h) ? (PTimerQueue) (h) : NULL)
// Internal Functions
STATUS timerQueueCreateInternal(UINT32, PTimerQueue*);
STATUS timerQueueFreeInternal(PTimerQueue*);
STATUS timerQueueEvaluateNextInvocation(PTimerQueue);
// Executor routine
PVOID timerQueueExecutor(PVOID);
//////////////////////////////////////////////////////////////////////////////////////////////
// Semaphore functionality
//////////////////////////////////////////////////////////////////////////////////////////////
// Shutdown spinlock will sleep this period and check
#define SEMAPHORE_SHUTDOWN_SPINLOCK_SLEEP_DURATION (5 * HUNDREDS_OF_NANOS_IN_A_MILLISECOND)
/**
* Internal semaphore definition
*/
typedef struct {
// Current granted permit count
volatile SIZE_T permitCount;
// Whether the semaphore is locked for granting any more permits
volatile ATOMIC_BOOL locked;
// Whether we are shutting down
volatile ATOMIC_BOOL shutdown;
// Max allowed permits
SIZE_T maxPermitCount;
// Semaphore notification await cvar
CVAR semaphoreNotify;
// Notification cvar lock
MUTEX semaphoreLock;
// Notification cvar for awaiting till drained
CVAR drainedNotify;
// Draining notification lock
MUTEX drainedLock;
} Semaphore, *PSemaphore;
// Public handle to and from object converters
#define TO_SEMAPHORE_HANDLE(p) ((SEMAPHORE_HANDLE) (p))
#define FROM_SEMAPHORE_HANDLE(h) (IS_VALID_SEMAPHORE_HANDLE(h) ? (PSemaphore) (h) : NULL)
// Internal Functions
STATUS semaphoreCreateInternal(UINT32, PSemaphore*);
STATUS semaphoreFreeInternal(PSemaphore*);
STATUS semaphoreAcquireInternal(PSemaphore, UINT64);
STATUS semaphoreReleaseInternal(PSemaphore);
STATUS semaphoreSetLockInternal(PSemaphore, BOOL);
STATUS semaphoreWaitUntilClearInternal(PSemaphore, UINT64);
//////////////////////////////////////////////////////////////////////////////////////////////
// Instrumented allocators functionality
//////////////////////////////////////////////////////////////////////////////////////////////
PVOID instrumentedAllocatorsMemAlloc(SIZE_T);
PVOID instrumentedAllocatorsMemAlignAlloc(SIZE_T, SIZE_T);
PVOID instrumentedAllocatorsMemCalloc(SIZE_T, SIZE_T);
PVOID instrumentedAllocatorsMemRealloc(PVOID, SIZE_T);
VOID instrumentedAllocatorsMemFree(PVOID);
#ifdef __cplusplus
}
#endif
#endif // __UTILS_I_H__
| 30.243478 | 120 | 0.719379 | [
"object"
] |
a0626c2b0e5a4bd91538c1a4cdbf2c36085abd85 | 6,059 | h | C | simd/simd.h | pps83/pik | 9747f8dbe9c10079b7473966fc974e4b3bcef034 | [
"Apache-2.0"
] | null | null | null | simd/simd.h | pps83/pik | 9747f8dbe9c10079b7473966fc974e4b3bcef034 | [
"Apache-2.0"
] | null | null | null | simd/simd.h | pps83/pik | 9747f8dbe9c10079b7473966fc974e4b3bcef034 | [
"Apache-2.0"
] | null | null | null | // Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef SIMD_SIMD_H_
#define SIMD_SIMD_H_
// Performance-portable SIMD API for SSE4/AVX2/ARMv8, later AVX-512 and PPC8.
// Each operation is efficient on all platforms.
// WARNING: this header may be included from translation units compiled with
// different flags. To prevent ODR violations, all functions defined here or
// in dependent headers must be inlined and/or within namespace SIMD_NAMESPACE.
// The namespace name varies depending on compile flags, so this header requires
// textual inclusion.
#include <stddef.h> // size_t
#include "simd/port.h"
#include "simd/util.h"
// Ensures an array is aligned and suitable for load()/store() functions.
// Example: SIMD_ALIGN T lanes[V::N];
#define SIMD_ALIGN alignas(32)
namespace pik {
#ifdef SIMD_NAMESPACE
namespace SIMD_NAMESPACE {
#endif
// SIMD operations are implemented as overloaded functions selected using a
// "descriptor" D := Desc<T, N[, Target]>. For example: `D::V setzero(D)`.
// T is the lane type, N the number of lanes, Target is an instruction set
// (e.g. SSE4), defaulting to the best available. The return type D::V is either
// a full vector of at least 128 bits, an N-lane (=2^j) part, or a scalar.
// Specialized in platform-specific headers; see Desc::V.
template <typename T, size_t N, class Target>
struct VecT;
// Descriptor: properties that uniquely identify a vector/part/scalar. Used to
// select overloaded functions; see Full/Part/Scalar aliases below.
template <typename LaneT, size_t kLanes, class TargetT>
struct Desc {
constexpr Desc() {}
using T = LaneT;
static constexpr size_t N = kLanes;
using Target = TargetT;
// Alias for the actual vector data, e.g. scalar<float> for <float, 1, NONE>,
// returned by initializers such as setzero(). Parts and full vectors are
// distinct types on x86 to avoid inadvertent conversions. By contrast, PPC
// parts are merely aliases for full vectors to avoid wrapper overhead.
using V = typename VecT<T, N, Target>::type;
static_assert((N & (N - 1)) == 0, "N must be a power of two");
static_assert(N <= Target::template NumLanes<T>(), "N too large");
};
// Avoid having to specify SIMD_TARGET in every Part<>/Full<>. Option 1: macro,
// required in attr mode, where we want a different default target for each
// expansion of target-specific code (via foreach_target.h's includes).
#define SIMD_FULL(T) Full<T, SIMD_TARGET>
#define SIMD_PART(T, N) Part<T, N, SIMD_TARGET>
#if SIMD_USE_ATTR
#define SIMD_DEFAULT_TARGET
#else
// Option 2 (normal mode): default argument; sufficient because this entire
// header is included from each target-specific translation unit.
#define SIMD_DEFAULT_TARGET = SIMD_TARGET
#endif
// Shorthand for a full vector.
template <typename T, class Target SIMD_DEFAULT_TARGET>
using Full = Desc<T, Target::template NumLanes<T>(), Target>;
// Shorthand for a part (or full) vector. N=2^j. Note that PartTarget selects
// a 128-bit Target when T and N are small enough (avoids additional AVX2
// versions of SSE4 initializers/loads).
template <typename T, size_t N, class Target SIMD_DEFAULT_TARGET>
using Part = Desc<T, N, PartTarget<T, N, Target>>;
// Shorthand for a scalar; note that scalar<T> is the actual data class.
template <typename T>
using Scalar = Desc<T, 1, NONE>;
// Convenient shorthand for VecT. Chooses the smallest possible Target.
template <typename T, size_t N, class Target>
using VT = typename VecT<T, N, PartTarget<T, N, Target>>::type;
// Type tags for get_half(Upper(), v) etc.
struct Upper {};
struct Lower {};
#define SIMD_HALF Lower()
// Returns a name for the vector/part/scalar. The type prefix is u/i/f for
// unsigned/signed/floating point, followed by the number of bits per lane;
// then 'x' followed by the number of lanes. Example: u8x16. This is useful for
// understanding which instantiation of a generic test failed.
template <class D>
inline const char* vec_name() {
using T = typename D::T;
constexpr size_t N = D::N;
constexpr int kTarget = D::Target::value;
// Avoids depending on <type_traits>.
const bool is_float = T(2.25) != T(2);
const bool is_signed = T(-1) < T(0);
constexpr char prefix = is_float ? 'f' : (is_signed ? 'i' : 'u');
constexpr size_t bits = sizeof(T) * 8;
constexpr char bits10 = '0' + (bits / 10);
constexpr char bits1 = '0' + (bits % 10);
// Scalars: omit the xN suffix.
if (kTarget == SIMD_NONE) {
static constexpr char name1[8] = {prefix, bits1};
static constexpr char name2[8] = {prefix, bits10, bits1};
return sizeof(T) == 1 ? name1 : name2;
}
constexpr char N1 = (N < 10) ? '\0' : '0' + (N % 10);
constexpr char N10 = (N < 10) ? '0' + (N % 10) : '0' + (N / 10);
static constexpr char name1[8] = {prefix, bits1, 'x', N10, N1};
static constexpr char name2[8] = {prefix, bits10, bits1, 'x', N10, N1};
return sizeof(T) == 1 ? name1 : name2;
}
// Include all headers #if SIMD_DEPS to ensure they are added to deps.mk.
// This has no other effect because the headers are empty #if SIMD_DEPS.
// Also used by x86_avx2.h => must be included first.
#if SIMD_DEPS || (SIMD_ENABLE_SSE4 || SIMD_ENABLE_AVX2)
#include "simd/x86_sse4.h"
#endif
#if SIMD_DEPS || SIMD_ENABLE_AVX2
#include "simd/x86_avx2.h"
#endif
#if SIMD_DEPS || SIMD_ENABLE_ARM8
#include "simd/arm64_neon.h"
#endif
// Always available
#include "simd/scalar.h"
#ifdef SIMD_NAMESPACE
} // namespace SIMD_NAMESPACE
#endif
} // namespace pik
#endif // SIMD_SIMD_H_
| 36.721212 | 80 | 0.71662 | [
"vector"
] |
a0647c11b9d6bdace5fefe76fabb62df4e494b0d | 7,441 | h | C | demos/TaakLabyrinth/src/Scene/extraGame_scene.h | kodjodegbey/gba-sprite-engine | 3f480a824320dee01fb94d98b75761a591b86327 | [
"MIT"
] | null | null | null | demos/TaakLabyrinth/src/Scene/extraGame_scene.h | kodjodegbey/gba-sprite-engine | 3f480a824320dee01fb94d98b75761a591b86327 | [
"MIT"
] | null | null | null | demos/TaakLabyrinth/src/Scene/extraGame_scene.h | kodjodegbey/gba-sprite-engine | 3f480a824320dee01fb94d98b75761a591b86327 | [
"MIT"
] | null | null | null | //
// Created by esaie on 30-07-20.
//
#ifndef GBA_SPRITE_ENGINE_PROJECT_EXTRAGAME_SCENE_H
#define GBA_SPRITE_ENGINE_PROJECT_EXTRAGAME_SCENE_H
#include <libgba-sprite-engine/scene.h>
#include <libgba-sprite-engine/sprites/sprite_builder.h>
#include "../Model/BonusModel.h"
#include "../Model/BomModel.h"
#include "../Model/speler.h"
class ExtraGame : public Scene {
private:
std::unique_ptr<Sprite> speler;
std::unique_ptr<Speler> spelerModel;
std::unique_ptr<Sprite> muntSprite;
std::unique_ptr<Sprite> muntSprite1;
std::unique_ptr<Sprite> muntSprite2;
std::unique_ptr<Sprite> muntSprite3;
std::unique_ptr<Sprite> muntSprite4;
std::unique_ptr<Sprite> bomSprite;
std::unique_ptr<Sprite> bomSprite1;
std::unique_ptr<Sprite> bomSprite2;
std::unique_ptr<Sprite> bomSprite3;
int score =0 ;
bool wisselPlaatst = false;
bool tegenbonus = false;
bool tegenbonus1 = false;
bool tegenbonus2= false;
bool tegenbonus3= false;
bool tegenbonus4= false;
bool tegenbom = false;
bool tegenbom1 = false;
bool tegenbom2= false;
bool tegenbom3= false;
int aantalmunten = 5;
int keuze;
public:
ExtraGame(std::shared_ptr<GBAEngine> engine, int oudeScore,int keuze) : Scene(engine),score(oudeScore),keuze(keuze) {}
std::vector<Sprite *> sprites() override;
std::vector<Background *> backgrounds() override;
void load() override;
void tick(u16 keys) override;
void moveItems(){
if(tegenbonus){
muntSprite->setVelocity(0,0 );
muntSprite->moveTo(300,300);
}else{
if(muntSprite->isOffScreen()){
muntSprite->moveTo((rand()%(200 + 2) ),(rand()%(140 + 2) ));
muntSprite->setVelocity(0,1 );
}
else{
muntSprite->setVelocity(0,1 );
}
}
if(tegenbonus1){
muntSprite1->setVelocity(0,0 );
muntSprite1->moveTo(300,300);
}else{
if(muntSprite1->isOffScreen()){
muntSprite1->moveTo((rand()%(200 + 2) ),(rand()%(140 + 2) ));
muntSprite1->setVelocity(0,1 );
}
else{
muntSprite1->setVelocity(0,1 );
}
}
if(tegenbonus2){
muntSprite2->setVelocity(0,0 );
muntSprite2->moveTo(300,300);
}else{
if(muntSprite2->isOffScreen()){
muntSprite2->moveTo((rand()%(200 + 2) ),(rand()%(140 + 2) ));
muntSprite2->setVelocity(0,1 );
}
else{
muntSprite2->setVelocity(0,1 );
}
}
if(tegenbonus3){
muntSprite3->setVelocity(0,0 );
muntSprite3->moveTo(300,300);
}else{
if(muntSprite3->isOffScreen()){
muntSprite3->moveTo((rand()%(200 + 2) ),(rand()%(140 + 2) ));
muntSprite3->setVelocity(0,1 );
}
else{
muntSprite3->setVelocity(0,1 );
}
}
if(tegenbonus4){
muntSprite4->setVelocity(0,0 );
muntSprite4->moveTo(300,300);
}else{
if(muntSprite4->isOffScreen()){
muntSprite4->moveTo((rand()%(200 + 2) ),(rand()%(140 + 2) ));
muntSprite4->setVelocity(0,1 );
}
else{
muntSprite4->setVelocity(0,1 );
}
}
if(tegenbom){
bomSprite->setVelocity(0,0 );
bomSprite->moveTo(300,300);
}else{
if(bomSprite->isOffScreen()){
bomSprite->moveTo(30,20);
bomSprite->setVelocity(0,1 );
}else{
bomSprite->setVelocity(0,1 );
}
}
if(tegenbom1){
bomSprite1->setVelocity(0,0 );
bomSprite1->moveTo(300,300);
}else{
if(bomSprite1->isOffScreen()){
bomSprite1->moveTo(90,20);
bomSprite1->setVelocity(0,1 );
}else{
bomSprite1->setVelocity(0,1 );
}
}
if(tegenbom2){
bomSprite2->setVelocity(0,0 );
bomSprite2->moveTo(300,300);
}
else{
if(bomSprite2->isOffScreen()){
bomSprite2->moveTo(150,20);
bomSprite2->setVelocity(0,1 );
}else{
bomSprite2->setVelocity(0,1 );
}
}
if(tegenbom3){
bomSprite3->setVelocity(0,0 );
bomSprite3->moveTo(300,300);
}
else{
if(bomSprite3->isOffScreen()){
bomSprite3->moveTo(200,20);
bomSprite3->setVelocity(0,1 );
}else{
bomSprite3->setVelocity(0,1 );
}
}
}
bool tegenMunt(){
if(muntSprite->collidesWith(*spelerModel->getSpelerSprite())){
aantalmunten -=1;
return tegenbonus =true;
}
else if(muntSprite1->collidesWith(*spelerModel->getSpelerSprite())){
aantalmunten -=1;
return tegenbonus1 =true;
}
else if(muntSprite2->collidesWith(*spelerModel->getSpelerSprite())){
aantalmunten -=1;
return tegenbonus2 =true;
}
else if(muntSprite3->collidesWith(*spelerModel->getSpelerSprite())){
aantalmunten -=1;
return tegenbonus3 =true;
}
else if(muntSprite4->collidesWith(*spelerModel->getSpelerSprite())){
aantalmunten -=1;
return tegenbonus4 =true;
}else{
return false;
}
}
bool tegenBom(){
if(bomSprite->collidesWith(*spelerModel->getSpelerSprite())){
return tegenbom =true;
}
else if(bomSprite1->collidesWith(*spelerModel->getSpelerSprite())){
return tegenbom1 =true;
}
else if(bomSprite2->collidesWith(*spelerModel->getSpelerSprite())){
return tegenbom2 =true;
}
else if(bomSprite3->collidesWith(*spelerModel->getSpelerSprite())){
return tegenbom3 =true;
}else{
return false;
}
}
void stopGame(){
TextStream::instance().clear();
bomSprite->setVelocity(0,0 );
bomSprite->moveTo(300,300);
bomSprite1->setVelocity(0,0 );
bomSprite1->moveTo(300,300);
bomSprite2->setVelocity(0,0 );
bomSprite2->moveTo(300,300);
bomSprite3->setVelocity(0,0 );
bomSprite3->moveTo(300,300);
muntSprite->setVelocity(0,0 );
muntSprite->moveTo(300,300);
muntSprite1->setVelocity(0,0 );
muntSprite1->moveTo(300,300);
muntSprite2->setVelocity(0,0 );
muntSprite2->moveTo(300,300);
muntSprite3->setVelocity(0,0 );
muntSprite3->moveTo(300,300);
muntSprite4->setVelocity(0,0 );
muntSprite4->moveTo(300,300);
TextStream::instance().setText("Druk A voor rubi" , 1, 0);
TextStream::instance().setText("Druk B voor zelda", 2, 0);
TextStream::instance().setText(std::string("U extra scoren is : ") + std::to_string(score ), 11, 1);
TextStream::instance().setText("Druk start ", 10, 1);
spelerModel->getSpelerSprite()->moveTo(200,90);
}
};
#endif //GBA_SPRITE_ENGINE_PROJECT_EXTRAGAME_SCENE_H
| 30.621399 | 122 | 0.539847 | [
"vector",
"model"
] |
a066d4fa6731ce40ece4502b853fa1d897bcd18f | 3,919 | h | C | src/core/support/obj_pool.h | EdgeCast/hurl | ac93b1d092688f50d9165bb3310084d596cadec1 | [
"Apache-2.0"
] | 19 | 2021-08-13T18:48:00.000Z | 2022-03-15T20:55:47.000Z | src/core/support/obj_pool.h | EdgeCast/hurl | ac93b1d092688f50d9165bb3310084d596cadec1 | [
"Apache-2.0"
] | 3 | 2021-08-05T02:28:49.000Z | 2021-11-19T17:51:29.000Z | src/core/support/obj_pool.h | EdgeCast/hurl | ac93b1d092688f50d9165bb3310084d596cadec1 | [
"Apache-2.0"
] | 1 | 2021-08-05T01:46:16.000Z | 2021-08-05T01:46:16.000Z | //! ----------------------------------------------------------------------------
//! Copyright Edgecast Inc.
//!
//! \file: TODO
//! \details: TODO
//!
//! Licensed under the terms of the Apache 2.0 open source license.
//! Please refer to the LICENSE file in the project root for the terms.
//! ----------------------------------------------------------------------------
#ifndef _OBJ_POOL_H
#define _OBJ_POOL_H
//! ----------------------------------------------------------------------------
//! includes
//! ----------------------------------------------------------------------------
#include <vector>
#include <unordered_set>
namespace ns_hurl {
//! ----------------------------------------------------------------------------
//! Obj Pool
//! ----------------------------------------------------------------------------
template<class _Tp>
class obj_pool
{
public:
// ---------------------------------------
// Types
// ---------------------------------------
typedef uint64_t idx_t;
typedef std::unordered_set<idx_t> obj_idx_set_t;
typedef std::vector<_Tp *> obj_vec_t;
//typedef int (*delete_cb_t) (void* o_1, void *a_2);
// ---------------------------------------
// Public methods
// ---------------------------------------
_Tp *get_free(void)
{
if(m_free_idx_set.size())
{
idx_t l_idx = *(m_free_idx_set.begin());
m_free_idx_set.erase(l_idx);
m_used_idx_set.insert(l_idx);
return m_obj_vec[l_idx];
}
return NULL;
}
void add(_Tp *a_obj)
{
if(!a_obj)
{
return;
}
m_obj_vec.push_back(a_obj);
idx_t l_idx = m_obj_vec.size() - 1;
a_obj->set_idx(l_idx);
m_used_idx_set.insert(l_idx);
}
void release(_Tp *a_obj)
{
if(!a_obj)
{
return;
}
idx_t l_idx = a_obj->get_idx();
m_used_idx_set.erase(l_idx);
m_free_idx_set.insert(a_obj->get_idx());
}
uint64_t free_size(void) const
{
return m_free_idx_set.size();
}
uint64_t used_size(void) const
{
return m_used_idx_set.size();
}
// TODO --release all unused -shrink routine...
obj_pool(void):
m_obj_vec(),
m_used_idx_set(),
m_free_idx_set()
{}
~obj_pool(void)
{
for(typename obj_vec_t::iterator i_obj = m_obj_vec.begin();
i_obj != m_obj_vec.end();
++i_obj)
{
if(*i_obj)
{
delete *i_obj;
*i_obj = NULL;
}
}
m_obj_vec.clear();
}
//void set_delete_cb(delete_cb_t a_delete_cb, void *a_o_1)
//{
// m_delete_cb = a_delete_cb;
// m_o_1 = a_o_1;
//}
private:
// ---------------------------------------
// Private methods
// ---------------------------------------
// Disallow copy/assign
obj_pool& operator=(const obj_pool &);
obj_pool(const obj_pool &);
// ---------------------------------------
// Private members
// ---------------------------------------
//delete_cb_t m_delete_cb;
//void *m_o_1;
obj_vec_t m_obj_vec;
obj_idx_set_t m_used_idx_set;
obj_idx_set_t m_free_idx_set;
};
} //namespace ns_hurl {
#endif
| 30.379845 | 80 | 0.357234 | [
"vector"
] |
a067b7b55c013cdad30e11fe0b72cde693306a18 | 4,510 | h | C | open/Inspur/code/resnet/schedule/src/inference/inference.h | EldritchJS/inference_results_v0.5 | 5552490e184d9fc342d871fcc410ac423ea49053 | [
"Apache-2.0"
] | null | null | null | open/Inspur/code/resnet/schedule/src/inference/inference.h | EldritchJS/inference_results_v0.5 | 5552490e184d9fc342d871fcc410ac423ea49053 | [
"Apache-2.0"
] | null | null | null | open/Inspur/code/resnet/schedule/src/inference/inference.h | EldritchJS/inference_results_v0.5 | 5552490e184d9fc342d871fcc410ac423ea49053 | [
"Apache-2.0"
] | 1 | 2019-12-05T18:53:17.000Z | 2019-12-05T18:53:17.000Z | #ifndef __INTERFACE_H
#define __INTERFACE_H
#include <iostream>
#include <iterator>
#include <memory>
#include <numeric>
#include <string>
#include <vector>
#include <new>
#include <cassert>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <future>
#include <thread>
#include <cmath>
#include <sys/stat.h>
#include <time.h>
#include <cstdlib>
#include <exception>
#include <type_traits>
#include <stdbool.h>
//#define CUDA_API_PER_THREAD_DEFAULT_STREAM
#include <cublas_v2.h>
#include <cudnn.h>
#include <cuda_runtime_api.h>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include "NvInfer.h"
#include "./ssd_Calibration/common.h"
#include "../schedule/data_set.h"
namespace inference
{
using namespace std;
using namespace nvinfer1;
using namespace schedule;
// using namespace nvcaffeparser1;
typedef struct result_struct
{
vector<int> detection_nums;
vector<vector<vector<int>>> detection_boxes;
vector<float> detection_scores;
vector<string> detection_classes;
}result_struct;
struct ResultTensor
{
int64_t num;
float* boxes;
float* scores;
float* detected_classes;
};
struct InferDeleter
{
template <typename T>
void operator()(T* obj) const
{
if (obj)
{
obj->destroy();
}
}
};
template <typename T>
struct destroyer
{
void operator()(T* t) { t->destroy(); }
};
class GpuEngine
{
public:
GpuEngine();
GpuEngine(ICudaEngine* engine,
IExecutionContext* context,
float* h_input, // CPU input memory
void* d_input, // GPU input memory
float* h_output, // CPU output memory
void* d_output, // GPU output memory
cudaStream_t stream,
size_t max_batchsize,
size_t h_input_size,
size_t h_output_size,
int thread_num,
void* bindings[3],
bool exist,
string profile,
int gpu_num,
vector<ResultTensor> result_tensor);
~GpuEngine(){
cudaStreamDestroy(stream);
delete h_output;
}
static vector<shared_ptr<GpuEngine>> InitGpuEngines(string model_path,
string data_path,
string profile_name,
unsigned int max_batchsize,
string backend,
unsigned int threads);
static shared_ptr<GpuEngine> InitImgGpuEngines(string model_path,
string data_path,
string profile_name,
unsigned int max_batchsize,
string backend,
unsigned int threads,
size_t gpu_num);
static shared_ptr<GpuEngine> InitSSDGpuEngines(string model_path,
string data_path,
string profile_name,
uint max_batchsize,
string profile,
uint threads,
size_t gpu_num);
void doInference(shared_ptr<Batch<MemoryData>> input);
void doSSDInference(shared_ptr<Batch<MemoryData>> input);
vector<ResultTensor>* Predict(shared_ptr<Batch<MemoryData>> input);
vector<size_t> doTestInference(vector<shared_ptr<cv::Mat>> input,int max_batchsize,float* loaded_data);
static vector<float*> test(void* input,int max_batchsize,void *param);
size_t GetInputSize() { return h_input_size; }
size_t GetOutputSize() { return h_output_size; }
private:
ICudaEngine* engine;
IExecutionContext* context;
float* h_input;
void* d_input;
float* h_output;
void* d_output;
cudaStream_t stream;
int max_batchsize;
size_t h_input_size;
size_t h_output_size;
int thread;
void** bindings;
bool exist = false;
string profile;
int gpu_num;
vector<ResultTensor> result_tensor;
};
class TRT_Logger : public nvinfer1::ILogger {
nvinfer1::ILogger::Severity _verbosity;
ostream* _ostream;
public:
TRT_Logger(Severity verbosity=Severity::kWARNING,
ostream& ostream=cout)
: _verbosity(verbosity), _ostream(&ostream) {}
void log(Severity severity, const char* msg) override {
if( severity <= _verbosity ) {
time_t rawtime = time(0);
char buf[256];
strftime(&buf[0], 256,
"%Y-%m-%d %H:%M:%S",
gmtime(&rawtime));
const char* sevstr = (severity == Severity::kINTERNAL_ERROR ? " BUG" :
severity == Severity::kERROR ? " ERROR" :
severity == Severity::kWARNING ? "WARNING" :
severity == Severity::kINFO ? " INFO" :
"UNKNOWN");
(*_ostream) << "[" << buf << " " << sevstr << "] "
<< msg
<< endl;
}
}
};
tuple<char*,int> read_engine(string model_path);
ICudaEngine* loadEngine(const std::string& engine, int DLACore);
}
#endif
| 24.917127 | 106 | 0.672949 | [
"vector"
] |
a071b341f0823e3e0b0c61880f2416ebb53390e8 | 6,119 | h | C | exegesis/llvm/llvm_utils.h | mrexodia/EXEgesis | 91af85cfdd5d5b2e8d5d2a04aaa5d5175685acc7 | [
"Apache-2.0"
] | null | null | null | exegesis/llvm/llvm_utils.h | mrexodia/EXEgesis | 91af85cfdd5d5b2e8d5d2a04aaa5d5175685acc7 | [
"Apache-2.0"
] | null | null | null | exegesis/llvm/llvm_utils.h | mrexodia/EXEgesis | 91af85cfdd5d5b2e8d5d2a04aaa5d5175685acc7 | [
"Apache-2.0"
] | null | null | null | // Copyright 2017 Google 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.
// Contains helper function for interacting with LLVM subsystems.
#ifndef EXEGESIS_LLVM_LLVM_UTILS_H_
#define EXEGESIS_LLVM_LLVM_UTILS_H_
#include <string>
#include <vector>
#include "absl/status/statusor.h"
#include "absl/strings/str_join.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineMemOperand.h"
#include "llvm/CodeGen/MachineOperand.h"
#include "llvm/CodeGen/ScheduleDAG.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/Value.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCTargetOptions.h"
#include "llvm/MC/TargetRegistry.h"
#include "llvm/Target/TargetOptions.h"
namespace exegesis {
// Ensures that LLVM subsystems were initialized for instruction scheduling.
// This function can be called safely multiple times, all calls except for the
// first one are effectively no-ops.
// TODO(ondrasej): Pass some command-line flags to LLVM?
void EnsureLLVMWasInitialized();
// Calling this method before EnsureLLVMWasInitialized() turns it into a no-op.
// This is useful in binaries that do custom LLVM initialization and/or depend
// on LLVM parsing the command-line flags.
void MarkLLVMInitialized();
// Looks up the LLVM target based on the command-line flags passed to the
// program or the default LLVM target for the current architecture; the target
// is the target for the triple returned by GetNormalizedLLVMTripleName. The
// returned pointer is not owned by the caller and it must not be deleted.
absl::StatusOr<const llvm::Target*> GetLLVMTarget();
// Returns normalized LLVM Triple name based on the current platform and the
// command-line flags.
std::string GetNormalizedLLVMTripleName();
// Creates a human-readable string representation of a LLVM IR object. This
// function can be used for example to get the IR code of llvm::Function in a
// string form.
std::string DumpIRToString(const llvm::Value* ir);
// Creates a human-readable string representation of 'instruction' that can be
// used e.g. for logging.
std::string DumpMachineInstrToString(const llvm::MachineInstr* instruction);
// Creates a human-readable string representation of an operand that can be used
// e.g. for logging.
std::string DumpMachineOperandToString(const llvm::MachineOperand* operand);
// Creates a human-readable string representation of the scheduling unit that
// can be used e.g. for logging.
std::string DumpMachineInstrSUnitToString(const llvm::SUnit* sunit);
// Creates a human-readable string representation of an MC instruction object
// that can be used e.g. for logging.
std::string DumpMCInstToString(const llvm::MCInst* instruction);
// Creates a human-readable string representation of the MC instruction object.
// Unlike the version with a single argument above, this function translates
// instruction and register codes to their symbolic names.
std::string DumpMCInstToString(const llvm::MCInst& instruction,
const llvm::MCInstrInfo* mc_instruction_info,
const llvm::MCRegisterInfo* register_info);
// Creates a human-readable string representation of the scheduling dependency.
std::string DumpSDepToString(const llvm::SDep& sdep);
// Creates a human-readable string that describes the given LLVM register.
std::string DumpRegisterToString(unsigned reg,
const llvm::MCRegisterInfo* register_info);
// Assumes that collection is a collection of LLVM registers. Creates a string
// that contains a comma-separated list of their string representations (via
// RegisterToString).
template <typename CollectionType>
std::string DumpRegistersToString(const CollectionType& collection,
const llvm::MCRegisterInfo* register_info) {
return absl::StrJoin(
collection, ", ", [register_info](std::string* buffer, unsigned reg) {
buffer->append(DumpRegisterToString(reg, register_info));
});
}
// Creates a human-readable string representation of the MC operand object.
std::string DumpMCOperandToString(const llvm::MCOperand& operand,
const llvm::MCRegisterInfo* register_info);
// Creates a human-readable string representation of 'mem_operand' that can be
// used e.g. for logging.
std::string DumpMachineMemOperandToString(
const llvm::MachineMemOperand* mem_operand);
// Returns the list of X86 LLVM instruction mnemonics.
std::vector<std::string> GetLLVMMnemonicListOrDie();
template <typename StringType>
llvm::StringRef MakeStringRef(const StringType& source) {
return llvm::StringRef(source.data(), source.size());
}
// Converts an absl::Span<const T> to llvm::ArrayRef<T> pointing to the same
// data.
template <typename ValueType>
llvm::ArrayRef<ValueType> MakeArrayRef(absl::Span<const ValueType> span) {
return llvm::ArrayRef<ValueType>(span.data(), span.size());
}
// Parses the asm dialect from a human-readable string representation. Accepted
// values are "att" and "intel".
absl::StatusOr<llvm::InlineAsm::AsmDialect> ParseAsmDialectName(
const std::string& asm_dialect_name);
// Wrapper around LLVM InitTargetOptionsFromCodeGenFlags to avoid linker issues.
llvm::TargetOptions LLVMInitTargetOptionsFromCodeGenFlags();
// Wrapper around LLVM InitMCTargetOptionsFromFlags to avoid linker issues.
llvm::MCTargetOptions LLVMInitMCTargetOptionsFromFlags();
} // namespace exegesis
#endif // EXEGESIS_LLVM_LLVM_UTILS_H_
| 41.344595 | 80 | 0.758457 | [
"object",
"vector"
] |
a075172e340cc2926ed5500330220b6e1ef5e53f | 287 | h | C | 3dEngine/src/scene/renderer3d/transparent/TransparentMeshFilter.h | petitg1987/UrchinEngine | 32d4b62b1ab7e2aa781c99de11331e3738078b0c | [
"MIT"
] | 24 | 2015-10-05T00:13:57.000Z | 2020-05-06T20:14:06.000Z | 3dEngine/src/scene/renderer3d/transparent/TransparentMeshFilter.h | petitg1987/urchinEngine | a14a57ac49a19237d748d2eafc7c2a38a45b95d6 | [
"BSL-1.0"
] | 1 | 2019-11-01T08:00:55.000Z | 2019-11-01T08:00:55.000Z | 3dEngine/src/scene/renderer3d/transparent/TransparentMeshFilter.h | petitg1987/UrchinEngine | 32d4b62b1ab7e2aa781c99de11331e3738078b0c | [
"MIT"
] | 10 | 2015-11-25T07:33:13.000Z | 2020-03-02T08:21:10.000Z | #pragma once
#include <scene/renderer3d/model/displayer/MeshFilter.h>
namespace urchin {
class TransparentMeshFilter : public MeshFilter {
public:
bool isAccepted(const Model&) const override;
bool isAccepted(const Mesh&) const override;
};
}
| 20.5 | 57 | 0.672474 | [
"mesh",
"model"
] |
a07bd51f65372e7036e00cefc00e9bdb2e454f75 | 17,139 | h | C | groups/lsp/lspcore/lspcore_symbolutil.h | dgoffredo/bdelisp | ea1411cd99aa69605f0a8281fe3be89db09c4aac | [
"blessing"
] | null | null | null | groups/lsp/lspcore/lspcore_symbolutil.h | dgoffredo/bdelisp | ea1411cd99aa69605f0a8281fe3be89db09c4aac | [
"blessing"
] | null | null | null | groups/lsp/lspcore/lspcore_symbolutil.h | dgoffredo/bdelisp | ea1411cd99aa69605f0a8281fe3be89db09c4aac | [
"blessing"
] | null | null | null | #ifndef INCLUDED_LSPCORE_SYMBOLUTIL
#define INCLUDED_LSPCORE_SYMBOLUTIL
#include <bdld_datum.h>
#include <bdld_datumudt.h>
#include <bsl_algorithm.h>
#include <bsl_cstddef.h>
#include <bsl_string.h>
#include <bsl_string_view.h>
#include <bsl_utility.h>
#include <bslma_allocator.h>
#include <bsls_assert.h>
#include <bsls_types.h>
#include <lspcore_endian.h>
#include <lspcore_environment.h>
#include <lspcore_procedure.h>
#include <lspcore_userdefinedtypes.h>
namespace lspcore {
namespace bdld = BloombergLP::bdld;
namespace bslma = BloombergLP::bslma;
namespace bsls = BloombergLP::bsls;
struct SymbolUtil {
static bdld::Datum create(const bdld::Datum& stringValue,
int typeOffset,
bslma::Allocator* allocator);
static bdld::Datum create(bsl::string_view string,
int typeOffset,
bslma::Allocator* allocator);
static bdld::Datum create(
const bsl::pair<const bsl::string, bdld::Datum>& entry,
int typeOffset);
static bdld::Datum create(bsl::size_t argumentsOffset, int typeOffset);
// Return a 'Datum' containing or referring to a string that is the name
// associated with the specified 'symbol'. The behavior is undefined if
// 'symbol' is encoded as an offset to an environment argument vector. Note
// that the overloads of 'name' that take an 'Procedure' parameter do not
// have this limitation.
// TODO: What about lifetime? (referring to a 'bsl::string' in some env)
static bdld::Datum name(const bdld::Datum& symbol);
static bdld::Datum name(const bdld::DatumUdt& symbol);
// Return a 'Datum' containing or referring to a string that is the name
// associated with the specified 'symbol', possibly in the specified
// 'Procedure'.
// TODO: What about lifetime? (referring to a 'bsl::string' in some env)
static bdld::Datum name(const bdld::Datum& symbol,
const Procedure& procedure);
static bdld::Datum name(const bdld::DatumUdt& symbol,
const Procedure& procedure);
// Return a pointer to the environment entry to which 'symbol' refers in
// the specified 'environment'. Return a null pointer if 'symbol' is
// unbound in 'environment'. The behavior is undefined if 'symbol' is
// encoded as an environment entry pointer or as an argument vector offset
// for an environment other than 'environment'.
static const bsl::pair<const bsl::string, bdld::Datum>* resolve(
const bdld::Datum& symbol, const Environment& environment);
static const bsl::pair<const bsl::string, bdld::Datum>* resolve(
const bdld::DatumUdt& symbol, const Environment& environment);
static bool isSymbol(const bdld::Datum& datum, int typeOffset);
static bool isSymbol(const bdld::DatumUdt& datum, int typeOffset);
// Return whether the specified 'datum' is a symbol encoded as a pointer to
// an environment entry. The behavior is undefined unless 'datum' is a
// symbol.
static bool isResolved(const bdld::Datum& datum);
private:
enum Encoding { e_DATUM_PTR, e_IN_PLACE, e_ENTRY_PTR, e_ARGUMENTS_OFFSET };
static Encoding encoding(void* udtData);
static bdld::Datum createInPlace(bsl::string_view value, int typeOffset);
static bdld::Datum createOutOfPlace(const bdld::Datum& stringValue,
int typeOffset,
bslma::Allocator* allocator);
static bdld::Datum nameInPlace(void* udtData);
static bdld::Datum nameOutOfPlace(void* udtData);
static bdld::Datum nameEntry(void* udtData);
static bdld::Datum nameOffset(void* udtData, const Procedure&);
static const bsl::pair<const bsl::string, bdld::Datum>* entry(
void* udtData);
static const bsl::pair<const bsl::string, bdld::Datum>* fromOffset(
void* udtData, const Environment&);
static bsl::string_view fromOffset(void* udtData, const Procedure&);
static bslma::Allocator* const s_neverAllocate;
};
inline bool SymbolUtil::isSymbol(const bdld::Datum& datum, int typeOffset) {
return datum.isUdt() && isSymbol(datum.theUdt(), typeOffset);
}
inline bool SymbolUtil::isSymbol(const bdld::DatumUdt& udt, int typeOffset) {
return udt.type() == UserDefinedTypes::e_SYMBOL + typeOffset;
}
inline bool SymbolUtil::isResolved(const bdld::Datum& datum) {
BSLS_ASSERT(datum.isUdt());
return encoding(datum.theUdt().data()) == e_ENTRY_PTR;
}
// Symbols have four different representations:
//
// 1. 'bdld::Datum*' where the datum has type 'bdld::Datum::e_STRING'
// 2. tiny in-place string
// 3. 'bsl::pair<bsl::string, bdld::Datum>*' to a resolved environment entry
// 4. an offset into the local environment's vector of procedure arguments
//
// In all cases, the length of the name of a symbol must not exceed 65,535
// bytes. This allows 'bdld::Datum::createStringRef' to be used on 32-bit
// systems without allocating memory. It might seem an unnecessary restriction,
// but do you really need symbol names longer than 64k?
//
// For (2), symbols containing very small strings are optimized to reside
// within the 'bdld::DatumUdt' itself. One byte of the internal 'void*' is
// reserved, but the other bytes may contain a UTF-8 sequence. On 64-bit
// systems we can store seven bytes of UTF-8. On 32-bit systems we can store
// three bytes of UTF-8.
//
// Three bytes doesn't seem like much, but it covers:
//
// - single-ASCII identifiers, e.g. "i", "+", "=", ">"
// - "if"
// - "λ" (two bytes in UTF-8)
// - "let"
// - "not"
// - "~>"
//
// It's more useful on 64-bit systems, where up to seven bytes are available:
//
// - "cond"
// - "define"
// - "lambda"
// - "filter"
// - "string?"
// The 'void*' within a 'bdld::DatumUdt' referring to a 'bdld::Datum' string or
// a 'bsl::pair<bsl::string, bdld::Datum>' will be at least word-aligned, which
// means the two least significant bits will always be zero (on a 32-bit
// system). Thus a symbol can have up to four distinct representations.
//
// Where in memory the two "selector" bits reside, and where the in-place
// buffer (if any) begins, depend on whether the platform is little-endian
// (e.g. x86) or big-endian (e.g. SPARC).
//
// See 'lspcore_endian.h'.
//
// The interpretation of the bits within the lest significant byte depends upon
// the values of the least significant byte's two least significant bits:
//
//
// bit position: 7 6 5 4 3 2 1 0
// bit value: _ _ _ _ _ _ 0 0
// ^ ^ ^ ^ ^ ^ ^ ^
// bdld::Datum-string-ptr selector
//
//
// bit position: 7 6 5 4 3 2 1 0
// bit value: _ _ _ _ _ _ 0 1
// ^ ^ ^ ^ ^ ^ ^ ^
// reserved length selector
//
//
// bit position: 7 6 5 4 3 2 1 0
// bit value: _ _ _ _ _ _ 1 0
// ^ ^ ^ ^ ^ ^ ^ ^
// environment-entry-ptr selector
//
//
// bit position: 7 6 5 4 3 2 1 0
// bit value: _ _ _ _ _ _ 1 1
// ^ ^ ^ ^ ^ ^ ^ ^
// argument-offset-index selector
//
//
// In cases (1), (3), and (4) -- so, all but in-place string -- the
// pointer/index continues for the rest of the bits of the word.
inline bdld::Datum SymbolUtil::create(const bdld::Datum& stringValue,
int typeOffset,
bslma::Allocator* allocator) {
BSLS_ASSERT(stringValue.isString());
const bsl::string_view string = stringValue.theString();
BSLS_ASSERT(string.size() < 65536);
if (string.size() <= sizeof(void*) - 1) {
// in-place optimization
return createInPlace(string, typeOffset);
}
return createOutOfPlace(stringValue, typeOffset, allocator);
}
inline bdld::Datum SymbolUtil::create(bsl::string_view string,
int typeOffset,
bslma::Allocator* allocator) {
BSLS_ASSERT(string.size() < 65536);
if (string.size() <= sizeof(void*) - 1) {
// in-place optimization
return createInPlace(string, typeOffset);
}
return createOutOfPlace(
bdld::Datum::copyString(string, allocator), typeOffset, allocator);
}
inline bdld::Datum SymbolUtil::create(
const bsl::pair<const bsl::string, bdld::Datum>& entry, int typeOffset) {
void* const fakePtr = reinterpret_cast<void*>(
reinterpret_cast<bsls::Types::UintPtr>(&entry) | e_ENTRY_PTR);
return bdld::Datum::createUdt(fakePtr,
UserDefinedTypes::e_SYMBOL + typeOffset);
}
inline bdld::Datum SymbolUtil::create(bsl::size_t argumentsOffset,
int typeOffset) {
void* const fakePtr =
reinterpret_cast<void*>((argumentsOffset << 2) | e_ARGUMENTS_OFFSET);
return bdld::Datum::createUdt(fakePtr,
UserDefinedTypes::e_SYMBOL + typeOffset);
}
inline bdld::Datum SymbolUtil::createInPlace(bsl::string_view value,
int typeOffset) {
BSLS_ASSERT(value.size() <= sizeof(void*) - 1);
char buffer[sizeof(void*)] = {};
bsl::copy(value.begin(), value.end(), LSPCORE_BEGIN(buffer));
LSPCORE_LOWBYTE(buffer) = (value.size() << 2) | e_IN_PLACE;
void* fakePtr = *reinterpret_cast<void**>(&buffer[0]);
return bdld::Datum::createUdt(fakePtr,
UserDefinedTypes::e_SYMBOL + typeOffset);
}
inline bdld::Datum SymbolUtil::createOutOfPlace(const bdld::Datum& stringValue,
int typeOffset,
bslma::Allocator* allocator) {
BSLS_ASSERT(e_DATUM_PTR == 0);
BSLS_ASSERT(stringValue.isString());
BSLS_ASSERT(stringValue.theString().size() >= sizeof(void*));
return bdld::Datum::createUdt(new (*allocator) bdld::Datum(stringValue),
UserDefinedTypes::e_SYMBOL + typeOffset);
}
inline bdld::Datum SymbolUtil::name(const bdld::Datum& symbol) {
BSLS_ASSERT(symbol.isUdt());
// udt stands for "user-defined type"
return name(symbol.theUdt());
}
inline bdld::Datum SymbolUtil::name(const bdld::Datum& symbol,
const Procedure& procedure) {
BSLS_ASSERT(symbol.isUdt());
// udt stands for "user-defined type"
return name(symbol.theUdt(), procedure);
}
inline bdld::Datum SymbolUtil::name(const bdld::DatumUdt& udt) {
// udt stands for "user-defined type"
switch (const Encoding format = encoding(udt.data())) {
case e_DATUM_PTR:
return nameOutOfPlace(udt.data());
case e_IN_PLACE:
return nameInPlace(udt.data());
default:
(void)format;
BSLS_ASSERT(format == e_ENTRY_PTR);
// 'e_ARGUMENTS_OFFSET' is disallowed, because we don't have an
// 'Environment' where we can look up the name.
return nameEntry(udt.data());
}
}
inline bdld::Datum SymbolUtil::name(const bdld::DatumUdt& udt,
const Procedure& procedure) {
// udt stands for "user-defined type"
switch (const Encoding format = encoding(udt.data())) {
case e_DATUM_PTR:
return nameOutOfPlace(udt.data());
case e_IN_PLACE:
return nameInPlace(udt.data());
case e_ENTRY_PTR:
return nameEntry(udt.data());
default:
(void)format;
BSLS_ASSERT(format == e_ARGUMENTS_OFFSET);
return nameOffset(udt.data(), procedure);
}
}
inline SymbolUtil::Encoding SymbolUtil::encoding(void* udtData) {
// 0000...0000011, i.e. just the lowest two bits
const bsls::Types::UintPtr mask = bsls::Types::UintPtr(3);
return SymbolUtil::Encoding(
reinterpret_cast<bsls::Types::UintPtr>(udtData) & mask);
}
inline bdld::Datum SymbolUtil::nameInPlace(void* udtData) {
BSLS_ASSERT(encoding(udtData) == e_IN_PLACE);
// 'bytes' points at the pointer 'data' itself, not what 'data' points to.
const char* const bytes = reinterpret_cast<const char*>(&udtData);
const bsl::size_t length = LSPCORE_LOWBYTE(bytes) >> 2;
// Since 'length' is always less than or equal to
// 'bdld::Datum::k_SHORTSTRING_SIZE' (a private constant that we can't
// access), 'copyString' will not use the supplied allocator.
//
// However, the contract of 'copyString' implicitly requires that the
// allocator pointer is not zero, so we have to pass _some_ allocator. We
// could pass a nonsense pointer, but we can do better.
//
// We define a component-private allocator type whose 'allocate' method
// only asserts that it shall never be called. There is one instance of
// this allocator in static memory in the implementation of this component.
return bdld::Datum::copyString(
LSPCORE_BEGIN(bytes), length, s_neverAllocate);
}
inline bdld::Datum SymbolUtil::nameOutOfPlace(void* udtData) {
const bdld::Datum* const string = static_cast<bdld::Datum*>(udtData);
BSLS_ASSERT(string);
return *string;
}
inline const bsl::pair<const bsl::string, bdld::Datum>* SymbolUtil::entry(
void* udtData) {
BSLS_ASSERT(encoding(udtData) == e_ENTRY_PTR);
// 11111...11111100, i.e. unset the lowest two bits.
const bsls::Types::UintPtr mask = ~bsls::Types::UintPtr(3);
const void* const realPtr = reinterpret_cast<const void*>(
reinterpret_cast<bsls::Types::UintPtr>(udtData) & mask);
const bsl::pair<const bsl::string, bdld::Datum>* const result =
static_cast<const bsl::pair<const bsl::string, bdld::Datum>*>(realPtr);
BSLS_ASSERT(result);
return result;
}
inline const bsl::pair<const bsl::string, bdld::Datum>* SymbolUtil::fromOffset(
void* udtData, const Environment& environment) {
BSLS_ASSERT(encoding(udtData) == e_ARGUMENTS_OFFSET);
const bsls::Types::UintPtr offset =
reinterpret_cast<bsls::Types::UintPtr>(udtData) >> 2;
BSLS_ASSERT(offset < environment.arguments().size());
BSLS_ASSERT(environment.arguments()[offset]);
return environment.arguments()[offset];
}
inline bsl::string_view SymbolUtil::fromOffset(void* udtData,
const Procedure& procedure) {
BSLS_ASSERT(encoding(udtData) == e_ARGUMENTS_OFFSET);
const bsls::Types::UintPtr offset =
reinterpret_cast<bsls::Types::UintPtr>(udtData) >> 2;
if (offset < procedure.positionalParameters.size()) {
return procedure.positionalParameters[offset];
}
else {
BSLS_ASSERT(!procedure.restParameter.empty());
BSLS_ASSERT(offset == procedure.positionalParameters.size());
return procedure.restParameter;
}
}
inline bdld::Datum SymbolUtil::nameEntry(void* udtData) {
// TODO: What about lifetime? (referring to a 'bsl::string' in some env)
// Right now I'm not copying, because I figure it will be fine; but when
// you look into garbage collection more closely, look at this again.
return bdld::Datum::createStringRef(entry(udtData)->first,
s_neverAllocate);
}
inline bdld::Datum SymbolUtil::nameOffset(void* udtData,
const Procedure& procedure) {
// TODO: What about lifetime? (referring to a 'bsl::string' in some env)
// Right now I'm not copying, because I figure it will be fine; but when
// you look into garbage collection more closely, look at this again.
return bdld::Datum::createStringRef(fromOffset(udtData, procedure),
s_neverAllocate);
}
inline const bsl::pair<const bsl::string, bdld::Datum>* SymbolUtil::resolve(
const bdld::Datum& symbol, const Environment& environment) {
BSLS_ASSERT(symbol.isUdt());
return resolve(symbol.theUdt(), environment);
}
inline const bsl::pair<const bsl::string, bdld::Datum>* SymbolUtil::resolve(
const bdld::DatumUdt& symbol, const Environment& environment) {
switch (const Encoding format = encoding(symbol.data())) {
case e_DATUM_PTR: // fall through
case e_IN_PLACE:
return environment.lookup(name(symbol).theString());
case e_ENTRY_PTR:
return entry(symbol.data());
default:
(void)format;
BSLS_ASSERT(format == e_ARGUMENTS_OFFSET);
return fromOffset(symbol.data(), environment);
}
}
} // namespace lspcore
#endif
| 39.581986 | 79 | 0.622032 | [
"vector"
] |
a08617ade56222322115bfab0007f1b48f92372c | 6,283 | h | C | media/fuchsia/audio/fuchsia_audio_output_device.h | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | media/fuchsia/audio/fuchsia_audio_output_device.h | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | media/fuchsia/audio/fuchsia_audio_output_device.h | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2020 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.
#ifndef MEDIA_FUCHSIA_AUDIO_FUCHSIA_AUDIO_OUTPUT_DEVICE_H_
#define MEDIA_FUCHSIA_AUDIO_FUCHSIA_AUDIO_OUTPUT_DEVICE_H_
#include <fuchsia/media/cpp/fidl.h>
#include <memory>
#include <vector>
#include "base/memory/ref_counted.h"
#include "base/memory/shared_memory_mapping.h"
#include "base/synchronization/lock.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "media/base/audio_renderer_sink.h"
namespace base {
class SingleThreadTaskRunner;
class WritableSharedMemoryMapping;
} // namespace base
namespace media {
// AudioRendererSink implementation for Fuchsia. It sends audio to AudioConsumer
// provided by the OS. Unlike AudioOutputDevice (used by default on other
// platforms) this class sends to the system directly from the renderer process,
// without additional IPC layer to the audio service.
// All work is performed on the TaskRunner passed to Create(). It must be an IO
// thread to allow FIDL usage. AudioRendererSink can be used on a different
// thread.
class FuchsiaAudioOutputDevice : public AudioRendererSink {
public:
static scoped_refptr<FuchsiaAudioOutputDevice> Create(
fidl::InterfaceHandle<fuchsia::media::AudioConsumer>
audio_consumer_handle,
scoped_refptr<base::SingleThreadTaskRunner> task_runner);
// Same as above, but creates a FuchsiaAudioOutputDevice that runs on the
// default audio thread.
static scoped_refptr<FuchsiaAudioOutputDevice> CreateOnDefaultThread(
fidl::InterfaceHandle<fuchsia::media::AudioConsumer>
audio_consumer_handle);
// AudioRendererSink implementation.
void Initialize(const AudioParameters& params,
RenderCallback* callback) override;
void Start() override;
void Stop() override;
void Pause() override;
void Play() override;
void Flush() override;
bool SetVolume(double volume) override;
OutputDeviceInfo GetOutputDeviceInfo() override;
void GetOutputDeviceInfoAsync(OutputDeviceInfoCB info_cb) override;
bool IsOptimizedForHardwareParameters() override;
bool CurrentThreadIsRenderingThread() override;
private:
friend class FuchsiaAudioOutputDeviceTest;
explicit FuchsiaAudioOutputDevice(
scoped_refptr<base::SingleThreadTaskRunner> task_runner);
~FuchsiaAudioOutputDevice() override;
void BindAudioConsumerOnAudioThread(
fidl::InterfaceHandle<fuchsia::media::AudioConsumer>
audio_consumer_handle);
// AudioRendererSink handlers for the audio thread.
void InitializeOnAudioThread(const AudioParameters& params);
void StartOnAudioThread();
void StopOnAudioThread();
void PauseOnAudioThread();
void PlayOnAudioThread();
void FlushOnAudioThread();
void SetVolumeOnAudioThread(double volume);
// Initializes |stream_sink_|.
void CreateStreamSink();
// Sends current volume to |volume_control_|.
void UpdateVolume();
// Polls current |audio_consumer_| status.
void WatchAudioConsumerStatus();
// Callback for AudioConsumer::WatchStatus().
void OnAudioConsumerStatusChanged(fuchsia::media::AudioConsumerStatus status);
// Schedules next PumpSamples() to pump next audio packet.
void SchedulePumpSamples();
// Pumps a single packet to AudioConsumer and calls SchedulePumpSamples() to
// pump the next packet.
void PumpSamples(base::TimeTicks playback_time, int frames_skipped);
// Callback for StreamSink::SendPacket().
void OnStreamSendDone(size_t buffer_index);
// Reports an error and shuts down the AudioConsumer connection.
void ReportError();
// Task runner used for all activity. Normally this is the audio thread owned
// by FuchsiaAudioDeviceFactory. All AudioRendererSink methods are called on
// another thread (normally the main renderer thread on which this object is
// created).
scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
fuchsia::media::AudioConsumerPtr audio_consumer_;
fuchsia::media::StreamSinkPtr stream_sink_;
fuchsia::media::audio::VolumeControlPtr volume_control_;
AudioParameters params_;
// Lock used to control access to |callback_|.
base::Lock callback_lock_;
// Callback passed to Initialize(). It's set on the main thread (that calls
// Initialize() and Stop()), but used on the audio thread (which corresponds
// to the |task_runner_|). This is necessary because AudioRendererSink must
// guarantee that the callback is not called after Stop(). |callback_lock_| is
// used to synchronize access to the |callback_|.
RenderCallback* callback_ GUARDED_BY(callback_lock_) = nullptr;
// Mapped memory for buffers shared with |stream_sink_|.
std::vector<base::WritableSharedMemoryMapping> stream_sink_buffers_;
// Indices of unused buffers in |stream_sink_buffers_|.
std::vector<size_t> available_buffers_indices_;
float volume_ = 1.0;
// Current position in the stream in samples since the stream was started.
size_t media_pos_frames_ = 0;
// Current minimum lead time returned by the |audio_consumer_|.
base::TimeDelta min_lead_time_;
// Current timeline parameters provided by the |audio_consumer_| in the last
// AudioConsumerStatus. See
// https://fuchsia.dev/reference/fidl/fuchsia.media#TimelineFunction for
// details on how these parameters are used. |timeline_reference_time_| is set
// to null value when there is no presentation timeline (i.e. playback isn't
// active).
base::TimeTicks timeline_reference_time_;
base::TimeDelta timeline_subject_time_;
uint32_t timeline_reference_delta_;
uint32_t timeline_subject_delta_;
// Set to true between DoPause() and DoPlay(). AudioConsumer implementations
// should drop |presentation_timeline| when the stream is paused, but the
// state is updated asynchronously. This flag is used to avoid sending packets
// until the state is updated.
bool paused_ = false;
// Timer for PumpSamples().
base::OneShotTimer pump_samples_timer_;
// AudioBus used in PumpSamples(). Stored here to avoid re-allocating it for
// every packet.
std::unique_ptr<AudioBus> audio_bus_;
};
} // namespace media
#endif // MEDIA_FUCHSIA_AUDIO_FUCHSIA_AUDIO_OUTPUT_DEVICE_H_
| 36.958824 | 80 | 0.770969 | [
"object",
"vector"
] |
a0881cd5d59bd5d87d37f444f975a4e2b349f06a | 561 | h | C | include/bcdb/WholeProgram.h | yotann/bcdb | e1b1cb4d279041e05ae35ec5d33edfca0df75407 | [
"Apache-2.0"
] | 6 | 2020-11-16T06:19:13.000Z | 2021-05-04T13:28:57.000Z | include/bcdb/WholeProgram.h | yotann/bcdb | e1b1cb4d279041e05ae35ec5d33edfca0df75407 | [
"Apache-2.0"
] | 4 | 2020-11-14T02:19:42.000Z | 2021-04-08T01:37:22.000Z | include/bcdb/WholeProgram.h | yotann/bcdb | e1b1cb4d279041e05ae35ec5d33edfca0df75407 | [
"Apache-2.0"
] | null | null | null | #ifndef BCDB_WHOLEPROGRAM_H
#define BCDB_WHOLEPROGRAM_H
#include <memory>
#include <string>
#include <vector>
namespace llvm {
class LLVMContext;
class Module;
namespace object {
class Binary;
} // end namespace object
} // end namespace llvm
namespace bcdb {
std::unique_ptr<llvm::Module>
ExtractModuleFromBinary(llvm::LLVMContext &Context, llvm::object::Binary &B);
bool AnnotateModuleWithBinary(llvm::Module &M, llvm::object::Binary &B);
std::vector<std::string> ImitateClangArgs(llvm::Module &M);
} // end namespace bcdb
#endif // BCDB_WHOLEPROGRAM_H
| 21.576923 | 77 | 0.762923 | [
"object",
"vector"
] |
a08dcd60001adbb4499bdff1d7416c808f7eb3e6 | 1,420 | h | C | Pod/Classes/rcsid.h | wjk/OmniBase | 1233bab11b2a69965512851371def3999c505b85 | [
"MIT"
] | 4 | 2015-05-05T01:32:17.000Z | 2016-02-08T02:25:35.000Z | Pod/Classes/rcsid.h | wjk/OmniBase | 1233bab11b2a69965512851371def3999c505b85 | [
"MIT"
] | null | null | null | Pod/Classes/rcsid.h | wjk/OmniBase | 1233bab11b2a69965512851371def3999c505b85 | [
"MIT"
] | null | null | null | // Copyright 1997-2005, 2010 Omni Development, Inc. All rights reserved.
//
// This software may only be used and reproduced according to the
// terms in the file OmniSourceLicense.html, which should be
// distributed with this project and can also be found at
// <http://www.omnigroup.com/developer/sourcecode/sourcelicense/>.
//
// $Id$
#if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
// On the iPhone OS, don't record RCS ids in object code: executable size matters.
#define RCS_ID(rcsIdString) ;
#define NAMED_RCS_ID(name, rcsIdString) ;
#else
// Define a wrapper macro for rcs_id generation that doesn't produce warnings on any platform. The old hack of rcs_id = (rcs_id, string) is no longer warning free.
#if defined(__GNUC__)
#if __GNUC__ > 2
#define RCS_ID(rcsIdString) \
static __attribute__((used, section("__TEXT,rcsid"))) const char rcs_id[] = rcsIdString;
#define NAMED_RCS_ID(name, rcsIdString) \
static __attribute__((used, section("__TEXT,rcsid"))) const char rcs_id_ ## name [] = rcsIdString;
#endif
#endif
#ifndef RCS_ID
#define RCS_ID(rcsIdString) \
static const void *rcs_id = rcsIdString; \
static const void *__rcs_id_hack() { __rcs_id_hack(); return rcs_id; }
#define NAMED_RCS_ID(name, rcsIdString) \
static const void *rcs_id_ ## name = rcsIdString; \
static const void *__rcs_id_ ## name ## _hack() { __rcs_id_ ## name ## _hack(); return rcs_id_ ## name; }
#endif
#endif
| 32.272727 | 164 | 0.735915 | [
"object"
] |
a09a8790fcb0d5ddedc8f9012ffb7b368563b24e | 2,996 | h | C | davis_ros_driver/include/davis_ros_driver/driver.h | jfvilaro/rpg_dvs_ros | 41e89399ece5735d81b4920566d1f454ecaacc60 | [
"MIT"
] | null | null | null | davis_ros_driver/include/davis_ros_driver/driver.h | jfvilaro/rpg_dvs_ros | 41e89399ece5735d81b4920566d1f454ecaacc60 | [
"MIT"
] | null | null | null | davis_ros_driver/include/davis_ros_driver/driver.h | jfvilaro/rpg_dvs_ros | 41e89399ece5735d81b4920566d1f454ecaacc60 | [
"MIT"
] | null | null | null | // This file is part of DVS-ROS - the RPG DVS ROS Package
#pragma once
#include <ros/ros.h>
#include <string>
// boost
#include <boost/thread.hpp>
#include <boost/thread/thread_time.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
// messages
#include <dvs_msgs/Event.h>
#include <dvs_msgs/EventArray.h>
#include <std_msgs/Empty.h>
#include <std_msgs/Time.h>
#include <sensor_msgs/Imu.h>
#include <sensor_msgs/Image.h>
// DAVIS driver
#include <libcaer/libcaer.h>
#include <libcaer/devices/davis.h>
// dynamic reconfigure
#include <dynamic_reconfigure/server.h>
#include <davis_ros_driver/DAVIS_ROS_DriverConfig.h>
// camera info manager
#include <sensor_msgs/CameraInfo.h>
#include <camera_info_manager/camera_info_manager.h>
namespace davis_ros_driver {
class DavisRosDriver {
public:
DavisRosDriver(ros::NodeHandle & nh, ros::NodeHandle nh_private);
~DavisRosDriver();
void dataStop();
static void onDisconnectUSB(void*);
private:
void changeDvsParameters();
void callback(davis_ros_driver::DAVIS_ROS_DriverConfig &config, uint32_t level);
void readout();
void resetTimestamps();
void caerConnect();
int computeNewExposure(const std::vector<uint8_t>& img_data,
const uint32_t current_exposure) const;
ros::NodeHandle nh_;
ros::Publisher event_array_pub_;
ros::Publisher camera_info_pub_;
ros::Publisher imu_pub_;
ros::Publisher image_pub_;
ros::Publisher exposure_pub_;
caerDeviceHandle davis_handle_;
std::string ns;
volatile bool running_;
boost::shared_ptr<dynamic_reconfigure::Server<davis_ros_driver::DAVIS_ROS_DriverConfig> > server_;
dynamic_reconfigure::Server<davis_ros_driver::DAVIS_ROS_DriverConfig>::CallbackType dynamic_reconfigure_callback_;
ros::Subscriber reset_sub_;
ros::Publisher reset_pub_;
void resetTimestampsCallback(const std_msgs::Time::ConstPtr& msg);
ros::Subscriber imu_calibration_sub_;
void imuCalibrationCallback(const std_msgs::Empty::ConstPtr& msg);
int imu_calibration_sample_size_;
bool imu_calibration_running_;
std::vector<sensor_msgs::Imu> imu_calibration_samples_;
sensor_msgs::Imu bias;
void updateImuBias();
template <typename T> int sgn(T val) {
return (T(0) < val) - (val < T(0));
}
ros::Subscriber snapshot_sub_;
void snapshotCallback(const std_msgs::Empty::ConstPtr& msg);
boost::shared_ptr<boost::thread> parameter_thread_;
boost::shared_ptr<boost::thread> readout_thread_;
boost::posix_time::time_duration delta_;
davis_ros_driver::DAVIS_ROS_DriverConfig current_config_;
std::shared_ptr<camera_info_manager::CameraInfoManager> camera_info_manager_;
struct caer_davis_info davis_info_;
bool master_;
std::string device_id_;
ros::Time reset_time_;
static constexpr double STANDARD_GRAVITY = 9.81;
ros::Timer timestamp_reset_timer_;
void resetTimerCallback(const ros::TimerEvent& te);
bool parameter_update_required_;
bool parameter_bias_update_required_;
};
} // namespace
| 27.236364 | 116 | 0.766689 | [
"vector"
] |
a09f6ce51f6a6b5e9fbaf512356cbe4af391411c | 2,564 | h | C | libs/cairo/include/cairo/cairo-mempool-private.h | jegun/openFrameworks | 79d43f249b50eb36ddcbc093dfea2c0a4bf20aa5 | [
"MIT"
] | 590 | 2015-08-05T03:00:17.000Z | 2022-03-27T14:37:10.000Z | libs/cairo/include/cairo/cairo-mempool-private.h | jegun/openFrameworks | 79d43f249b50eb36ddcbc093dfea2c0a4bf20aa5 | [
"MIT"
] | 509 | 2015-11-05T13:54:43.000Z | 2022-03-30T22:15:30.000Z | libs/cairo/include/cairo/cairo-mempool-private.h | jegun/openFrameworks | 79d43f249b50eb36ddcbc093dfea2c0a4bf20aa5 | [
"MIT"
] | 247 | 2015-07-06T10:13:48.000Z | 2022-03-20T13:08:21.000Z | /* Cairo - a vector graphics library with display and print output
*
* Copyright © 2007 Chris Wilson
* Copyright © 2009 Intel Corporation
*
* This library is free software; you can redistribute it and/or
* modify it either under the terms of the GNU Lesser General Public
* License version 2.1 as published by the Free Software Foundation
* (the "LGPL") or, at your option, under the terms of the Mozilla
* Public License Version 1.1 (the "MPL"). If you do not alter this
* notice, a recipient may use your version of this file under either
* the MPL or the LGPL.
*
* You should have received a copy of the LGPL along with this library
* in the file COPYING-LGPL-2.1; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA
* You should have received a copy of the MPL along with this library
* in the file COPYING-MPL-1.1
*
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (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.mozilla.org/MPL/
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY
* OF ANY KIND, either express or implied. See the LGPL or the MPL for
* the specific language governing rights and limitations.
*
* The Original Code is the cairo graphics library.
*
* The Initial Developer of the Original Code is Red Hat, Inc.
*
* Contributors(s):
* Chris Wilson <chris@chris-wilson.co.uk>
*/
#ifndef CAIRO_MEMPOOL_PRIVATE_H
#define CAIRO_MEMPOOL_PRIVATE_H
#include "cairo-compiler-private.h"
#include "cairo-error-private.h"
#include <stddef.h> /* for size_t */
CAIRO_BEGIN_DECLS
typedef struct _cairo_mempool cairo_mempool_t;
struct _cairo_mempool {
char *base;
struct _cairo_memblock {
int bits;
cairo_list_t link;
} *blocks;
cairo_list_t free[32];
unsigned char *map;
unsigned int num_blocks;
int min_bits; /* Minimum block size is 1 << min_bits */
int num_sizes;
int max_free_bits;
size_t free_bytes;
size_t max_bytes;
};
cairo_private cairo_status_t
_cairo_mempool_init (cairo_mempool_t *pool,
void *base,
size_t bytes,
int min_bits,
int num_sizes);
cairo_private void *
_cairo_mempool_alloc (cairo_mempool_t *pi, size_t bytes);
cairo_private void
_cairo_mempool_free (cairo_mempool_t *pi, void *storage);
cairo_private void
_cairo_mempool_fini (cairo_mempool_t *pool);
CAIRO_END_DECLS
#endif /* CAIRO_MEMPOOL_PRIVATE_H */
| 29.813953 | 78 | 0.732839 | [
"vector"
] |
a0a131e81c47f0a16bce711b278d72a03ff9fff4 | 5,129 | h | C | src/Engine/ConjugateGradient.h | TianyiWang918/dmrgpp | c007840eef1ebf423b6abc6b5b6ca2096ea6eef9 | [
"Unlicense"
] | 24 | 2016-02-22T20:53:19.000Z | 2022-03-17T07:29:32.000Z | src/Engine/ConjugateGradient.h | TianyiWang918/dmrgpp | c007840eef1ebf423b6abc6b5b6ca2096ea6eef9 | [
"Unlicense"
] | 31 | 2015-06-29T21:32:33.000Z | 2022-01-06T12:41:31.000Z | src/Engine/ConjugateGradient.h | TianyiWang918/dmrgpp | c007840eef1ebf423b6abc6b5b6ca2096ea6eef9 | [
"Unlicense"
] | 18 | 2015-08-13T04:17:47.000Z | 2021-04-27T15:50:23.000Z | /*
Copyright (c) 2009-2014, UT-Battelle, LLC
All rights reserved
[DMRG++, Version 5.]
[by G.A., Oak Ridge National Laboratory]
UT Battelle Open Source Software License 11242008
OPEN SOURCE LICENSE
Subject to the conditions of this License, each
contributor to this software hereby grants, free of
charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), a
perpetual, worldwide, non-exclusive, no-charge,
royalty-free, irrevocable copyright license to use, copy,
modify, merge, publish, distribute, and/or sublicense
copies of the Software.
1. Redistributions of Software must retain the above
copyright and license notices, this list of conditions,
and the following disclaimer. Changes or modifications
to, or derivative works of, the Software should be noted
with comments and the contributor and organization's
name.
2. Neither the names of UT-Battelle, LLC or the
Department of Energy nor the names of the Software
contributors may be used to endorse or promote products
derived from this software without specific prior written
permission of UT-Battelle.
3. The software and the end-user documentation included
with the redistribution, with or without modification,
must include the following acknowledgment:
"This product includes software produced by UT-Battelle,
LLC under Contract No. DE-AC05-00OR22725 with the
Department of Energy."
*********************************************************
DISCLAIMER
THE SOFTWARE IS SUPPLIED 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, CONTRIBUTORS, UNITED STATES GOVERNMENT,
OR THE UNITED STATES DEPARTMENT OF ENERGY 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.
NEITHER THE UNITED STATES GOVERNMENT, NOR THE UNITED
STATES DEPARTMENT OF ENERGY, NOR THE COPYRIGHT OWNER, NOR
ANY OF THEIR EMPLOYEES, REPRESENTS THAT THE USE OF ANY
INFORMATION, DATA, APPARATUS, PRODUCT, OR PROCESS
DISCLOSED WOULD NOT INFRINGE PRIVATELY OWNED RIGHTS.
*********************************************************
*/
/** \ingroup DMRG */
/*@{*/
/*! \file ConjugateGradient.h
*
* impl. of the conjugate gradient method
*
*/
#ifndef CONJ_GRAD_H
#define CONJ_GRAD_H
#include "Matrix.h"
#include "Vector.h"
#include "ProgressIndicator.h"
namespace Dmrg {
template<typename MatrixType>
class ConjugateGradient {
typedef typename MatrixType::value_type FieldType;
typedef typename PsimagLite::Vector<FieldType>::Type VectorType;
typedef typename PsimagLite::Real<FieldType>::Type RealType;
public:
ConjugateGradient(SizeType max,RealType eps)
: progress_("ConjugateGradient"), max_(max), eps_(eps) {}
//! A and b, the result x, and also the initial solution x0
void operator()(VectorType& x,
const MatrixType& A,
const VectorType& b) const
{
VectorType v = multiply(A,x);
VectorType p(b.size());
VectorType rprev(b.size());
VectorType rnext;
for (SizeType i=0;i<rprev.size();i++) {
rprev[i] = b[i] - v[i];
p[i] = rprev[i];
}
SizeType k = 0;
while (k<max_) {
VectorType tmp = multiply(A,p);
FieldType scalarrprev = scalarProduct(rprev,rprev);
FieldType val = scalarrprev/scalarProduct(p,tmp);
v <= x + val * p;
x = v;
v <= rprev - val * tmp;
rnext = v;
if (PsimagLite::norm(rnext)<eps_) break;
val = scalarProduct(rnext,rnext)/scalarrprev;
v <= rnext - val*p;
p = v;
rprev = rnext;
k++;
}
PsimagLite::OstringStream msgg(std::cout.precision());
PsimagLite::OstringStream::OstringStreamType& msg = msgg();
msg<<"Finished after "<<k<<" steps out of "<<max_;
msg<<" requested eps= "<<eps_;
RealType finalEps = PsimagLite::norm(rnext);
msg<<" actual eps= "<<finalEps;
progress_.printline(msgg, std::cout);
if (finalEps <= eps_) return;
PsimagLite::OstringStream msgg2(std::cout.precision());
PsimagLite::OstringStream::OstringStreamType& msg2 = msgg2();
msg2<<"WARNING: actual eps "<<finalEps<<" greater than requested eps= "<<eps_;
progress_.printline(msgg2, std::cout);
}
private:
FieldType scalarProduct(const VectorType& v1,const VectorType& v2) const
{
FieldType sum = 0;
for (SizeType i=0;i<v1.size();i++) sum += PsimagLite::conj(v1[i])*v2[i];
return sum;
}
VectorType multiply(const MatrixType& A,const VectorType& v) const
{
VectorType y(A.rows(),0);
A.matrixVectorProduct(y,v);
return y;
}
PsimagLite::ProgressIndicator progress_;
SizeType max_;
RealType eps_;
}; // class ConjugateGradient
} // namespace Dmrg
/*@}*/
#endif // CONJ_GRAD_H
| 29.819767 | 80 | 0.720998 | [
"vector"
] |
a0a6280d454956da7355b24e3d95b0feaf3744fd | 562 | h | C | include/Divider.h | NithishkumarS/Arithmetic | 61a8a53d9ad525ee7ae9be0c89c9bdc6e8b1aa2b | [
"MIT"
] | null | null | null | include/Divider.h | NithishkumarS/Arithmetic | 61a8a53d9ad525ee7ae9be0c89c9bdc6e8b1aa2b | [
"MIT"
] | null | null | null | include/Divider.h | NithishkumarS/Arithmetic | 61a8a53d9ad525ee7ae9be0c89c9bdc6e8b1aa2b | [
"MIT"
] | null | null | null | /*
* Divider.h
*
* Created on: July 31, 2020
* Author: Nithish
*/
#ifndef INCLUDE_DIVIDER_H_
#define INCLUDE_DIVIDER_H_
#include <Arithmetic.h>
#include <iostream>
#include <vector>
template <typename T>
class Divider : public Arithmetic<T>{
public:
/*
* Constructor
*/
Divider();
/*
* Virtual Destructor
*/
virtual ~Divider();
/*
* Function redefinition from the base class
* params : vector of operands
* return : Computed engine output
*/
double operation(std::vector<T>& arr);
};
#endif /* INCLUDE_DIVIDER_H_ */
| 13.707317 | 45 | 0.658363 | [
"vector"
] |
ae03e304c806b27633614ccf9a9098b6e533fd46 | 21,194 | c | C | 36_vertexArrayObjects/gl/gl_LFont.c | haxpor/lazyfoo-opengl2c | de2a49b33b115ffa7586f1b74ed8ef5026ba4b23 | [
"MIT"
] | 2 | 2019-02-25T11:12:39.000Z | 2019-09-13T20:09:16.000Z | 36_vertexArrayObjects/gl/gl_LFont.c | haxpor/lazyfoo-opengl2c | de2a49b33b115ffa7586f1b74ed8ef5026ba4b23 | [
"MIT"
] | null | null | null | 36_vertexArrayObjects/gl/gl_LFont.c | haxpor/lazyfoo-opengl2c | de2a49b33b115ffa7586f1b74ed8ef5026ba4b23 | [
"MIT"
] | null | null | null | #include "gl_LFont.h"
#include <stdlib.h>
#include <stddef.h>
#include "SDL_log.h"
#include "foundation/vector.h"
#include "gl/gl_LTexture_internals.h"
#include FT_BITMAP_H
#include "gl/gl_LShaderProgram.h"
#include "gl/gl_LFont_internals.h"
#include "gl/gl_lfont_polygon_program2d.h"
// spacing when render between character in pixel
#define BETWEEN_CHAR_SPACING 4
struct gl_lfont_polygon_program2d_* shared_font_shaderprogram = NULL;
// freetype font library
// single shared variable for all instance of gl_LFont during lifetime of application
static FT_Library freetype_library_ = NULL;
static void init_defaults_(gl_LFont* font);
static void free_internals_(gl_LFont* font);
static void report_freetype_error_(const FT_Error* error);
void init_defaults_(gl_LFont* font)
{
font->spritesheet = NULL;
font->space = 0.f;
font->line_height = 0.f;
font->newline = 0.f;
}
void report_freetype_error_(const FT_Error* error)
{
SDL_Log("FreeType error with code: %X", *error);
}
void free_internals_(gl_LFont* font)
{
gl_LSpritesheet_free(font->spritesheet);
font->space = 0.f;
font->line_height = 0.f;
font->newline = 0.f;
}
gl_LFont* gl_LFont_new(gl_LSpritesheet* spritesheet)
{
gl_LFont *out = malloc(sizeof(gl_LFont));
init_defaults_(out);
// set spritesheet
out->spritesheet = spritesheet;
return out;
}
void gl_LFont_free(gl_LFont* font)
{
free_internals_(font);
free(font);
font = NULL;
}
bool gl_LFont_load_bitmap(gl_LFont* font, const char* path)
{
// expect image that is grayscale, in 16x16 ASCII order
// now gl_LTexture supports 8-bit grayscale image
// so black color is 0x0
const GLubyte black_pixel = 0x00;
// get rid of the font if it exists
gl_LFont_free_font(font);
// image pixels loaded
gl_LTexture* texture = font->spritesheet->ltexture;
// load from grayscale 8-bit image
if (!gl_LTexture_load_pixels_from_file8(texture, path))
{
SDL_Log("Unable to load pixels from file");
return false;
}
// get cell dimensions
// image has 16x16 cells
GLfloat cell_width = texture->width / 16.f;
GLfloat cell_height = texture->height / 16.f;
// get letter top and bottom
GLuint top = cell_height;
GLuint bottom = 0.f;
GLuint a_bottom = 0.f;
// current pixel coordinate
int p_x = 0;
int p_y = 0;
// base cell offsets
int b_x = 0;
int b_y = 0;
// begin parsing bitmap font
GLuint current_char = 0;
LRect next_clip = { 0.f, 0.f, cell_width, cell_height };
// go through cell rows
for (int row = 0; row < 16; row++)
{
// go through each cell column in the row
for (int col = 0; col < 16; col++)
{
// begin cell parsing
// set base offsets
b_x = cell_width * col;
b_y = cell_height * row;
// initialize clip
next_clip.x = b_x;
next_clip.y = b_y;
next_clip.w = cell_width;
next_clip.h = cell_height;
// find boundary for character
// left side
for (int p_col = 0; p_col < cell_width; p_col++)
{
for (int p_row = 0; p_row < cell_height; p_row++)
{
// set pixel offset
p_x = b_x + p_col;
p_y = b_y + p_row;
// non-background pixel found
if (gl_LTexture_get_pixel8(texture, p_x, p_y) != black_pixel)
{
// set sprite's x offset
next_clip.x = p_x;
// break the loop
p_col = cell_width;
p_row = cell_height;
}
}
}
// right side
for (int p_col = cell_width-1; p_col >= 0; p_col--)
{
for (int p_row = 0; p_row < cell_height; p_row++)
{
// set pixel offset
p_x = b_x + p_col;
p_y = b_y + p_row;
// non background pixel found
if (gl_LTexture_get_pixel8(texture, p_x, p_y) != black_pixel)
{
// set sprite's width
next_clip.w = (p_x - next_clip.x) + 1;
// break the loop
p_col = -1;
p_row = cell_height;
}
}
}
// find top
for (int p_row = 0; p_row < cell_height; p_row++)
{
for (int p_col = 0; p_col < cell_width; p_col++)
{
// set pixel offset
p_x = b_x + p_col;
p_y = b_y + p_row;
// non background pixel found
if (gl_LTexture_get_pixel8(texture, p_x, p_y) != black_pixel)
{
// new top found
if (p_row < top)
{
top = p_row;
}
// break the loop
p_row = cell_height;
p_col = cell_width;
}
}
}
// find bottom
for (int p_row = cell_height - 1; p_row >= 0; p_row--)
{
for (int p_col = 0; p_col < cell_width; p_col++)
{
// set pixel offset
p_x = b_x + p_col;
p_y = b_y + p_row;
// non background pixel found
if (gl_LTexture_get_pixel8(texture, p_x, p_y) != black_pixel)
{
// set baseline
if (current_char == 'A')
{
a_bottom = p_row;
}
// new bottom found
if (p_row > bottom)
{
bottom = p_row;
}
// break the loop
p_row = -1;
p_col = cell_width;
}
}
}
// go to the next character
vector_add(font->spritesheet->clips, &next_clip);
current_char++;
}
}
// set top
// by lopping off extra height from all the character sprites
vector* clips = font->spritesheet->clips;
for (int t = 0; t < clips->len; t++)
{
// get LRect
LRect* rect = (LRect*)vector_get(clips, t);
// update back
rect->y += top;
rect->h -= top;
}
// create texture from manipulated pixels
if (!gl_LTexture_load_texture_from_precreated_pixels8(texture))
{
SDL_Log("Unable to create texture from precreated pixels");
return false;
}
// build vertex buffer from spritesheet data
if (!gl_LSpritesheet_generate_databuffer(font->spritesheet))
{
SDL_Log("Unable to generate databuffer for spritesheet");
return false;
}
// set texture wrap
glBindTexture(GL_TEXTURE_2D, texture->texture_id);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
glBindTexture(GL_TEXTURE_2D, 0);
// set spacing variables
font->space = cell_width / 2.f;
font->newline = a_bottom - top;
font->line_height = bottom - top;
return true;
}
bool gl_LFont_load_freetype(gl_LFont* font, const char* path, GLuint pixel_size)
{
// free previously loaded font
gl_LFont_free_font(font);
// init freetype
FT_Error error = 0;
error = FT_Init_FreeType(&freetype_library_);
if (error)
{
report_freetype_error_(&error);
return false;
}
// get cell dimensions
GLuint cell_width = 0;
GLuint cell_height = 0;
int max_bearing = 0;
int min_hang = 0;
// character data
// this is an array of pointer to gl_LTexture
gl_LTexture* bitmaps[256];
FT_Glyph_Metrics metrics[256];
// load face
FT_Face face = NULL;
error = FT_New_Face(freetype_library_, path, 0, &face);
// error 0 means success for FreeType
if (error)
{
report_freetype_error_(&error);
return false;
}
// set face size
error = FT_Set_Pixel_Sizes(face, 0, pixel_size);
if (error)
{
report_freetype_error_(&error);
return false;
}
// go through extended ASCII to get glyph data
for (int i=0; i<256; i++)
{
// load and render glyph
error = FT_Load_Char(face, i, FT_LOAD_RENDER);
if (error)
{
report_freetype_error_(&error);
// report error but still keep going until finish all glyphs
continue;
}
// get metrics
metrics[i] = face->glyph->metrics;
// initialize gl_LTexture inside bitmaps array
bitmaps[i] = gl_LTexture_new();
// copy glyph bitmap
gl_LTexture_copy_pixels8(bitmaps[i], face->glyph->bitmap.buffer, face->glyph->bitmap.width, face->glyph->bitmap.rows);
// calculate max bearing
// as in http://lazyfoo.net/tutorials/OpenGL/23_freetype_fonts/index.php
// author claims that 1 point = 64 pixels
if (metrics[i].horiBearingY / 64 > max_bearing)
{
max_bearing = metrics[i].horiBearingY / 64;
}
// calculate max width
if (metrics[i].width / 64 > cell_width)
{
cell_width = metrics[i].width / 64;
}
// calculate glyph hang
int glyph_hang = (metrics[i].horiBearingY - metrics[i].height) / 64;
if (glyph_hang < min_hang)
{
min_hang = glyph_hang;
}
}
// create bitmap font
cell_height = max_bearing - min_hang;
// 16 by 16 cells in creation
gl_LTexture_create_pixels8(font->spritesheet->ltexture, cell_width * 16, cell_height * 16);
// begin creating bitmap font
GLuint current_char = 0;
LRect next_clip = { 0.f, 0.f, cell_width, cell_height };
// blitting coordinates
int b_x = 0;
int b_y = 0;
// go through cell rows
for (unsigned int rows = 0; rows < 16; rows++)
{
// go through each cell column in the row
for (unsigned int cols = 0; cols < 16; cols++)
{
// set base offsets
b_x = cell_width * cols;
b_y = cell_height * rows;
// initialize clip
next_clip.x = b_x;
next_clip.y = b_y;
next_clip.w = metrics[current_char].width / 64;
next_clip.h = cell_height;
// blit character
gl_LTexture_blit_pixels8(bitmaps[current_char], b_x, b_y + max_bearing - metrics[current_char].horiBearingY / 64, font->spritesheet->ltexture);
// go to the next character
vector_add(font->spritesheet->clips, &next_clip);
current_char++;
}
}
// we are done with bitmaps
// free them all now
// free all allocated bitmaps
for (int i=0; i<256; i++)
{
if (bitmaps[i] != NULL)
{
gl_LTexture_free(bitmaps[i]);
bitmaps[i] = NULL;
}
}
// make texture power of two
gl_LTexture_pad_pixels8(font->spritesheet->ltexture);
// create texture
if (!gl_LTexture_load_texture_from_precreated_pixels8(font->spritesheet->ltexture))
{
SDL_Log("Unable to create texture from pre-created pixels8");
return false;
}
// build vertex buffer from sprite sheet data
if (!gl_LSpritesheet_generate_databuffer(font->spritesheet))
{
SDL_Log("Unable to geneate databuffer");
return false;
}
// set texture wrap
glBindTexture(GL_TEXTURE_2D, font->spritesheet->ltexture->texture_id);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
glBindTexture(GL_TEXTURE_2D, 0);
// set spacing variables
font->space = cell_width / 2.0f;
font->line_height = cell_height;
font->newline = max_bearing;
// free face
FT_Done_Face(face);
face = NULL;
// free freetype
FT_Done_FreeType(freetype_library_);
freetype_library_ = NULL;
return true;
}
void gl_LFont_free_font(gl_LFont* font)
{
// clear the sheet
gl_LSpritesheet_free_sheet(font->spritesheet);
// clear the underlying
gl_LTexture_free_internal_texture(font->spritesheet->ltexture);
// reinitialize spacing constants
font->space = 0.f;
font->line_height = 0.f;
font->newline = 0.f;
}
void gl_LFont_render_text(gl_LFont* font, const char* text, GLfloat x, GLfloat y)
{
// if there is texture to render from
if (font->spritesheet->ltexture->texture_id != 0)
{
// get spritesheet
gl_LSpritesheet* ss = font->spritesheet;
// get texture id
GLuint texture_id = ss->ltexture->texture_id;
// draw position
GLfloat render_x = x;
GLfloat render_y = y;
// save current state of modelview matrix
mat4 original_modelview_matrix;
// copy the current modelview matrix to original one, then we will work further on modelview matrix attached to shared_font_shaderprogram
glm_mat4_copy(shared_font_shaderprogram->modelview_matrix, original_modelview_matrix);
// translate to rendering position
glm_translate(shared_font_shaderprogram->modelview_matrix, (vec3){x, y, 0.f});
// issue update to gpu
gl_lfont_polygon_program2d_update_modelview_matrix(shared_font_shaderprogram);
// set texture
glBindTexture(GL_TEXTURE_2D, texture_id);
// enable all attribute pointers
gl_lfont_polygon_program2d_enable_attrib_pointers(shared_font_shaderprogram);
// bind vertex data
glBindBuffer(GL_ARRAY_BUFFER, ss->vertex_data_buffer);
// set texture coordinate attrib pointer
gl_lfont_polygon_program2d_set_texcoord_pointer(shared_font_shaderprogram, sizeof(LVertexData2D), (GLvoid*)offsetof(LVertexData2D, texcoord));
// set vertex data attrib pointer
gl_lfont_polygon_program2d_set_vertex_pointer(shared_font_shaderprogram, sizeof(LVertexData2D), (GLvoid*)offsetof(LVertexData2D, position));
// go through string
int text_length = strlen(text);
for (int i=0; i<text_length; i++)
{
// space
if (text[i] == ' ')
{
// translate modelview matrix
glm_translate_x(shared_font_shaderprogram->modelview_matrix, font->space);
// issue update to gpu
gl_lfont_polygon_program2d_update_modelview_matrix(shared_font_shaderprogram);
render_x += font->space;
}
else if (text[i] == '\n')
{
// translate modelview matrix
glm_translate(shared_font_shaderprogram->modelview_matrix, (vec3){ x - render_x, font->newline, 0.f});
// issue update to gpu
gl_lfont_polygon_program2d_update_modelview_matrix(shared_font_shaderprogram);
render_y += font->newline;
render_x += x - render_x;
}
else
{
// get ascii
GLuint ascii = (unsigned char)text[i];
// draw quad using vertex data and index data
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ss->index_buffers[ascii]);
glDrawElements(GL_TRIANGLE_FAN, 4, GL_UNSIGNED_INT, NULL);
// get clip
LRect* clip = (LRect*)vector_get(ss->clips, ascii);
// move over
glm_translate_x(shared_font_shaderprogram->modelview_matrix, clip->w + BETWEEN_CHAR_SPACING);
// issue update to gpu
gl_lfont_polygon_program2d_update_modelview_matrix(shared_font_shaderprogram);
render_x += clip->w + BETWEEN_CHAR_SPACING;
}
}
// unbind
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
// disable all attribute pointers
gl_lfont_polygon_program2d_disable_attrib_pointers(shared_font_shaderprogram);
// set modelview matrix back to original one
glm_mat4_copy(original_modelview_matrix, shared_font_shaderprogram->modelview_matrix);
}
}
void gl_LFont_render_textex(gl_LFont* font, const char* text, GLfloat x, GLfloat y, const LSize* area_size, int align)
{
// get spritesheet
gl_LSpritesheet* ss = font->spritesheet;
// get texture id
GLuint texture_id = ss->ltexture->texture_id;
// draw position
GLfloat render_x = x;
GLfloat render_y = y;
// if the text needs to be aligned
if (area_size != NULL)
{
// correct empty alignment
if (align == 0)
{
align = gl_LFont_TEXT_ALIGN_LEFT | gl_LFont_TEXT_ALIGN_TOP;
}
// handle horizontal alignment
if (align & gl_LFont_TEXT_ALIGN_CENTERED_H)
{
render_x = x + (area_size->w - gl_LFont_string_width(font, text)) / 2.f;
}
else if (align & gl_LFont_TEXT_ALIGN_RIGHT)
{
render_x = x + area_size->w - gl_LFont_string_width(font, text);
}
// handle vertical alignment
if (align & gl_LFont_TEXT_ALIGN_CENTERED_V)
{
render_y = y + (area_size->h - gl_LFont_string_height(font, text)) / 2.f;
}
else if (align & gl_LFont_TEXT_ALIGN_BOTTOM)
{
render_y = y + area_size->h - gl_LFont_string_height(font, text);
}
}
// save current state of modelview matrix
mat4 original_modelview_matrix;
// from this frame, we will operate on top of current modelview matrix then when done
// we will set back original modelview matrix back (pretty much similar to fixed-function pipeline)
glm_mat4_copy(shared_font_shaderprogram->modelview_matrix, original_modelview_matrix);
// translate to render position
glm_translate(shared_font_shaderprogram->modelview_matrix, (vec3){render_x, render_y, 0.f});
// update modelview matrix immediately
gl_lfont_polygon_program2d_update_modelview_matrix(shared_font_shaderprogram);
// set texture
glBindTexture(GL_TEXTURE_2D, texture_id);
// enable all attribute pointers
gl_lfont_polygon_program2d_enable_attrib_pointers(shared_font_shaderprogram);
// bind vertex data
glBindBuffer(GL_ARRAY_BUFFER, ss->vertex_data_buffer);
// set texcoord vertex pointer
gl_lfont_polygon_program2d_set_texcoord_pointer(shared_font_shaderprogram, sizeof(LVertexData2D), (GLvoid*)offsetof(LVertexData2D, texcoord));
gl_lfont_polygon_program2d_set_vertex_pointer(shared_font_shaderprogram, sizeof(LVertexData2D), (GLvoid*)offsetof(LVertexData2D, position));
// go through string
int text_length = strlen(text);
for (int i=0; i<text_length; i++)
{
// space
if (text[i] == ' ')
{
// translate modelview matrix
glm_translate_x(shared_font_shaderprogram->modelview_matrix, font->space);
// immediately issue udpate to gpu
gl_lfont_polygon_program2d_update_modelview_matrix(shared_font_shaderprogram);
render_x += font->space;
}
// newlines
else if (text[i] == '\n')
{
// handle horizontal alignment
GLfloat target_x = x;
if (area_size != NULL)
{
// handle horizontal alignment
if (align & gl_LFont_TEXT_ALIGN_CENTERED_H)
{
target_x += (area_size->w - gl_LFont_string_width(font, text + i + 1)) / 2.f;
}
else if (align & gl_LFont_TEXT_ALIGN_RIGHT)
{
target_x += area_size->w - gl_LFont_string_width(font, text + i + 1);
}
}
// translate modelview matrix
glm_translate(shared_font_shaderprogram->modelview_matrix, (vec3){target_x - render_x, font->newline, 0.f});
// issue update to gpu immediately
gl_lfont_polygon_program2d_update_modelview_matrix(shared_font_shaderprogram);
render_y += font->newline;
render_x += target_x - render_x;
}
else
{
// get ascii
GLuint ascii = (unsigned char)text[i];
// draw quad using vertex data and index data
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ss->index_buffers[ascii]);
glDrawElements(GL_TRIANGLE_FAN, 4, GL_UNSIGNED_INT, NULL);
// get clip
LRect* clip = (LRect*)vector_get(ss->clips, ascii);
// move over
glm_translate_x(shared_font_shaderprogram->modelview_matrix, clip->w + BETWEEN_CHAR_SPACING);
// issue update to gpu
gl_lfont_polygon_program2d_update_modelview_matrix(shared_font_shaderprogram);
render_x += clip->w + BETWEEN_CHAR_SPACING;
}
}
// unbind buffers
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
// disable all attribute pointers
gl_lfont_polygon_program2d_disable_attrib_pointers(shared_font_shaderprogram);
}
GLfloat gl_LFont_string_width(gl_LFont* font, const char* string)
{
GLfloat width = 0.f;
// go through string
for (int i=0; string[i] != '\0' && string[i] != '\n'; i++)
{
// space
if (string[i] == ' ')
{
width += font->space + BETWEEN_CHAR_SPACING;
}
// character
else
{
// get ASCII
GLuint ascii = (unsigned char)string[i];
// note: will possibly be bottleneck later as it needs to convert data type here
// consider has a specific type of vector here later?
width += (*(LRect*)vector_get(font->spritesheet->clips, ascii)).w + BETWEEN_CHAR_SPACING;
}
}
return width;
}
GLfloat gl_LFont_string_height(gl_LFont* font, const char* string)
{
GLfloat height = font->line_height;
// go through string
for (int i=0; string[i] != '\0'; i++)
{
// more space accumulated
if (string[i] == '\n')
{
height += font->line_height;
}
}
return height;
}
LSize gl_LFont_get_string_area_size(gl_LFont* font, const char* text)
{
// initialize area
GLfloat sub_width = 0.f;
LSize area = {sub_width, font->line_height};
// go through string
for (int i=0; i<strlen(text); i++)
{
// space
if (text[i] == ' ')
{
sub_width += font->space + BETWEEN_CHAR_SPACING;
}
// newline
else if (text[i] == '\n')
{
// add another line
area.h += font->line_height;
// check for max width to update max width
if (sub_width > area.w)
{
area.w = sub_width;
sub_width = 0.f;
}
}
// Character
else
{
// get ascii
GLuint ascii = (unsigned char)text[i];
sub_width += (*(LRect*)vector_get(font->spritesheet->clips, ascii)).w + BETWEEN_CHAR_SPACING;
}
}
// check for max width
if (sub_width > area.w)
{
area.w = sub_width;
}
return area;
}
| 27.488975 | 149 | 0.652071 | [
"render",
"vector"
] |
ae06601b4f36ab01d6c1469333809b425bbc399d | 1,489 | h | C | clang-tidy/zircon/TemporaryObjectsCheck.h | Szelethus/clang-tools-extra | 4bff9e7bc96ac495d7b6b2e8cc6c6f629e824022 | [
"Apache-2.0"
] | null | null | null | clang-tidy/zircon/TemporaryObjectsCheck.h | Szelethus/clang-tools-extra | 4bff9e7bc96ac495d7b6b2e8cc6c6f629e824022 | [
"Apache-2.0"
] | 2 | 2019-01-24T00:38:27.000Z | 2019-02-28T00:23:56.000Z | clang-tidy/zircon/TemporaryObjectsCheck.h | Szelethus/clang-tools-extra | 4bff9e7bc96ac495d7b6b2e8cc6c6f629e824022 | [
"Apache-2.0"
] | null | null | null | //===--- TemporaryObjectsCheck.h - clang-tidy------------------*- C++ -*-===//
//
// 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
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ZIRCON_TEMPORARYOBJECTSCHECK_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ZIRCON_TEMPORARYOBJECTSCHECK_H
#include "../ClangTidy.h"
#include "../utils/OptionsUtils.h"
namespace clang {
namespace tidy {
namespace zircon {
/// Construction of specific temporary objects in the Zircon kernel is
/// discouraged.
///
/// For the user-facing documentation see:
/// http://clang.llvm.org/extra/clang-tidy/checks/zircon-temporary-objects.html
class TemporaryObjectsCheck : public ClangTidyCheck {
public:
TemporaryObjectsCheck(StringRef Name, ClangTidyContext *Context)
: ClangTidyCheck(Name, Context),
Names(utils::options::parseStringList(Options.get("Names", ""))) {}
void storeOptions(ClangTidyOptions::OptionMap &Opts) override;
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
private:
std::vector<std::string> Names;
};
} // namespace zircon
} // namespace tidy
} // namespace clang
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ZIRCON_TEMPORARYOBJECTSCHECK_H
| 35.452381 | 80 | 0.715917 | [
"vector"
] |
ae08bf3e0a389722028acfddfa36ac5de369164d | 1,361 | h | C | src/RTL/Component/Include/IFXKeyTrackArray.h | alemuntoni/u3d | 7907b907464a2db53dac03fdc137dcb46d447513 | [
"Apache-2.0"
] | 44 | 2016-05-06T00:47:11.000Z | 2022-02-11T06:51:37.000Z | src/RTL/Component/Include/IFXKeyTrackArray.h | alemuntoni/u3d | 7907b907464a2db53dac03fdc137dcb46d447513 | [
"Apache-2.0"
] | 3 | 2016-06-27T12:37:31.000Z | 2021-03-24T12:39:48.000Z | src/RTL/Component/Include/IFXKeyTrackArray.h | alemuntoni/u3d | 7907b907464a2db53dac03fdc137dcb46d447513 | [
"Apache-2.0"
] | 15 | 2016-02-28T11:08:30.000Z | 2021-06-01T03:32:01.000Z |
//***************************************************************************
//
// Copyright (c) 1999 - 2006 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//***************************************************************************
#ifndef __IFXKeyTrackArray_h__
#define __IFXKeyTrackArray_h__
#include "IFXArray.h"
#include "IFXKeyTrack.h"
/**
An array of keyframe tracks used to hold an associated collection
of 3D motions, such as the articulation of a skeltal body.
*/
class IFXKeyTrackArray : public IFXArray<IFXKeyTrack>
{
public:
/// Gets the name of track.
virtual IFXString GetElementName(U32 index)
{
return GetElement(index).GetName();
}
/// Gets the number of keyframes in a track.
virtual U32 GetElementSize(U32 index)
{
return GetElement(index).GetNumberElements();
}
};
#endif
| 28.354167 | 77 | 0.650257 | [
"3d"
] |
ae13c4f09b857e9d4527f05d96f187f9c2b05a67 | 14,292 | c | C | libexec/ld.elf_so/map_object.c | calmsacibis995/minix | dfba95598f553b6560131d35a76658f1f8c9cf38 | [
"Unlicense"
] | null | null | null | libexec/ld.elf_so/map_object.c | calmsacibis995/minix | dfba95598f553b6560131d35a76658f1f8c9cf38 | [
"Unlicense"
] | null | null | null | libexec/ld.elf_so/map_object.c | calmsacibis995/minix | dfba95598f553b6560131d35a76658f1f8c9cf38 | [
"Unlicense"
] | null | null | null | /* $NetBSD: map_object.c,v 1.53 2014/10/30 07:53:41 martin Exp $ */
/*
* Copyright 1996 John D. Polstra.
* Copyright 1996 Matt Thomas <matt@3am-software.com>
* Copyright 2002 Charles M. Hannum <root@ihack.net>
* 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. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by John Polstra.
* 4. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 <sys/cdefs.h>
#ifndef lint
__RCSID("$NetBSD: map_object.c,v 1.53 2014/10/30 07:53:41 martin Exp $");
#endif /* not lint */
#include <errno.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/mman.h>
#include "debug.h"
#include "rtld.h"
static int protflags(int); /* Elf flags -> mmap protection */
#define EA_UNDEF (~(Elf_Addr)0)
/*
* Map a shared object into memory. The argument is a file descriptor,
* which must be open on the object and positioned at its beginning.
*
* The return value is a pointer to a newly-allocated Obj_Entry structure
* for the shared object. Returns NULL on failure.
*/
Obj_Entry *
_rtld_map_object(const char *path, int fd, const struct stat *sb)
{
Obj_Entry *obj;
Elf_Ehdr *ehdr;
Elf_Phdr *phdr;
#if defined(__HAVE_TLS_VARIANT_I) || defined(__HAVE_TLS_VARIANT_II)
Elf_Phdr *phtls;
#endif
size_t phsize;
Elf_Phdr *phlimit;
Elf_Phdr *segs[2];
int nsegs;
caddr_t mapbase = MAP_FAILED;
size_t mapsize = 0;
int mapflags;
Elf_Off base_offset;
#ifdef MAP_ALIGNED
Elf_Addr base_alignment;
#endif
Elf_Addr base_vaddr;
Elf_Addr base_vlimit;
Elf_Addr text_vlimit;
int text_flags;
caddr_t base_addr;
Elf_Off data_offset;
Elf_Addr data_vaddr;
Elf_Addr data_vlimit;
int data_flags;
caddr_t data_addr;
#if defined(__HAVE_TLS_VARIANT_I) || defined(__HAVE_TLS_VARIANT_II)
Elf_Addr tls_vaddr = 0; /* Noise GCC */
#endif
Elf_Addr phdr_vaddr;
size_t phdr_memsz;
#if defined(__minix) && (defined(__HAVE_TLS_VARIANT_I) || defined(__HAVE_TLS_VARIANT_II))
caddr_t gap_addr;
size_t gap_size;
#endif /* defined(__minix) */
int i;
#ifdef RTLD_LOADER
Elf_Addr clear_vaddr;
caddr_t clear_addr;
size_t nclear;
#endif
if (sb != NULL && sb->st_size < (off_t)sizeof (Elf_Ehdr)) {
_rtld_error("%s: not ELF file (too short)", path);
return NULL;
}
obj = _rtld_obj_new();
obj->path = xstrdup(path);
obj->pathlen = strlen(path);
if (sb != NULL) {
obj->dev = sb->st_dev;
obj->ino = sb->st_ino;
}
ehdr = mmap(NULL, _rtld_pagesz, PROT_READ, MAP_FILE | MAP_SHARED, fd,
(off_t)0);
obj->ehdr = ehdr;
if (ehdr == MAP_FAILED) {
_rtld_error("%s: read error: %s", path, xstrerror(errno));
goto bad;
}
/* Make sure the file is valid */
if (memcmp(ELFMAG, ehdr->e_ident, SELFMAG) != 0) {
_rtld_error("%s: not ELF file (magic number bad)", path);
goto bad;
}
if (ehdr->e_ident[EI_CLASS] != ELFCLASS) {
_rtld_error("%s: invalid ELF class %x; expected %x", path,
ehdr->e_ident[EI_CLASS], ELFCLASS);
goto bad;
}
/* Elf_e_ident includes class */
if (ehdr->e_ident[EI_VERSION] != EV_CURRENT ||
ehdr->e_version != EV_CURRENT ||
ehdr->e_ident[EI_DATA] != ELFDEFNNAME(MACHDEP_ENDIANNESS)) {
_rtld_error("%s: unsupported file version", path);
goto bad;
}
if (ehdr->e_type != ET_EXEC && ehdr->e_type != ET_DYN) {
_rtld_error("%s: unsupported file type", path);
goto bad;
}
switch (ehdr->e_machine) {
ELFDEFNNAME(MACHDEP_ID_CASES)
default:
_rtld_error("%s: unsupported machine", path);
goto bad;
}
/*
* We rely on the program header being in the first page. This is
* not strictly required by the ABI specification, but it seems to
* always true in practice. And, it simplifies things considerably.
*/
assert(ehdr->e_phentsize == sizeof(Elf_Phdr));
assert(ehdr->e_phoff + ehdr->e_phnum * sizeof(Elf_Phdr) <=
_rtld_pagesz);
/*
* Scan the program header entries, and save key information.
*
* We rely on there being exactly two load segments, text and data,
* in that order.
*/
phdr = (Elf_Phdr *) ((caddr_t)ehdr + ehdr->e_phoff);
#if defined(__HAVE_TLS_VARIANT_I) || defined(__HAVE_TLS_VARIANT_II)
phtls = NULL;
#endif
phsize = ehdr->e_phnum * sizeof(phdr[0]);
obj->phdr = NULL;
phdr_vaddr = EA_UNDEF;
phdr_memsz = 0;
phlimit = phdr + ehdr->e_phnum;
nsegs = 0;
while (phdr < phlimit) {
switch (phdr->p_type) {
case PT_INTERP:
obj->interp = (void *)(uintptr_t)phdr->p_vaddr;
dbg(("%s: PT_INTERP %p", obj->path, obj->interp));
break;
case PT_LOAD:
if (nsegs < 2)
segs[nsegs] = phdr;
++nsegs;
dbg(("%s: %s %p phsize %" PRImemsz, obj->path, "PT_LOAD",
(void *)(uintptr_t)phdr->p_vaddr, phdr->p_memsz));
break;
case PT_PHDR:
phdr_vaddr = phdr->p_vaddr;
phdr_memsz = phdr->p_memsz;
dbg(("%s: %s %p phsize %" PRImemsz, obj->path, "PT_PHDR",
(void *)(uintptr_t)phdr->p_vaddr, phdr->p_memsz));
break;
case PT_DYNAMIC:
obj->dynamic = (void *)(uintptr_t)phdr->p_vaddr;
dbg(("%s: %s %p phsize %" PRImemsz, obj->path, "PT_DYNAMIC",
(void *)(uintptr_t)phdr->p_vaddr, phdr->p_memsz));
break;
#if defined(__HAVE_TLS_VARIANT_I) || defined(__HAVE_TLS_VARIANT_II)
case PT_TLS:
phtls = phdr;
dbg(("%s: %s %p phsize %" PRImemsz, obj->path, "PT_TLS",
(void *)(uintptr_t)phdr->p_vaddr, phdr->p_memsz));
break;
#endif
#ifdef __ARM_EABI__
case PT_ARM_EXIDX:
obj->exidx_start = (void *)(uintptr_t)phdr->p_vaddr;
obj->exidx_sz = phdr->p_memsz;
break;
#endif
}
++phdr;
}
phdr = (Elf_Phdr *) ((caddr_t)ehdr + ehdr->e_phoff);
obj->entry = (void *)(uintptr_t)ehdr->e_entry;
if (!obj->dynamic) {
_rtld_error("%s: not dynamically linked", path);
goto bad;
}
if (nsegs != 2) {
_rtld_error("%s: wrong number of segments (%d != 2)", path,
nsegs);
goto bad;
}
/*
* Map the entire address space of the object as a file
* region to stake out our contiguous region and establish a
* base for relocation. We use a file mapping so that
* the kernel will give us whatever alignment is appropriate
* for the platform we're running on.
*
* We map it using the text protection, map the data segment
* into the right place, then map an anon segment for the bss
* and unmap the gaps left by padding to alignment.
*/
#ifdef MAP_ALIGNED
base_alignment = segs[0]->p_align;
#endif
base_offset = round_down(segs[0]->p_offset);
base_vaddr = round_down(segs[0]->p_vaddr);
base_vlimit = round_up(segs[1]->p_vaddr + segs[1]->p_memsz);
text_vlimit = round_up(segs[0]->p_vaddr + segs[0]->p_memsz);
text_flags = protflags(segs[0]->p_flags);
data_offset = round_down(segs[1]->p_offset);
data_vaddr = round_down(segs[1]->p_vaddr);
data_vlimit = round_up(segs[1]->p_vaddr + segs[1]->p_filesz);
data_flags = protflags(segs[1]->p_flags);
#ifdef RTLD_LOADER
clear_vaddr = segs[1]->p_vaddr + segs[1]->p_filesz;
#endif
obj->textsize = text_vlimit - base_vaddr;
obj->vaddrbase = base_vaddr;
obj->isdynamic = ehdr->e_type == ET_DYN;
#if defined(__HAVE_TLS_VARIANT_I) || defined(__HAVE_TLS_VARIANT_II)
if (phtls != NULL) {
++_rtld_tls_dtv_generation;
obj->tlsindex = ++_rtld_tls_max_index;
obj->tlssize = phtls->p_memsz;
obj->tlsalign = phtls->p_align;
obj->tlsinitsize = phtls->p_filesz;
tls_vaddr = phtls->p_vaddr;
}
#endif
obj->phdr_loaded = false;
for (i = 0; i < nsegs; i++) {
if (phdr_vaddr != EA_UNDEF &&
segs[i]->p_vaddr <= phdr_vaddr &&
segs[i]->p_memsz >= phdr_memsz) {
obj->phdr_loaded = true;
break;
}
if (segs[i]->p_offset <= ehdr->e_phoff &&
segs[i]->p_memsz >= phsize) {
phdr_vaddr = segs[i]->p_vaddr + ehdr->e_phoff;
phdr_memsz = phsize;
obj->phdr_loaded = true;
break;
}
}
if (obj->phdr_loaded) {
obj->phdr = (void *)(uintptr_t)phdr_vaddr;
obj->phsize = phdr_memsz;
} else {
Elf_Phdr *buf;
buf = xmalloc(phsize);
if (buf == NULL) {
_rtld_error("%s: cannot allocate program header", path);
goto bad;
}
memcpy(buf, phdr, phsize);
obj->phdr = buf;
obj->phsize = phsize;
}
dbg(("%s: phdr %p phsize %zu (%s)", obj->path, obj->phdr, obj->phsize,
obj->phdr_loaded ? "loaded" : "allocated"));
/* Unmap header if it overlaps the first load section. */
if (base_offset < _rtld_pagesz) {
munmap(ehdr, _rtld_pagesz);
obj->ehdr = MAP_FAILED;
}
/*
* Calculate log2 of the base section alignment.
*/
mapflags = 0;
#ifdef MAP_ALIGNED
if (base_alignment > _rtld_pagesz) {
unsigned int log2 = 0;
for (; base_alignment > 1; base_alignment >>= 1)
log2++;
mapflags = MAP_ALIGNED(log2);
}
#endif
#ifdef RTLD_LOADER
base_addr = obj->isdynamic ? NULL : (caddr_t)base_vaddr;
#else
base_addr = NULL;
#endif
mapsize = base_vlimit - base_vaddr;
mapbase = mmap(base_addr, mapsize, text_flags,
mapflags | MAP_FILE | MAP_PRIVATE, fd, base_offset);
if (mapbase == MAP_FAILED) {
_rtld_error("mmap of entire address space failed: %s",
xstrerror(errno));
goto bad;
}
/* Overlay the data segment onto the proper region. */
data_addr = mapbase + (data_vaddr - base_vaddr);
if (mmap(data_addr, data_vlimit - data_vaddr, data_flags,
MAP_FILE | MAP_PRIVATE | MAP_FIXED, fd, data_offset) ==
MAP_FAILED) {
_rtld_error("mmap of data failed: %s", xstrerror(errno));
goto bad;
}
/* Overlay the bss segment onto the proper region. */
#if defined(__minix)
/* MINIX's mmap is strict and refuses 0-bytes mappings. */
if (0 < base_vlimit - data_vlimit)
#endif /*defined(__minix) */
if (mmap(mapbase + data_vlimit - base_vaddr, base_vlimit - data_vlimit,
data_flags, MAP_ANON | MAP_PRIVATE | MAP_FIXED, -1, 0) ==
MAP_FAILED) {
_rtld_error("mmap of bss failed: %s", xstrerror(errno));
goto bad;
}
/* Unmap the gap between the text and data. */
#if !defined(__minix)
gap_addr = mapbase + round_up(text_vlimit - base_vaddr);
gap_size = data_addr - gap_addr;
if (gap_size != 0 && mprotect(gap_addr, gap_size, PROT_NONE) == -1) {
_rtld_error("mprotect of text -> data gap failed: %s",
xstrerror(errno));
goto bad;
}
#endif /* !defined(__minix) */
#ifdef RTLD_LOADER
/* Clear any BSS in the last page of the data segment. */
clear_addr = mapbase + (clear_vaddr - base_vaddr);
if ((nclear = data_vlimit - clear_vaddr) > 0)
memset(clear_addr, 0, nclear);
/* Non-file portion of BSS mapped above. */
#endif
#if defined(__HAVE_TLS_VARIANT_I) || defined(__HAVE_TLS_VARIANT_II)
if (phtls != NULL)
obj->tlsinit = mapbase + tls_vaddr;
#endif
obj->mapbase = mapbase;
obj->mapsize = mapsize;
obj->relocbase = mapbase - base_vaddr;
if (obj->dynamic)
obj->dynamic = (void *)(obj->relocbase + (Elf_Addr)(uintptr_t)obj->dynamic);
if (obj->entry)
obj->entry = (void *)(obj->relocbase + (Elf_Addr)(uintptr_t)obj->entry);
if (obj->interp)
obj->interp = (void *)(obj->relocbase + (Elf_Addr)(uintptr_t)obj->interp);
if (obj->phdr_loaded)
obj->phdr = (void *)(obj->relocbase + (Elf_Addr)(uintptr_t)obj->phdr);
#ifdef __ARM_EABI__
if (obj->exidx_start)
obj->exidx_start = (void *)(obj->relocbase + (Elf_Addr)(uintptr_t)obj->exidx_start);
#endif
return obj;
bad:
if (obj->ehdr != MAP_FAILED)
munmap(obj->ehdr, _rtld_pagesz);
if (mapbase != MAP_FAILED)
munmap(mapbase, mapsize);
_rtld_obj_free(obj);
return NULL;
}
void
_rtld_obj_free(Obj_Entry *obj)
{
Objlist_Entry *elm;
Name_Entry *entry;
#if defined(__HAVE_TLS_VARIANT_I) || defined(__HAVE_TLS_VARIANT_II)
if (obj->tls_done)
_rtld_tls_offset_free(obj);
#endif
xfree(obj->path);
while (obj->needed != NULL) {
Needed_Entry *needed = obj->needed;
obj->needed = needed->next;
xfree(needed);
}
while ((entry = SIMPLEQ_FIRST(&obj->names)) != NULL) {
SIMPLEQ_REMOVE_HEAD(&obj->names, link);
xfree(entry);
}
while ((elm = SIMPLEQ_FIRST(&obj->dldags)) != NULL) {
SIMPLEQ_REMOVE_HEAD(&obj->dldags, link);
xfree(elm);
}
while ((elm = SIMPLEQ_FIRST(&obj->dagmembers)) != NULL) {
SIMPLEQ_REMOVE_HEAD(&obj->dagmembers, link);
xfree(elm);
}
if (!obj->phdr_loaded)
xfree((void *)(uintptr_t)obj->phdr);
#ifdef COMBRELOC
_rtld_combreloc_reset(obj);
#endif
xfree(obj);
}
Obj_Entry *
_rtld_obj_new(void)
{
Obj_Entry *obj;
obj = CNEW(Obj_Entry);
SIMPLEQ_INIT(&obj->names);
SIMPLEQ_INIT(&obj->dldags);
SIMPLEQ_INIT(&obj->dagmembers);
return obj;
}
/*
* Given a set of ELF protection flags, return the corresponding protection
* flags for MMAP.
*/
static int
protflags(int elfflags)
{
int prot = 0;
if (elfflags & PF_R)
prot |= PROT_READ;
#ifdef RTLD_LOADER
if (elfflags & PF_W)
prot |= PROT_WRITE;
#endif
if (elfflags & PF_X)
prot |= PROT_EXEC;
#if defined(__minix)
/* Minix has to map it writable so we can do relocations
* as we don't have mprotect() yet.
*/
prot |= PROT_WRITE;
#endif /* defined(__minix) */
return prot;
}
| 28.814516 | 89 | 0.68255 | [
"object"
] |
ae1fa157a4f94b244cc05e070e087bdf622959c0 | 2,138 | h | C | ClassBeacon/Pods/EstimoteSDK/EstimoteSDK/Headers/ESTNearableDefinitions.h | LukeAlexanderHarris/ClassBeacon | 7daf45a11fbd4f4955376b4a402432de7d708f0d | [
"MIT"
] | 3 | 2016-03-09T19:37:51.000Z | 2016-11-23T03:53:35.000Z | plugin/src/ios/Headers/ESTNearableDefinitions.h | gnazarkin/phonegap-estimotebeacons | 22f85637e567570c9c542c29baddd025047008e8 | [
"MIT"
] | 5 | 2015-06-18T17:22:56.000Z | 2021-07-14T16:54:26.000Z | plugin/src/ios/Headers/ESTNearableDefinitions.h | gnazarkin/phonegap-estimotebeacons | 22f85637e567570c9c542c29baddd025047008e8 | [
"MIT"
] | 1 | 2016-02-27T23:26:18.000Z | 2016-02-27T23:26:18.000Z | //
// ESTNearableDefinitions.h
// EstimoteSDK
//
// Created by Marcin Klimek on 16/01/15.
// Copyright (c) 2015 Estimote. All rights reserved.
//
#import "ESTDefinitions.h"
/**
* Color of the device enclosure.
*/
typedef NS_ENUM(NSInteger, ESTNearableColor)
{
ESTNearableColorUnknown = 0,
ESTNearableColorMintCocktail = 1,
ESTNearableColorIcyMarshmallow,
ESTNearableColorBlueberryPie,
ESTNearableColorSweetBeetroot,
ESTNearableColorCandyFloss,
ESTNearableColorLemonTart
};
/**
* Type of the device marked on enclosure.
*/
typedef NS_ENUM(NSInteger, ESTNearableType)
{
ESTNearableTypeUnknown = 0,
ESTNearableTypeDog,
ESTNearableTypeCar,
ESTNearableTypeFridge,
ESTNearableTypeBag,
ESTNearableTypeBike,
ESTNearableTypeChair,
ESTNearableTypeBed,
ESTNearableTypeDoor,
ESTNearableTypeShoe,
ESTNearableTypeGeneric,
ESTNearableTypeAll
};
/**
* Physical orientation of the device in 3D space.
*/
typedef NS_ENUM(NSInteger, ESTNearableOrientation)
{
ESTNearableOrientationUnknown = 0,
ESTNearableOrientationHorizontal,
ESTNearableOrientationHorizontalUpsideDown,
ESTNearableOrientationVertical,
ESTNearableOrientationVerticalUpsideDown,
ESTNearableOrientationLeftSide,
ESTNearableOrientationRightSide
};
/**
* Proximity zone related to distance from the device.
*/
typedef NS_ENUM(NSInteger, ESTNearableZone)
{
ESTNearableZoneUnknown = 0,
ESTNearableZoneImmediate,
ESTNearableZoneNear,
ESTNearableZoneFar
};
/**
* Type of firmware running on the device.
*/
typedef NS_ENUM(NSInteger, ESTNearableFirmwareState)
{
ESTNearableFirmwareStateBoot = 0,
ESTNearableFirmwareStateApp
};
@interface ESTNearableDefinitions : ESTDefinitions
/**
* Returns NSString representation of nearable type.
*
* @param type type of nearable
*
* @return name of type
*/
+ (NSString *)nameForType:(ESTNearableType)type;
/**
* Returns NSString representation of nearable color.
*
* @param color color of nearable
*
* @return name of color
*/
+ (NSString *)nameForColor:(ESTNearableColor)color;
@end
| 21.38 | 55 | 0.746024 | [
"3d"
] |
ae252fbf32151acd802b2c13285c0a4610748f1f | 1,055 | h | C | worker/deps/catch/include/internal/catch_enum_values_registry.h | vanga-top/mediasoup | 75a0d63767d30ed9671cf612661190b8fc3b4c5e | [
"0BSD"
] | 1,461 | 2022-02-25T17:44:34.000Z | 2022-03-30T06:18:29.000Z | worker/deps/catch/include/internal/catch_enum_values_registry.h | vanga-top/mediasoup | 75a0d63767d30ed9671cf612661190b8fc3b4c5e | [
"0BSD"
] | 116 | 2021-05-29T16:32:51.000Z | 2021-08-13T16:05:29.000Z | worker/deps/catch/include/internal/catch_enum_values_registry.h | vanga-top/mediasoup | 75a0d63767d30ed9671cf612661190b8fc3b4c5e | [
"0BSD"
] | 135 | 2019-04-16T09:10:13.000Z | 2022-03-18T10:22:40.000Z | /*
* Created by Phil on 4/4/2019.
* Copyright 2019 Two Blue Cubes Ltd. All rights reserved.
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef TWOBLUECUBES_CATCH_ENUMVALUESREGISTRY_H_INCLUDED
#define TWOBLUECUBES_CATCH_ENUMVALUESREGISTRY_H_INCLUDED
#include "catch_interfaces_enum_values_registry.h"
#include <vector>
#include <memory>
namespace Catch {
namespace Detail {
std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values );
class EnumValuesRegistry : public IMutableEnumValuesRegistry {
std::vector<std::unique_ptr<EnumInfo>> m_enumInfos;
EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values) override;
};
std::vector<StringRef> parseEnums( StringRef enums );
} // Detail
} // Catch
#endif //TWOBLUECUBES_CATCH_ENUMVALUESREGISTRY_H_INCLUDED | 30.142857 | 126 | 0.738389 | [
"vector"
] |
ae2a49cc7899a3107a21ebd0ae7badc161cdcbd3 | 2,057 | h | C | src/ios/SDK/StreetHawkCore_Pointzi.framework/Headers/SHTipBaseElement.h | Xingyuj/PhonegapPointzi-beta | 29e4bb0a3a659831754527557adad605be689f19 | [
"Apache-2.0"
] | null | null | null | src/ios/SDK/StreetHawkCore_Pointzi.framework/Headers/SHTipBaseElement.h | Xingyuj/PhonegapPointzi-beta | 29e4bb0a3a659831754527557adad605be689f19 | [
"Apache-2.0"
] | null | null | null | src/ios/SDK/StreetHawkCore_Pointzi.framework/Headers/SHTipBaseElement.h | Xingyuj/PhonegapPointzi-beta | 29e4bb0a3a659831754527557adad605be689f19 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) StreetHawk, All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3.0 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library.
*/
#import <UIKit/UIKit.h>
//header from StreetHawk
#import "SHTipDef.h"
/**
Base class for tip element, providing basic functions.
The tip elements will be separated step by step.
*/
@interface SHTipBaseElement : NSObject
#pragma mark - public APIs
/**
Create an instance from feed dict. Must let child class to implement.
*/
+ (instancetype)createFromFeed:(NSDictionary *)dictPayload;
/**
Serialize this object into mutable dictionary. Must let child class to implement.
*/
- (NSDictionary *)serializeToDictionary;
/**
Serialize this object from dictionary. Must let child class to implement.
*/
+ (instancetype)deserializeFromDictionary:(NSDictionary *)dict;
/**
Whether equal to an object.
*/
- (BOOL)isEqual:(id)object;
#pragma mark - override APIs
/**
Serialize this object into mutable dictionary. The excluded name properties are ignored.
*/
- (void)serializeToDictionary:(NSMutableDictionary *)dict withExcludeProperties:(NSArray<NSString *> *)arrayProperties;
/**
Serialize this object from dictionary. The excluded name properties are ignored.
*/
- (BOOL)deserializeFromDictionary:(NSDictionary *)dict withExcludeProperties:(NSArray<NSString *> *)arrayProperties;
/**
Whether equal to an object. The excluded name properties are ignored.
*/
- (BOOL)isEqual:(id)object withExcludeProperties:(NSArray<NSString *> *)arrayProperties;
@end
| 30.25 | 119 | 0.754983 | [
"object"
] |
ae2aa1c1067f0cb3dfacb9a6b349b73047910df5 | 903 | h | C | AlphaZero/include/Game.h | Georg-S/AlphaZero | c76ce6cb273c2a54710a123ce7b3dbab8a04773a | [
"BSD-3-Clause"
] | 2 | 2021-04-24T19:36:32.000Z | 2021-04-24T22:54:07.000Z | AlphaZero/include/Game.h | Georg-S/AlphaZero | c76ce6cb273c2a54710a123ce7b3dbab8a04773a | [
"BSD-3-Clause"
] | 3 | 2021-04-08T14:29:38.000Z | 2021-04-14T18:14:56.000Z | AlphaZero/include/Game.h | Georg-S/AlphaZero | c76ce6cb273c2a54710a123ce7b3dbab8a04773a | [
"BSD-3-Clause"
] | null | null | null | #ifndef DEEPREINFORCEMENTLEARNING_GAME_H
#define DEEPREINFORCEMENTLEARNING_GAME_H
#include <string>
#include <torch/torch.h>
#include <vector>
class Game
{
public:
virtual int getInitialPlayer() = 0;
virtual std::string getInitialGameState() = 0;
virtual bool isGameOver(const std::string& state) = 0;
virtual int gameOverReward(const std::string& state, int currentPlayer) = 0;
virtual int getPlayerWon(const std::string& state) = 0;
virtual torch::Tensor convertStateToNeuralNetInput(const std::string& state, int currentPlayer, torch::Device device = torch::kCPU) = 0;
virtual std::vector<int> getAllPossibleMoves(const std::string& state, int currentPlayer) = 0;
virtual std::string makeMove(const std::string& state, int move, int currentPlayer) = 0;
virtual int getNextPlayer(int currentPlayer) = 0;
virtual int getActionCount() const = 0;
};
#endif //DEEPREINFORCEMENTLEARNING_GAME_H
| 39.26087 | 137 | 0.771872 | [
"vector"
] |
ae2b85f08f9da99d505a2bb7d306858f8517ab9f | 9,024 | h | C | Source/Foundation/bsfUtility/ThirdParty/simdpp/core/detail/get_expr_uint.h | Milerius/bsf | 8715b344d6b7893f64fd5dccaaf10603a27c7a15 | [
"MIT"
] | 1,745 | 2018-03-16T02:10:28.000Z | 2022-03-26T17:34:21.000Z | include/simdpp/core/detail/get_expr_uint.h | leannejdong/MGOSDT | 29559e5feb19490e77b11d0382558cd8529feba4 | [
"BSD-3-Clause"
] | 395 | 2018-03-16T10:18:20.000Z | 2021-08-04T16:52:08.000Z | include/simdpp/core/detail/get_expr_uint.h | leannejdong/MGOSDT | 29559e5feb19490e77b11d0382558cd8529feba4 | [
"BSD-3-Clause"
] | 267 | 2018-03-17T19:32:54.000Z | 2022-02-17T16:55:50.000Z | /* Copyright (C) 2014 Povilas Kanapickas <povilas@radix.lt>
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef LIBSIMDPP_SIMDPP_CORE_DETAIL_GET_EXPR_UINT_H
#define LIBSIMDPP_SIMDPP_CORE_DETAIL_GET_EXPR_UINT_H
#include <simdpp/detail/get_expr.h>
namespace simdpp {
namespace SIMDPP_ARCH_NAMESPACE {
namespace detail {
/* We want to reduce the number of overloads that need to be created in order
to match a specific case of an expression tree containing various integer
operation nodes, such as add(int), mul_lo(int), etc. For particular
vector size each of these operations are equivalent regardless of the
argument types. Thus we simply convert the arguments of the expression to
uint expressions of certain configuration.
As a result, the following tuples of types will appear as the arguments
of the returned expression:
* uint8, uint8
* uint16, uint16
* uint32, uint32
* uint64, uint64
*/
template<class V1, class V2>
struct expr2_uint_maybe_scalar_tags {
static const unsigned v1_type_tag = V1::type_tag;
static const unsigned v1_size_tag = V1::size_tag;
static const unsigned v2_type_tag = V2::type_tag;
static const unsigned v2_size_tag = V2::size_tag;
static const unsigned length_bytes = V1::length_bytes;
};
template<class V2>
struct expr2_uint_maybe_scalar_tags<int, V2> {
static const unsigned v1_type_tag = SIMDPP_TAG_INT;
static const unsigned v1_size_tag = V2::size_tag;
static const unsigned v2_type_tag = V2::type_tag;
static const unsigned v2_size_tag = V2::size_tag;
static const unsigned length_bytes = V2::length_bytes;
};
template<class V2>
struct expr2_uint_maybe_scalar_tags<long, V2> {
static const unsigned v1_type_tag = SIMDPP_TAG_INT;
static const unsigned v1_size_tag = V2::size_tag;
static const unsigned v2_type_tag = V2::type_tag;
static const unsigned v2_size_tag = V2::size_tag;
static const unsigned length_bytes = V2::length_bytes;
};
template<class V2>
struct expr2_uint_maybe_scalar_tags<long long, V2> {
static const unsigned v1_type_tag = SIMDPP_TAG_INT;
static const unsigned v1_size_tag = V2::size_tag;
static const unsigned v2_type_tag = V2::type_tag;
static const unsigned v2_size_tag = V2::size_tag;
static const unsigned length_bytes = V2::length_bytes;
};
template<class V2>
struct expr2_uint_maybe_scalar_tags<unsigned, V2> {
static const unsigned v1_type_tag = SIMDPP_TAG_UINT;
static const unsigned v1_size_tag = V2::size_tag;
static const unsigned v2_type_tag = V2::type_tag;
static const unsigned v2_size_tag = V2::size_tag;
static const unsigned length_bytes = V2::length_bytes;
};
template<class V2>
struct expr2_uint_maybe_scalar_tags<unsigned long, V2> {
static const unsigned v1_type_tag = SIMDPP_TAG_UINT;
static const unsigned v1_size_tag = V2::size_tag;
static const unsigned v2_type_tag = V2::type_tag;
static const unsigned v2_size_tag = V2::size_tag;
static const unsigned length_bytes = V2::length_bytes;
};
template<class V2>
struct expr2_uint_maybe_scalar_tags<unsigned long long, V2> {
static const unsigned v1_type_tag = SIMDPP_TAG_UINT;
static const unsigned v1_size_tag = V2::size_tag;
static const unsigned v2_type_tag = V2::type_tag;
static const unsigned v2_size_tag = V2::size_tag;
static const unsigned length_bytes = V2::length_bytes;
};
template<class V2>
struct expr2_uint_maybe_scalar_tags<float, V2> {
static const unsigned v1_type_tag = SIMDPP_TAG_INT;
static const unsigned v1_size_tag = V2::size_tag;
static const unsigned v2_type_tag = V2::type_tag;
static const unsigned v2_size_tag = V2::size_tag;
static const unsigned length_bytes = V2::length_bytes;
};
template<class V2>
struct expr2_uint_maybe_scalar_tags<double, V2> {
static const unsigned v1_type_tag = SIMDPP_TAG_INT;
static const unsigned v1_size_tag = V2::size_tag;
static const unsigned v2_type_tag = V2::type_tag;
static const unsigned v2_size_tag = V2::size_tag;
static const unsigned length_bytes = V2::length_bytes;
};
template<class V1>
struct expr2_uint_maybe_scalar_tags<V1, int> {
static const unsigned v1_type_tag = V1::type_tag;
static const unsigned v1_size_tag = V1::size_tag;
static const unsigned v2_type_tag = SIMDPP_TAG_INT;
static const unsigned v2_size_tag = V1::size_tag;
static const unsigned length_bytes = V1::length_bytes;
};
template<class V1>
struct expr2_uint_maybe_scalar_tags<V1, long> {
static const unsigned v1_type_tag = V1::type_tag;
static const unsigned v1_size_tag = V1::size_tag;
static const unsigned v2_type_tag = SIMDPP_TAG_INT;
static const unsigned v2_size_tag = V1::size_tag;
static const unsigned length_bytes = V1::length_bytes;
};
template<class V1>
struct expr2_uint_maybe_scalar_tags<V1, long long> {
static const unsigned v1_type_tag = V1::type_tag;
static const unsigned v1_size_tag = V1::size_tag;
static const unsigned v2_type_tag = SIMDPP_TAG_INT;
static const unsigned v2_size_tag = V1::size_tag;
static const unsigned length_bytes = V1::length_bytes;
};
template<class V1>
struct expr2_uint_maybe_scalar_tags<V1, unsigned> {
static const unsigned v1_type_tag = V1::type_tag;
static const unsigned v1_size_tag = V1::size_tag;
static const unsigned v2_type_tag = SIMDPP_TAG_UINT;
static const unsigned v2_size_tag = V1::size_tag;
static const unsigned length_bytes = V1::length_bytes;
};
template<class V1>
struct expr2_uint_maybe_scalar_tags<V1, unsigned long> {
static const unsigned v1_type_tag = V1::type_tag;
static const unsigned v1_size_tag = V1::size_tag;
static const unsigned v2_type_tag = SIMDPP_TAG_UINT;
static const unsigned v2_size_tag = V1::size_tag;
static const unsigned length_bytes = V1::length_bytes;
};
template<class V1>
struct expr2_uint_maybe_scalar_tags<V1, unsigned long long> {
static const unsigned v1_type_tag = V1::type_tag;
static const unsigned v1_size_tag = V1::size_tag;
static const unsigned v2_type_tag = SIMDPP_TAG_UINT;
static const unsigned v2_size_tag = V1::size_tag;
static const unsigned length_bytes = V1::length_bytes;
};
template<class V1>
struct expr2_uint_maybe_scalar_tags<V1, float> {
static const unsigned v1_type_tag = V1::type_tag;
static const unsigned v1_size_tag = V1::size_tag;
static const unsigned v2_type_tag = SIMDPP_TAG_INT;
static const unsigned v2_size_tag = V1::size_tag;
static const unsigned length_bytes = V1::length_bytes;
};
template<class V1>
struct expr2_uint_maybe_scalar_tags<V1, double> {
static const unsigned v1_type_tag = V1::type_tag;
static const unsigned v1_size_tag = V1::size_tag;
static const unsigned v2_type_tag = SIMDPP_TAG_INT;
static const unsigned v2_size_tag = V1::size_tag;
static const unsigned length_bytes = V1::length_bytes;
};
template<class V1, class V2>
struct get_expr_uint_impl {
using tags = expr2_uint_maybe_scalar_tags<V1, V2>;
#if SIMDPP_EXPR_DEBUG
static_assert(tags::v1_size_tag == tags::v2_size_tag, "Mismatching vector sizes");
static_assert(tags::v1_type_tag == SIMDPP_TAG_MASK_INT ||
tags::v1_type_tag == SIMDPP_TAG_UINT ||
tags::v1_type_tag == SIMDPP_TAG_INT, "Incorrect type parameter");
static_assert(tags::v2_type_tag == SIMDPP_TAG_MASK_INT ||
tags::v2_type_tag == SIMDPP_TAG_UINT ||
tags::v2_type_tag == SIMDPP_TAG_INT, "Incorrect type parameter");
#endif
// the size tag of the expression
static const unsigned size_tag = tags::v1_size_tag;
// (type_tag) get the type tag of the expression. Pretty much the same as
// get_expr2_nomask does
static const unsigned type_tag_t1 = tags::v1_type_tag > tags::v2_type_tag ? tags::v1_type_tag : tags::v2_type_tag;
static const unsigned type_tag = (type_tag_t1 == SIMDPP_TAG_MASK_INT) ? SIMDPP_TAG_UINT : type_tag_t1;
// strip signed integer types and masks
static const unsigned v1_type_tag = SIMDPP_TAG_UINT;
static const unsigned v2_type_tag = SIMDPP_TAG_UINT;
using v1_final_type = typename type_of_tag<v1_type_tag + size_tag,
tags::length_bytes, void>::type;
using v2_final_type = typename type_of_tag<v2_type_tag + size_tag,
tags::length_bytes, void>::type;
};
template<template<class, class> class E, class V1, class V2>
struct get_expr_uint {
using impl = get_expr_uint_impl<V1, V2>;
using type = typename type_of_tag<impl::type_tag + impl::size_tag,
impl::tags::length_bytes,
E<V1, V2>>::type;
};
} // namespace detail
} // namespace SIMDPP_ARCH_NAMESPACE
} // namespace simdpp
#endif
| 38.564103 | 118 | 0.734597 | [
"vector"
] |
ae2ee61f3c80a3f1bd6eb5527fec1ef97345b553 | 2,011 | h | C | frame/src/main/native/jni_user.h | daisy8867/hadoop- | ca772aaf1739bc8e8d60f4c798661617dcaeb5f6 | [
"Apache-2.0"
] | null | null | null | frame/src/main/native/jni_user.h | daisy8867/hadoop- | ca772aaf1739bc8e8d60f4c798661617dcaeb5f6 | [
"Apache-2.0"
] | null | null | null | frame/src/main/native/jni_user.h | daisy8867/hadoop- | ca772aaf1739bc8e8d60f4c798661617dcaeb5f6 | [
"Apache-2.0"
] | null | null | null | #include "jni.h"
#include <vector>
using namespace std;
#define ERR_CODE_ERR -1
#define ERR_CODE_OK 0
#define ERR_CODE_CONTINUE 1
#define INT_SIZE sizeof(int)
#define FLOAT_SIZE sizeof(float)
#define LONG_SIZE sizeof(long)
#define DOUBLE_SIZE sizeof(double)
extern "C"
{
/***********************************************/
/************ ****************/
/************ user function gpu ****************/
/************ ****************/
/***********************************************/
// args1:pointer of init_buf
// args2:buffer order
// args3:init args
jint init_env_gpu(char*,const int ,const char*);
//args1:args from java
//args2:offset
//args3:pointer of data_buf
//args4:size of data
//args5:order of data_buf
//args6:size of global mem
jint put_data_gpu(const char* ,vector<int> ,char*,const int,const int,unsigned int*);
//args1:args from java
//args2:order of out_buf
//args3:size of global mem
//args4:out buffer pointer
//args5:out buffer size
//args6:the buffer capacity
jint calc_gpu(const char* ,const int ,const unsigned int,char*,int*,const int);
jint free_mem_gpu();
/***********************************************/
/************ ****************/
/************ user function cpu ****************/
/************ ****************/
/***********************************************/
// args1:pointer of init_buf
// args2:buffer order
// args3:init args
jint init_env_cpu(char*,const int,const char*);
//args1:args from java
//args2:offset
//args3:pointer of data_buf
//args4:size of data
//args5:order of data_buf
//args6:size of global mem
jint put_data_cpu(const char*,vector<int> ,char*,const int,const int,unsigned int*);
//args1:args from java
//args2:order of out_buf
//args3:size of global mem
//args4:out buffer pointer
//args5:out buffer size
//args6:the buffer capacity
jint calc_cpu(const char*,const int ,const unsigned int,char*,int*,const int);
jint free_mem_cpu();
}//#extern c
| 25.782051 | 85 | 0.572849 | [
"vector"
] |
ae331013f935569e92c5fa88a821ba93f1cb0352 | 3,563 | h | C | imex/snakeoil/spritesheet/spritesheet.h | aconstlink/snakeoil | 3c6e02655e1134f8422f01073090efdde80fc109 | [
"MIT"
] | 1 | 2017-08-11T19:12:24.000Z | 2017-08-11T19:12:24.000Z | imex/snakeoil/spritesheet/spritesheet.h | aconstlink/snakeoil | 3c6e02655e1134f8422f01073090efdde80fc109 | [
"MIT"
] | 11 | 2018-07-07T20:09:44.000Z | 2020-02-16T22:45:09.000Z | imex/snakeoil/spritesheet/spritesheet.h | aconstlink/snakeoil | 3c6e02655e1134f8422f01073090efdde80fc109 | [
"MIT"
] | null | null | null | //------------------------------------------------------------
// snakeoil (c) Alexis Constantin Link
// Distributed under the MIT license
//------------------------------------------------------------
#pragma once
#include "../../api.h"
#include "../../typedefs.h"
#include <snakeoil/io/typedefs.h>
#include <snakeoil/std/container/vector.hpp>
#include <snakeoil/math/vector/vector2.hpp>
#include <snakeoil/math/vector/vector4.hpp>
namespace so_imex
{
namespace so_snakeoil
{
//***********************************************************
struct spritesheet_hitzone
{
enum class type
{
rect,
circle
};
type t ;
so_math::vec4ui_t values ;
};
so_typedef( spritesheet_hitzone ) ;
//***********************************************************
struct spritesheet_frame
{
so_this_typedefs( spritesheet_frame ) ;
so_math::vec4ui_t rect ;
so_math::vec2f_t pivot ;
uint_t duration ;
so_typedefs( so_std::vector< spritesheet_hitzone >, spritesheet_hitzones ) ;
spritesheet_hitzones_t hitzones ;
spritesheet_frame( void_t ) {}
spritesheet_frame( this_cref_t ) = delete ;
spritesheet_frame( this_rref_t rhv )
{
*this = std::move(rhv) ;
}
~spritesheet_frame(void_t ) {}
this_ref_t operator = ( this_rref_t rhv )
{
rect = rhv.rect ;
duration = rhv.duration ;
pivot = rhv.pivot ;
hitzones = std::move( rhv.hitzones ) ;
return *this ;
}
};
so_typedef( spritesheet_frame ) ;
//***********************************************************
struct spritesheet_sequence
{
so_this_typedefs( spritesheet_sequence ) ;
so_typedefs( so_std::vector< spritesheet_frame >, frames ) ;
frames_t frames ;
so_std::string_t id ;
float_t speed ;
spritesheet_sequence( void_t ) {}
spritesheet_sequence( this_cref_t ) = delete ;
spritesheet_sequence( this_rref_t rhv ) {
*this = std::move( rhv ) ;
}
~spritesheet_sequence( void_t ){}
this_ref_t operator = ( this_rref_t rhv )
{
id = std::move( rhv.id ) ;
speed = rhv.speed ;
frames = std::move( rhv.frames ) ;
return *this ;
}
};
so_typedef( spritesheet_sequence ) ;
//***********************************************************
struct spritesheet
{
so_this_typedefs( spritesheet ) ;
so_io::path_t uri ;
so_typedefs( so_std::vector< spritesheet_sequence >, sequences ) ;
sequences_t sequences ;
spritesheet( void_t ) {}
spritesheet( this_cref_t ) = delete ;
spritesheet( this_rref_t rhv )
{
*this = std::move( rhv ) ;
}
~spritesheet( void_t ) {}
this_ref_t operator = ( this_rref_t rhv )
{
uri = std::move( rhv.uri ) ;
sequences = std::move( rhv.sequences ) ;
return *this ;
}
};
so_typedef( spritesheet ) ;
}
} | 28.733871 | 88 | 0.442043 | [
"vector"
] |
ae3e2a506906f0d5eaea6b4173b239c541d79d9b | 31,073 | h | C | source/sockets/vsocket.h | xvela/code-vault | 780dad2d2855e28d802a64baf781927b7edd9ed9 | [
"MIT"
] | 2 | 2019-01-09T19:09:45.000Z | 2019-04-02T17:53:49.000Z | source/sockets/vsocket.h | xvela/code-vault | 780dad2d2855e28d802a64baf781927b7edd9ed9 | [
"MIT"
] | 17 | 2015-01-07T02:05:04.000Z | 2019-08-30T16:57:42.000Z | source/sockets/vsocket.h | xvela/code-vault | 780dad2d2855e28d802a64baf781927b7edd9ed9 | [
"MIT"
] | 3 | 2016-04-06T19:01:11.000Z | 2017-09-20T09:28:00.000Z | /*
Copyright c1997-2014 Trygve Isaacson. All rights reserved.
This file is part of the Code Vault version 4.1
http://www.bombaydigital.com/
License: MIT. See LICENSE.md in the Vault top level directory.
*/
#ifndef vsocket_h
#define vsocket_h
/** @file */
#include "vinstant.h"
#include "vstring.h"
// This pulls in any platform-specific declarations and includes:
#include "vsocket_platform.h"
/**
@defgroup vsocket Vault Sockets
The Vault implements platform-independent sockets, for both clients and
servers. The class VSocket defines the low-level API for dealing with sockets.
It's low-level in the sense that most Vault users will not have to use this API
other than calling connectToHostName() or connectToIPAddress() to connect the
socket when implementing a client-side connection. Instead, you'll mostly be
using classes like VSocketStream to associate a stream with a socket, and the upper
layer stream classes to perform the actual socket i/o. And server implementors will
similarly just be attaching a stream object to each socket that gets created for an
incoming client connection.
Each socket platform (BSD/Unix sockets, or Winsock) has a slightly different API,
but they are very close. The platform-specific quirks are separated out in the
vsocket_platform.h and .cpp files per-platform.
Client code that needs to connect will instantiate a VSocket, and then presumably
use a VSocketStream and a VIOStream to do i/o over the socket. Server code will
typically create a VListenerThread, which will use a VListenerSocket, and turn
each incoming connection into a VSocket and VSocketThread, both created via a
factory that you can supply to define the concrete classes that are instantiated
for each. There are related classes for server-side client session/thread/socket/io
management that you will find very helpful, located in the server directory: key
classes are VServer, VClientSession, and related classes for messages, message queues,
and i/o threads.
*/
typedef Vu32 VNetAddr; ///< A 32-bit IP address, in network byte order (think of it as an array of 4 bytes, not as a 32-bit integer).
/**
@ingroup vsocket
*/
/**
VNetworkInterfaceInfo describes an Internet interface on this computer. You can
get a list of the interfaces present by calling VSocket::enumerateNetworkInterfaces.
If you are just looking for the "local ip address", you should just call
VSocket::getLocalHostIPAddress(), which takes this information into account along
with the concept of a "preferred" interface on a multi-home system (where multiple
interfaces are active).
*/
class VNetworkInterfaceInfo {
public:
VNetworkInterfaceInfo() : mFamily(0), mName(), mAddress() {}
~VNetworkInterfaceInfo() {}
int mFamily; ///< Indicator of the type of interface.
VString mName; ///< Interface name.
VString mAddress; ///< IP address of the interface.
};
typedef std::vector<VNetworkInterfaceInfo> VNetworkInterfaceList;
class VSocketConnectionStrategy;
/**
VSocket is the class that defines a BSD or Winsock socket connection.
The basic way of using a client socket is to instantiate a VSocket (either
directly or through a VSocketFactory), and then call connectToHostName() or
connectToIPAddress() to connect to the desired server.
The basic way of using a server socket is to instantiate a VListenerThread
and supplying it a VSocketFactory and a subclass of VSocketThreadFactory
that will create your kind of VSocketThread to handle requests for a given
connection.
The best way to do i/o on a socket once it's connected, is to instantiate
a VSocketStream for the socket, and then instantiate the appropriate subclass
of VIOStream to do well-typed reads and writes on the socket.
Here is how you would connect to a host, write a 32-bit integer in network
byte order, receive a similar response, and clean up:
<tt>
Vu32 exchangeSingleMessage(const VString& host, int port, Vu32 request)<br>
{<br>
VSocket socket;<br>
socket.init(host, port);<br>
<br>
VSocketStream stream(socket);<br>
VBinaryIOStream io(stream);<br>
Vu32 response;<br>
<br>
io.writeU32(request);<br>
io.flush();<br>
response = io.readU32();<br>
<br>
return response;<br>
}
</tt>
@see VSocketFactory
@see VSocketStream
@see VListenerSocket
@see VIOStream
FIXME:
According to some docs I have found, the proper shutdown sequence for a connected
socket is:
1. call shutdown(id, 1) // well, not 1, so SHUT_WR or SHUT_RDWR? SHUT_RD would seem to make the next step fail
2. loop on recv until it returns 0 or any error
3. call close (or closesocket + WSACleanup on Win (is WSACleanup gone in WS2?))
*/
class VSocket {
public:
/**
This function lets you specify the preferred network interface to be used
when locating the local IP address from among multiple available interfaces.
By default, "en0" (ethernet 0) is used. Note: This technique has no effect
on Windows because the interfaces do not have names; you will need to use
setPreferredLocalIPAddressPrefix() to achieve a similar effect.
@param interfaceName the name of a network interface to choose first as
the local IP address when calling getLocalHostIPAddress()
*/
static void setPreferredNetworkInterface(const VString& interfaceName);
/**
This function lets you specify the preferred address to be used when locating
the local IP address from among multiple available interfaces, by specifying
part or all of the address. By default, there is no setting. If you set a
value that is a complete address (for example, "10.40.5.210") then when you
call getLocalHostIPAddress(), if that address exists on any interface it will
be returned. If you set a value this is a partial/prefix of an address (for
example, "10.40.") then the first interface whose address starts with that
prefix will be returned; this may be useful in DHCP situations where the
address changes but is somewhat consistent and different from the range of
unwanted addresses (e.g., ethernet vs. wifi).
@param addressPrefix the partial (prefix) or full local IP address to
return if found on any interface when calling
getLocalHostIPAddress()
*/
static void setPreferredLocalIPAddressPrefix(const VString& addressPrefix);
/**
Returns the current processor's IP address. If an error occurs, this
function throws an exception containing the error code and message.
Normally the first call gets the address, and later calls return a
cached value; but you can pass refresh=true to force it to get the
address again. If you have set a preferred interface by calling
setPreferredNetworkInterface(), it will return that interface's address
if found. Otherwise, the first interface's address is returned.
The 127.0.0.1 loopback address is never returned.
@param ipAddress a string in which to place the host name
@param refresh set true to force the address to be re-obtained by
the call; otherwise, we obtain it once and cache
that to be returned on subsequent calls
*/
static void getLocalHostIPAddress(VString& ipAddress, bool refresh = false);
/**
Returns a list of network interface info elements, by probing the
network APIs and getting all of the AF_INET elements. Note that this
may include multiple addresses if you have multiple network interfaces
such as ethernet, wi-fi, etc. To obtain the "local host" IP address,
you should call VSocket::getLocalHostIPAddress() rather than examining
the results of this call, because it examines this information but
takes into account the "preferred" interface that you can set with
VSocket::setPreferredNetworkInterface().
@return a list of zero or more network interfaces
*/
static VNetworkInterfaceList enumerateNetworkInterfaces() { return VSocket::_platform_enumerateNetworkInterfaces(); }
/**
Converts an IPv4 address string in dot notation to a 4-byte binary value
that can be stored in a stream. Note that the return value is in network
byte order by definition--think of it as an array of 4 bytes, not a
32-bit integer. Note that the VNetAddr data type should be avoided as
much as possible, since it is IPv4 only.
@param ipAddress the string to convert (must be in x.x.x.x
notation)
@return a 4-byte binary IPv4 address
*/
static VNetAddr ipAddressStringToNetAddr(const VString& ipAddress);
/**
Converts a 4-byte binary IPv4 address value into a string in the dot
notation format. Note that the input value is in network byte order by
definition--think of it as an array of 4 bytes, not a 32-bit integer.
Note that the VNetAddr data type should be avoided as much as possible,
since it is IPv4 only.
@param netAddr the 4-byte binary IPv4 address
@param ipAddress the string in which to place the dot notation
version of the address
*/
static void netAddrToIPAddressString(VNetAddr netAddr, VString& ipAddress);
/**
Resolves a internet host name to one or more numeric IP address strings.
Typically you will use this for a user-entered address that you want to
then open a socket to. If multiple addresses are returned, you have to
decide what strategy to use when connecting: a) use the first address only,
b) try each one in sequence until you succeed, or c) try all or several in
parallel and go with the fastest one to succed. Note that the returned
strings may be in IPv4 dotted decimal format (n.n.n.n) or IPv6 format
(x:x:x:x::n for example; there are several related forms, see RFC 2373).
If there is an error, or if no addresses are resolved, this function will
throw a VException. It will never return an empty vector.
@param hostName the host name to resolve; a numeric IP address is allowed
and will presumably resolve to itself
@return one or more numeric IP address strings that the OS has resolved the
host name to; if there are none, a VException is thrown instead of
returning an empty vector
*/
static VStringVector resolveHostName(const VString& hostName);
/**
Returns true if the supplied numeric IP address string appears to be in IPv4
dotted decimal format (n.n.n.n). We just check basic contents: dots, decimals,
and minimum length. RFC 2373 describes all the possible variants.
@param ipAddress a string to examine
@return obvious
*/
static bool isIPv4NumericString(const VString& ipAddress);
/**
Returns true if the supplied numeric IP address string appears to be in IPv6
format. We just check basic contents: colons, dots, hexadecimals, and minimum length.
@param ipAddress a string to examine
@return obvious
*/
static bool isIPv6NumericString(const VString& ipAddress);
/**
Returns true if the supplied numeric IP address string appears to be in IPv6
or IPv4 format. This is a combined check that is more efficient than calling
both of the above checks separately since it only has to scan the string once.
Use this to distinguish from a host name.
@param ipAddress a string to examine
@return obvious
*/
static bool isIPNumericString(const VString& ipAddress);
/**
The usual way to construct a VSocket is with the default constructor. You then subsequently
call one of the connect() functions to cause it to connect using the appropriate strategy.
You could also call setSockID() with an already-open low-level socket ID.
*/
VSocket();
/**
The other way to construct a VSocket is to supply it an already-opened low-level socket ID.
The VSocket will take ownership of the socket, and unless you later call setSockID(kNoSocketID),
it will close the underlying socket upon destruction or a call to close().
Constructs the object with an already-opened low-level
socket connection identified by its ID.
@param id an existing already-opened low-level socket ID
*/
VSocket(VSocketID id);
/**
Destructor, cleans up by closing the socket.
*/
virtual ~VSocket();
/**
Connects to the server using the specified numeric IP address and port. If the connection
cannot be opened, a VException is thrown. This is also the API that the strategy object
used by connectToHostName() will call (possibly on a temporary VSocket object) in
order to establish a connection on a particular resolved IP address.
@param ipAddress the IPv4 or IPv6 numeric address to connect to
@param portNumber the port number to connect to
*/
virtual void connectToIPAddress(const VString& ipAddress, int portNumber);
/**
Connects to the server using the specified host name and port; DNS resolution is performed
on the host name to determine the IP addresses; the first resolved address is used. To
choose a specific strategy for connecting to multiple resolved addresses, use the overloaded
version of this API that takes a VSocketConnectionStrategy object. This version is
equivalent to supplying a VSocketConnectionStrategySingle object.
If the connection cannot be opened, a VException is thrown.
@param hostName the name to resolve and then connect to
@param portNumber the port number to connect to
*/
virtual void connectToHostName(const VString& hostName, int portNumber);
/**
Connects to the server using the specified host name and port; DNS resolution is performed
on the host name to determine the IP address. The supplied strategy determines how we
connect when multiple addresses are returned by DNS resolution.
If the connection cannot be opened, a VException is thrown.
@param hostName the name to resolve and then connect to
@param portNumber the port number to connect to
@param connectionStrategy a strategy for connecting to a host name that resolves to multiple IP addresses
(@see VSocketConnectionStrategySingle, VSocketConnectionStrategyLinear, VSocketConnectionStrategyThreaded)
*/
virtual void connectToHostName(const VString& hostName, int portNumber, const VSocketConnectionStrategy& connectionStrategy);
/**
Associates this socket object with the specified socket id. This is
something you might use if you are managing sockets externally and
want to have a socket object own a socket temporarily.
Note that this method does not cause a previous socket to be closed,
nor does it update the name and port number properties of this object.
If you want those things to happen, you can call close() and
discoverHostAndPort() separately.
@param id the socket id of the socket to manage
*/
void setSockID(VSocketID id);
/**
Sets the host IP address and port for a subsequent connect() call.
@param hostIPAddress the host IP address, an IPv4 or IPv6 numeric string
@param portNumber the port number to connect to on the host
*/
virtual void setHostIPAddressAndPort(const VString& hostIPAddress, int portNumber);
// --------------- These are the various utility and accessor methods.
/**
Returns the socket id.
@return the socket id
*/
VSocketID getSockID() const;
/**
Returns the IP address of the host to which this socket is connected or has
been set via setHostIPAddressAndPort().
@return the host IP address; either an IPv4 or IPv6 numeric string
*/
VString getHostIPAddress() const;
/**
Returns the port number on the host to which this socket is
connected.
@return the host's port number to which this socket is connected
*/
int getPortNumber() const;
/**
Returns a string concatenating the host name and port number, for purposes
of socket connection identification when debugging and logging.
@return a string with this socket's address and port
*/
const VString& getName() const { return mSocketName; }
/**
Closes the socket. This terminates the connection.
*/
void close();
/**
Sets the linger value for the socket.
@param val the linger value in seconds
*/
void setLinger(int val);
/**
Removes the read timeout setting for the socket.
*/
void clearReadTimeOut();
/**
Sets the read timeout setting for the socket.
@param timeout the read timeout value
*/
void setReadTimeOut(const struct timeval& timeout);
/**
Removes the write timeout setting for the socket.
*/
void clearWriteTimeOut();
/**
Sets the write timeout setting for the socket.
@param timeout the write timeout value
*/
void setWriteTimeOut(const struct timeval& timeout);
/**
Sets the socket options to their default values.
*/
void setDefaultSockOpt();
/**
Returns the number of bytes that have been read from this socket.
@return the number of bytes read from this socket
*/
Vs64 numBytesRead() const;
/**
Returns the number of bytes that have been written to this socket.
@return the number of bytes written to this socket
*/
Vs64 numBytesWritten() const;
/**
Returns the amount of time since the last read or write activity
occurred on this socket.
*/
VDuration getIdleTime() const;
// --------------- These are the pure virtual methods that only a platform
// subclass can implement.
/**
Returns the number of bytes that are available to be read on this
socket. If you do a read() on that number of bytes, you know that
it will not block.
@return the number of bytes currently available for reading
*/
virtual int available() { return this->_platform_available(); }
/**
Reads data from the socket.
If you don't have a read timeout set up for this socket, then
read will block until all requested bytes have been read.
@param buffer the buffer to read into
@param numBytesToRead the number of bytes to read from the socket
@return the number of bytes read
*/
virtual int read(Vu8* buffer, int numBytesToRead);
/**
Writes data to the socket.
If you don't have a write timeout set up for this socket, then
write will block until all requested bytes have been written.
@param buffer the buffer to read out of
@param numBytesToWrite the number of bytes to write to the socket
@return the number of bytes written
*/
virtual int write(const Vu8* buffer, int numBytesToWrite);
/**
Flushes any unwritten bytes to the socket.
*/
virtual void flush();
/**
Sets the host name and port number properties of this socket by
asking the lower level services to whom the socket is connected.
*/
virtual void discoverHostAndPort();
/**
Shuts down just the read side of the connection.
*/
virtual void closeRead();
/**
Shuts down just the write side of the connection.
*/
virtual void closeWrite();
/**
Sets a specified socket option.
@param level the option level
@param name the option name
@param valuePtr a pointer to the new option value data
@param valueLength the length of the data pointed to by valuePtr
*/
virtual void setSockOpt(int level, int name, void* valuePtr, int valueLength);
/**
For "int" socket options, this helper function simplifies use of setSockOpt.
@param level the option level
@param name the option name
@param value the option value
*/
void setIntSockOpt(int level, int name, int value);
static const VSocketID kNoSocketID = V_NO_SOCKET_ID_CONSTANT; ///< The sock id for a socket that is not connected.
static const int kDefaultBufferSize = 65535; ///< The default buffer size.
static const int kDefaultServiceType = 0x08; ///< The default service type.
static const int kDefaultNoDelay = 1; ///< The default nodelay value.
protected:
/**
Connects to the server.
*/
virtual void _connectToIPAddress(const VString& ipAddress, int portNumber);
/**
Starts listening for incoming connections. Only useful to call
from a VListenerSocket subclass that exposes a public listen() API.
@param bindAddress if empty, the socket will bind to INADDR_ANY (usually a good
default); if a value is supplied the socket will bind to the
supplied IP address (can be useful on a multi-homed server)
@param backlog the backlog value to supply to the ::listen() function
*/
virtual void _listen(const VString& bindAddress, int backlog);
VSocketID mSocketID; ///< The socket id.
VString mHostIPAddress; ///< The IP address of the host to which the socket is connected.
int mPortNumber; ///< The port number on the host to which the socket is connected.
bool mReadTimeOutActive; ///< True if reads should time out.
struct timeval mReadTimeOut; ///< The read timeout value, if used.
bool mWriteTimeOutActive; ///< True if writes should time out.
struct timeval mWriteTimeOut; ///< The write timeout value, if used.
bool mRequireReadAll; ///< True if we throw when read returns less than # bytes asked for.
Vs64 mNumBytesRead; ///< Number of bytes read from this socket.
Vs64 mNumBytesWritten; ///< Number of bytes written to this socket.
VInstant mLastEventTime; ///< Timestamp of last read or write.
VString mSocketName; ///< Returned by getName(), useful purely for logging and debugging.
static VString gPreferredNetworkInterfaceName;
static VString gPreferredLocalIPAddressPrefix;
static VString gCachedLocalHostIPAddress;
protected: // will be private when complete
static bool gStaticInited; ///< Used internally to initialize at startup.
static bool _platform_staticInit(); ///< Used internally to initialize at startup.
/**
Platform-specific implementation of enumerateNetworkInterfaces() -- see doc
comments for public API above.
*/
static VNetworkInterfaceList _platform_enumerateNetworkInterfaces();
/**
Returns a string representation of the specified addrinfo internet address.
It may be an IPv4 dotted decimal format (n.n.n.n) or IPv6 format.
This function is used by resolveHostName() to convert each address it resolves.
@param hostName optional value to be used in an error message if we need to throw an exception
@param info the addrinfo containing the low-level information about the address;
you must only pass IPv4 (AF_INET) or IPv6 (AF_INET6) values; other types
will result in an exception being thrown
@return a string in IPv4 dotted decimal format (n.n.n.n) or IPv6 format
*/
static VString _platform_addrinfoToIPAddressString(const VString& hostName, const struct addrinfo* info);
/**
Returns true if the specified socket ID (e.g., returned from ::socket())
is valid. BSD and Winsock have different ranges of good values.
@param socketID a platform-specific socket ID
@return true if the socket ID is considered valid should an API such as ::socket() return it
*/
static bool _platform_isSocketIDValid(VSocketID socketID);
/**
Returns the number of bytes that are available to be read on this
socket. If you do a read() on that number of bytes, you know that
it will not block.
@return the number of bytes currently available for reading
*/
int _platform_available();
};
/**
VSocketInfo is essentially a structure that just contains a copy of
information about a VSocket as it existed at the point in time when
the VSocketInfo was created.
*/
class VSocketInfo {
public:
/**
Constructs the object by copying the info from the socket.
@param socket the socket to take the information from
*/
VSocketInfo(const VSocket& socket);
/**
Destructor.
*/
virtual ~VSocketInfo() {}
VSocketID mSocketID; ///< The sock id.
VString mHostIPAddress; ///< The IP address of the host to which the socket is connected.
int mPortNumber; ///< The port number on the host to which the socket is connected.
Vs64 mNumBytesRead; ///< Number of bytes read from this socket.
Vs64 mNumBytesWritten; ///< Number of bytes written to this socket.
VDuration mIdleTime; ///< Amount of time elapsed since last activity.
};
/**
VSocketInfoVector is simply a vector of VSocketInfo objects.
*/
typedef std::vector<VSocketInfo> VSocketInfoVector;
/**
A socket connection strategy determines how to connect a socket in the face of DNS resolution,
when an IP may resolve to more than one IP address. Provided concrete classes handle single,
multiple+synchronous, and multiple+multithreaded approaches.
*/
class VSocketConnectionStrategy {
public:
VSocketConnectionStrategy() : mDebugIPAddresses() {}
virtual ~VSocketConnectionStrategy() {}
/**
The VSocketConnectionStrategy interface to be implemented by concrete subclasses.
Connects to the host name by resolving it and then applying the strategy to the resolved
IP addresses. If the strategy fails (for whatever reason, be it a connect failure or a
timeout) it shall throw a VException.
@param hostName the name to resolve and connect to
@param portNumber the port number to connect to
@param socketToConnect if successful, this Vault socket object is to be mutated upon
return to have the connected socket's host IP address and low-level
VSocketID; for simple non-threaded strategies it is acceptable to
simply call this object's connectToIPAddress() and leave the results
in place if successful
*/
virtual void connect(const VString& hostName, int portNumber, VSocket& socketToConnect) const = 0;
// For testing purposes, you can inject a specific set of IP addresses, which
// will cause the hostName supplied with connect() to be ignored. You could supply
// specific bad IP addresses or slow-to-succeed IP addresses, in order to see
// what happens. Our unit tests do this.
void injectDebugIPAddresses(const VStringVector debugIPAddresses) { mDebugIPAddresses = debugIPAddresses; }
protected:
VStringVector mDebugIPAddresses; ///< If non-empty, use instead of resolving hostName in connect().
};
/**
Connects to the first DNS resolved IP address for a host name. Others are ignored.
*/
class VSocketConnectionStrategySingle : public VSocketConnectionStrategy {
public:
VSocketConnectionStrategySingle() {}
virtual ~VSocketConnectionStrategySingle() {}
// VSocketConnectionStrategy implementation:
virtual void connect(const VString& hostName, int portNumber, VSocket& socketToConnect) const;
};
/**
Connects to each DNS resolved IP address for a host name, in order, until one succeeds
or a specified timeout is reached. This strategy makes most sense with IPv4 where DNS is
supposed to return a randomized list of resolved addresses, thus achieving a form of round-robin
connection balancing by always using the first address.
*/
class VSocketConnectionStrategyLinear : public VSocketConnectionStrategy {
public:
VSocketConnectionStrategyLinear(const VDuration& timeout);
virtual ~VSocketConnectionStrategyLinear() {}
// VSocketConnectionStrategy implementation:
virtual void connect(const VString& hostName, int portNumber, VSocket& socketToConnect) const;
private:
const VDuration mTimeout;
};
/**
Connects to the all DNS resolved IP addresses for a host name, in parallel batches,
until one succeeds or a specified timeout is reached. This strategy makes most sense with IPv6
where DNS is supposed to return a preferred-order list of resolved names (rather than round-
robining) but where we have an opportunity to use the one that responds fastest.
*/
class VSocketConnectionStrategyThreaded : public VSocketConnectionStrategy {
public:
VSocketConnectionStrategyThreaded(const VDuration& timeoutInterval, int maxNumThreads = 4);
virtual ~VSocketConnectionStrategyThreaded() {}
// VSocketConnectionStrategy implementation:
virtual void connect(const VString& hostName, int portNumber, VSocket& socketToConnect) const;
private:
VDuration mTimeoutInterval;
int mMaxNumThreads;
};
#endif /* vsocket_h */
| 47.657975 | 142 | 0.669295 | [
"object",
"vector"
] |
ae3e697b0307d2714e5eb125cfe7536cf30304ab | 4,450 | h | C | tensorflow/core/distributed_runtime/eager/remote_tensor_handle_data.h | uve/tensorflow | e08079463bf43e5963acc41da1f57e95603f8080 | [
"Apache-2.0"
] | null | null | null | tensorflow/core/distributed_runtime/eager/remote_tensor_handle_data.h | uve/tensorflow | e08079463bf43e5963acc41da1f57e95603f8080 | [
"Apache-2.0"
] | null | null | null | tensorflow/core/distributed_runtime/eager/remote_tensor_handle_data.h | uve/tensorflow | e08079463bf43e5963acc41da1f57e95603f8080 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2019 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.
==============================================================================*/
#ifndef TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_EAGER_REMOTE_TENSOR_HANDLE_DATA_H_
#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_EAGER_REMOTE_TENSOR_HANDLE_DATA_H_
#include "tensorflow/core/common_runtime/eager/tensor_handle_data.h"
#include "tensorflow/core/distributed_runtime/eager/eager_client.h"
namespace tensorflow {
// Remote Tensor Handle: A handle to a Tensor on a remote host. Note that only
// the shape is known.
class RemoteTensorHandleData : public TensorHandleData {
public:
RemoteTensorHandleData(int64 op_id, int output_num, const TensorShape& shape,
eager::EagerClient* eager_client, uint64 context_id,
EagerContext* ctx);
~RemoteTensorHandleData() override;
// A remote tensor handle does not have a Tensor object, hence it can only
// support the shape requests.
Status Tensor(const tensorflow::Tensor** t) const override;
Status TensorValue(tensorflow::TensorValue* t) override;
Status Shape(TensorShape* shape) const override;
Status NumDims(int* num_dims) const override;
Status Dim(int dim_index, int64* dim) const override;
Status NumElements(int64* num_elements) const override;
string DebugString() const override;
int64 op_id() const { return op_id_; }
int32 output_num() const { return output_num_; }
private:
// IDs required when this class is representing a remote tensor handle.
const int64 op_id_;
const int32 output_num_;
const TensorShape shape_;
eager::EagerClient* eager_client_;
uint64 context_id_;
EagerContext* const ctx_;
};
// Async Remote Tensor Handle: A handle to a Tensor on a remote host. Once the
// shape has been computed this is replaced with a remote tensor handle.
class UnshapedRemoteTensorHandleData : public TensorHandleData {
public:
UnshapedRemoteTensorHandleData(int64 op_id, int32 output_num,
eager::EagerClient* eager_client,
uint64 context_id, EagerContext* ctx);
~UnshapedRemoteTensorHandleData() override;
// Unshaped remote tensor handles are not ready and hence cannot satisfy any
// of these requests.
Status Tensor(const tensorflow::Tensor** t) const override;
Status TensorValue(tensorflow::TensorValue* t) override;
Status Shape(TensorShape* shape) const override;
Status NumDims(int* num_dims) const override;
Status Dim(int dim_index, int64* dim) const override;
Status NumElements(int64* num_elements) const override;
string DebugString() const override;
int64 op_id() const { return op_id_; }
int32 output_num() const { return output_num_; }
eager::EagerClient* eager_client() const { return eager_client_; }
uint64 context_id() const { return context_id_; }
EagerContext* ctx() const { return ctx_; }
// When constructed, UnshapedRemoteTensorHandleData owns the remote
// TensorHandle and should delete it by issuing an RPC. Once the remote
// shape has been learned, the ownership is transferred to
// RemoteTensorHandleData. This method must be called to let `this` know
// that it no longer owns the remote handle.
// TODO(iga): Add a factory method here that will create a new
// RemoteTensorHandleData from this and transfer ownership in the process.
void ReleaseRemoteTensorHandle() { delete_remote_tensor_ = false; }
private:
// IDs required when this class is representing a remote tensor handle.
const int64 op_id_;
const int32 output_num_;
bool delete_remote_tensor_;
eager::EagerClient* eager_client_;
uint64 context_id_;
EagerContext* const ctx_;
};
} // namespace tensorflow
#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_EAGER_REMOTE_TENSOR_HANDLE_DATA_H_
| 42.788462 | 82 | 0.728989 | [
"object",
"shape"
] |
ae4af8e2bef6622d294fdc7a7fdb8d3e6142e337 | 3,502 | h | C | View/OpenGLRenderer.h | LukasKalinski/Gravity-Game | 5c817e3ae7658e5e42a8cff760a57380eb11fe3e | [
"MIT"
] | null | null | null | View/OpenGLRenderer.h | LukasKalinski/Gravity-Game | 5c817e3ae7658e5e42a8cff760a57380eb11fe3e | [
"MIT"
] | null | null | null | View/OpenGLRenderer.h | LukasKalinski/Gravity-Game | 5c817e3ae7658e5e42a8cff760a57380eb11fe3e | [
"MIT"
] | null | null | null | ///////////////////////////////////////////////////////////
// OpenGLRenderer.h
// Implementation of the Class OpenGLRenderer
// Created on: 28-mar-2008 10:30:58
// Original author: Lukas Kalinski
///////////////////////////////////////////////////////////
#if !defined(EA_724C1AA5_2FA0_41ff_B385_65DB3D314434__INCLUDED_)
#define EA_724C1AA5_2FA0_41ff_B385_65DB3D314434__INCLUDED_
#include "SDL.h"
#include "SDL_main.h"
#include "SDL_opengl.h"
#include "Renderer.h"
#include "PlayState.h"
#include "SinglePlayerPlayState.h"
#include "TwoPlayersPlayState.h"
#include "MenuState.h"
#include "Canvas.h"
#include "MenuCanvas.h"
#include "GamePlayCanvas.h"
/**
* Responsible for rendering graphics by using OpenGL.
*/
class OpenGLRenderer : public Renderer
{
public:
OpenGLRenderer();
virtual ~OpenGLRenderer();
OpenGLRenderer(const OpenGLRenderer& renderer);
/**
* Initializes OpenGL etc.
*/
virtual void init();
/**
* Renders graphics for current game state by accessing the corresponding game
* state sprite manager's sprites.
*/
virtual void render();
/**
* Catches the unknown game state case.
*
* @param state
*/
virtual void notifyGameStateEnter(GameState* state);
/**
* Creates a Screen instance and makes it monitor the entered menu game state.
*
* @param state
*/
virtual void notifyGameStateEnter(MenuState* state);
/**
* Creates a Screen instance and makes it monitor the entered single player game
* state.
*
* @param state
*/
virtual void notifyGameStateEnter(SinglePlayerPlayState* state);
/**
* Creates a Screen instance and makes it monitor the entered two-players game
* state.
*
* @param state
*/
virtual void notifyGameStateEnter(TwoPlayersPlayState* state);
private:
GLuint LoadFont(const std::string&);
GLuint loadTexture(const std::string&);
/**
* Initialises SDL, sets videmodes etc.
*/
void initSDL();
/**
* Initialise OpenGL specific settings.
*/
void initGL();
/**
* Initialise textures
*/
void initTextures();
/**
* Handle window resize.
*/
void resizeWindow(unsigned short width, unsigned short height);
/**
* Catches the unknown canvas case. Throws an exception if called.
*
* @param canvas
*/
virtual void render(const Canvas& canvas);
/**
* Renders graphics for a menu state by accessing the corresponding canvas' sprite
* managers and their sprites.
*
* @param canvas
*/
virtual void render(const MenuCanvas& canvas);
/**
* Renders graphics for a play state by accessing the corresponding canvas'
* viewport(s) and their sprite managers' sprites.
*
* @param canvas
*/
virtual void render(const GamePlayCanvas& canvas);
/**
* Draws the provided set of sprites.
*
* @param sprites
*/
virtual void render(const CanvasViewport::sprites_t& sprites);
typedef std::map<Sprite::sprite_image_t, std::string> filepaths_t;
std::map<Sprite::sprite_image_t, GLuint> m_textures;
filepaths_t m_filepaths;
SDL_Surface *m_screen;
SDL_Event m_event;
/**
* Screen resolution on the horizontal axis.
*/
unsigned short m_screenPxWidth;
/**
* Screen resolution on the vertical axis.
*/
unsigned short m_screenPxHeight;
static const int FULLSCREEN=1, SCREEN_BPP=32;
};
#endif // !defined(EA_724C1AA5_2FA0_41ff_B385_65DB3D314434__INCLUDED_)
| 22.164557 | 84 | 0.659052 | [
"render"
] |
ae4d431c19e589734f30480a128e31b07a5a4cde | 3,039 | h | C | mbed/FunctionPointer.h | adamstebbing/AdaptiveThermostat | 28e2ea3b08caaa61107fd40345591986f89abd55 | [
"MIT"
] | 3 | 2018-09-19T12:36:26.000Z | 2022-01-04T23:14:47.000Z | libraries/mbed/api/FunctionPointer.h | suparit/mbed | 49df530ae72ce97ccc773d1f2c13b38e868e6abd | [
"Apache-2.0"
] | 1 | 2016-12-23T10:59:06.000Z | 2016-12-23T10:59:06.000Z | libraries/mbed/api/FunctionPointer.h | suparit/mbed | 49df530ae72ce97ccc773d1f2c13b38e868e6abd | [
"Apache-2.0"
] | 1 | 2018-03-02T17:11:27.000Z | 2018-03-02T17:11:27.000Z | /* mbed Microcontroller Library
* Copyright (c) 2006-2013 ARM Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef MBED_FUNCTIONPOINTER_H
#define MBED_FUNCTIONPOINTER_H
#include <string.h>
namespace mbed {
typedef void (*pvoidf_t)(void);
/** A class for storing and calling a pointer to a static or member void function
*/
class FunctionPointer {
public:
/** Create a FunctionPointer, attaching a static function
*
* @param function The void static function to attach (default is none)
*/
FunctionPointer(void (*function)(void) = 0);
/** Create a FunctionPointer, attaching a member function
*
* @param object The object pointer to invoke the member function on (i.e. the this pointer)
* @param function The address of the void member function to attach
*/
template<typename T>
FunctionPointer(T *object, void (T::*member)(void)) {
attach(object, member);
}
/** Attach a static function
*
* @param function The void static function to attach (default is none)
*/
void attach(void (*function)(void) = 0);
/** Attach a member function
*
* @param object The object pointer to invoke the member function on (i.e. the this pointer)
* @param function The address of the void member function to attach
*/
template<typename T>
void attach(T *object, void (T::*member)(void)) {
_object = static_cast<void*>(object);
memcpy(_member, (char*)&member, sizeof(member));
_membercaller = &FunctionPointer::membercaller<T>;
_function = 0;
}
/** Call the attached static or member function
*/
void call();
pvoidf_t get_function() const {
return (pvoidf_t)_function;
}
#ifdef MBED_OPERATORS
void operator ()(void);
#endif
private:
template<typename T>
static void membercaller(void *object, char *member) {
T* o = static_cast<T*>(object);
void (T::*m)(void);
memcpy((char*)&m, member, sizeof(m));
(o->*m)();
}
void (*_function)(void); // static function pointer - 0 if none attached
void *_object; // object this pointer - 0 if none attached
char _member[16]; // raw member function pointer storage - converted back by registered _membercaller
void (*_membercaller)(void*, char*); // registered membercaller function to convert back and call _member on _object
};
} // namespace mbed
#endif
| 31.989474 | 128 | 0.655808 | [
"object"
] |
ae4f6259245b89b7468ccb980b542f21fabfd21e | 12,083 | h | C | OpenSim/Simulation/Model/ExternalForce.h | chrisdembia/opensim-debian | 50c255ce850aab252f26ac73b67bd2b78dc65cfe | [
"Apache-2.0"
] | null | null | null | OpenSim/Simulation/Model/ExternalForce.h | chrisdembia/opensim-debian | 50c255ce850aab252f26ac73b67bd2b78dc65cfe | [
"Apache-2.0"
] | null | null | null | OpenSim/Simulation/Model/ExternalForce.h | chrisdembia/opensim-debian | 50c255ce850aab252f26ac73b67bd2b78dc65cfe | [
"Apache-2.0"
] | null | null | null | #ifndef OPENSIM_EXTERNAL_FORCE_H_
#define OPENSIM_EXTERNAL_FORCE_H_
/* -------------------------------------------------------------------------- *
* OpenSim: ExternalForce.h *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2012 Stanford University and the Authors *
* Author(s): Ajay Seth *
* *
* 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
#include "Force.h"
namespace OpenSim {
class Model;
class Body;
class Storage;
class Function;
/**
* An ExternalForce is a Force class specialized at applying an external force
* and/or torque to a body as described by arrays (columns) of a Storage object.
* The source of the Storage may be experimental sensor recording or user
* generated data. The Storage must be able to supply (1) an array of time, (2)
* arrays for the x,y,z, components of force and/or torque in time. Optionally,
* (3) arrays for the point of force application in time. An ExternalForce
* must specify the identifier (e.g. Force1.x Force1.y Force1.z) for the force
* components (columns) listed in the Storage either by individual labels or
* collectively (e.g. as "Force1"). Similarly, identifiers for the applied
* torque and optionally the point of force application must be specified.
*
* If an identifier is supplied and it cannot uniquely identify the force data
* (e.g. the force, torque, or point) in the Storage, then an Exception is
* thrown.
*
* An ExternalForce must apply at least a force or a torque and therefore both
* identifiers cannot be empty.
*
* @author Ajay Seth
*/
class OSIMSIMULATION_API ExternalForce : public Force {
OpenSim_DECLARE_CONCRETE_OBJECT(ExternalForce, Force);
public:
//==============================================================================
// PROPERTIES
//==============================================================================
OpenSim_DECLARE_PROPERTY(applied_to_body, std::string,
"Name of the body the force is applied to.");
OpenSim_DECLARE_PROPERTY(force_expressed_in_body, std::string,
"Name of the body the force is expressed in (default is ground).");
OpenSim_DECLARE_OPTIONAL_PROPERTY(point_expressed_in_body, std::string,
"Name of the body the point is expressed in (default is ground).");
OpenSim_DECLARE_OPTIONAL_PROPERTY(force_identifier, std::string,
"Identifier (string) to locate the force to be applied in the data source.");
OpenSim_DECLARE_OPTIONAL_PROPERTY(point_identifier, std::string,
"Identifier (string) to locate the point to be applied in the data source.");
OpenSim_DECLARE_OPTIONAL_PROPERTY(torque_identifier, std::string,
"Identifier (string) to locate the torque to be applied in the data source.");
OpenSim_DECLARE_OPTIONAL_PROPERTY(data_source_name, std::string,
"Name of the data source (Storage) that will supply the force data.");
//==============================================================================
// PUBLIC METHODS
//==============================================================================
/**
* Default Construct of an ExternalForce.
* By default ExternalForce has data source identified by name.
* By setup() time, Tool or modeler must setDataSource() on this Force for
* it to be able to apply any force. Otherwise, an exception is thrown.
*
*/
ExternalForce();
/**
* Convenience Constructor of an ExternalForce.
*
* @param dataSource a storage containing the pertinent force data through time
* @param forceIdentifier string used to access the force data in the dataSource
* @param pointIdentifier string used to access the point of application of the force in dataSource
* @param torqueIdentifier string used to access the force data in the dataSource
* @param appliedToBodyName string used to specify the body to which the force is applied
* @param forceExpressedInBodyName string used to define in which body the force is expressed
* @param pointExpressedInBodyName string used to define the body in which the point is expressed
*/
ExternalForce(const Storage& dataSource,
const std::string& forceIdentifier="force",
const std::string& pointIdentifier="point",
const std::string& torqueIdentifier="torque",
const std::string& appliedToBodyName="",
const std::string& forceExpressedInBodyName="ground",
const std::string& pointExpressedInBodyName="ground");
explicit ExternalForce(SimTK::Xml::Element& aNode);
// Uses default (compiler-generated) destructor, copy constructor, copy
// assignment operator.
// Copy properties from XML into member variables
void updateFromXMLNode(SimTK::Xml::Element& aNode, int versionNumber=-1) override;
// ACCESS METHODS
/**
* Associate the data source from which the force, point and/or torque data
* is to be extracted.
*/
void setDataSource(const Storage& dataSource);
/** Get the name of the data source for the force data. **/
const std::string& getDataSourceName() const
{ return get_data_source_name(); }
/**
* Specify or obtain the body to which the force will be applied
*/
void setAppliedToBodyName(const std::string& applyToName)
{ set_applied_to_body(applyToName); }
const std::string& getAppliedToBodyName() const
{ return get_applied_to_body(); }
/**
* Specify or obtain the body in which the point of application is expressed
*/
void setPointExpressedInBodyName(const std::string& pointInBodyName)
{ set_point_expressed_in_body(pointInBodyName); }
const std::string& getPointExpressedInBodyName() const
{ return get_point_expressed_in_body(); }
/**
* Specify or obtain the body in which the force is expressed
*/
void setForceExpressedInBodyName(const std::string &forceInBodyName)
{ set_force_expressed_in_body(forceInBodyName); }
const std::string& getForceExpressedInBodyName() const
{ return get_force_expressed_in_body(); }
/**
* Identifiers
*/
void setForceIdentifier(const std::string aForceIdentifier)
{ set_force_identifier(aForceIdentifier); }
void setPointIdentifier(const std::string aPointIdentifier)
{ set_point_identifier(aPointIdentifier); }
void setTorqueIdentifier(const std::string aTorqueIdentifier)
{ set_torque_identifier(aTorqueIdentifier); }
const std::string& getForceIdentifier() const
{ return get_force_identifier(); }
const std::string& getPointIdentifier() const
{ return get_point_identifier(); }
const std::string& getTorqueIdentifier() const
{ return get_torque_identifier(); }
/**
* Convenience methods to access external forces at a given time
*/
SimTK::Vec3 getForceAtTime(double aTime) const;
SimTK::Vec3 getPointAtTime(double aTime) const;
SimTK::Vec3 getTorqueAtTime(double aTime) const;
/**
* Methods used for reporting.
* First identify the labels for individual components
*/
OpenSim::Array<std::string> getRecordLabels() const override;
/**
* Given SimTK::State object extract all the values necessary to report
* forces, application location frame, etc. used in conjunction with
* getRecordLabels and should return same size Array.
*/
OpenSim::Array<double> getRecordValues(const SimTK::State& state) const override;
/**
* Methods to query the force properties to find out if it's a body vs.
* point force and/or if it applies a torque.
*/
bool appliesForce() const {
if(getProperty_force_identifier().size() < 1)
return false;
const std::string &forceIdentifier = get_force_identifier();
return !((forceIdentifier.find_first_not_of(" \t")==std::string::npos)
|| (forceIdentifier == "Unassigned"));
}
bool specifiesPoint() const {
if(getProperty_point_identifier().size() < 1)
return false;
const std::string &pointIdentifier = get_point_identifier();
return !((pointIdentifier.find_first_not_of(" \t")==std::string::npos)
|| (pointIdentifier == "Unassigned"));
}
bool appliesTorque() const {
if(getProperty_torque_identifier().size() < 1)
return false;
const std::string &torqueIdentifier = get_torque_identifier();
return !((torqueIdentifier.find_first_not_of(" \t")==std::string::npos)
|| (torqueIdentifier == "Unassigned"));
}
protected:
/** ModelComponent interface */
void extendConnectToModel(Model& model) override;
/**
* Compute the force.
*/
void computeForce(const SimTK::State& state,
SimTK::Vector_<SimTK::SpatialVec>& bodyForces,
SimTK::Vector& generalizedForces) const override;
private:
void setNull();
void constructProperties();
//==============================================================================
// DATA
//==============================================================================
/** Pointer to the body that force is applied to */
SimTK::ReferencePtr<const PhysicalFrame> _appliedToBody;
/** Pointer to the body that force is expressed in */
SimTK::ReferencePtr<const PhysicalFrame> _forceExpressedInBody;
/** Pointer to the body that point is expressed in */
SimTK::ReferencePtr<const PhysicalFrame> _pointExpressedInBody;
/** Pointer to the data source owned by the caller/creator of this force.
Note that it is not a RefPtr because we want to point to the same data
source when the ExternalForce is copied, without copying the data. */
const Storage* _dataSource;
/** characterize the force/torque being applied */
bool _appliesForce;
bool _specifiesPoint;
bool _appliesTorque;
/** force data as a function of time used internally */
ArrayPtrs<Function> _forceFunctions;
ArrayPtrs<Function> _torqueFunctions;
ArrayPtrs<Function> _pointFunctions;
friend class ExternalLoads;
//==============================================================================
}; // END of class ExternalForce
//==============================================================================
//==============================================================================
} // end of namespace OpenSim
#endif // OPENSIM_EXTERNAL_FORCE_H_
| 45.596226 | 105 | 0.613176 | [
"object",
"vector",
"model"
] |
ae5140e324cca0527a5c636c1b6318b8ac3da0c7 | 6,151 | h | C | util/memory/segmented_string_pool.h | SitdikovRustam/CatBoost | 39fb9dfddb24e977ed87efc71063b03cd4bc8f16 | [
"Apache-2.0"
] | 33 | 2016-12-15T21:47:13.000Z | 2020-10-27T23:53:59.000Z | util/memory/segmented_string_pool.h | dsferz/machinelearning_yandex | 8fde8314c5c70299ece8b8f00075ddfcd5e07ddf | [
"Apache-2.0"
] | null | null | null | util/memory/segmented_string_pool.h | dsferz/machinelearning_yandex | 8fde8314c5c70299ece8b8f00075ddfcd5e07ddf | [
"Apache-2.0"
] | 14 | 2016-12-28T17:00:33.000Z | 2022-01-16T20:15:27.000Z | #pragma once
#include <util/system/align.h>
#include <util/system/yassert.h>
#include <util/system/defaults.h>
#include <util/generic/vector.h>
#include <util/generic/strbuf.h>
#include <memory>
#include <cstdio>
#include <cstdlib>
/*
* Non-reallocated storage for the objects of POD type
*/
template <class T, class Alloc = std::allocator<T>>
class segmented_pool {
protected:
using pointer = typename Alloc::pointer;
Alloc seg_allocator;
struct seg_inf {
pointer data; // allocated chunk
size_t _size; // size of allocated chunk in sizeof(T)-units
size_t freepos; // offset to free chunk's memory in bytes
seg_inf()
: data(nullptr)
, _size(0)
, freepos(0)
{
}
seg_inf(pointer d, size_t sz)
: data(d)
, _size(sz)
, freepos(0)
{
}
};
using seg_container = yvector<seg_inf>;
using seg_iterator = typename seg_container::iterator;
using seg_const_iterator = typename seg_container::const_iterator;
const size_t segment_size; // default size of a memory chunk in sizeof(T)-units
size_t last_free; // size of free memory in chunk in sizeof(T)-units
size_t last_ins_size; // size of memory used in chunk by the last append() in bytes
seg_container segs; // array of memory chunks
seg_iterator curseg; // a segment for the current insertion
const char* Name; // for debug memory usage
protected:
void check_capacity(size_t len) {
if (Y_UNLIKELY(!last_free || len > last_free)) {
if (curseg != segs.end() && curseg->freepos > 0)
++curseg;
last_free = (len > segment_size ? len : segment_size);
if (curseg == segs.end() || curseg->_size < last_free) {
segs.push_back(seg_inf(seg_allocator.allocate(last_free), last_free));
if (Y_UNLIKELY(Name))
printf("Pool \"%s\" was increased by %" PRISZT " bytes to %" PRISZT " Mb.\n", Name, last_free * sizeof(T), capacity() / 0x100000);
curseg = segs.end() - 1;
}
Y_ASSERT(curseg->freepos == 0);
Y_ASSERT(curseg->_size >= last_free);
}
}
public:
explicit segmented_pool(size_t segsz, const char* name = nullptr)
: segment_size(segsz)
, last_free(0)
, last_ins_size(0)
, Name(name)
{
curseg = segs.begin();
}
~segmented_pool() {
clear();
}
/* src - array of objects, len - count of elements in array */
T* append(const T* src, size_t len) {
check_capacity(len);
ui8* rv = (ui8*)curseg->data + curseg->freepos;
last_ins_size = sizeof(T) * len;
if (src)
memcpy(rv, src, last_ins_size);
curseg->freepos += last_ins_size, last_free -= len;
return (T*)rv;
}
T* append() {
T* obj = get_raw();
new (obj) T();
return obj;
}
T* get_raw() { // append(0, 1)
check_capacity(1);
ui8* rv = (ui8*)curseg->data + curseg->freepos;
last_ins_size = sizeof(T);
curseg->freepos += last_ins_size, last_free -= 1;
return (T*)rv;
}
size_t get_segment_size() const {
return segment_size;
}
bool contains(const T* ptr) const {
for (seg_const_iterator i = segs.begin(), ie = segs.end(); i != ie; ++i)
if ((char*)ptr >= (char*)i->data && (char*)ptr < (char*)i->data + i->freepos)
return true;
return false;
}
size_t size() const {
size_t r = 0;
for (seg_const_iterator i = segs.begin(); i != segs.end(); ++i)
r += i->freepos;
return r;
}
size_t capacity() const {
return segs.size() * segment_size * sizeof(T);
}
void restart() {
if (curseg != segs.end())
++curseg;
for (seg_iterator i = segs.begin(); i != curseg; ++i)
i->freepos = 0;
curseg = segs.begin();
last_free = 0;
last_ins_size = 0;
}
void clear() {
for (seg_iterator i = segs.begin(); i != segs.end(); ++i)
seg_allocator.deallocate(i->data, i->_size);
segs.clear();
curseg = segs.begin();
last_free = 0;
last_ins_size = 0;
}
void undo_last_append() {
Y_ASSERT(curseg != segs.end()); // do not use before append()
if (last_ins_size) {
Y_ASSERT(last_ins_size <= curseg->freepos);
curseg->freepos -= last_ins_size;
last_free += last_ins_size / sizeof(T);
last_ins_size = 0;
}
}
void alloc_first_seg() {
Y_ASSERT(capacity() == 0);
check_capacity(segment_size);
Y_ASSERT(capacity() == segment_size * sizeof(T));
}
Y_DISABLE_COPY(segmented_pool);
};
class segmented_string_pool: public segmented_pool<char> {
private:
using _Base = segmented_pool<char>;
public:
segmented_string_pool()
: segmented_string_pool(1024 * 1024)
{
}
explicit segmented_string_pool(size_t segsz)
: _Base(segsz)
{
}
char* append(const char* src) {
Y_ASSERT(src);
return _Base::append(src, strlen(src) + 1);
}
char* append(const char* src, size_t len) {
char* rv = _Base::append(nullptr, len + 1);
if (src)
memcpy(rv, src, len);
rv[len] = 0;
return rv;
}
char* Append(const TStringBuf s) {
return append(~s, +s);
}
void align_4() {
size_t t = (curseg->freepos + 3) & ~3;
last_free -= t - curseg->freepos;
curseg->freepos = t;
}
char* Allocate(size_t len) {
return append(nullptr, len);
}
Y_DISABLE_COPY(segmented_string_pool);
};
template <typename T, typename C>
inline T* pool_push(segmented_pool<C>& pool, const T* v) {
static_assert(sizeof(C) == 1, "only char type supported");
size_t len = SizeOf(v);
C* buf = pool.append(nullptr, AlignUp(len));
memcpy(buf, v, len);
return (T*)buf;
}
| 31.22335 | 150 | 0.560234 | [
"vector"
] |
ae5c488b956877c608d9f12d70f0acfda05ea4f8 | 14,807 | h | C | mapnikvt/src/mapnikvt/ExpressionGenerator.h | farfromrefug/mobile-carto-libs | c7e81a7c73661aa047de9ba7e8bbdf3a24bbf1df | [
"BSD-3-Clause"
] | null | null | null | mapnikvt/src/mapnikvt/ExpressionGenerator.h | farfromrefug/mobile-carto-libs | c7e81a7c73661aa047de9ba7e8bbdf3a24bbf1df | [
"BSD-3-Clause"
] | null | null | null | mapnikvt/src/mapnikvt/ExpressionGenerator.h | farfromrefug/mobile-carto-libs | c7e81a7c73661aa047de9ba7e8bbdf3a24bbf1df | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2016 CartoDB. All rights reserved.
* Copying and using this code is allowed only according
* to license terms, as given in https://cartodb.com/terms/
*/
#ifndef _CARTO_MAPNIKVT_EXPRESSIONGENERATOR_H_
#define _CARTO_MAPNIKVT_EXPRESSIONGENERATOR_H_
#include "Value.h"
#include "Expression.h"
#include "Predicate.h"
#include "ValueGenerator.h"
#include <memory>
#include <functional>
#include <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/karma_alternative.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_bind.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_function.hpp>
namespace carto { namespace mvt {
namespace exprgenimpl {
using Delimiter = boost::spirit::karma::iso8859_1::space_type;
template <typename OutputIterator, bool StringExpression>
struct Grammar : boost::spirit::karma::grammar<OutputIterator, Expression()> {
Grammar() : Grammar::base_type(StringExpression ? stringExpression : genericExpression) {
using namespace boost;
using namespace boost::spirit;
using karma::_pass;
using karma::_val;
using karma::_1;
using karma::_2;
using karma::_3;
string %=
karma::string
;
stringExpression =
string [_pass = phoenix::bind(&getString, _val, _1)]
| (stringExpression << stringExpression) [_pass = phoenix::bind(&getBinaryExpression, BinaryExpression::Op::CONCAT, _val, _1, _2)]
| ('[' << stringExpression << ']' ) [_pass = phoenix::bind(&getVariableExpression, _val, _1)]
| ('{' << karma::delimit(Delimiter())[expression << '}']) [_1 = _val]
;
genericExpression =
karma::delimit(Delimiter())[expression] [_1 = _val]
;
expression =
(term0 << '?' << expression << ':' << expression) [_pass = phoenix::bind(&getTertiaryExpression, TertiaryExpression::Op::CONDITIONAL, _val, _1, _2, _3)]
| term0 [_1 = _val]
;
term0 =
(term0 << "and" << term1) [_pass = phoenix::bind(&getAndPredicate, _val, _1, _2)]
| (term0 << "or" << term1) [_pass = phoenix::bind(&getOrPredicate, _val, _1, _2)]
| term1 [_1 = _val]
;
term1 =
(term1 << "<>" << term2) [_pass = phoenix::bind(&getComparisonPredicate, ComparisonPredicate::Op::NEQ, _val, _1, _2)]
| (term1 << "<=" << term2) [_pass = phoenix::bind(&getComparisonPredicate, ComparisonPredicate::Op::LTE, _val, _1, _2)]
| (term1 << ">=" << term2) [_pass = phoenix::bind(&getComparisonPredicate, ComparisonPredicate::Op::GTE, _val, _1, _2)]
| (term1 << "!=" << term2) [_pass = phoenix::bind(&getComparisonPredicate, ComparisonPredicate::Op::NEQ, _val, _1, _2)]
| (term1 << '<' << term2) [_pass = phoenix::bind(&getComparisonPredicate, ComparisonPredicate::Op::LT, _val, _1, _2)]
| (term1 << '>' << term2) [_pass = phoenix::bind(&getComparisonPredicate, ComparisonPredicate::Op::GT, _val, _1, _2)]
| (term1 << '=' << term2) [_pass = phoenix::bind(&getComparisonPredicate, ComparisonPredicate::Op::EQ, _val, _1, _2)]
| term2 [_1 = _val]
;
term2 =
(term2 << '+' << term3) [_pass = phoenix::bind(&getBinaryExpression, BinaryExpression::Op::ADD, _val, _1, _2)]
| (term2 << '-' << term3) [_pass = phoenix::bind(&getBinaryExpression, BinaryExpression::Op::SUB, _val, _1, _2)]
| term3 [_1 = _val]
;
term3 =
(term3 << '*' << unary) [_pass = phoenix::bind(&getBinaryExpression, BinaryExpression::Op::MUL, _val, _1, _2)]
| (term3 << '/' << unary) [_pass = phoenix::bind(&getBinaryExpression, BinaryExpression::Op::DIV, _val, _1, _2)]
| (term3 << '%' << unary) [_pass = phoenix::bind(&getBinaryExpression, BinaryExpression::Op::MOD, _val, _1, _2)]
| unary [_1 = _val]
;
unary =
('-' << unary) [_pass = phoenix::bind(&getUnaryExpression, UnaryExpression::Op::NEG, _val, _1)]
| ('!' << unary) [_pass = phoenix::bind(&getNotPredicate, _val, _1)]
| postfix [_1 = _val]
;
postfix =
(postfix << '.' << karma::lit("length")) [_pass = phoenix::bind(&getUnaryExpression, UnaryExpression::Op::LENGTH, _val, _1)]
| (postfix << '.' << karma::lit("uppercase")) [_pass = phoenix::bind(&getUnaryExpression, UnaryExpression::Op::UPPER, _val, _1)]
| (postfix << '.' << karma::lit("lowercase")) [_pass = phoenix::bind(&getUnaryExpression, UnaryExpression::Op::LOWER, _val, _1)]
| (postfix << '.' << karma::lit("capitalize")) [_pass = phoenix::bind(&getUnaryExpression, UnaryExpression::Op::CAPITALIZE, _val, _1)]
| (postfix << '.' << karma::lit("concat") << '(' << expression << ')') [_pass = phoenix::bind(&getBinaryExpression, BinaryExpression::Op::CONCAT, _val, _1, _2)]
| (postfix << '.' << karma::lit("match") << '(' << expression << ')') [_pass = phoenix::bind(&getComparisonPredicate, ComparisonPredicate::Op::MATCH, _val, _1, _2)]
| (postfix << '.' << karma::lit("replace") << '(' << expression << ',' << expression << ')') [_pass = phoenix::bind(&getTertiaryExpression, TertiaryExpression::Op::REPLACE, _val, _1, _2, _3)]
| factor [_1 = _val]
;
factor =
constant [_pass = phoenix::bind(&getConstant, _val, _1)]
| (karma::lit("pow" ) << '(' << expression << ',' << expression << ')') [_pass = phoenix::bind(&getBinaryExpression, BinaryExpression::Op::POW, _val, _1, _2)]
| (karma::lit("step") << '(' << expression << ',' << (constant % ',') << ')') [_pass = phoenix::bind(&getInterpolateExpression, InterpolateExpression::Method::STEP, _val, _1, _2)]
| (karma::lit("linear") << '(' << expression << ',' << (constant % ',') << ')') [_pass = phoenix::bind(&getInterpolateExpression, InterpolateExpression::Method::LINEAR, _val, _1, _2)]
| (karma::lit("cubic") << '(' << expression << ',' << (constant % ',') << ')') [_pass = phoenix::bind(&getInterpolateExpression, InterpolateExpression::Method::CUBIC, _val, _1, _2)]
| predicate [_pass = phoenix::bind(&getExpressionPredicate, _val, _1)]
| (karma::no_delimit['[' << stringExpression] << ']') [_pass = phoenix::bind(&getVariableExpression, _val, _1)]
| ('(' << expression << ')') [_1 = _val]
;
predicate =
expression [_pass = phoenix::bind(&getPredicateExpression, _val, _1)]
;
}
ValueGeneratorGrammar<OutputIterator> constant;
boost::spirit::karma::rule<OutputIterator, std::string()> string;
boost::spirit::karma::rule<OutputIterator, Expression()> stringExpression, genericExpression;
boost::spirit::karma::rule<OutputIterator, Expression(), Delimiter> expression, term0, term1, term2, term3, unary, postfix, factor;
boost::spirit::karma::rule<OutputIterator, Predicate(), Delimiter> predicate;
private:
static bool getString(const Expression& expr, std::string& str) {
if (auto val = std::get_if<Value>(&expr)) {
if (auto strVal = std::get_if<std::string>(val)) {
str = *strVal;
return true;
}
}
return false;
}
static bool getConstant(const Expression& expr, Value& val1) {
if (auto val = std::get_if<Value>(&expr)) {
val1 = *val;
return true;
}
return false;
}
static bool getExpressionPredicate(const Expression& expr, Predicate& pred1) {
if (auto pred = std::get_if<Predicate>(&expr)) {
pred1 = *pred;
return true;
}
return false;
}
static bool getVariableExpression(const Expression& expr, Expression& expr1) {
if (auto varExpr = std::get_if<std::shared_ptr<VariableExpression>>(&expr)) {
expr1 = (*varExpr)->getVariableExpression();
return true;
}
return false;
}
static bool getPredicateExpression(const Predicate& pred, Expression& expr1) {
if (auto exprPred = std::get_if<std::shared_ptr<ExpressionPredicate>>(&pred)) {
expr1 = (*exprPred)->getExpression();
return true;
}
return false;
}
static bool getNotPredicate(const Expression& expr, Expression& expr1) {
if (auto pred = std::get_if<Predicate>(&expr)) {
if (auto notPred = std::get_if<std::shared_ptr<NotPredicate>>(pred)) {
expr1 = (*notPred)->getPredicate();
return true;
}
}
return false;
}
static bool getOrPredicate(const Expression& expr, Expression& expr1, Expression& expr2) {
if (auto pred = std::get_if<Predicate>(&expr)) {
if (auto orPred = std::get_if<std::shared_ptr<OrPredicate>>(pred)) {
expr1 = (*orPred)->getPredicate1();
expr2 = (*orPred)->getPredicate2();
return true;
}
}
return false;
}
static bool getAndPredicate(const Expression& expr, Expression& expr1, Expression& expr2) {
if (auto pred = std::get_if<Predicate>(&expr)) {
if (auto andPred = std::get_if<std::shared_ptr<AndPredicate>>(pred)) {
expr1 = (*andPred)->getPredicate1();
expr2 = (*andPred)->getPredicate2();
return true;
}
}
return false;
}
static bool getComparisonPredicate(ComparisonPredicate::Op op, const Expression& expr, Expression& expr1, Expression& expr2) {
if (auto pred = std::get_if<Predicate>(&expr)) {
if (auto comparisonPred = std::get_if<std::shared_ptr<ComparisonPredicate>>(pred)) {
if ((*comparisonPred)->getOp() == op) {
expr1 = (*comparisonPred)->getExpression1();
expr2 = (*comparisonPred)->getExpression2();
return true;
}
}
}
return false;
}
static bool getUnaryExpression(UnaryExpression::Op op, const Expression& expr,Expression& expr1) {
if (auto unaryExpr = std::get_if<std::shared_ptr<UnaryExpression>>(&expr)) {
if ((*unaryExpr)->getOp() == op) {
expr1 = (*unaryExpr)->getExpression();
return true;
}
}
return false;
}
static bool getBinaryExpression(BinaryExpression::Op op, const Expression& expr, Expression& expr1, Expression& expr2) {
if (auto binaryExpr = std::get_if<std::shared_ptr<BinaryExpression>>(&expr)) {
if ((*binaryExpr)->getOp() == op) {
expr1 = (*binaryExpr)->getExpression1();
expr2 = (*binaryExpr)->getExpression2();
return true;
}
}
return false;
}
static bool getTertiaryExpression(TertiaryExpression::Op op, const Expression& expr, Expression& expr1, Expression& expr2, Expression& expr3) {
if (auto tertiaryExpr = std::get_if<std::shared_ptr<TertiaryExpression>>(&expr)) {
if ((*tertiaryExpr)->getOp() == op) {
expr1 = (*tertiaryExpr)->getExpression1();
expr2 = (*tertiaryExpr)->getExpression2();
expr3 = (*tertiaryExpr)->getExpression3();
return true;
}
}
return false;
}
static bool getInterpolateExpression(InterpolateExpression::Method method, const Expression& expr, Expression& timeExpr, std::vector<Value>& keyFrames) {
if (auto interpolateExpr = std::get_if<std::shared_ptr<InterpolateExpression>>(&expr)) {
if ((*interpolateExpr)->getMethod() == method) {
timeExpr = (*interpolateExpr)->getTimeExpression();
keyFrames = (*interpolateExpr)->getKeyFrames();
return true;
}
}
return false;
}
};
}
template <typename Iterator> using ExpressionGeneratorGrammar = exprgenimpl::Grammar<Iterator, false>;
template <typename Iterator> using StringExpressionGeneratorGrammar = exprgenimpl::Grammar<Iterator, true>;
} }
#endif
| 55.25 | 211 | 0.489836 | [
"vector"
] |
e280b269cda6342ea99d0d39d428cf278beb3719 | 4,655 | h | C | lib/Basics/ResourceUsage.h | elfringham/arangodb | 5baaece1c7a5ce73fe016f07ed66255cc555e8cb | [
"BSL-1.0",
"Apache-2.0"
] | 12,278 | 2015-01-29T17:11:33.000Z | 2022-03-31T21:12:00.000Z | lib/Basics/ResourceUsage.h | elfringham/arangodb | 5baaece1c7a5ce73fe016f07ed66255cc555e8cb | [
"BSL-1.0",
"Apache-2.0"
] | 9,469 | 2015-01-30T05:33:07.000Z | 2022-03-31T16:17:21.000Z | lib/Basics/ResourceUsage.h | elfringham/arangodb | 5baaece1c7a5ce73fe016f07ed66255cc555e8cb | [
"BSL-1.0",
"Apache-2.0"
] | 892 | 2015-01-29T16:26:19.000Z | 2022-03-20T07:44:30.000Z | ////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2021 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "Basics/Common.h"
#include "Basics/NumberUtils.h"
#include <atomic>
#include <cstdint>
namespace arangodb {
class GlobalResourceMonitor;
struct alignas(64) ResourceMonitor final {
/// @brief: granularity of allocations that we track. this should be a
/// power of 2, so dividing by it is efficient!
/// note: whatever this value is, it will also dictate the minimum granularity
/// of the global memory usage counter, plus the granularity for each query's
/// peak memory usage value.
/// note: if you adjust this value, keep in mind that making the chunk size
/// smaller will lead to better granularity, but also will increase the number
/// of atomic updates we need to make inside increaseMemoryUsage() and
/// decreaseMemoryUsage().
static constexpr std::uint64_t chunkSize = 32768;
static_assert(NumberUtils::isPowerOfTwo(chunkSize));
ResourceMonitor(ResourceMonitor const&) = delete;
ResourceMonitor& operator=(ResourceMonitor const&) = delete;
explicit ResourceMonitor(GlobalResourceMonitor& global) noexcept;
~ResourceMonitor();
/// @brief sets a memory limit
void memoryLimit(std::uint64_t value) noexcept;
/// @brief returns the current memory limit
std::uint64_t memoryLimit() const noexcept;
/// @brief increase memory usage by <value> bytes. may throw!
void increaseMemoryUsage(std::uint64_t value);
/// @brief decrease memory usage by <value> bytes. will not throw
void decreaseMemoryUsage(std::uint64_t value) noexcept;
/// @brief return the current memory usage of the instance
std::uint64_t current() const noexcept;
/// @brief return the peak memory usage of the instance
std::uint64_t peak() const noexcept;
/// @brief reset counters for the local instance
void clear() noexcept;
/// @brief calculate the "number of chunks" used by an allocation size.
/// for this, we simply divide the size by a constant value, which is large
/// enough so that many subsequent small allocations mostly fall into the
/// same chunk.
static constexpr std::int64_t numChunks(std::uint64_t value) noexcept {
// this is intentionally an integer division, which truncates any remainders.
// we want this to be fast, so chunkSize should be a power of 2 and the div
// operation can be substituted by a bit shift operation.
static_assert(chunkSize != 0);
static_assert(NumberUtils::isPowerOfTwo(chunkSize));
return static_cast<std::int64_t>(value / chunkSize);
}
private:
std::atomic<std::uint64_t> _current;
std::atomic<std::uint64_t> _peak;
std::uint64_t _limit;
GlobalResourceMonitor& _global;
};
/// @brief RAII object for temporary resource tracking
/// will track the resource usage on creation, and untrack it
/// on destruction, unless the responsibility is stolen
/// from it.
class ResourceUsageScope {
public:
ResourceUsageScope(ResourceUsageScope const&) = delete;
ResourceUsageScope& operator=(ResourceUsageScope const&) = delete;
explicit ResourceUsageScope(ResourceMonitor& resourceMonitor) noexcept;
/// @brief track <value> bytes of memory, may throw!
explicit ResourceUsageScope(ResourceMonitor& resourceMonitor, std::uint64_t value);
~ResourceUsageScope();
/// @brief steal responsibility for decreasing the memory
/// usage on destruction
void steal() noexcept;
/// @brief revert all memory usage tracking operations in this scope
void revert() noexcept;
/// @brief track <value> bytes of memory, may throw!
void increase(std::uint64_t value);
void decrease(std::uint64_t value) noexcept;
private:
ResourceMonitor& _resourceMonitor;
std::uint64_t _value;
};
} // namespace arangodb
| 35.807692 | 85 | 0.70956 | [
"object"
] |
e28fbf0d9edd78f7527f0e334fe3337fd6928c83 | 11,559 | h | C | src/shmfw/vector.h | ShmFw/shmfw | d386841f8b1425cbeca8c8a3fc6919bf8d83c38e | [
"BSD-3-Clause"
] | 1 | 2016-02-06T14:57:32.000Z | 2016-02-06T14:57:32.000Z | src/shmfw/vector.h | ShmFw/shmfw | d386841f8b1425cbeca8c8a3fc6919bf8d83c38e | [
"BSD-3-Clause"
] | null | null | null | src/shmfw/vector.h | ShmFw/shmfw | d386841f8b1425cbeca8c8a3fc6919bf8d83c38e | [
"BSD-3-Clause"
] | 1 | 2018-11-07T02:45:24.000Z | 2018-11-07T02:45:24.000Z | /***************************************************************************
* Software License Agreement (BSD License) *
* Copyright (C) 2012 by Markus Bader <markus.bader@tuwien.ac.at> *
* *
* 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. *
***************************************************************************/
#ifndef SHARED_MEM_VECTOR_H
#define SHARED_MEM_VECTOR_H
#include <shmfw/header.h>
#include <boost/interprocess/containers/vector.hpp>
namespace ShmFw {
/// Class to manage a shared vectors
template<typename T>
class Vector : public Header {
friend class boost::serialization::access;
typedef bi::vector<T, Allocator<T> > VectorShm;
typedef typename Allocator<T>::size_type size_type;
VectorShm *data_element;
public:
/** Default constructor
* @post Vector::construct
**/
Vector() : data_element ( NULL ) {
}
/** Constructor
* @param name name of the variable
* @param shmHdl pointer to the shared memory segment
* @pre the ShmPtr poitner must be created first
* @see ShmFw::createSegment
**/
Vector ( const std::string &name, HandlerPtr &shmHdl ) : data_element ( NULL ) {
if ( construct ( name, shmHdl ) == ERROR ) exit ( 1 );
}
/**
* @param shm_instance_name name of the shared header element in the memory segment
* @param shmHdl pointer to the shared memory segment handler
* @param data on NULL the fnc will an anonymous instance otherwise this data will be linked to the shared header
* @pre the ShmPtr poitner must be created first
* @see ShmFw::createSegment
**/
int construct ( const std::string &shm_instance_name, HandlerPtr &shmHdl, boost::interprocess::offset_ptr<T> data = NULL ) {
#if __cplusplus > 199711L
size_t type_hash_code = typeid ( Vector<T> ).hash_code();
const char *type_name = typeid ( Vector<T> ).name();
#else
size_t type_hash_code = 0;
const char *type_name = typeid ( Vector<T> ).name();
#endif
if ( constructHeader ( shm_instance_name, shmHdl, type_name, type_hash_code ) == ERROR ) return ERROR;
if ( header_local.creator ) {
/// constructing shared data
try {
ScopedLock myLock ( header_shared->mutex );
header_shared->container = ShmFw::Header::CONTAINER_VECTOR;
Allocator<T> a ( header_local.shm_handler->getShm()->get_segment_manager() );
if ( data ) {
header_shared->data = data;
} else {
header_shared->data = header_local.shm_handler->getShm()->construct< VectorShm > ( bi::anonymous_instance ) ( a );
}
} catch ( ... ) {
std::cerr << "Error when constructing shared data" << std::endl;
return ERROR;
}
}
data_element = ( VectorShm* ) header_shared->data.get();
return OK;
}
/** UNSAVE!! (user have to lock and to update timestamp)
* returns a pointer to the shared object
* @return ref to shared data
**/
VectorShm *get() {
return data_element;
}
/** UNSAVE!! (user have to lock and to update timestamp)
* returns a pointer to the shared object
* @return ref to shared data
**/
const VectorShm *get() const {
return data_element;
}
/** UNSAVE!! (user have to lock and to update timestamp)
* returns a pointer to the shared object
* @return ref to shared data
**/
VectorShm *operator->() {
return get();
}
/** UNSAVE!! (user have to lock and to update timestamp)
* returns a pointer to the shared object
* @return ref to shared data
**/
const VectorShm *operator->() const {
return get();
}
/** UNSAVE!! (user have to lock and to update timestamp)
* returns a reference to the shared object
* @return ref to shared data
**/
VectorShm &operator*() {
return *get();
}
/** UNSAVE!! (user have to lock and to update timestamp)
* returns a reference to the shared object
* @return ref to shared data
**/
const VectorShm &operator*() const {
return *get();
}
/** UNSAVE!! (user have to lock and to update timestamp)
* returns a reference to the shared vector object by index
* @return ref to shared data
**/
const T &operator [] ( size_type n ) const {
return ( *get() ) [n];
}
/** UNSAVE!! (user have to lock and to update timestamp)
* returns a reference to the shared vector object by index
* @return ref to shared data
**/
T &operator [] ( size_type n ) {
return ( *get() ) [n];
}
/** SAVE ACCESS :-) (the function will to the lock and the timstamp stuff)
* copies data to the shared variable and updated the timestamps and locks the variable while accessing
* @param src source vector
**/
void set ( const std::vector<T> &src ) {
lock();
get()->resize ( src.size() );
for ( size_t i = 0; i < src.size(); i++ ) {
( *get() ) [i] = src[i];
}
unlock();
itHasChanged();
}
/** SAVE ACCESS :-) (the function will to the lock and the timstamp stuff)
* copies data to the shared vector index and updated the timestamps and locks the variable while accessing
* @param src source vector
* @param n index
**/
void set ( const T &src, size_type n ) {
lock();
( *get() ) [n] = src;
unlock();
itHasChanged();
}
/** SAVE ACCESS :-) (the function will to the lock and the timstamp stuff)
* copies data form the shared variable into a local varaiable and sets local timestamps and locks the variable while accessing
* @param des
* @return copy of the shared timestamp
**/
bp::ptime get ( std::vector<T> &des ) {
lock();
bp::ptime t = timestampShm();;
des.resize ( get()->size() );
for ( size_t i = 0; i < des.size(); i++ ) {
des[i] = ( *get() ) [i];
}
unlock();
updateTimestampLocal();
return t;
}
/** SAVE ACCESS :-) (the function will to the lock and the timstamp stuff)
* copies data form the shared vetor index into a local varaiable and sets local timestamps and locks the variable while accessing
* @param des
* @return copy of the shared timestamp
**/
bp::ptime get ( T &des, size_type n ) {
lock();
bp::ptime t = timestampShm();;
des = ( *get() ) [n];
unlock();
updateTimestampLocal();
return t;
}
/** UNSAVE!! (user have to lock and to update timestamp)
* @return vetor size
**/
size_t size() const {
return get()->size();
}
/** UNSAVE!! (user have to lock and to update timestamp)
* @return Returns true if the vector contains no elements
**/
bool empty() const {
return get()->empty();
}
/** UNSAVE!! (user have to lock and to update timestamp)
* Inserts or erases elements at the end such that the size becomes n. New elements are default constructed.
**/
void resize ( size_t n ) {
get()->resize ( n );
}
/** UNSAVE!! (user have to lock and to update timestamp)
* Inserts or erases elements at the end such that the size becomes n. New elements are default constructed.
**/
void resize ( size_t n, const T& v ) {
get()->resize ( n, v );
}
/** UNSAVE!! (user have to lock and to update timestamp)
* If n is less than or equal to capacity(), this call has no effect.
* Otherwise, it is a request for allocation of additional memory.
**/
void reserve ( size_t n ) {
get()->reserve ( n );
}
/** UNSAVE!! (user have to lock and to update timestamp)
* Removes all elements from the vector (which are destroyed), leaving the container with a size of 0.
**/
void clear () {
get()->clear ( );
}
/** UNSAVE!! (user have to lock and to update timestamp)
* destroies the shared memory
* @ToDo
**/
virtual void destroy() const {
// header_local.shm_handler->getShm()->destroy_ptr(data_local.ptr);
// Header::destroy();
std::cerr << "vector::destroy() -> kown to have problem!" << std::endl;
};
/** UNSAVE!! (user have to lock and to update timestamp)
* @param o vector for comparison
**/
template<typename T1>
bool operator == ( const T1 &o ) const {
if ( size() != o.size() ) return false;
return ( memcmp ( & ( *get() ) [0], &o[0], size() ) == 0 );
//for ( size_t i = 0; i < size(); i++ ) if ( at ( i ) != o[i] ) return false;
//return true;
}
/** UNSAVE!! (user have to lock and to update timestamp)
* @param o vector for comparison
**/
template<typename T1>
bool operator != ( const T1 &o ) const {
if ( size() != o.size() ) return true;
return ( memcmp ( & ( *get() ) [0], &o[0], size() ) != 0 );
}
/**
* overloads the << and calls the varalible overloades operator
**/
friend std::ostream &operator << ( std::ostream &os, const Vector<T> &o ) {
for ( size_t i = 0; i < o.size(); i++ ) {
os << ( i==0?"[":" " ) << o[i] << ( ( i<o.size()-1 ) ?", ":"]" );
}
return os;
}
};
};
#endif //SHARED_MEM_VECTOR_H
| 39.858621 | 135 | 0.56536 | [
"object",
"vector"
] |
e2a361d4181c10838fb323afa0f73fd37b7ff881 | 21,298 | h | C | include/gravity/constant.h | mikiec84/Gravity | 863a30445ca0d29ccf8c4814fc0c099d1b75e7da | [
"BSD-3-Clause"
] | null | null | null | include/gravity/constant.h | mikiec84/Gravity | 863a30445ca0d29ccf8c4814fc0c099d1b75e7da | [
"BSD-3-Clause"
] | null | null | null | include/gravity/constant.h | mikiec84/Gravity | 863a30445ca0d29ccf8c4814fc0c099d1b75e7da | [
"BSD-3-Clause"
] | null | null | null | //
// Created by Hassan on 19/11/2015.
//
#ifndef GRAVITY_CONSTANT_H
#define GRAVITY_CONSTANT_H
#include <iostream>
#include <iomanip>
#include <vector>
#include <forward_list>
#include <assert.h>
#include <string>
#include <map>
#include <complex>
#include <memory>
#include <typeinfo>
#include <typeindex>
#include <limits>
#include <gravity/types.h>
#include <gravity/utils.h>
using namespace std;
namespace gravity {
class param_;
class func_;
template<typename T=double> class func;
/**
Transform a scalar to a string with user-specified precision.
@param[in] a_value number to be transformed.
@param[in] n number of decimals in transformation.
@return a string with the specified precision.
*/
template<class T, class = typename enable_if<is_arithmetic<T>::value>::type>
string to_string_with_precision(const T a_value, const int n)
{
std::ostringstream out;
if(std::is_same<T,bool>::value && a_value==numeric_limits<T>::lowest()){
return "0";
}
if(std::is_same<T,bool>::value && a_value==numeric_limits<T>::max()){
return "1";
}
if(std::numeric_limits<T>::is_specialized && a_value==numeric_limits<T>::max()){
return "+∞";
}
if(std::numeric_limits<T>::is_specialized && a_value==numeric_limits<T>::lowest()){
return "−∞";
}
if(std::numeric_limits<T>::is_specialized && a_value==numeric_limits<T>::max()){
return "+∞";
}
out << std::setprecision(n) << a_value;
return out.str();
}
/**
Transform a complex number to a string with user-specified precision.
@param[in] a_value complex number to be transformed.
@param[in] n number of decimals in transformation.
@return a string with the specified precision.
*/
string to_string_with_precision(const Cpx& a_value, const int n);
/** Backbone class for constant */
class constant_{
public:
CType _type; /**< Constant type: { binary_c, short_c, integer_c, float_c, double_c, long_c, complex_c, par_c, uexp_c, bexp_c, var_c, func_c}*/
void set_type(CType type){ _type = type;}
bool _is_transposed = false; /**< True if the constant is transposed */
bool _is_vector = false; /**< True if the constant is a vector or matrix */
size_t _dim[2] = {1,1}; /*< dimension of current object */
bool _polar = false; /**< True in case this is a complex number with a polar representation, rectangular representation if false */
virtual ~constant_(){};
CType get_type() const { return _type;}
/** Querries */
bool is_binary() const{
return (_type==binary_c);
};
bool is_short() const{
return (_type==short_c);
}
bool is_integer() const{
return (_type==integer_c);
};
bool is_float() const{
return (_type==float_c);
};
bool is_double() const{
return (_type==double_c);
};
bool is_long() const{
return (_type==long_c);
};
bool is_complex() const{
return (_type==complex_c);
};
virtual void eval_all() {};
virtual bool func_is_number() const{return is_number();};
virtual bool is_number() const{
return (_type!=par_c && _type!=uexp_c && _type!=bexp_c && _type!=var_c && _type!=func_c);
}
bool is_param() const{
return (_type==par_c);
};
/**
@return true if current object is a unitary expression.
*/
bool is_uexpr() const{
return (_type==uexp_c);
};
/**
@return true if current object is a binary expression.
*/
bool is_bexpr() const{
return (_type==bexp_c);
};
/**
@return true if current object is a unitary or binary expression.
*/
bool is_expr() const{
return (_type==uexp_c || _type==bexp_c);
};
bool is_var() const{
return (_type==var_c);
};
bool is_matrix() const{
return (_dim[0]>1 && _dim[1]>1);
}
bool is_function() const{
return (_type==func_c);
};
virtual void update_double_index() {};
virtual Sign get_all_sign() const {return unknown_;};
virtual Sign get_sign(size_t idx=0) const{return unknown_;};
/** Memory allocation */
virtual void allocate_mem(){};/*<< allocates memory for current and all sub-functions */
/** Dimension propagation */
virtual void propagate_dim(size_t){};/*<< Set dimensions to current and all sub-functions */
virtual bool is_evaluated() const{return false;};
virtual void evaluated(bool val){};
virtual void reverse_sign(){};/*<< reverses the sign of current object */
virtual size_t get_dim(size_t i) const {
if (i>1) {
return _dim[0];
throw invalid_argument("In function: size_t constant_::get_dim(size_t i) const, i is out of range!\n");
}
return _dim[i];
}
/**
Returns a copy of the current object, detecting the right class, i.e., param, var, func...
@return a shared pointer with a copy of the current object
*/
virtual shared_ptr<constant_> copy() const{return nullptr;};
virtual void relax(const map<size_t, shared_ptr<param_>>& vars){};
virtual void print(){};
virtual void uneval(){};
virtual string to_str() {return string();};
virtual string to_str(int prec) {return string();};
virtual string to_str(size_t idx, int prec) {return string();};
virtual string to_str(size_t idx1, size_t idx2, int prec) {return string();};
size_t get_dim() const {
size_t dim = _dim[0];
if(_dim[1]>0){
dim*= _dim[1];
}
return dim;
}
void vec(){
_is_vector = true;
}
virtual void transpose(){
_is_transposed = !_is_transposed;
_is_vector = true;
auto temp = _dim[0];
_dim[0] = _dim[1];
_dim[1] = temp;
}
/**
Update the dimensions of current object after it is multiplied with c2.
@param[in] c2 object multiplying this.
*/
void update_dot_dim(const constant_& c2){
update_dot_dim(*this, c2);
}
bool is_row_vector() const{
return _dim[0]==1 && _dim[1]>1;
}
bool is_column_vector() const{
return _dim[1]==1 && _dim[0]>1;
}
bool is_scalar() const{
return !_is_vector && _dim[0]==1 && _dim[1]==1;
}
/**
Update the dimensions of current object to correspond to c1.c2.
@param[in] c1 first element in product.
@param[in] c2 second element in product.
*/
void update_dot_dim(const constant_& c1, const constant_& c2){
/* If c2 is a scalar or if multiplying a matrix with a row vector */
if(c2.is_scalar() || (c1.is_matrix() && c2.is_row_vector())){
_dim[0] = c1._dim[0];
_dim[1] = c1._dim[1];
_is_vector = c1._is_vector;
_is_transposed = c1._is_transposed;
return;
}
/* If c1 is a scalar or if multiplying a row vector with a matrix */
else if(c1.is_scalar() || (c2.is_matrix() && c1.is_column_vector())){
_dim[0] = c2._dim[0];
_dim[1] = c2._dim[1];
_is_vector = c2._is_vector;
_is_transposed = c2._is_transposed;
return;
}
/* Both c1 and c2 are non-scalars */
/* If it is a dot product */
if(c1.is_row_vector() && c2.is_column_vector()){ /* c1^T.c2 */
if(!c1.is_double_indexed() && !c2.is_double_indexed() && c1._dim[1]!=c2._dim[0]){
throw invalid_argument("Dot product with mismatching dimensions");
}
_is_transposed = false;/* The result of a dot product is not transposed */
}
else if(c1.is_row_vector() && c2.is_row_vector()){
_is_transposed = true;/* this is a term-wise product of transposed vectors */
}
_dim[0] = c1._dim[0];
_dim[1] = c2._dim[1];
if(get_dim()==1){
_is_vector = false;
}
}
/**
Sets the object dimension to the maximum dimension among all arguments.
@param[in] p1 first element in list.
@param[in] ps remaining elements in list.
*/
template<typename... Args>
void set_max_dim(const constant_& p1, Args&&... ps){
_dim[0] = max(_dim[0], p1._dim[0]);
list<constant_*> list = {forward<constant_*>((constant_*)&ps)...};
for(auto &p: list){
_dim[0] = max(_dim[0], p->_dim[0]);
}
}
virtual bool is_double_indexed() const{return false;};
virtual bool is_constant() const{return false;};
virtual bool is_zero() const{return false;}; /**< Returns true if constant equals 0 */
virtual bool is_unit() const{return false;}; /**< Returns true if constant equals 1 */
virtual bool is_neg_unit() const{return false;}; /**< Returns true if constant equals -1 */
virtual bool is_positive() const{return false;}; /**< Returns true if constant is positive */
virtual bool is_negative() const{return false;}; /**< Returns true if constant is negative */
virtual bool is_non_positive() const{return false;}; /**< Returns true if constant is non positive */
virtual bool is_non_negative() const{return false;}; /**< Returns true if constant is non negative */
};
/** Polymorphic class constant, can store an arithmetic or a complex number.*/
template<typename type = double>
class constant: public constant_{
public:
type _val;/**< value of current constant */
template<class T, typename enable_if<is_arithmetic<T>::value>::type* = nullptr>
T zero(){
return (T)(0);
}
template<class T, typename enable_if<is_same<T, Cpx>::value>::type* = nullptr>
T zero(){
return Cpx(0,0);
}
/** Constructors */
void update_type(){
if(typeid(type)==typeid(bool)){
set_type(binary_c);
return;
}
if(typeid(type)==typeid(short)) {
set_type(short_c);
return;
}
if(typeid(type)==typeid(int)) {
set_type(integer_c);
return;
}
if(typeid(type)==typeid(float)) {
set_type(float_c);
return;
}
if(typeid(type)==typeid(double)) {
set_type(double_c);
return;
}
if(typeid(type)==typeid(long double)) {
set_type(long_c);
return;
}
if(typeid(type)==typeid(complex<double>)) {
set_type(complex_c);
return;
}
throw invalid_argument("Unknown constant type.");
}
constant(){
_val = zero<type>();
update_type();
}
~constant(){};
constant& operator=(const constant& c) {
_type = c._type;
_is_transposed = c._is_transposed;
_is_vector = c._is_vector;
_val = c._val;
return *this;
}
template<class T2, typename std::enable_if<is_convertible<T2, type>::value && sizeof(T2) < sizeof(type)>::type* = nullptr>
constant& operator=(const constant<T2>& c) {
update_type();
_is_transposed = c._is_transposed;
_is_vector = c._is_vector;
_val = c._val;
return *this;
}
template<class T2, typename std::enable_if<is_convertible<T2, type>::value && sizeof(T2) < sizeof(type)>::type* = nullptr>
constant(const constant<T2>& c){ /**< Copy constructor */
*this = c;
};
constant(const constant& c){ /**< Copy constructor */
*this = c;
};
shared_ptr<constant_> copy() const{return make_shared<constant>(*this);};
constant(const type& val):constant(){
_val = val;
};
shared_ptr<pair<type,type>> range() const{
return make_shared<pair<type,type>>(_val,_val);
}
constant tr() const{
auto newc(*this);
newc.transpose();
return newc;
};
type eval() const { return _val;}
void set_val(type val) {
_val = val;
}
void reverse_sign(){
_val *= -1;
}
Sign get_all_sign() const {return get_sign();};
Sign get_sign(size_t idx = 0) const{
return get_sign_();
}
template<class T=type, class = typename enable_if<is_same<T, Cpx>::value>::type> Sign get_sign_() const{
if (_val == Cpx(0,0)) {
return zero_;
}
if ((_val.real() < 0 && _val.imag() < 0)) {
return neg_;
}
if ((_val.real() > 0 && _val.imag() > 0)) {
return pos_;
}
if (_val.real() >= 0 && _val.imag() >= 0) {
return non_neg_;
}
if (_val.real() <= 0 && _val.imag() <= 0) {
return non_pos_;
}
return unknown_;
}
template<typename T=type,
typename std::enable_if<is_arithmetic<T>::value>::type* = nullptr> Sign get_sign_() const{
if (_val==0) {
return zero_;
}
if (_val > 0) {
return pos_;
}
if (_val < 0) {
return neg_;
}
return unknown_;
}
/** Operators */
bool is_zero() const { return zero_val();};
template<class T=type, class = typename enable_if<is_same<T, Cpx>::value>::type> bool zero_val() const{
return (_val == Cpx(0,0));
}
template<typename T=type,
typename std::enable_if<is_arithmetic<T>::value>::type* = nullptr> bool zero_val() const{
return (_val == 0);
}
bool is_unit() const{
return unit_val();
}
template<class T=type, class = typename enable_if<is_same<T, Cpx>::value>::type> bool unit_val() const{
return (!_is_vector && _val == Cpx(1,0));
}
template<typename T=type,
typename std::enable_if<is_arithmetic<T>::value>::type* = nullptr> bool unit_val() const{
return (!_is_vector && _val == 1);
}
bool is_negative() const {
return get_sign()==neg_;
}
bool is_non_negative() const {
return (get_sign()==zero_||get_sign()==pos_||get_sign()==non_neg_);
}
bool is_non_positive() const {
return (get_sign()==zero_||get_sign()==neg_||get_sign()==non_pos_);
}
bool is_positive() const {
return get_sign()==pos_;
}
bool operator==(const constant& c) const {
return (_type==c._type && _val==c._val);
}
bool operator==(const type& v) const{
return _val==v;
}
constant& operator=(const type& val){
_val = val;
return *this;
}
constant& operator+=(const type& v){
_val += v;
return *this;
}
constant& operator-=(const type& v){
_val -= v;
return *this;
}
constant& operator*=(const type& v){
_val *= v;
return *this;
}
constant& operator/=(const type& v){
_val /= v;
return *this;
}
friend constant operator+(const constant& c1, const constant& c2){
return constant(c1._val + c2._val);
}
friend constant operator-(const constant& c1, const constant& c2){
return constant(c1._val - c2._val);
}
friend constant operator/(const constant& c1, const constant& c2){
return constant(c1._val / c2._val);
}
friend constant operator*(const constant& c1, const constant& c2){
return constant(c1._val * c2._val);
}
friend constant operator^(const constant& c1, const constant& c2){
return constant(pow(c1._val,c2._val));
}
friend constant operator+(const constant& c, type cst){
return constant(c._val + cst);
}
friend constant operator-(const constant& c, type cst){
return constant(c._val - cst);
}
friend constant operator*(const constant& c, type cst){
return constant(c._val * cst);
}
friend constant operator/(const constant& c, type cst){
return constant(c._val / cst);
}
friend constant operator+(type cst, const constant& c){
return constant(c._val + cst);
}
friend constant operator-(type cst, const constant& c){
return constant(cst - c._val);
}
friend constant operator*(type cst, const constant& c){
return constant(c._val * cst);
}
friend constant operator/(type cst, const constant& c){
return constant(cst / c._val);
}
friend constant cos(const constant& c){
return constant(cos(c._val));
}
friend constant sin(const constant& c){
return constant(sin(c._val));
}
friend constant sqrt(const constant& c){
return constant(sqrt(c._val));
}
friend constant expo(const constant& c){
return constant(exp(c._val));
}
friend constant log(const constant& c){
return constant(log(c._val));
}
/** Output */
void print(){
cout << to_str(10);
}
void print(int prec) {
cout << to_str(prec);
}
void println(int prec = 10) {
cout << to_str(prec) << endl;
}
string to_str() {
return to_string_with_precision(_val,5);
}
string to_str(int prec = 10) {
return to_string_with_precision(_val,prec);
}
string to_str(size_t index, int prec = 10) {
return to_string_with_precision(_val,prec);
}
};
/**
Returns the conjugate of cst.
@param[in] cst complex number.
@return the conjugate of cst.
*/
constant<Cpx> conj(const constant<Cpx>& cst);
constant<double> real(const constant<Cpx>& cst);
constant<double> imag(const constant<Cpx>& cst);
/**
Returns the square magnitude of cst.
@param[in] cst complex number.
@return the square magnitude of cst.
*/
constant<double> sqrmag(const constant<Cpx>& cst);
constant<double> angle(const constant<Cpx>& cst);
template<class T, typename enable_if<is_arithmetic<T>::value>::type* = nullptr>
constant<T> unit(){
return constant<T>(1);
}
template<class T, typename enable_if<is_same<T, Cpx>::value>::type* = nullptr>
constant<T> unit(){
return constant<T>(Cpx(1,0));
}
template<class T, typename enable_if<is_arithmetic<T>::value>::type* = nullptr>
constant<T> zero(){
return constant<T>(0);
}
template<class T, typename enable_if<is_same<T, Cpx>::value>::type* = nullptr>
constant<T> zero(){
return constant<T>(Cpx(0,0));
}
}
#endif //GRAVITY_CONSTANT_H
| 31.64636 | 176 | 0.506526 | [
"object",
"vector",
"transform"
] |
e2a728c4db74a63cfe3a6cd0bcf1ebb36fffed3b | 9,583 | h | C | src/server/plugins/fastcgi/fastcgistub.h | jvirkki/heliod | efdf2d105e342317bd092bab2d727713da546174 | [
"BSD-3-Clause"
] | 13 | 2015-10-09T05:59:20.000Z | 2021-11-12T10:38:51.000Z | src/server/plugins/fastcgi/fastcgistub.h | JamesLinus/heliod | efdf2d105e342317bd092bab2d727713da546174 | [
"BSD-3-Clause"
] | null | null | null | src/server/plugins/fastcgi/fastcgistub.h | JamesLinus/heliod | efdf2d105e342317bd092bab2d727713da546174 | [
"BSD-3-Clause"
] | 6 | 2016-05-23T10:53:29.000Z | 2019-12-13T17:57:32.000Z | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2008 Sun Microsystems, Inc. All rights reserved.
*
* THE BSD LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* File: Fastcgistub.h
*
* Description:
*
* This header file defines the internal message layouts
* used between the child stub processes and the child
* stub API library.
*
* NOTE: This header file is not intended for use by upper level
* applications; please use cstubapi.h.
*
* Contact: Seema Alevoor (seema.alevoor@nsun.com) 10Sep04
*/
#ifndef __FASTCGISTUB_H__
#define __FASTCGISTUB_H__
#include "constants.h"
#include "fcgiprocess.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
* A Note on the child stub processing subsystem
*
* the child stub process subsystem consists of a single executable
* that runs in three modes:
*
* There is, initially and until it's stdin is closed/hung up on, a
* 'listener' process that manages an IPC socket (AF_UNIX domain)
* awaiting connections from other processes. The listener gets
* started, binds a AF_UNIX domain socket to the default name or
* the name passed to it in it's initial args, and sends back
* an OKMSG to STDIN when it's ready to accept connections. Note
* that as soon as stdin to the listener is closed, the listener goes
* away; it's intended that the listener pipe be kept open.
*
* Secondly, there are a series of concurrent processes that get started
* following a 'connect' to the 'listen' socket. Each of these processes
* await a request, as described in the RequestHeader layout below, to
* start a subprocess. Each of these processes read the connected AF_UNIX
* socket (the request pipe), awaiting a request, processing the
* request (by fork()ing itself) and responding with a response message.
* Note that requests will be serially processed; a start_response
* will be generated upon complete processing of a start_request.
* There is no support in the application protocol for interleaving
* requests and responses to a single child; concurrency should be
* managed by having multiple request pipes (ie, multiple 'connect()s'
* being done to the bound AF_UNIX socket).
* One more important note: the start RESPONSE message coming back
* also comes back with the stdin and stdout FDs of (stream) socketpairs;
* in order to obtain these 2 fds, the caller MUST use the recvmsg()
* call. Use of normal read/recv on the request pipes will cause
* loss of fds and very odd errors to occur.
*
* Thirdly, while processing a request, the second-stage process will
* create socket pairs for the child's stdin & out, fork(), do some
* minimal processing involving moving around stdin and stdout/err, and
* then exec...() the real child process. Any errors during this will
* be reported back to the second-stage process, which will send it
* back to the requestor via the request pipe.
*
* to summarize, to get the subsystem created:
*
* create a pipe
* start the Cgistub process with the pipe as stdin
* (optionally, passing in a unique socket name via the -f arg)
* wait for the OK message on the pipe
* save the pipe FD somewhere (as, for example, listener_pipe_fd)
*
* for as many concurrent requests as you want to support:
* rqpipe_fd = socket(AF_UNIX, SOCK_STREAM... );
* connect(rqpipe_fd, listeners_afunix_socket_name )
*
* then, when you want to start programs
* get a request pipe fd that isn't being used (up to you to manage)
* write()/send() a RequestHeader message
* recvmsg() to get ResponseHeader and two fds
*
* if you want to kill an individual second-stage process, just close
* the listener_pipe_fd
*
* if you want to close the listener process, close the listener_pipe_fd
*
* this was designed such that all children go away when the
* original process using this subsystem goes away.
*
* All this is encoded in the ChildExec and CExecReqPipe classes
*/
/* the default visible name the child stub listener binds */
#ifndef STUB_DEFSOCKNAME
#define STUB_DEFSOCKNAME "/tmp/.fastcgistub"
#endif /* STUB_DEFSOCKNAME */
/* the default name of the child stub process' executable */
#ifndef STUB_DEFLISTENPROG
#define STUB_DEFLISTENPROG "./Fastcgistub"
#endif /* STUB_DEFLISTENPROG */
#define STUB_NAME "Fastcgistub"
/*
* internal use protocol definitions
*/
typedef enum {
RQ_START = 1,
RQ_OVERLOAD = 2,
RQ_VS_SHUTDOWN = 3
} RequestMessageType;
#define PROGNAMESZ 256
#define ARGLEN 256
#define STUBVERSION 1 /* version of library */
/* type-len-vector (TLV) */
typedef enum {
RQT_PATH = 1, /* path vector */
RQT_BIND_PATH = 2, /* bind path vector */
RQT_ARGV0 = 3, /* progname vector */
RQT_ENVP = 4, /* env pointer vector */
RQT_ARGV = 5, /* arg pointer vector */
RQT_CHDIRPATH = 6, /* chdir path */
RQT_CHROOTPATH = 7, /* chroot path */
RQT_USERNAME = 8, /* user name */
RQT_GROUPNAME = 9, /* group name */
RQT_NICE = 10, /* nice increment */
RQT_RLIMIT_AS = 11, /* setrlimit(RLIMIT_AS) values */
RQT_RLIMIT_CORE = 12,/* setrlimit(RLIMIT_CORE) values */
RQT_RLIMIT_CPU = 13,/* setrlimit(RLIMIT_CPU) values */
RQT_RLIMIT_NOFILE = 14,/* setrlimit(RLIMIT_NOFILE) values */
RQT_MIN_PROCS = 15,/* minimum child procs */
RQT_MAX_PROCS = 16,/* maximum child procs */
RQT_LISTENQ_SIZE = 17,/* maximum child procs */
RQT_RESTART_ON_EXIT = 18,
RQT_RESTART_INTERVAL = 19, /* restart interval */
RQT_NUM_FAILURE = 20,
RQT_VS_ID = 21,
RQT_END = 22 /* no more (optional) vector */
} RequestType;
/* All TLVs start on a REQUEST_ALIGN offset in a linear buffer */
typedef struct {
short type; /* type of this request */
short len; /* len of this request (inclusive) */
char vector; /* data associated with type/len */
} RequestDataHeader;
#define REQUEST_ALIGN sizeof(unsigned long)
#define REQUEST_VECOFF offsetof(RequestDataHeader, vector)
/*
* sniped from <nss_dbdefs.h>
* Power-of-two alignments only.
*/
#define ROUND_DOWN(n, align) (((long)n) & ~((align) - 1))
#define ROUND_UP(n, align) ROUND_DOWN(((long)n) + (align) - 1, (align))
/* end sniped code */
/* IMPORTANT NOTE :
*
* all REQUESTS on the request pipe are preceded by a single 32bit
* length containing the length of the entire request (to allow the
* request handling process to differentiate messages on STREAM sockets)
* this length is non-inclusive of itself.
*
* RESPONSEs are not length-preceded, as it is expected (and serious
* problems would otherwise result) that recvmsg() will be called
* to receive (2) fds; the IPC message carrying fds will be atomic
* in nature and MUST pull the fds out, otherwise subsequent reads of
* the pipe will error out in unpredictable ways.
*/
/* start request; most info is carried in tlvs */
typedef struct {
int reqMsgLen;
RequestMessageType reqMsgType;
unsigned long reqVersion;
unsigned long reqFlags; /* for future use */
RequestDataHeader dataHeader;
} RequestHeader;
/*
* following an initial (listener process) fork, the listener
* sends back a message on it's standard IN to say that it did,
* in fact, bind the correct socket and is ready to continue.
* receiving this message is an indication that things are
* ready -- this is for optional use
*/
#ifdef XP_UNIX
#define FCGI_STUB_NAME "Fastcgistub"
#else
#define FCGI_STUB_NAME "Fastcgistub.exe"
#endif //XP_UNIX
#define BIND_PATH_PARAM "-b"
#define TMP_DIR_PARAM "-t"
#define SERVER_ID_PARAM "-i"
#define LOG_DIR_PARAM "-l"
#define STUB_LOG_FILE_NAME "Fastcgistub.log"
#ifdef __cplusplus
}
#endif
#endif /* __FASTCGISTUB_H__ */
| 39.929167 | 79 | 0.693415 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.