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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ee148235615367c27897d78e5f57edd23e09ed20 | 8,308 | h | C | src/framework/licensee.h | AMS21/PreyRun | 3efc9d70228bcfb8bc18f6ff23a05c8be1e45101 | [
"MIT"
] | 2 | 2018-08-30T23:48:22.000Z | 2021-04-07T19:16:18.000Z | src/framework/licensee.h | AMS21/PreyRun | 3efc9d70228bcfb8bc18f6ff23a05c8be1e45101 | [
"MIT"
] | null | null | null | src/framework/licensee.h | AMS21/PreyRun | 3efc9d70228bcfb8bc18f6ff23a05c8be1e45101 | [
"MIT"
] | null | null | null | // Copyright (C) 2004 Id Software, Inc.
//
/*
===============================================================================
Definitions for information that is related to a licensee's game name and location.
===============================================================================
*/
#include "../../src/PreyRun/PreyRun.hpp"
#define GAME_NAME "PreyRun" // appears on window titles and errors
#define ENGINE_VERSION "PreyRun-" PR_VERSION // printed in console
// paths
#define CD_BASEDIR "Prey"
//HUMANHEAD jsh PCF 5/26/06: prey demo uses "base" so that save games all go in same folder
//#ifdef ID_DEMO_BUILD
// #define BASE_GAMEDIR "demo"
//#else
#define BASE_GAMEDIR "base"
//#endif
// filenames
#define CD_EXE "prey.exe"
#define CONFIG_FILE "preyconfig.cfg"
// base folder where the source code lives
#define SOURCE_CODE_BASE_FOLDER "."
// default idnet host address
#ifndef IDNET_HOST
//Q4MASTER
//#define IDNET_HOST "q4master.idsoftware.com"
#define IDNET_HOST "preymaster.humanhead.com"
#endif
// default idnet master port
#ifndef IDNET_MASTER_PORT
#ifdef ID_DEMO_BUILD
#define IDNET_MASTER_PORT "27655"
#else
#define IDNET_MASTER_PORT "27650"
#endif
#endif
// default network server port
#ifndef PORT_SERVER
#define PORT_SERVER 27719 // ID used 27666
#endif
// broadcast scan this many ports after PORT_SERVER so a single machine can run multiple servers
#define NUM_SERVER_PORTS 4
// see ASYNC_PROTOCOL_VERSION
// use a different major for each game
//Q4MASTER
//use 2
#ifdef ID_DEMO_BUILD
#define ASYNC_PROTOCOL_MAJOR 4 // Doom3=1, Quake4=2, Prey=3, Prey Demo=4
#else
#define ASYNC_PROTOCOL_MAJOR 3 // Doom3=1, Quake4=2, Prey=3
#endif
// Savegame Version
// Update when you can no longer maintain compatibility with previous savegames
// NOTE: a seperate core savegame version and game savegame version could be useful
#define SAVEGAME_VERSION 114
#define RENDERDEMO_VERSION 100
// editor info
#define EDITOR_DEFAULT_PROJECT "prey.qe4"
#define EDITOR_REGISTRY_KEY "PreyRadiant"
#define EDITOR_WINDOWTEXT "PREDITOR"
// win32 info
#define WIN32_CONSOLE_CLASS "Prey WinConsole"
#define WIN32_WINDOW_CLASS_NAME "PREY"
#define WIN32_FAKE_WINDOW_CLASS_NAME "PREY_WGL_FAKE"
// Linux info
#ifdef ID_DEMO_BUILD
#define LINUX_DEFAULT_PATH "/usr/local/games/prey-demo"
#else
#define LINUX_DEFAULT_PATH "/usr/local/games/prey"
#endif
// CD Key file info
// goes into BASE_GAMEDIR whatever the fs_game is set to
// two distinct files for easier win32 installer job
#define CDKEY_FILE "preykey"
#ifdef HUMANHEAD_XP // HUMANHEAD mdl
#define XPKEY_FILE "xpkey"
#endif // HUMANHEAD END
// HUMANHEAD PCF mdl 05-08-06 - Changed CDKEY_TEXT
#define CDKEY_TEXT "\n// Do not give this file to ANYONE.\n" \
"// Human Head Studios and 2K Games will NOT ask you to send this file to them.\n"
// FIXME: Update to Doom
// Product ID. Stored in "productid.txt".
// This file is copyright 1999 Id Software, and may not be duplicated except during a licensed installation of the full commercial version of Quake 3:Arena
#undef PRODUCT_ID
#define PRODUCT_ID 220, 129, 255, 108, 244, 163, 171, 55, 133, 65, 199, 36, 140, 222, 53, 99, 65, 171, 175, 232, 236, 193, 210, 250, 169, 104, 231, 231, 21, 201, 170, 208, 135, 175, 130, 136, 85, 215, 71, 23, 96, 32, 96, 83, 44, 240, 219, 138, 184, 215, 73, 27, 196, 247, 55, 139, 148, 68, 78, 203, 213, 238, 139, 23, 45, 205, 118, 186, 236, 230, 231, 107, 212, 1, 10, 98, 30, 20, 116, 180, 216, 248, 166, 35, 45, 22, 215, 229, 35, 116, 250, 167, 117, 3, 57, 55, 201, 229, 218, 222, 128, 12, 141, 149, 32, 110, 168, 215, 184, 53, 31, 147, 62, 12, 138, 67, 132, 54, 125, 6, 221, 148, 140, 4, 21, 44, 198, 3, 126, 12, 100, 236, 61, 42, 44, 251, 15, 135, 14, 134, 89, 92, 177, 246, 152, 106, 124, 78, 118, 80, 28, 42
#undef PRODUCT_ID_LENGTH
#define PRODUCT_ID_LENGTH 152
#define CONFIG_SPEC "config.spec"
// HUMANHEAD pdm: Our additions go here
#define SINGLE_MAP_BUILD 1 // For single map external builds
#define PARTICLE_BOUNDS 1 // rdr - New type of particle bounds calc
#define SOUND_TOOLS_BUILD 1 // Turn on for making builds for Ed to change reverbs, should be 0 in gold build
#define GUIS_IN_DEMOS 1 // Include guis in demo streams
#define MUSICAL_LEVELLOADS 1 // Allow music playback during level loads
#define GAMEPORTAL_PVS 1 // Allow PVS to flow through game portals
#define GAMEPORTAL_SOUND 1 // Allow sound to flow through game portals (requires GAMEPORTAL_PVS)
#define DEATHWALK_AUTOLOAD 1 // Append deathwalk map to all maps loaded
#define GAME_PLAYERDEFNAME "player_tommy"
#define GAME_PLAYERDEFNAME_MP "player_tommy_mp"
#define AUTOMAP 0
#define EDITOR_HELP_LOCATOR "http://www.3drealms.com/prey/wiki"
#define PREY_SITE_LOCATOR "http://www.prey.com"
#define CREATIVE_DRIVER_LOCATOR "http://www.creative.com/language.asp?sDestUrl=/support/downloads"
#define TRITON_LOCATOR "http://www.playtriton.com/prey"
#define NVIDIA_DRIVER_LOCATOR "www.nvidia.com"
#define ATI_DRIVER_LOCATOR "www.ati.com"
#define _HH_RENDERDEMO_HACKS 1 //rww - if 1 enables hacks to make renderdemos work through whatever nefarious means necessary
#define _HH_CLIP_FASTSECTORS 1 //rww - much faster method for clip sector checking
#define NEW_MESH_TRANSFORM 1 //bjk - SSE new vert transform
#define SIMD_SHADOW 0 //bjk - simd shadow calculations
#define MULTICORE 1 // Multicore optimizations
#define DEBUG_SOUND_LOG 0 // Write out a debug log, remove from final build
#ifdef _USE_SECUROM_ // mdl: Only enable securom for certain builds
#define _HH_SECUROM 1 //rww - enables securom api hooks
#else
#define _HH_SECUROM 0
#endif
#define _HH_INLINED_PROC_CLIPMODELS 0 //rww - enables crazy last-minute proc geometry clipmodel support
#ifdef ID_DEDICATED
#define _HH_MYGAMES_SAVES 0
#else
#define _HH_MYGAMES_SAVES 1 //HUMANHEAD PCF rww 05/10/06 - use My Games for saves
#endif
// Map to start with 'New Game' button
#ifdef ID_DEMO_BUILD
#define STARTING_LEVEL "roadhouse"
#else
#if SINGLE_MAP_BUILD
#define STARTING_LEVEL "feedingtowerc"
#else
#define STARTING_LEVEL "feedingtowera"
#endif
#endif
#ifdef ID_DEMO_BUILD
#define DEMO_END_LEVEL "game/feedingtowerd"
#endif
// Flip these for final final
//HH rww SDK - gold must be enabled, to match the state of the release exe.
#if 1
#define GOLD 1 // Used for disabling development code
#define CONSOLE_IDENTITY 0 // Print build identity on console
#define REMOTE_DMAP 0 // Remote dmap support (development only)
#else
#define GOLD 0 // Off for development
#define CONSOLE_IDENTITY 1 // Print build identity on console
#define REMOTE_DMAP 1 // Remote dmap support (development only)
#endif
// profiler/debugger
#ifdef ID_DEMO_BUILD
#define INGAME_DEBUGGER_ENABLED 0
#define INGAME_PROFILER_ENABLED 0
#else
#define INGAME_DEBUGGER_ENABLED 1
#define INGAME_PROFILER_ENABLED 1
#endif
#ifndef _NODONGLE_
#define __HH_DONGLE__ 0 // always require a dongle somewhere on the net
#endif
#ifdef _GERMAN_BUILD_
# define GERMAN_VERSION 1
#else
# define GERMAN_VERSION 0 // Set to 1 to disable gore
#endif
// Venom
#define XENON 0 // Turn on at venom: anything exclusive to the xenon port
#define VENOM 0 // Turn on at venom
#define GAMEPAD_SUPPORT 0 // windows gamepad controller support (doesn't work on win2000)
#if !GOLD //rww - if not gold enable network entity stat tracking and float protection
//HUMANHEAD PCF rww 04/26/06 - i'm done with these internally for now as well.
//#define _HH_NET_DEBUGGING
//#define _HH_FLOAT_PROTECTION
#endif
// mdl: Moved here from BuildDefines.h because we need GOLD and _SYSTEM_BUILD_ defined
#ifndef ID_ENFORCE_KEY
# if GOLD && !defined( _INTERNAL_BUILD_ ) && !defined( _SYSTEM_BUILD_ ) && !defined( ID_DEDICATED ) && !defined( ID_DEMO_BUILD ) && !defined( _HH_DEMO_BUILD_ ) // HUMANHEAD mdl: Added GOLD, _SYSTEM_BUILD_, and _HH_DEMO_BUILD_
# define ID_ENFORCE_KEY 1
# else
# define ID_ENFORCE_KEY 0
# endif
#endif
// HUMANHEAD mdl: save debugging
//#define HUMANHEAD_SAVEDEBUG
//#define HUMANHEAD_TESTSAVEGAME
// HUMANHEAD END
| 37.423423 | 718 | 0.714853 | [
"geometry",
"transform"
] |
ee1998b2c6a7793f8a7b6e6dabb607759f503481 | 319 | h | C | Framework/Sources/o2/Render/Windows/TextureBase.h | zenkovich/o2 | cdbf10271f1bf0f3198c8005b13b66e6ca13a9db | [
"MIT"
] | 181 | 2015-12-09T08:53:36.000Z | 2022-03-26T20:48:39.000Z | Framework/Sources/o2/Render/Windows/TextureBase.h | zenkovich/o2 | cdbf10271f1bf0f3198c8005b13b66e6ca13a9db | [
"MIT"
] | 29 | 2016-04-22T08:24:04.000Z | 2022-03-06T07:06:28.000Z | Framework/Sources/o2/Render/Windows/TextureBase.h | zenkovich/o2 | cdbf10271f1bf0f3198c8005b13b66e6ca13a9db | [
"MIT"
] | 13 | 2018-04-24T17:12:04.000Z | 2021-11-12T23:49:53.000Z | #pragma once
#ifdef PLATFORM_WINDOWS
#include "o2/Render/Windows/OpenGL.h"
namespace o2
{
class TextureBase
{
friend class Render;
friend class VectorFont;
protected:
GLuint mHandle; // Texture handle
GLuint mFrameBuffer; // Frame buffer for rendering into texture
};
}
#endif // PLATFORM_WINDOWS
| 15.190476 | 65 | 0.730408 | [
"render"
] |
ee28b126ea6caed779335ff88577426f7e2a1cf7 | 985 | h | C | LYLZSDK/MVC/Model/LYTChatMessageCellFrame.h | install-b/LYLZDemo | 19e35da87982a2f00a48d42c097fde18f220eee4 | [
"MIT"
] | null | null | null | LYLZSDK/MVC/Model/LYTChatMessageCellFrame.h | install-b/LYLZDemo | 19e35da87982a2f00a48d42c097fde18f220eee4 | [
"MIT"
] | null | null | null | LYLZSDK/MVC/Model/LYTChatMessageCellFrame.h | install-b/LYLZDemo | 19e35da87982a2f00a48d42c097fde18f220eee4 | [
"MIT"
] | null | null | null | //
// LYTChatMessageCellFrame.h
// LYTDemo
//
// Created by SYLing on 2017/2/7.
// Copyright © 2017年 Vieene. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "LYLZRedPacketMessageBody.h"
#import "LYLZOrderMessageBody.h"
#import "LYLZSDK.h"
@class LYTChatMessageCellFrame;
@protocol LYTChatMessageCellFrameDestrucDelegate <NSObject>
- (void)chatMessageModelWillDelete:(LYTChatMessageCellFrame *)model;
- (void)chatMessageModelWillRefreshStatu:(LYTChatMessageCellFrame *)model;
@end
@interface LYTChatMessageCellFrame : NSObject
- (instancetype)initWithChartModel:(LYTMessage *)message;
@property (nonatomic,strong) LYTMessage *chartMessage;
@property (nonatomic,assign) CGRect iconRect;
@property (nonatomic,assign) CGRect bubbleViewFrame;
@property (nonatomic, assign) CGFloat cellHeight; //cell高度
@property (nonatomic,weak) id <LYTChatMessageCellFrameDestrucDelegate> destrucDelegate;
@property (nonatomic,strong) LYLZmessageBody * messageBody;
@end
| 25.25641 | 87 | 0.795939 | [
"model"
] |
ee2dcd7acfdba36b6bc501764db378ec8dbb7ac1 | 8,756 | h | C | godot_remote/GRNotifications.h | DmitriySalnikov/GodotRemote | b4ec8baee07a3334e784886f9e0e7fc45b911ef8 | [
"MIT"
] | 24 | 2020-08-08T04:54:41.000Z | 2022-02-26T19:00:12.000Z | godot_remote/GRNotifications.h | DmitriySalnikov/GodotRemote | b4ec8baee07a3334e784886f9e0e7fc45b911ef8 | [
"MIT"
] | 1 | 2021-05-25T06:41:44.000Z | 2021-05-26T14:37:41.000Z | godot_remote/GRNotifications.h | DmitriySalnikov/GodotRemote | b4ec8baee07a3334e784886f9e0e7fc45b911ef8 | [
"MIT"
] | null | null | null | /* GRNotifications.h */
#pragma once
#include "GRUtils.h"
#ifndef GDNATIVE_LIBRARY
#include "scene/gui/box_container.h"
#include "scene/gui/panel_container.h"
#include "scene/main/canvas_layer.h"
#else
#include <Button.hpp>
#include <CanvasLayer.hpp>
#include <Font.hpp>
#include <HBoxContainer.hpp>
#include <ImageTexture.hpp>
#include <Label.hpp>
#include <PanelContainer.hpp>
#include <StyleBoxEmpty.hpp>
#include <StyleBoxFlat.hpp>
#include <TextureRect.hpp>
#include <Theme.hpp>
#include <Tween.hpp>
#include <VBoxContainer.hpp>
using namespace godot;
#endif
class GRNotificationPanel;
class GRNotificationStyle;
class GRNotificationListWithSafeZone;
class GRNotificationPanelSTATIC_DATA;
class GRNotifications : public CanvasLayer {
GD_CLASS(GRNotifications, CanvasLayer);
friend class GRNotificationPanel;
public:
enum NotificationIcon : int {
ICON_NONE,
ICON_ERROR,
ICON_WARNING,
ICON_SUCCESS,
ICON_FAIL,
ICON_MAX,
};
enum NotificationsPosition : int {
TOP_LEFT = 0,
TOP_CENTER = 1,
TOP_RIGHT = 2,
BOTTOM_LEFT = 3,
BOTTOM_CENTER = 4,
BOTTOM_RIGHT = 5,
};
private:
static GRNotifications *singleton;
bool clearing_notifications = false;
float notifications_duration = 2.0;
bool notifications_enabled = true;
NotificationsPosition notifications_position = NotificationsPosition::TOP_LEFT;
GRNotificationListWithSafeZone *notif_list_node = nullptr;
std::vector<GRNotificationPanel *> notifications; // GRNotificationPanel *
Ref<GRNotificationStyle> style;
std::vector<GRNotificationPanel *> _get_notifications_with_title(String title); // GRNotificationPanel *
GRNotificationPanel *_get_notification(String title);
void _set_all_notifications_positions(NotificationsPosition pos);
void _set_notifications_position(ENUM_ARG(NotificationsPosition) positon);
void _add_notification_or_append_string(String title, String text, ENUM_ARG(NotificationIcon) icon, bool new_string, float duration_multiplier);
void _add_notification_or_update_line(String title, String id, String text, ENUM_ARG(NotificationIcon) icon, float duration_multiplier);
void _add_notification(String title, String text, ENUM_ARG(NotificationIcon) icon, bool update_existing, float duration_multiplier);
void _remove_notification(String title, bool all_entries);
void _remove_exact_notification(Node *_notif);
void _clear_notifications();
protected:
#ifndef GDNATIVE_LIBRARY
static void _bind_methods();
#else
public:
static void _register_methods();
protected:
#endif
void _notification(int p_what);
public:
/// All functions below need to be called after init notification manager
/// For example call this after yield(get_tree(), "idle_frame")
static GRNotificationPanel *get_notification(String title);
static Array get_all_notifications();
static Array get_notifications_with_title(String title);
static NotificationsPosition get_notifications_position();
static void set_notifications_position(NotificationsPosition positon);
static bool get_notifications_enabled();
static void set_notifications_enabled(bool _enabled);
static float get_notifications_duration();
static void set_notifications_duration(float _duration);
static Ref<class GRNotificationStyle> get_notifications_style();
static void set_notifications_style(Ref<class GRNotificationStyle> _style);
// append text to existing notification or add new notification
static void add_notification_or_append_string(String title, String text, NotificationIcon icon = NotificationIcon::ICON_NONE, bool new_string = true, float duration_multiplier = 1.f);
// update text in existing notification or add new notification
static void add_notification_or_update_line(String title, String id, String text, NotificationIcon icon = NotificationIcon::ICON_NONE, float duration_multiplier = 1.);
static void add_notification(String title, String text, NotificationIcon icon DEF_ARG(= NotificationIcon::ICON_NONE), bool update_existing = true, float duration_multiplier = 1.f);
static void remove_notification(String title, bool all_entries = true);
static void remove_notification_exact(Node *_notif);
static void clear_notifications();
static GRNotifications *get_singleton();
void _init();
void _deinit();
};
// Stupid class to bypass GDNative limitations
// but also it can be changed back by changing default-style generating
class GRNotificationPanelSTATIC_DATA {
public:
Ref<GRNotificationStyle> _default_style;
#ifndef NO_GODOTREMOTE_DEFAULT_RESOURCES
Dictionary _default_textures;
Ref<ImageTexture> _default_close_texture;
#endif
};
class GRNotificationPanel : public PanelContainer {
GD_CLASS(GRNotificationPanel, PanelContainer);
friend GRNotifications;
protected:
GRNotifications *owner = nullptr;
GRNotifications::NotificationIcon notification_icon = GRNotifications::NotificationIcon::ICON_NONE;
float duration_mul = 1.f;
bool is_hovered = false;
Ref<GRNotificationStyle> style;
static GRNotificationPanelSTATIC_DATA *_default_data;
class VBoxContainer *vbox_node = nullptr;
class HBoxContainer *hbox_node = nullptr;
class TextureRect *icon_tex_node = nullptr;
class Label *title_node = nullptr;
class Label *text_node = nullptr;
class Button *close_node = nullptr;
class Tween *tween_node = nullptr;
void _panel_hovered();
void _panel_lose_hover();
void _remove_this_notification();
void _setup_tween(Tween *_tween);
void _update_style();
static Ref<class GRNotificationStyle> generate_default_style();
#ifndef NO_GODOTREMOTE_DEFAULT_RESOURCES
static void _load_default_textures();
#endif
protected:
#ifndef GDNATIVE_LIBRARY
static void _bind_methods();
#else
public:
static void _register_methods();
protected:
#endif
void _notification(int p_notification);
public:
static void clear_styles();
void set_notification_position(GRNotifications::NotificationsPosition position);
virtual void set_data(GRNotifications *_owner, String title, String text, GRNotifications::NotificationIcon icon, float duration_multiplier DEF_ARG(= 1.f), Ref<GRNotificationStyle> _style DEF_ARG(= Ref<GRNotificationStyle>()));
String get_title();
String get_text();
ENUM_ARG(GRNotifications::NotificationIcon)
get_icon_id();
void update_text(String text);
void _init();
void _deinit();
};
class GRNotificationPanelUpdatable : public GRNotificationPanel {
GD_CLASS(GRNotificationPanelUpdatable, GRNotificationPanel);
friend GRNotifications;
protected:
std::map<String, String> lines;
String _get_text_from_lines();
bool configured = false;
#ifndef GDNATIVE_LIBRARY
static void _bind_methods();
#else
public:
static void _register_methods();
protected:
#endif
void _notification(int p_notification);
public:
void set_updatable_line(GRNotifications *_owner, String title, String id, String text, GRNotifications::NotificationIcon icon, float duration_multiplier DEF_ARG(= 1.f), Ref<GRNotificationStyle> _style DEF_ARG(= Ref<GRNotificationStyle>()));
void remove_updatable_line(String id);
void clear_lines();
void _init();
void _deinit();
};
// STYLE REF
class GRNotificationStyle : public Reference {
GD_CLASS(GRNotificationStyle, Reference);
private:
Ref<StyleBox> panel_style;
Ref<Theme> close_button_theme;
Ref<Texture> close_button_icon;
Ref<Font> title_font;
Ref<Font> text_font;
Ref<Texture> n_icons[GRNotifications::NotificationIcon::ICON_MAX];
protected:
#ifndef GDNATIVE_LIBRARY
static void _bind_methods();
#else
public:
static void _register_methods();
protected:
#endif
void _notification(int p_notification);
public:
void set_panel_style(Ref<StyleBox> style);
Ref<StyleBox> get_panel_style();
void set_close_button_theme(Ref<Theme> theme);
Ref<Theme> get_close_button_theme();
void set_close_button_icon(Ref<Texture> icon);
Ref<Texture> get_close_button_icon();
void set_title_font(Ref<Font> font);
Ref<Font> get_title_font();
void set_text_font(Ref<Font> font);
Ref<Font> get_text_font();
void set_notification_icon(ENUM_ARG(GRNotifications::NotificationIcon) notification_icon, Ref<Texture> icon_texture);
Ref<Texture> get_notification_icon(ENUM_ARG(GRNotifications::NotificationIcon) notification_icon);
void _init();
void _deinit();
};
// SAFE ZONE
class GRNotificationListWithSafeZone : public VBoxContainer {
GD_CLASS(GRNotificationListWithSafeZone, VBoxContainer);
private:
protected:
#ifndef GDNATIVE_LIBRARY
static void _bind_methods();
#else
public:
static void _register_methods();
protected:
#endif
bool is_manual_changing = false;
void _on_resize();
void _notification(int p_what);
public:
void _set_safe_zone();
void _init();
void _deinit();
};
#ifndef GDNATIVE_LIBRARY
VARIANT_ENUM_CAST(GRNotifications::NotificationsPosition)
VARIANT_ENUM_CAST(GRNotifications::NotificationIcon)
#endif
| 28.33657 | 241 | 0.803106 | [
"vector"
] |
5a0715a19cb65af6983700b72259af0f46f3443b | 3,599 | h | C | libs/celt/vq.h | tzhuan/llcon | c5a4b7abcc62ce3aad334dfa650ff3512c4262be | [
"BSD-3-Clause"
] | 1 | 2016-10-16T00:33:31.000Z | 2016-10-16T00:33:31.000Z | libs/celt/vq.h | tzhuan/llcon | c5a4b7abcc62ce3aad334dfa650ff3512c4262be | [
"BSD-3-Clause"
] | 1 | 2020-09-27T14:24:16.000Z | 2020-09-27T14:24:16.000Z | libs/celt/vq.h | tzhuan/llcon | c5a4b7abcc62ce3aad334dfa650ff3512c4262be | [
"BSD-3-Clause"
] | null | null | null | /* (C) 2007-2008 Jean-Marc Valin, CSIRO
*/
/**
@file vq.h
@brief Vector quantisation of the residual
*/
/*
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 Xiph.org Foundation 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 FOUNDATION 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 VQ_H
#define VQ_H
#include "entenc.h"
#include "entdec.h"
#include "modes.h"
/** Algebraic pulse-vector quantiser. The signal x is replaced by the sum of
* the pitch and a combination of pulses such that its norm is still equal
* to 1. This is the function that will typically require the most CPU.
* @param x Residual signal to quantise/encode (returns quantised version)
* @param W Perceptual weight to use when optimising (currently unused)
* @param N Number of samples to encode
* @param K Number of pulses to use
* @param p Pitch vector (it is assumed that p+x is a unit vector)
* @param enc Entropy encoder state
*/
void alg_quant(celt_norm_t *X, celt_mask_t *W, int N, int K, celt_norm_t *P, ec_enc *enc);
/** Algebraic pulse decoder
* @param x Decoded normalised spectrum (returned)
* @param N Number of samples to decode
* @param K Number of pulses to use
* @param p Pitch vector (automatically added to x)
* @param dec Entropy decoder state
*/
void alg_unquant(celt_norm_t *X, int N, int K, celt_norm_t *P, ec_dec *dec);
celt_word16_t renormalise_vector(celt_norm_t *X, celt_word16_t value, int N, int stride);
/** Intra-frame predictor that matches a section of the current frame (at lower
* frequencies) to encode the current band.
* @param x Residual signal to quantise/encode (returns quantised version)
* @param W Perceptual weight
* @param N Number of samples to encode
* @param K Number of pulses to use
* @param Y Lower frequency spectrum to use, normalised to the same standard deviation
* @param P Pitch vector (it is assumed that p+x is a unit vector)
* @param B Stride (number of channels multiplied by the number of MDCTs per frame)
* @param N0 Number of valid offsets
*/
void intra_fold(const CELTMode *m, celt_norm_t * __restrict x, int N, int *pulses, celt_norm_t *Y, celt_norm_t * __restrict P, int N0, int B);
#endif /* VQ_H */
| 44.9875 | 143 | 0.732426 | [
"vector"
] |
5a0d8d9d3cf9859a51b125c81edf2ca87af03d1d | 6,442 | h | C | Assignment4/BinarySearchTree.h | HEYHO8037/POCU | 811979ec56ec6401807e6967845c6f4581884d5f | [
"MIT"
] | null | null | null | Assignment4/BinarySearchTree.h | HEYHO8037/POCU | 811979ec56ec6401807e6967845c6f4581884d5f | [
"MIT"
] | null | null | null | Assignment4/BinarySearchTree.h | HEYHO8037/POCU | 811979ec56ec6401807e6967845c6f4581884d5f | [
"MIT"
] | null | null | null | #pragma once
#include <memory>
#include <vector>
namespace assignment4
{
template<typename T>
class TreeNode;
template<typename T>
class BinarySearchTree final
{
public:
void Insert(std::unique_ptr<T> data);
bool Search(const T& data);
bool Delete(const T& data);
const std::weak_ptr<TreeNode<T>> GetRootNode() const;
static std::vector<T> TraverseInOrder(const std::shared_ptr<TreeNode<T>> startNode);
private:
std::shared_ptr<TreeNode<T>> findMinNode(std::shared_ptr<TreeNode<T>> treeNode);
void deleteNoSearch(std::shared_ptr<TreeNode<T>> treeNode);
std::shared_ptr<TreeNode<T>> mTreeNode;
};
template<typename T>
void BinarySearchTree<T>::Insert(std::unique_ptr<T> data)
{
std::shared_ptr<TreeNode<T>> saveTreeNode;
std::shared_ptr<TreeNode<T>> saveParentNode;
if (mTreeNode == nullptr)
{
mTreeNode = std::make_shared<TreeNode<T>>(move(data));
return;
}
else
{
saveTreeNode = mTreeNode;
while (true)
{
if (*saveTreeNode->Data >= *data)
{
if (saveTreeNode->Left == nullptr)
{
saveParentNode = saveTreeNode;
saveTreeNode->Left = std::make_shared<TreeNode<T>>(move(data));
saveTreeNode = saveTreeNode->Left;
saveTreeNode->Parent = saveParentNode;
return;
}
else
{
saveTreeNode = saveTreeNode->Left;
}
}
else
{
if (saveTreeNode->Right == nullptr)
{
saveParentNode = saveTreeNode;
saveTreeNode->Right = std::make_shared<TreeNode<T>>(move(data));
saveTreeNode = saveTreeNode->Right;
saveTreeNode->Parent = saveParentNode;
return;
}
else
{
saveTreeNode = saveTreeNode->Right;
}
}
}
}
}
template<typename T>
const std::weak_ptr<TreeNode<T>> BinarySearchTree<T>::GetRootNode() const
{
return mTreeNode;
}
template<typename T>
bool BinarySearchTree<T>::Search(const T& data)
{
std::shared_ptr<TreeNode<T>> saveTreeNode = mTreeNode;
while (saveTreeNode != nullptr)
{
if (*saveTreeNode->Data == data)
{
return true;
}
else if (*saveTreeNode->Data > data)
{
saveTreeNode = saveTreeNode->Left;
}
else
{
saveTreeNode = saveTreeNode->Right;
}
}
return false;
}
template<typename T>
std::shared_ptr<TreeNode<T>> BinarySearchTree<T>::findMinNode(std::shared_ptr<TreeNode<T>> treeNode)
{
if (treeNode->Left == nullptr)
{
return treeNode;
}
else
{
return findMinNode(treeNode->Left);
}
}
template<typename T>
void BinarySearchTree<T>::deleteNoSearch(std::shared_ptr<TreeNode<T>> treeNode)
{
std::shared_ptr<TreeNode<T>> saveTreeNode = treeNode;
std::shared_ptr<TreeNode<T>> saveLeftRightNode;
if (saveTreeNode->Left == nullptr && saveTreeNode->Right == nullptr)
{
saveLeftRightNode = saveTreeNode;
saveTreeNode = saveTreeNode->Parent.lock();
if (saveTreeNode->Left == saveLeftRightNode)
{
saveTreeNode->Left.reset();
}
else if (saveTreeNode->Right == saveLeftRightNode)
{
saveTreeNode->Right.reset();
}
}
else if (saveTreeNode->Left == nullptr || saveTreeNode->Right == nullptr)
{
if (saveTreeNode->Left != nullptr)
{
saveLeftRightNode = saveTreeNode->Left;
}
else
{
saveLeftRightNode = saveTreeNode->Right;
}
if (saveTreeNode->Parent.lock()->Left == saveTreeNode)
{
saveTreeNode = saveTreeNode->Parent.lock();
saveTreeNode->Left = saveLeftRightNode;
saveLeftRightNode->Parent = saveTreeNode;
}
else
{
saveTreeNode = saveTreeNode->Parent.lock();
saveTreeNode->Right = saveLeftRightNode;
saveLeftRightNode->Parent = saveTreeNode;
}
}
}
template<typename T>
bool BinarySearchTree<T>::Delete(const T& data)
{
std::shared_ptr<TreeNode<T>> saveTreeNode = mTreeNode;
std::shared_ptr<TreeNode<T>> saveLeftRightNode;
if (mTreeNode == nullptr)
{
return false;
}
while (saveTreeNode != nullptr)
{
if (*saveTreeNode->Data == data)
{
break;
}
else if (*saveTreeNode->Data > data)
{
saveTreeNode = saveTreeNode->Left;
if (saveTreeNode == nullptr)
{
return false;
}
}
else if (*saveTreeNode->Data < data)
{
saveTreeNode = saveTreeNode->Right;
if (saveTreeNode == nullptr)
{
return false;
}
}
}
if (saveTreeNode == mTreeNode && saveTreeNode->Left == nullptr && saveTreeNode->Right == nullptr)
{
mTreeNode.reset();
return true;
}
if (saveTreeNode->Left == nullptr && saveTreeNode->Right == nullptr)
{
saveLeftRightNode = saveTreeNode;
saveTreeNode = saveTreeNode->Parent.lock();
if (saveTreeNode->Left == saveLeftRightNode)
{
saveTreeNode->Left.reset();
}
else if (saveTreeNode->Right == saveLeftRightNode)
{
saveTreeNode->Right.reset();
}
}
else if (saveTreeNode->Left == nullptr || saveTreeNode->Right == nullptr)
{
if (saveTreeNode->Left != nullptr)
{
saveLeftRightNode = saveTreeNode->Left;
}
else
{
saveLeftRightNode = saveTreeNode->Right;
}
if (saveTreeNode->Parent.lock() != nullptr)
{
if (saveTreeNode->Parent.lock()->Left == saveTreeNode)
{
saveTreeNode = saveTreeNode->Parent.lock();
saveTreeNode->Left = saveLeftRightNode;
saveLeftRightNode->Parent = saveTreeNode;
}
else
{
saveTreeNode = saveTreeNode->Parent.lock();
saveTreeNode->Right = saveLeftRightNode;
saveLeftRightNode->Parent = saveTreeNode;
}
}
else
{
saveLeftRightNode->Parent = saveTreeNode->Parent;
mTreeNode = saveLeftRightNode;
}
}
else if ((saveTreeNode->Left != nullptr) && (saveTreeNode->Right != nullptr))
{
saveLeftRightNode = findMinNode(saveTreeNode->Right);
saveTreeNode->Data = std::move(saveLeftRightNode->Data);
deleteNoSearch(saveLeftRightNode);
}
return true;
}
template<typename T>
std::vector<T> BinarySearchTree<T>::TraverseInOrder(const std::shared_ptr<TreeNode<T>> startNode)
{
std::vector<T> inorderVector;
std::vector<T> saveVector;
if (startNode == nullptr)
{
return inorderVector;
}
saveVector = TraverseInOrder(startNode->Left);
inorderVector.insert(inorderVector.end(), saveVector.begin(), saveVector.end());
inorderVector.push_back(*startNode->Data);
saveVector = TraverseInOrder(startNode->Right);
inorderVector.insert(inorderVector.end(), saveVector.begin(), saveVector.end());
return inorderVector;
}
} | 21.763514 | 101 | 0.657715 | [
"vector"
] |
5a0e298bee766239650ce050b128a9f28ab518f5 | 3,046 | h | C | Coda/src/nlp-stack/Dictionary/DictionaryNodeModel.h | Samsung/veles.nlp | 972fde27203cb04d301e34274b57435ed58372c4 | [
"Apache-2.0"
] | 8 | 2016-02-16T10:15:39.000Z | 2020-03-12T21:14:36.000Z | src/nlp-stack/Dictionary/Core/DictionaryTrie/DictionaryNodeModel.h | bdbabiak/Coda | 5e84624ae2b759fb1743778316f64c801591c48a | [
"Apache-2.0"
] | null | null | null | src/nlp-stack/Dictionary/Core/DictionaryTrie/DictionaryNodeModel.h | bdbabiak/Coda | 5e84624ae2b759fb1743778316f64c801591c48a | [
"Apache-2.0"
] | 6 | 2016-02-16T10:15:47.000Z | 2020-01-20T20:33:25.000Z | /**
* DictionaryNodeModel.h
* Class DictionaryNodeModel
*
* .. invisible:
* _ _ _____ _ _____ _____
*
* | | | | ___| | | ___/ ___|
*
* | | | | |__ | | | |__ \ `--.
*
* | | | | __|| | | __| `--. \
*
* \ \_/ / |___| |___| |___/\__/ /
*
* \___/\____/\_____|____/\____/
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License
*
*/
//#pragma warning( disable: 4018 )
#ifndef _DICTIONARYNODEMODEL_H_
#define _DICTIONARYNODEMODEL_H_
#include "DictionaryDataTypes.h"
using namespace std;
class DictionaryNode;
class DictionaryNodeModel
{
public:
DictionaryNodeModel(int _modelId, int _lemmaId);
~DictionaryNodeModel(void);
/**
* @brief return id of model (models are saved in TrieVer3)
*/
int getModelId(void) { return modelId;}
/**
* @brief set id for model
*/
void setModelId(int _modelId) { modelId = _modelId;}
/**
* @brief return id of lemma (id of lemma in OpenCorpora)
*/
int getLemmaId(void) { return lemmaId;}
/**
* @brief set lemma id for model
*/
void setLemmaId(int _lemmaId) { lemmaId = _lemmaId;}
/**
* @brief return DictionaryNodeModel that this one links to
*/
inline DictionaryNodeModel* getLink(void) { return linkNode;}
/**
* @brief set link to other DictionaryNodeModels
*/
void setLink(DictionaryNodeModel* _linkNode) { linkNode = _linkNode; _linkNode->addLinkFrom(this);}
/**
* @brief set link from other DictionaryNodeModels
*/
void addLinkFrom(DictionaryNodeModel* _linkNode) { linkFrom.push_back(_linkNode);}
/**
* @brief get links from this node model
*/
vector<DictionaryNodeModel*> getLinkFrom(void) { return linkFrom;}
/**
* @brief return NodeVer3 of this model
*/
DictionaryNode* getNode() { return node;}
/**
* @brief set NodeVer3 for this model
*/
void setNode(DictionaryNode* _node) { node = _node;}
/**
* @brief get prefix-string from root to this DictionaryNodeModel's node
*/
wstring getStringFromRoot(void);
private:
// id of model
int modelId;
// id of lemma
int lemmaId;
// node of this model
DictionaryNode* node;
// link to this model
DictionaryNodeModel* linkNode;
// 2013-04-11 link from this model -> for finding word form by basic form and features
vector<DictionaryNodeModel*> linkFrom;
};
#endif /* _DICTIONARYNODEMODEL_H_ */
| 27.690909 | 100 | 0.690742 | [
"vector",
"model"
] |
5a148bc8b36389e78037dc98a642e479b97d6971 | 25,257 | c | C | mex/include/sisl-4.5.0/src/s1785.c | sangyoonHan/extern | a3c874538a7262b895b60d3c4d493e5b34cf81f8 | [
"BSD-2-Clause"
] | null | null | null | mex/include/sisl-4.5.0/src/s1785.c | sangyoonHan/extern | a3c874538a7262b895b60d3c4d493e5b34cf81f8 | [
"BSD-2-Clause"
] | null | null | null | mex/include/sisl-4.5.0/src/s1785.c | sangyoonHan/extern | a3c874538a7262b895b60d3c4d493e5b34cf81f8 | [
"BSD-2-Clause"
] | null | null | null | //===========================================================================
// SISL - SINTEF Spline Library, version 4.5.0.
// Definition and interrogation of NURBS curves and surfaces.
//
// Copyright (C) 2000-2005, 2010 SINTEF ICT, Applied Mathematics, Norway.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation version 2 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc.,
// 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
//
// Contact information: E-mail: tor.dokken@sintef.no
// SINTEF ICT, Department of Applied Mathematics,
// P.O. Box 124 Blindern,
// 0314 Oslo, Norway.
//
// Other licenses are also available for this software, notably licenses
// for:
// - Building commercial software.
// - Building software whose source code you wish to keep private.
//===========================================================================
#include "sisl-copyright.h"
/*
*
* $Id: s1785.c,v 1.3 2005-02-28 09:04:49 afr Exp $
*
*/
#define S1785
#include "sislP.h"
#if defined(SISLNEEDPROTOTYPES)
/* static void s1785_s9eval(double [], double [], double [],double [], int, int *); */
#else
/* static void s1785_s9eval(); */
#endif
#if defined(SISLNEEDPROTOTYPES)
void
s1785(SISLCurve *pcurve,SISLSurf *psurf,double aepsge,
double epar1[],double epar2[],int icur,int *jstat)
#else
void s1785(pcurve,psurf,aepsge,epar1,epar2,icur,jstat)
SISLCurve *pcurve;
SISLSurf *psurf;
double aepsge;
double epar1[];
double epar2[];
int icur;
int *jstat;
#endif
/*
*********************************************************************
*
*********************************************************************
*
* PURPOSE : Test if a curve and a surface coincide beetween
* two intersection points.
* This function is used when the first derivative
* for the curve and the surface is matching in both
* intersection points.
*
*
* INPUT : pcurve - Pointer to the curve.
* psurf - Pointer to the surface.
* aepsge - Geometry resolution.
* epar1[3] - Parameter values for the first intersection point.
* epar2[3] - Parameter values for the second intersection point.
* icur - = 1 , epar[0] is the parameter value
* for the curve and epar[1],epar[2] is
* the parameter values for the surface.
* = 0 , epar[2] is the parameter value
* for the curve and epar[0],epar[1] is
* the parameter values for the surface.
*
*
*
* OUTPUT : jstat - status messages
* = 1 : Coincidence of curve and surface
* = 0 : No coincidence.
* < 0 : Error.
*
*
* METHOD : March along the curve and iterate down to the surface for
* each midpoint and endpoint of each step. The steplenght
* is computed from the curvature of the curve and the surface
* in the direction of the curve, and from the knot vector
* of the curve. If any knot lines of the surface are crossed,
* the marching are drawn back to the knot line, and a new
* step is initiated. NB. To speed up the marching, the step
* length estimate from the surface is commented out.
*
*
* REFERENCES :
*
* WRITTEN BY : Tor Dokken, SI, Oslo, Norway. July 1989
* REWISED BY : Vibeke Skytt, SI, Oslo, Norway. Oct. 1990
*
*********************************************************************
*/
{
int kstat; /* Status variable */
int ki; /* Counter. */
int kleftc=0; /* Left indicator for point calculation */
int kleft1=0; /* Left indicator for point calculation in 1. par.
direction of surface. */
int kleft2=0; /* Left indicator for point calculation in 2. par dir.*/
int kleft1prev,kleft2prev; /* Previous left indicators of surface. */
int khelp; /* Help index of knot vector. */
int kn; /* The number of B-splines, i.e., the dimension of
the spline space associated with the knot
vector. */
int kk; /* The polynomial order of the curve. */
int kk1,kk2,kn1,kn2;/* Orders and nu,ber of vertices of surface */
int kdimc; /* The dimension of the space in which the curve
lies. Equivalently, the number of components
of each B-spline coefficient. */
int kdims; /* Dimension of space where the surface lies */
int kpos=0; /* Position of error */
int kderc=2; /* Number of derivatives to be claculated on curve */
int kders=1; /* Number of derivatives to be calculated on surface
If step lenght is to be generated from surface,
kders must be equal to 2. */
int kdum; /* Temporary variable */
int kpar; /* Parameter value of constant parameter curve. */
double tclose1,tclose2; /* Parameter values of closest point between curves. */
double snorm[3]; /* Normal vector of surface */
double s3dinf1[10]; /* Pointer to storage for point info of curve
(10 dobules prpoint when idim=3, 7 when idim=3) */
double *st; /* Pointer to the first element of the knot vector
of the curve. The knot vector has [kn+kk]
elements. */
double *st1; /* First knot direction of surface */
double *st2; /* Second knot direction of surface */
double sfirst[2]; /* Start parameter par in surface */
double slast[2]; /* End parameter par in surface */
double tfirst; /* Fist parameter on curve */
double tend; /* Last parameter on curve */
double sderc[9]; /* Position, first and second derivative of curve */
double sders[18]; /* Position, first and second derivatives of surface */
double tx,tx1,tx2; /* Parameter value */
double tcstep; /* Step length based on curvature of objects. */
double tstep; /* Final step length */
double tmaxinc; /* Maximal increment in parameter value along curve*/
double tlengthend; /* Length of 1st derivative at end of segment */
double tincre; /* Parameter value increment */
double tsmax,tcmax; /* Local maximal step length based of boxsizes of objects */
double tdist; /* Distance */
double tref; /* Referance value in equality test. */
double sstart[2]; /* Lower boundary of parameter intervals */
double send[2]; /* Upper bounadry of parameter intervals */
double snext[3]; /* Existing iteration point on surface */
double spos[3]; /* New iteration point on surface */
double snext2[2]; /* Help parameter values. */
SISLPoint *qpoint=SISL_NULL;
SISLCurve *qc = SISL_NULL; /* Constant parameter curve. */
*jstat = 0;
/* Make maximal step length based on box-size of surface */
sh1992su(psurf,0,aepsge,&kstat);
if (kstat < 0) goto error;
tsmax = MAX(psurf->pbox->e2max[0][0] - psurf->pbox->e2min[0][0],
psurf->pbox->e2max[0][1] - psurf->pbox->e2min[0][1]);
tsmax = MAX(tsmax,psurf->pbox->e2max[0][2] - psurf->pbox->e2min[0][2]);
/* Make maximal step length based on box-size of curve */
sh1992cu(pcurve,0,aepsge,&kstat);
if (kstat < 0) goto error;
tcmax = MAX(pcurve->pbox->e2max[0][0] - pcurve->pbox->e2min[0][0],
pcurve->pbox->e2max[0][1] - pcurve->pbox->e2min[0][1]);
tcmax = MAX(tcmax,pcurve->pbox->e2max[0][2] - pcurve->pbox->e2min[0][2]);
/* Copy curve attributes to local parameters. */
kdimc = pcurve -> idim;
kk = pcurve -> ik;
kn = pcurve -> in;
st = pcurve -> et;
/* Copy surface attributes to local parameters. */
kdims = psurf -> idim;
kk1 = psurf -> ik1;
kk2 = psurf -> ik2;
kn1 = psurf -> in1;
kn2 = psurf -> in2;
st1 = psurf -> et1;
st2 = psurf -> et2;
/* Set reference value. */
tref = MAX(st[kn]-st[kk-1],MAX(st1[kn1]-st1[kk1-1],st2[kn2]-st2[kk2-1]));
/* Check that dimensions are 3 */
if (kdimc != 3 || kdims != 3) goto err105;
sstart[0] = st1[kk1-1];
sstart[1] = st2[kk2-1];
send[0] = st1[kn1];
send[1] = st2[kn2];
/* Copy interval description into local variables */
if (icur ==1)
if ( epar1[0]<epar2[0] )
{
sfirst[0] = epar1[1];
sfirst[1] = epar1[2];
slast[0] = epar2[1];
slast[1] = epar2[2];
tfirst = epar1[0];
tend = epar2[0];
}
else
{
sfirst[0] = epar2[1];
sfirst[1] = epar2[2];
slast[0] = epar1[1];
slast[1] = epar1[2];
tfirst = epar2[0];
tend = epar1[0];
}
else
if ( epar1[2]<epar2[2] )
{
sfirst[0] = epar1[0];
sfirst[1] = epar1[1];
slast[0] = epar2[0];
slast[1] = epar2[1];
tfirst = epar1[2];
tend = epar2[2];
}
else
{
sfirst[0] = epar2[0];
sfirst[1] = epar2[1];
slast[0] = epar1[0];
slast[1] = epar1[1];
tfirst = epar2[2];
tend = epar1[2];
}
/* To make sure we do not start outside or end outside the curve we
truncate tstart and tend to the knot interval of the curve */
tfirst = MAX(tfirst,st[kk-1]);
tend = MIN(tend,st[kn]);
if (DEQUAL(tfirst,tend)) goto out;
/* Set start point of iteration on surface */
spos[0] = sfirst[0];
spos[1] = sfirst[1];
/* Store knot values at start of curve */
tx2 = tfirst;
kdum = MAX(kk1,kk2);
kdum = MAX(kdum,kk);
tmaxinc = (tend-tfirst)/(kdum*kdum);
/* Make start point of curve */
s1221(pcurve,kderc,tx2,&kleftc,sderc,&kstat);
if (kstat<0) goto error;
/* Make start point of surface. */
s1421(psurf,kders,spos,&kleft1,&kleft2,sders,snorm,&kstat);
if (kstat < 0) goto error;
/* While end not reached */
while (tx2 < tend)
{
/* Save parameters of previous step. */
tx1 = tx2;
snext[0] = spos[0];
snext[1] = spos[1];
kleft1prev = kleft1;
kleft2prev = kleft2;
/* Calculate unit tangent and radius of curvature of curve. */
s1307(sderc,kdimc,s3dinf1,&kstat);
if (kstat<0) goto error;
/* Calculate step length based on curvature */
tcstep = s1311(s3dinf1[3*kdimc],aepsge,tsmax,&kstat);
if (kstat<0) goto error;
/* Remember length of start tangent, end of zero segment */
tlengthend = s6length(sderc+kdimc,kdimc,&kstat);
if (kstat<0) goto error;
/* Compute position, first and second derivative of the curve in the
surface going through the evaluated point in this point.
s1785_s9eval(sders,snorm,sderc+kdimc,sder2,kdims,&kstat);
if (kstat < 0) goto error;
Calculate unit tangent and radius of curvature of curve in surface.
s1307(sder2,kdims,s3dinf2,&kstat);
if (kstat<0) goto error;
Calculate step length based on curvature
tsstep = s1311(s3dinf2[3*kdims],aepsge,tcmax,&kstat);
if (kstat<0) goto error;
Compute minimum step length.
tstep = MIN(tcstep,tsstep); */
tstep = tcstep;
/* Find candidate end point, make sure that no breaks in tangent or
curvature exists between start and endpoints of the segment */
/* Make step length equal to resolution if the length is zero */
/* Find parameter value of candidate end point of segment */
if (DEQUAL(tlengthend,DZERO))
tincre = REL_PAR_RES;
else
tincre = tstep/tlengthend;
/* Make sure that we don't pass any knots of the curve. */
tincre = MIN(tincre,tmaxinc);
tx2 = MIN(tx1 + tincre,st[kleftc+1]);
for (ki=0, tx=(tx1+tx2)/(double)2.0; ki<2; ki++, tx=tx2)
{
if (tx >= tend) break;
/* Make point sderc at curve at tx */
s1221(pcurve,kderc,tx,&kleftc,sderc,&kstat);
if (kstat<0) goto error;
/* Find closest point on surface to sderc */
qpoint = newPoint(sderc,kdimc,0);
if (qpoint==SISL_NULL) goto err101;
snext2[0] = snext[0];
snext2[1] = snext[1];
s1773(qpoint,psurf,aepsge,sstart,send,snext2,spos,&kstat);
if(kstat<0) goto error;
freePoint(qpoint); qpoint = SISL_NULL;
/* Calculate point and derivatives in surface */
s1421(psurf,kders,spos,&kleft1,&kleft2,sders,snorm,&kstat);
if (kstat<0) goto error;
/* Check if point on curve and surface are within positional and
angular tolerances */
tdist = s6dist(sderc,sders,kdimc);
if (tdist>aepsge)
{
/* Points not within tolerances, curve and surface do not
coincide */
goto war01;
}
/* Check if any parameter lines of the surface is crossed in the 1.
parameter direction. */
/* changed by Michael Metzger, Feb 1993 */
/* for (khelp=kleft1prev-1; DEQUAL(st1[khelp],st1[kleft1prev]); khelp--); */
for (khelp=kleft1prev-1; khelp >= 0 && DEQUAL(st1[khelp],st1[kleft1prev]); khelp--);
if (kleft1 != kleft1prev &&
((DNEQUAL(spos[0]+tref,st1[kleft1]+tref) &&
DNEQUAL(snext[0]+tref,st1[kleft1]+tref)) ||
kleft1 != kleft1prev+1) &&
((DNEQUAL(snext[0]+tref,st1[kleft1prev]+tref) &&
DNEQUAL(spos[0]+tref,st1[kleft1prev]+tref)) || kleft1 != khelp))
{
/* At least one parameter line is crossed. Fetch the constant parameter
curve at the closest parameter line in the direction of the marching. */
if (kleft1 > kleft1prev) kpar = kleft1prev + 1;
else if (snext[0] != st1[kleft1prev]) kpar = kleft1prev;
else kpar = khelp;
/* Pick constant parameter curve. */
s1437(psurf,st1[kpar],&qc,&kstat);
if (kstat < 0) goto error;
/* Find the closest point between the input curve and the constant
parameter curve. */
s1770(pcurve,qc,aepsge,tx1,st2[kk2-1],tx,st2[kn2],(tx1+tx)/(double)2.0,
st2[kleft2],&tclose1,&tclose2,&kstat);
if (kstat < 0) goto error;
/* Set new parameter values to the iteration. */
spos[0] = st1[kpar];
spos[1] = tclose2;
tx2 = tclose1;
/* Test midpoint of reduced step. First evaluate curve in midpoint. */
tx = (tx1 + tx2)/(double)2.0;
s1221(pcurve,kderc,tx,&kleftc,sderc,&kstat);
if (kstat<0) goto error;
/* Find closest point on surface to sderc */
qpoint = newPoint(sderc,kdimc,0);
if (qpoint==SISL_NULL) goto err101;
snext2[0] = snext[0];
snext2[1] = snext[1];
s1773(qpoint,psurf,aepsge,sstart,send,snext2,snext2,&kstat);
if(kstat<0) goto error;
freePoint(qpoint); qpoint = SISL_NULL;
/* Calculate point and derivatives in surface */
s1421(psurf,kders,snext2,&kleft1,&kleft2,sders,snorm,&kstat);
if (kstat<0) goto error;
/* Check if point on curve and surface are within positional and
angular tolerances */
tdist = s6dist(sderc,sders,kdimc);
if (tdist>aepsge)
{
/* Points not within tolerances, curve and surface do not
coincide */
goto war01;
}
/* Calculate point and derivatives in the curve in the endpoint of the step. */
s1221(pcurve,kderc,tx2,&kleftc,sderc,&kstat);
if (kstat<0) goto error;
/* Calculate point and derivatives in the surface. */
s1421(psurf,kders,spos,&kleft1,&kleft2,sders,snorm,&kstat);
if (kstat<0) goto error;
/* Check if point on curve and surface are within positional and
angular tolerances */
tdist = s6dist(sderc,sders,kdimc);
if (tdist>aepsge)
{
/* Points not within tolerances, curve and surface do not
coincide */
goto war01;
}
/* Mark that a new step is to be initiated. */
ki = 2;
/* Free constant parameter curve. */
if (qc != SISL_NULL) freeCurve(qc); qc = SISL_NULL;
}
/* Check if any parameter lines of the surface is crossed in the 2.
parameter direction. */
/* changed by Michael Metzger, Feb 1993 */
/* for (khelp=kleft2prev-1; DEQUAL(st2[khelp],st2[kleft2prev]); khelp--); */
for (khelp=kleft2prev-1; khelp >= 0 && DEQUAL(st2[khelp],st2[kleft2prev]); khelp--);
if (kleft2 != kleft2prev &&
((DNEQUAL(spos[1]+tref,st2[kleft2]+tref) &&
DNEQUAL(snext[1]+tref,st2[kleft2]+tref)) ||
kleft2 != kleft2prev+1) &&
((DNEQUAL(snext[1]+tref,st2[kleft2prev]+tref) &&
DNEQUAL(spos[1]+tref,st2[kleft2prev]+tref)) ||
kleft2 != khelp))
{
/* At least one parameter line is crossed. Fetch the constant parameter
curve at the closest parameter line in the direction of the marching. */
if (kleft2 > kleft2prev) kpar = kleft2prev + 1;
else if (snext[1] != st2[kleft2prev]) kpar = kleft2prev;
else kpar = khelp;
/* Pick constant parameter curve. */
s1436(psurf,st2[kpar],&qc,&kstat);
if (kstat < 0) goto error;
/* Find the closest point between the input curve and the constant
parameter curve. */
s1770(pcurve,qc,aepsge,tx1,st1[kk1-1],tx,st1[kn1],(tx1+tx)/(double)2.0,
st1[kleft1],&tclose1,&tclose2,&kstat);
if (kstat < 0) goto error;
/* Set new parameter values to the iteration. */
spos[0] = tclose2;
spos[1] = st2[kpar];
tx2 = tclose1;
/* Test midpoint of reduced step. First evaluate curve in midpoint. */
tx = (tx1 + tx2)/(double)2.0;
s1221(pcurve,kderc,tx,&kleftc,sderc,&kstat);
if (kstat<0) goto error;
/* Find closest point on surface to sderc */
qpoint = newPoint(sderc,kdimc,0);
if (qpoint==SISL_NULL) goto err101;
snext2[0] = snext[0];
snext2[1] = snext[1];
s1773(qpoint,psurf,aepsge,sstart,send,snext2,snext2,&kstat);
if(kstat<0) goto error;
freePoint(qpoint); qpoint = SISL_NULL;
/* Calculate point and derivatives in surface */
s1421(psurf,kders,snext2,&kleft1,&kleft2,sders,snorm,&kstat);
if (kstat<0) goto error;
/* Check if point on curve and surface are within positional and
angular tolerances */
tdist = s6dist(sderc,sders,kdimc);
if (tdist>aepsge)
{
/* Points not within tolerances, curve and surface do not
coincide */
goto war01;
}
/* Calculate point and derivatives in the curve. */
s1221(pcurve,kderc,tx2,&kleftc,sderc,&kstat);
if (kstat<0) goto error;
/* Calculate point and derivatives in the surface. */
s1421(psurf,kders,spos,&kleft1,&kleft2,sders,snorm,&kstat);
if (kstat<0) goto error;
/* Check if point on curve and surface are within positional and
angular tolerances */
tdist = s6dist(sderc,sders,kdimc);
if (tdist>aepsge)
{
/* Points not within tolerances, curve and surface do not
coincide */
goto war01;
}
/* Mark that a new step is to be initiated. */
ki = 2;
/* Free constant parameter curve. */
if (qc != SISL_NULL) freeCurve(qc); qc = SISL_NULL;
}
}
}
/* Curves within tolerance. Test on whether the start- and
endpoint of the curve are identical. */
*jstat = (DEQUAL(tfirst,tend)) ? 0 : 1;
goto out;
/* Curve and surface not within tolerance */
war01: *jstat = 0;
goto out;
/* Error in memory allocation */
err101: *jstat = -101;
s6err("S1785",*jstat,kpos);
goto out;
/* Error in input, dimension not equal to 2 or 3 */
err105: *jstat = -105;
s6err("S1785",*jstat,kpos);
goto out;
/* Error in lower level function */
error: *jstat = kstat;
s6err("S1785",*jstat,kpos);
goto out;
out:
return;
}
#if 0
#if defined(SISLNEEDPROTOTYPES)
static
void
s1785_s9eval(double eders[],double enorms[],double etanc[],
double ederc[],int idim, int *jstat)
#else
static void s1785_s9eval(eders,enorms,etanc,ederc,idim,jstat)
double eders[];
double enorms[];
double etanc[];
double ederc[];
int idim;
int *jstat;
#endif
/*
*********************************************************************
*
*********************************************************************
*
* PURPOSE : Compute the position, first and second derivative of
* a curve going through a given point of the surface when
* the 0-2'th derivatives of the surface is given. The
* tangent of the wanted curve is parallel to the projection
* of a given vector into the tangent plane of the surface.
*
*
* INPUT : eders - 0-2'th derivatives of the surface. Dimension
* is 6*idim.
* enorms - Normal vector of the surface. Dimension is idim.
* etanc - Vector to be projected into the tangent plane
* of the surface. Dimension is idim.
* idim - Dimension of geometry space.
*
*
*
* OUTPUT : ederc - 0-2'th derivative of the curve in the surface.
* jstat - status messages
* > 0 : Warning.
* = 0 : Ok.
* < 0 : Error.
*
*
* METHOD :
*
*
* REFERENCES :
*
* WRITTEN BY : Vibeke Skytt, SI, Oslo, Norway. Oct. 1990
*
*********************************************************************
*/
{
int kstat = 0; /* Status variable. */
int ki; /* Counter. */
int ksign = 1; /* Parameter used in s6findfac. */
double tfac1,tfac2,tfac3; /* Factors found by s6findfac. */
/* Copy position of surface to output array. */
memcopy(ederc,eders,idim,DOUBLE);
/* Compute the factors used to express etanc by the derivatives and normal
of the surface. */
s6findfac(eders+idim,eders+2*idim,enorms,etanc,idim,ksign,&tfac1,&tfac2,
&tfac3,&kstat);
if (kstat < 0) goto error;
/* Compute first and second derivative of the curve in the surface. */
for (ki=0; ki<idim; ki++)
{
ederc[idim+ki] = tfac1*eders[idim+ki] + tfac2*eders[2*idim+ki];
ederc[2*idim+ki] = tfac1*tfac1*eders[3*idim+ki]
+ (double)2.0*tfac1*tfac2*eders[4*idim+ki] + tfac2*tfac2*eders[5*idim+ki];
}
*jstat = 0;
goto out;
/* Error in lower level routine. */
error:
*jstat = kstat;
goto out;
out:
return;
}
#endif /* if 0 */
| 34.410082 | 89 | 0.531338 | [
"geometry",
"vector"
] |
5a19b8f088f9fda92a7e967c6893a919e9a3cd0f | 6,272 | h | C | Engine/source/T3D/components/render/meshComponent_ScriptBinding.h | John3/t3d_benchmarking | 27a5780ad704aa91b45ff1bb0d69ed07668d03be | [
"MIT"
] | 10 | 2015-03-12T20:20:34.000Z | 2021-02-03T08:07:31.000Z | Engine/source/T3D/components/render/meshComponent_ScriptBinding.h | John3/t3d_benchmarking | 27a5780ad704aa91b45ff1bb0d69ed07668d03be | [
"MIT"
] | 3 | 2015-07-04T23:50:43.000Z | 2016-08-01T09:19:52.000Z | Engine/source/T3D/components/render/meshComponent_ScriptBinding.h | John3/t3d_benchmarking | 27a5780ad704aa91b45ff1bb0d69ed07668d03be | [
"MIT"
] | 6 | 2015-11-28T16:18:26.000Z | 2020-03-29T17:14:56.000Z | //-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "console/engineAPI.h"
#include "T3D/components/render/meshComponent.h"
#include "scene/sceneObject.h"
#include "math/mTransform.h"
DefineEngineMethod(MeshComponent, getShapeBounds, Box3F, (), ,
"@brief Get the cobject we're in contact with.\n\n"
"The controlling client is the one that will send moves to us to act on.\n"
"@return the ID of the controlling GameConnection, or 0 if this object is not "
"controlled by any client.\n"
"@see GameConnection\n")
{
return object->getShapeBounds();
}
DefineEngineMethod(MeshComponent, mountObject, bool,
(SceneObject* objB, String node, TransformF txfm), (MatrixF::Identity),
"@brief Mount objB to this object at the desired slot with optional transform.\n\n"
"@param objB Object to mount onto us\n"
"@param slot Mount slot ID\n"
"@param txfm (optional) mount offset transform\n"
"@return true if successful, false if failed (objB is not valid)")
{
if (objB)
{
//BUG: Unsure how it broke, but atm the default transform passed in here is rotated 180 degrees. This doesn't happen
//for the SceneObject mountobject method. Hackish, but for now, just default to a clean MatrixF::Identity
object->mountObjectToNode(objB, node, /*MatrixF::Identity*/txfm.getMatrix());
return true;
}
return false;
}
DefineEngineMethod(MeshComponent, getNodeTransform, TransformF,
(S32 node), (-1),
"@brief Mount objB to this object at the desired slot with optional transform.\n\n"
"@param objB Object to mount onto us\n"
"@param slot Mount slot ID\n"
"@param txfm (optional) mount offset transform\n"
"@return true if successful, false if failed (objB is not valid)")
{
if (node != -1)
{
//BUG: Unsure how it broke, but atm the default transform passed in here is rotated 180 degrees. This doesn't happen
//for the SceneObject mountobject method. Hackish, but for now, just default to a clean MatrixF::Identity
//object->mountObjectToNode( objB, node, /*MatrixF::Identity*/txfm.getMatrix() );
MatrixF mat = object->getNodeTransform(node);
return mat;
}
return TransformF::Identity;
}
DefineEngineMethod(MeshComponent, getNodeEulerRot, EulerF,
(S32 node, bool radToDeg), (-1, true),
"@brief Mount objB to this object at the desired slot with optional transform.\n\n"
"@param objB Object to mount onto us\n"
"@param slot Mount slot ID\n"
"@param txfm (optional) mount offset transform\n"
"@return true if successful, false if failed (objB is not valid)")
{
if (node != -1)
{
//BUG: Unsure how it broke, but atm the default transform passed in here is rotated 180 degrees. This doesn't happen
//for the SceneObject mountobject method. Hackish, but for now, just default to a clean MatrixF::Identity
//object->mountObjectToNode( objB, node, /*MatrixF::Identity*/txfm.getMatrix() );
MatrixF mat = object->getNodeTransform(node);
EulerF eul = mat.toEuler();
if (radToDeg)
eul = EulerF(mRadToDeg(eul.x), mRadToDeg(eul.y), mRadToDeg(eul.z));
return eul;
}
return EulerF(0, 0, 0);
}
DefineEngineMethod(MeshComponent, getNodePosition, Point3F,
(S32 node), (-1),
"@brief Mount objB to this object at the desired slot with optional transform.\n\n"
"@param objB Object to mount onto us\n"
"@param slot Mount slot ID\n"
"@param txfm (optional) mount offset transform\n"
"@return true if successful, false if failed (objB is not valid)")
{
if (node != -1)
{
//BUG: Unsure how it broke, but atm the default transform passed in here is rotated 180 degrees. This doesn't happen
//for the SceneObject mountobject method. Hackish, but for now, just default to a clean MatrixF::Identity
//object->mountObjectToNode( objB, node, /*MatrixF::Identity*/txfm.getMatrix() );
MatrixF mat = object->getNodeTransform(node);
return mat.getPosition();
}
return Point3F(0, 0, 0);
}
DefineEngineMethod(MeshComponent, getNodeByName, S32,
(String nodeName), ,
"@brief Mount objB to this object at the desired slot with optional transform.\n\n"
"@param objB Object to mount onto us\n"
"@param slot Mount slot ID\n"
"@param txfm (optional) mount offset transform\n"
"@return true if successful, false if failed (objB is not valid)")
{
if (!nodeName.isEmpty())
{
//BUG: Unsure how it broke, but atm the default transform passed in here is rotated 180 degrees. This doesn't happen
//for the SceneObject mountobject method. Hackish, but for now, just default to a clean MatrixF::Identity
//object->mountObjectToNode( objB, node, /*MatrixF::Identity*/txfm.getMatrix() );
S32 node = object->getNodeByName(nodeName);
return node;
}
return -1;
}
DefineEngineMethod(MeshComponent, changeMaterial, void, (U32 slot, const char* newMat), (0, ""),
"@brief Change one of the materials on the shape.\n\n")
{
object->changeMaterial(slot, newMat);
} | 40.464516 | 122 | 0.687819 | [
"render",
"object",
"shape",
"transform"
] |
5a281011b1a4257917fad06df7e6278d24bb91bc | 3,654 | c | C | src/mice/src/cspice/getcml_c.c | jared711/meteoroid_orbits | 84428bc33a695fb4bebee383f5094b80ae1d7193 | [
"MIT"
] | 9 | 2018-03-28T16:03:28.000Z | 2022-01-30T20:36:00.000Z | src/mice/src/cspice/getcml_c.c | jared711/meteoroid_orbits | 84428bc33a695fb4bebee383f5094b80ae1d7193 | [
"MIT"
] | null | null | null | src/mice/src/cspice/getcml_c.c | jared711/meteoroid_orbits | 84428bc33a695fb4bebee383f5094b80ae1d7193 | [
"MIT"
] | 2 | 2021-01-25T10:11:10.000Z | 2022-01-09T06:37:06.000Z | /*
-Procedure getcml_c ( Get the command line )
-Abstract
Store the contents of argv and argc for later access..
-Disclaimer
THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE
CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S.
GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE
ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE
PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS"
TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY
WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A
PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC
SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE
SOFTWARE AND RELATED MATERIALS, HOWEVER USED.
IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA
BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT
LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND,
INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS,
REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE
REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY.
RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF
THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY
CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE
ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE.
-Required_Reading
None.
-Keywords
UTILITY
*/
#include <string.h>
#include <stdlib.h>
#include "SpiceUsr.h"
void getcml_c ( SpiceInt * argc,
SpiceChar *** argv )
/*
-Brief_I/O
Variable I/O Description
-------- --- --------------------------------------------------
argc O The number of command line arguments.
argv O The vector of command line arguments.
-Detailed_Input
None.
-Detailed_Output
argc is the number of command line arguments.
argv is the vector of space delimited command line arguments.
Each entry entry contains one argument. argv[0] is the
command name.
-Parameters
None.
-Exceptions
This routines participates in error tracing but detects no errors.
Error detection is done in zzgetcml_c.c.
-Files
None.
-Particulars
This routine is a wrapper function for zzgetcml_c.c. getcml_c
allows a user to access the argv and argc values from any program
module.
-Examples
#include <stdio.h>
#include <stdlib.h>
#include "SpiceUsr.h"
void main( int argc, char *argv[] )
{
/. Store argv and argc for latter access. ./
putcml_c (argc, argv );
..... other stuff .....
..... .....
}
void goop ()
{
..... new module .....
SpiceInt argc;
SpiceChar ** argv;
.....
.....
/. Now get the stored information. ./
getcml_c ( &argc, &argv );
}
-Restrictions
None.
-Literature_References
None.
-Author_and_Institution
E.D. Wright (JPL)
-Version
-CSPICE Version 1.0.1, 08-FEB-1998 (EDW)
Routine rewritten to use private routine zzgetcml_c.c.
-CSPICE Version 1.0.1, 14-JAN-1997 (EDW)
Replaced a defined variable type for argv with a *** declaration.
-CSPICE Version 1.0.0, 6-JAN-1997 (EDW)
-Index_Entries
store/retrieve argc argv
-&
*/
{
/*
'zzgetcml_c' does all the real work. Make the call. The SPICEFALSE
boolean indicates the call is comming from getcml_c.c and not
putcml_c.c
*/
chkin_c( "getcml_c" );
zzgetcml_c ( argc, argv, SPICEFALSE );
chkout_c( "getcml_c" );
}
| 20.3 | 71 | 0.655172 | [
"vector"
] |
5a37c6d94f05f57962296842aeaec43fe5ed046d | 3,929 | h | C | pdb/src/sharedLibraries/headers/LDA/LDADocTopicProbSelection.h | dimitrijejankov/pdb | 395b5ebd48c2c1b14a56bf24aeea726b36559074 | [
"Apache-2.0"
] | 29 | 2018-06-14T03:19:32.000Z | 2021-04-27T02:45:12.000Z | applications/TestLDA/sharedLibraries/headers/LDADocTopicProbSelection.h | dcbdan/plinycompute | a6f1c8ac8f75c09615f08752c82179f33cfc6d89 | [
"Apache-2.0"
] | 4 | 2018-07-03T21:50:14.000Z | 2018-11-01T15:36:07.000Z | applications/TestLDA/sharedLibraries/headers/LDADocTopicProbSelection.h | dcbdan/plinycompute | a6f1c8ac8f75c09615f08752c82179f33cfc6d89 | [
"Apache-2.0"
] | 13 | 2018-06-14T03:39:14.000Z | 2020-08-03T00:58:24.000Z | /*****************************************************************************
* *
* Copyright 2018 Rice 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. *
* *
*****************************************************************************/
#ifndef LDA_DOC_TOPIC_PROB_SELECT_H
#define LDA_DOC_TOPIC_PROB_SELECT_H
#include "Lambda.h"
#include "LambdaCreationFunctions.h"
#include "SelectionComp.h"
#include "PDBVector.h"
#include "IntIntVectorPair.h"
#include "IntDoubleVectorPair.h"
#include "DocAssignment.h"
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <random>
#include <gsl/gsl_vector.h>
/* This class samples the topic probability for the document */
using namespace pdb;
class LDADocTopicProbSelection : public SelectionComp<IntDoubleVectorPair, DocAssignment> {
private:
Vector<double> prior;
Handle<Vector<char>> myMem;
int topicNum;
public:
ENABLE_DEEP_COPY
LDADocTopicProbSelection() {}
LDADocTopicProbSelection(Vector<double>& fromPrior) {
this->prior = fromPrior;
this->topicNum = fromPrior.size();
/* Set up the random number generator */
gsl_rng* src = gsl_rng_alloc(gsl_rng_mt19937);
std::random_device rd;
std::mt19937 gen(rd());
gsl_rng_set(src, gen());
int spaceNeeded = sizeof(gsl_rng) + src->type->size;
myMem = makeObject<Vector<char>>(spaceNeeded, spaceNeeded);
memcpy(myMem->c_ptr(), src, sizeof(gsl_rng));
memcpy(myMem->c_ptr() + sizeof(gsl_rng), src->state, src->type->size);
gsl_rng_free(src);
}
Lambda<bool> getSelection(Handle<DocAssignment> checkMe) override {
return makeLambda(checkMe, [](Handle<DocAssignment>& checkMe) { return true; });
}
Lambda<Handle<IntDoubleVectorPair>> getProjection(Handle<DocAssignment> checkMe) override {
return makeLambda(checkMe, [&](Handle<DocAssignment>& checkMe) {
gsl_rng* rng = getRng();
Vector<unsigned>& topicCount = checkMe->getVector();
Handle<Vector<double>> mySamples = makeObject<Vector<double>>(topicNum, topicNum);
double* totalProb = new double[topicNum];
for (int i = 0; i < topicNum; i++) {
totalProb[i] = (this->prior)[i] + topicCount[i];
}
/* Sample the topic probability */
gsl_ran_dirichlet(rng, topicNum, totalProb, mySamples->c_ptr());
Handle<IntDoubleVectorPair> result =
makeObject<IntDoubleVectorPair>(checkMe->getKey(), mySamples);
delete[] totalProb;
return result;
});
}
gsl_rng* getRng() {
gsl_rng* dst = (gsl_rng*)myMem->c_ptr();
dst->state = (void*)(myMem->c_ptr() + sizeof(gsl_rng));
dst->type = gsl_rng_mt19937;
return dst;
}
};
#endif
| 37.419048 | 95 | 0.537287 | [
"vector"
] |
5a3940824718608dd7fe448f452f629d5d92d2b1 | 770 | h | C | src/gui/databaseui.h | JKSH/Wique | 8365a54a98ce3cf89219e3320f638d3bb129d456 | [
"MIT"
] | null | null | null | src/gui/databaseui.h | JKSH/Wique | 8365a54a98ce3cf89219e3320f638d3bb129d456 | [
"MIT"
] | 1 | 2015-08-24T10:57:25.000Z | 2015-08-24T10:57:25.000Z | src/gui/databaseui.h | JKSH/Wique | 8365a54a98ce3cf89219e3320f638d3bb129d456 | [
"MIT"
] | null | null | null | // Copyright (c) 2015 Sze Howe Koh
// This code is licensed under the MIT license (see LICENSE.MIT for details)
#ifndef DATABASEUI_H
#define DATABASEUI_H
#include <QWidget>
class QAbstractTableModel;
class QSortFilterProxyModel;
namespace Ui {
class DatabaseUI;
}
class DatabaseUI : public QWidget
{
Q_OBJECT
signals:
void refreshDbRequested() const;
void forceRederiveRequested() const;
void exportRequested(const QString& exportDir) const;
public:
explicit DatabaseUI(QWidget* parent = nullptr);
~DatabaseUI();
void setDbModel(QAbstractTableModel* model);
void writeLog(const QString& message);
public slots:
void setButtonsEnabled(bool enabled = true);
private:
Ui::DatabaseUI *ui;
QSortFilterProxyModel* modelFilter;
};
#endif // DATABASEUI_H
| 18.333333 | 76 | 0.772727 | [
"model"
] |
5a3a609cd9254006308e6b2da99fca4a7ebf59a5 | 8,087 | h | C | pico-ps/service/TableDescriptor.h | 4paradigm/parameter-server | 17ce27df2f4777952d7c44a0aea2e3130144e615 | [
"Apache-2.0"
] | 3 | 2021-08-25T14:14:30.000Z | 2021-12-22T04:26:22.000Z | pico-ps/service/TableDescriptor.h | 4paradigm/parameter-server | 17ce27df2f4777952d7c44a0aea2e3130144e615 | [
"Apache-2.0"
] | null | null | null | pico-ps/service/TableDescriptor.h | 4paradigm/parameter-server | 17ce27df2f4777952d7c44a0aea2e3130144e615 | [
"Apache-2.0"
] | 2 | 2021-09-12T09:05:08.000Z | 2021-09-12T13:36:13.000Z | #ifndef PARADIGM4_PICO_PS_SERVICE_TABLEDESCRIPOTR_H
#define PARADIGM4_PICO_PS_SERVICE_TABLEDESCRIPOTR_H
#include <functional>
#include <memory>
#include <unordered_map>
#include <boost/any.hpp>
#include "pico-ps/common/core.h"
#include "pico-ps/common/Status.h"
#include "pico-ps/storage/Storage.h"
#include "pico-ps/service/IncrementStorage.h"
namespace paradigm4 {
namespace pico {
namespace ps {
constexpr int EMPTY_COMM_RANK = -1;
class Operator;
struct OperatorDescriptor {
std::string key;
std::string lib_name;
std::string op_name;
std::string config_str;
OperatorDescriptor();
OperatorDescriptor(const std::string& s0,
const std::string& s1,
const std::string& s2,
const std::string& s3);
PicoJsonNode to_json_node() const;
bool from_json_node(const PicoJsonNode& node);
};
enum class NodeStatus : int {
RUNNING = 0,
DEAD = 1,
LOADING = 2,
UNAVAILABALE = 3
};
enum class StorageStatus : int {
NORMAL = 0,
RESHARD = 1,
LOADING = 2
};
struct NodeDescriptor {
std::vector<int32_t> shard_list;
NodeStatus status;
int node_id;
NodeDescriptor();
NodeDescriptor(const Configure& config);
PicoJsonNode to_json_node() const;
bool from_json_node(const PicoJsonNode& node);
};
class RuntimeInfo;
struct TableDescriptor {
//应该使用指针或引用
TableDescriptor() = default;
TableDescriptor(const TableDescriptor&) = delete;
TableDescriptor& operator=(const TableDescriptor&) = delete;
TableDescriptor(TableDescriptor&&) = delete;
TableDescriptor& operator=(TableDescriptor&&) = delete;
// 用于快速查找 shard 所在 node, shards 与 node_descs 中信息一致, update_shards 与
// update_node_descs 中信息一致,其中不会包括状态为 DEAD 的 node 信息。
std::unordered_map<int32_t, std::vector<int>> shards, update_shards;
// 用于快速查找 node 中suo, shards 与 node_descs 中信息一致, update_shards 与
// update_node_descs 中信息一致,其中不会包括状态为 DEAD 的 node 信息。
std::unordered_map<int, std::vector<int32_t>> nodes, update_nodes;
// Master 上保存的 node 描述符
std::vector<NodeDescriptor> node_descs, update_node_descs;
std::string table_uri = ""; // full path
int version = 0;
int update_version = 0;
std::string version_uuid = "";
StorageStatus storage_status = StorageStatus::NORMAL;
//todo 每个push_operator对应一个delta_storage
std::unique_ptr<Storage> storage, delta_storage;
std::unique_ptr<Storage> update_storage;
//update_storage用于存储shuffle时的push item,否则读写相互等待导致死锁。
//更新增量存储
IncrementStorage* incr_storage = nullptr;
std::shared_ptr<Operator> storage_op;
OperatorDescriptor storage_op_desc;
// op_key -> handler id
std::unordered_map<std::string, int32_t> key_to_hdl;
// handler id -> Op desc
std::unordered_map<int32_t, OperatorDescriptor> op_descs;
// handler id -> Op object
std::unordered_map<int32_t, std::shared_ptr<Operator>> handlers; // for runtime
// 运行时信息, 运行时信息与 TableDescriptor 中信息冗余
std::unique_ptr<RuntimeInfo> runtime_info;
// reshard 目标状态的运行时信息, 运行时信息与 TableDescriptor 中信息冗余
std::unique_ptr<RuntimeInfo> new_runtime_info;
std::string table_name = "";
Configure to_yaml_create_storage_config() const;
bool add_handler(int32_t handler_id,
std::shared_ptr<Operator>& op,
const std::string& key,
const std::string& lib_name,
const std::string& op_name,
const Configure& config);
bool remove_handler(int32_t handler_id);
std::string to_json_str() const;
PicoJsonNode to_json_node() const;
bool from_json_node(const PicoJsonNode& node, bool& updated, bool force_update = false);
bool from_json_str(const std::string& str, bool& updated, bool force_update = false);
// 根据 node descriptor 更新 shards 和 nodes 信息
// 只有状态为 RUNNING 的 node 的信息才会被更新至 shards 和 nodes 中。
inline void refresh_info() {
refresh_info(node_descs, shards, nodes);
}
// 根据 update node descriptor 更新 update shards 和 update nodes 信息,
// 只有状态为 RUNNING 的 update node 的信息才会被更新至 update shards 和 update nodes 中。
inline void refresh_info_update() {
refresh_info(update_node_descs, update_shards, update_nodes);
}
bool update_node_status(const std::unordered_set<int>& live_servers);
// target_dead_node_id 是目标要替换的 dead node id,如果找到的dead node 里没有匹配的 dead node id,
// 即使有 dead node,该函数也不会替换此 node。
// 当 target_dead_node_id 为 -1 时,没有此限制。
// 返回值:替换掉的 dead node id,-1 表示没有替换。
int try_to_replace_one_dead_node(int my_node_id, int target_dead_node_id);
// 将 node descriptor 中此 node 状态中的 LOADING 状态改为 RUNNING 状态。
bool set_node_status_to_running(int my_node_id);
// 用 update_node 信息替换当前 node 信息,表示 reshard 结束
void apply_update();
void drop_update();
// 根据 config 中包含的 update node 配置信息更新当前的 update node 描述符。
Status create_update_info(const Configure& config);
void gen_new_version_uuid();
private:
void refresh_info(std::vector<NodeDescriptor>& nds,
std::unordered_map<int32_t, std::vector<int>>& shard_info,
std::unordered_map<int, std::vector<int32_t>>& node_info);
// 根据 (update) node descriptor 更新 (update) shards 和 (update) nodes 信息,
// 状态为 RUNNING 或者 LOADING 的 node 的信息都会被更新至 shards 和 nodes 中。
// 用于 restore 阶段
//void refresh_info_with_loading(std::vector<NodeDescriptor>& nds,
//std::unordered_map<int32_t, std::vector<int>>& shard_info,
//std::unordered_map<int, std::vector<int32_t>>& node_info);
};
enum class PickAlgo {
RANDOM,
ROUND_ROBIN,
};
class RuntimeInfo {
public:
RuntimeInfo(TableDescriptor& td, int my_rank, bool update = false);
std::vector<int> pick_one_replica(PickAlgo algo);
void update_nodes();
int32_t global_shard_num() {
return _shards->size();
}
const std::unordered_set<int32_t>& local_shards() {
return _local_shards;
}
const std::string local_shards_str() {
std::ostringstream oss;
std::copy(_local_shards.begin(), _local_shards.end(), std::ostream_iterator<int32_t>(oss, " "));
return oss.str();
}
const std::unordered_map<int32_t, std::vector<int>>& shards() {
return *_shards;
}
const std::unordered_map<int, std::vector<int32_t>>& nodes() {
return *_nodes;
}
int node_id() const {
return _node_id;
}
private:
std::vector<int> random_pick();
std::vector<int> rr_pick();
std::unordered_map<int32_t, std::vector<int>>* _shards;
std::unordered_map<int, std::vector<int32_t>>* _nodes;
std::vector<NodeDescriptor>* _node_descs;
int _node_id;
std::unordered_set<int32_t> _local_shards;
};
class TableDescriptorReader {
public:
TableDescriptorReader();
TableDescriptorReader(TableDescriptor* table, RWSpinLock& mtx);
TableDescriptorReader(const TableDescriptorReader&) = delete;
TableDescriptorReader& operator=(const TableDescriptorReader&) = delete;
TableDescriptorReader(TableDescriptorReader&& rhs);
TableDescriptorReader& operator=(TableDescriptorReader&& rhs);
~TableDescriptorReader();
void Release();
TableDescriptor& table() {
return *_table;
}
private:
TableDescriptor* _table = nullptr;
boost::shared_lock<RWSpinLock>* _lock = nullptr;
};
class TableDescriptorWriter {
public:
TableDescriptorWriter();
TableDescriptorWriter(TableDescriptor* table, RWSpinLock& mtx);
TableDescriptorWriter(const TableDescriptorWriter&) = delete;
TableDescriptorWriter& operator=(const TableDescriptorWriter&) = delete;
TableDescriptorWriter(TableDescriptorWriter&& rhs);
TableDescriptorWriter& operator=(TableDescriptorWriter&& rhs);
~TableDescriptorWriter();
void Release();
TableDescriptor& table() {
return *_table;
}
private:
TableDescriptor* _table = nullptr;
core::lock_guard<RWSpinLock>* _lock = nullptr;
};
} // namespace ps
} // namespace pico
} // namespace paradigm4
#endif // PARADIGM4_PICO_PS_SERVICE_TABLEDESCRIPOTR_H
| 28.276224 | 104 | 0.699394 | [
"object",
"vector"
] |
5a3cc84edc75330e8dc19b9225882141238e986b | 2,539 | h | C | include/fvm/impl/communicators/pattern.h | jackd/FVMPor | 96092319da04527d13a7af4485e8ca30052aba19 | [
"BSD-3-Clause"
] | 2 | 2020-07-18T13:29:38.000Z | 2021-01-05T05:48:11.000Z | include/fvm/impl/communicators/pattern.h | jackd/FVMPor | 96092319da04527d13a7af4485e8ca30052aba19 | [
"BSD-3-Clause"
] | null | null | null | include/fvm/impl/communicators/pattern.h | jackd/FVMPor | 96092319da04527d13a7af4485e8ca30052aba19 | [
"BSD-3-Clause"
] | 3 | 2015-06-01T19:39:55.000Z | 2021-01-05T05:48:27.000Z | #ifndef PATTERN_H
#define PATTERN_H
#include <algorithm>
#include <numeric>
#include <vector>
#include <map>
#include <mpi/mpicomm.h>
namespace mesh {
class Pattern{
public:
Pattern() {};
Pattern(mpi::MPICommPtr);
// return information about pattern to caller
const std::vector<int>& neighbour_list() const;
int num_neighbours() const;
int neighbour(int n) const;
const std::vector<int>& send_index(int n) const;
const std::vector<int>& recv_index(int n) const;
mpi::MPICommPtr comm() const;
bool is_neighbour( int n ) const;
// add a neighbour to the pattern
void add_neighbour( int n, std::vector<int>& send, std::vector<int>& recv );
// sanity check the pattern to ensure that it is consistent over all subdomains.
bool verify_pattern() const;
private:
mpi::MPICommPtr comm_;
std::vector<int> neighbours_;
std::map<int,std::vector<int> > send_index_;
std::map<int,std::vector<int> > recv_index_;
};
inline
Pattern::Pattern( mpi::MPICommPtr comm ){
comm_ = comm;
}
inline
const std::vector<int>& Pattern::neighbour_list() const{
return neighbours_;
}
inline
int Pattern::num_neighbours() const{
return neighbours_.size();
}
inline
mpi::MPICommPtr Pattern::comm() const{
return comm_;
}
inline
int Pattern::neighbour(int n) const{
assert( n>=0 && n<num_neighbours() );
return neighbours_[n];
}
inline
const std::vector<int>& Pattern::send_index(int n) const{
std::map<int,std::vector<int> >::const_iterator it = send_index_.find(n);
assert( it!=send_index_.end());
return it->second;
}
inline
const std::vector<int>& Pattern::recv_index(int n) const{
std::map<int,std::vector<int> >::const_iterator it = recv_index_.find(n);
assert( it!=recv_index_.end());
return it->second;
}
inline
bool Pattern::is_neighbour( int n ) const{
return( std::find(neighbours_.begin(), neighbours_.end(), n) != neighbours_.end() );
}
// add a neighbour to the pattern
inline
void Pattern::add_neighbour( int n, std::vector<int>& send, std::vector<int>& recv ){
// sanity check
//assert(n>=0 && n<comm_.size()); // ensure that n is in the MPI group
assert(n>=0 && n<comm_->size()); // ensure that n is in the MPI group
assert( !is_neighbour(n) ); // ensure that this neighbour has not already been added
neighbours_.push_back(n);
send_index_[n] = send;
recv_index_[n] = recv;
}
} // namespace fvm
#endif
| 25.39 | 88 | 0.652225 | [
"mesh",
"vector"
] |
5a452b10a688e78f7eefdcc11b2b6edd3999aef9 | 2,866 | h | C | src/Giles_tensor/Giles_tensor.h | inakleinbottle/tensor_playground | 868dba9e6050c75e68cf98db99ac94e0efcc7360 | [
"MIT"
] | 1 | 2022-01-11T14:04:54.000Z | 2022-01-11T14:04:54.000Z | src/Giles_tensor/Giles_tensor.h | inakleinbottle/tensor_playground | 868dba9e6050c75e68cf98db99ac94e0efcc7360 | [
"MIT"
] | null | null | null | src/Giles_tensor/Giles_tensor.h | inakleinbottle/tensor_playground | 868dba9e6050c75e68cf98db99ac94e0efcc7360 | [
"MIT"
] | null | null | null | //
// Created by sam on 07/11/2021.
//
#ifndef TENSOR_PLAYGROUND_GILES_TENSOR_H
#define TENSOR_PLAYGROUND_GILES_TENSOR_H
#include <iosfwd>
#include <vector>
class Giles_tensor : std::vector<double> {
using base_type = std::vector<double>;
public:
using typename base_type::size_type;
using base_type::operator[];
using base_type::assign;
using base_type::begin;
using base_type::data;
using base_type::emplace_back;
using base_type::end;
using base_type::size;
using base_type::operator=;
using degree_type = unsigned;
private:
degree_type m_degree;
degree_type m_width;
std::vector<size_type> size_array;
std::vector<double> transposed_data;
Giles_tensor(degree_type width);
void populate_size_array(degree_type maxd);
public:
Giles_tensor() = delete;
Giles_tensor(degree_type
width,
degree_type depth);
Giles_tensor(degree_type
width,
degree_type depth, std::initializer_list<double> args);
double *range_begin();
double *range_end();
const double *range_begin() const;
const double *range_end() const;
const double *trange_begin() const;
const double *trange_end() const;
degree_type degree() const;
degree_type width() const;
Giles_tensor &operator+=(const Giles_tensor &rhs);
Giles_tensor &operator-=(const Giles_tensor &rhs);
Giles_tensor &operator*=(double rhs);
Giles_tensor &operator/=(double rhs);
Giles_tensor operator+(const Giles_tensor &rhs) const;
Giles_tensor operator-(const Giles_tensor &rhs) const;
Giles_tensor operator*(double rhs) const;
Giles_tensor operator/(double rhs) const;
Giles_tensor &add_scal_prod(const Giles_tensor &rhs, double sca);
Giles_tensor &sub_scal_prod(const Giles_tensor &rhs, double sca);
Giles_tensor &add_scal_div(const Giles_tensor &rhs, double sca);
Giles_tensor &sub_scal_div(const Giles_tensor &rhs, double sca);
Giles_tensor &operator*=(const Giles_tensor &rhs);
Giles_tensor operator*(const Giles_tensor &rhs) const;
Giles_tensor &mul_scal_mul(const Giles_tensor &rhs, double sca);
Giles_tensor &mul_scal_div(const Giles_tensor &rhs, double sca);
bool operator==(const Giles_tensor &other) const;
bool operator!=(const Giles_tensor &other) const;
friend std::ostream &operator<<(std::ostream &os, const Giles_tensor &arg);
friend Giles_tensor exp(const Giles_tensor &arg);
friend double L1Norm(const Giles_tensor &arg) noexcept;
friend double LInfNorm(const Giles_tensor &arg) noexcept;
};
std::ostream &operator<<(std::ostream &os, const Giles_tensor &arg);
double L1Norm(const Giles_tensor &arg) noexcept;
double LInfNorm(const Giles_tensor &arg) noexcept;
#endif//TENSOR_PLAYGROUND_GILES_TENSOR_H
| 28.949495 | 79 | 0.710747 | [
"vector"
] |
5a4a42b6d16131fd7c8c78e0d6a2733f24d29ed7 | 12,253 | c | C | src/mutex.c | shuangmin/libpthread | 38821d529407dcb0b4661c6805d7b1bf83f3204d | [
"Apache-2.0"
] | 13 | 2015-04-25T17:34:44.000Z | 2021-01-22T08:25:13.000Z | src/mutex.c | shuangmin/libpthread | 38821d529407dcb0b4661c6805d7b1bf83f3204d | [
"Apache-2.0"
] | null | null | null | src/mutex.c | shuangmin/libpthread | 38821d529407dcb0b4661c6805d7b1bf83f3204d | [
"Apache-2.0"
] | 12 | 2015-01-04T06:22:56.000Z | 2020-06-06T16:16:22.000Z | /*
* Copyright (c) 2011, Dongsheng Song <songdongsheng@live.cn>
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file mutex.c
* @brief Implementation Code of Mutex Routines
*/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
#include "arch.h"
#include "misc.h"
/**
* Create a mutex attribute object.
* @param attr The pointer of the mutex attribute object.
* @return Always return 0.
* @remark We provide pthread_mutexattr_* functions only for compatibility,
* please use pthread_mutex_init(&mutex, NULL) for new applications.
*/
int pthread_mutexattr_init(pthread_mutexattr_t *attr)
{
arch_mutex_attr *pv = calloc(1, sizeof(arch_mutex_attr));
if (pv == NULL)
return ENOMEM;
pv->type = PTHREAD_MUTEX_DEFAULT;
pv->pshared = PTHREAD_PROCESS_PRIVATE;
pv->robust = PTHREAD_MUTEX_STALLED;
*attr = pv;
return 0;
}
/**
* Get the mutex robust attribute.
* @param attr The pointer of the mutex attribute object.
* @param robust The mutex robust attribute.
* @return Always return 0.
* @remark This function is provided for source code compatibility but no effect when called.
*/
int pthread_mutexattr_getrobust(const pthread_mutexattr_t *attr, int *robust)
{
arch_mutex_attr *pv = (arch_mutex_attr *) attr;
*robust = pv->robust;
return 0;
}
/**
* Set the mutex robust attribute.
* @param attr The pointer of the mutex attribute object.
* @param robust The mutex robust attribute.
* @return Always return 0.
* @remark This function is provided for source code compatibility but no effect when called.
*/
int pthread_mutexattr_setrobust(pthread_mutexattr_t *attr, int robust)
{
arch_mutex_attr *pv = (arch_mutex_attr *) attr;
pv->robust = robust;
return 0;
}
/**
* Get the mutex type attribute.
* @param attr The pointer of the mutex attribute object.
* @param type The mutex type.
* @return Always return 0.
* @remark This function is provided for source code compatibility but no effect when called.
*/
int pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *type)
{
arch_mutex_attr *pv = (arch_mutex_attr *) attr;
*type = pv->type;
return 0;
}
/**
* Set the mutex type attribute.
* @param attr The pointer of the mutex attribute object.
* @param type The mutex type.
* @return Always return 0.
* @remark This function is provided for source code compatibility but no effect when called.
*/
int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
{
arch_mutex_attr *pv = (arch_mutex_attr *) attr;
pv->type = type;
return 0;
}
/**
* Get the mutex process-shared attribute.
* @param attr The pointer of the mutex attribute object.
* @param pshared The process-shared attribute.
* @return Always return 0.
* @remark The only type we support is PTHREAD_PROCESS_PRIVATE.
* @remark This function is provided for source code compatibility but no effect when called.
*/
int pthread_mutexattr_getpshared(const pthread_mutexattr_t *attr, int *pshared)
{
arch_mutex_attr *pv = (arch_mutex_attr *) attr;
*pshared = pv->pshared;
return 0;
}
/**
* Set the mutex process-shared attribute.
* @param attr The pointer of the mutex attribute object.
* @param pshared The process-shared attribute.
* @return Always return 0.
* @remark The only type we support is PTHREAD_PROCESS_PRIVATE.
* @remark This function is provided for source code compatibility but no effect when called.
*/
int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared)
{
arch_mutex_attr *pv = (arch_mutex_attr *) attr;
pv->pshared = pshared;
return 0;
}
/**
* Get the mutex protocol attribute.
* @param attr The pointer of the mutex attribute object.
* @param protocol The mutex protocol.
* @return Always return 0.
* @remark This function is provided for source code compatibility but no effect when called.
*/
int pthread_mutexattr_getprotocol(const pthread_mutexattr_t *attr, int *protocol)
{
arch_mutex_attr *pv = (arch_mutex_attr *) attr;
*protocol = pv->protocol;
return 0;
}
/**
* Set the mutex protocol attribute.
* @param attr The pointer of the mutex attribute object.
* @param protocol The mutex protocol.
* @return Always return 0.
* @remark This function is provided for source code compatibility but no effect when called.
*/
int pthread_mutexattr_setprotocol(pthread_mutexattr_t *attr, int protocol)
{
arch_mutex_attr *pv = (arch_mutex_attr *) attr;
pv->protocol = protocol;
return 0;
}
/**
* Get the mutex prioceiling attribute.
* @param attr The pointer of the mutex attribute object.
* @param prioceiling The mutex prioceiling attribute.
* @return Always return 0.
* @remark This function is provided for source code compatibility but no effect when called.
*/
int pthread_mutexattr_getprioceiling(const pthread_mutexattr_t *attr, int *prioceiling)
{
arch_mutex_attr *pv = (arch_mutex_attr *) attr;
*prioceiling = pv->prioceiling;
return 0;
}
/**
* Set the mutex prioceiling attribute.
* @param attr The pointer of the mutex attribute object.
* @param prioceiling The mutex prioceiling attribute.
* @return Always return 0.
* @remark This function is provided for source code compatibility but no effect when called.
*/
int pthread_mutexattr_setprioceiling(pthread_mutexattr_t *attr, int prioceiling)
{
arch_mutex_attr *pv = (arch_mutex_attr *) attr;
pv->prioceiling = prioceiling;
return 0;
}
/**
* Destroy a mutex attribute object.
* @param attr The pointer of the mutex attribute object.
* @return Always return 0.
* @remark This function is provided for source code compatibility but no effect when called.
*/
int pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
{
if (attr != NULL) {
free(*attr);
*attr = NULL;
}
return 0;
}
static int arch_mutex_init(pthread_mutex_t *m, int lock)
{
int cpu_count = get_ncpu();
arch_mutex *pv = calloc(1, sizeof(arch_mutex));
if (pv == NULL)
return ENOMEM;
/* see test_speed, about 1/2 the system call*/
if (cpu_count > 1) pv->spin_count = 32;
if (!lock) {
*m = pv;
return 0;
}
if (atomic_cmpxchg_ptr(m, pv, NULL) != NULL) {
free(pv);
}
return 0;
}
static __inline int spin_lock_with_count(volatile long *lock, int count)
{
int i = 0;
do {
if (atomic_cmpxchg((volatile long *) lock, 1, 0) == 0)
return 1;
cpu_relax();
} while(++i < count);
return 0;
}
static __inline void spin_unlock(volatile long *lock)
{
*lock = 0;
}
static __inline void arch_mutex_init_handle(HANDLE *sync)
{
HANDLE handle;
while (*sync == NULL) {
handle = CreateEvent(NULL, FALSE, FALSE, NULL);
if (handle != NULL) {
if (atomic_cmpxchg_ptr(sync, handle, NULL) != NULL)
(void) CloseHandle(handle);
return;
} else {
(void) SleepEx(1000, TRUE); /* Waiting for resources available */
}
}
}
/**
* Create a mutex object.
* @param m The pointer of the mutex object.
* @param a The pointer of the mutex attribute object.
* @return If the function succeeds, the return value is 0.
* If the function fails, the return value is -1,
* with errno set to indicate the error (ENOMEM).
* @remark We provide pthread_mutexattr_* functions only for compatibility,
* please use pthread_mutex_init(&mutex, NULL) for new applications.
*/
int pthread_mutex_init(pthread_mutex_t *m, const pthread_mutexattr_t *a)
{
*m = NULL;
return arch_mutex_init(m, 0);
}
/**
* Get the mutex prioceiling attribute.
* @param mutex The pointer of the mutex object.
* @param prioceiling The mutex prioceiling attribute.
* @return Always return 0.
* @remark This function is provided for source code compatibility but no effect when called.
*/
int pthread_mutex_getprioceiling(const pthread_mutex_t *mutex, int *prioceiling)
{
*prioceiling = 0;
return 0;
}
/**
* Set the mutex prioceiling attribute.
* @param mutex The pointer of the mutex object.
* @param prioceiling The new mutex prioceiling attribute.
* @param old_ceiling The old mutex prioceiling attribute.
* @return Always return 0.
* @remark This function is provided for source code compatibility but no effect when called.
*/
int pthread_mutex_setprioceiling(pthread_mutex_t *mutex, int prioceiling, int *old_ceiling)
{
*old_ceiling = 0;
return 0;
}
/**
* Mark state protected by robust mutex as consistent.
* @param mutex The pointer of the mutex object.
* @return Always return 0.
* @remark This function is provided for source code compatibility but no effect when called.
*/
int pthread_mutex_consistent(pthread_mutex_t *mutex)
{
return 0;
}
/**
* Acquire a mutex lock.
* @param m The pointer of the mutex object.
* @return If the function succeeds, the return value is 0.
* If the function fails, the return value is -1,
* with errno set to indicate the error (ENOMEM, EDEADLK).
*/
int pthread_mutex_lock(pthread_mutex_t *m)
{
arch_mutex *pv;
if (*m == NULL) {
int rc = arch_mutex_init(m, 1);
if (rc != 0) return rc;
}
pv = (arch_mutex *) *m;
while(1) {
if (spin_lock_with_count(& pv->lock_status, pv->spin_count)) {
/* pv->thread_id = GetCurrentThreadId(); */
return 0;
}
if (pv->sync == NULL)
arch_mutex_init_handle(& pv->sync);
(void) atomic_fetch_and_add(& pv->wait, 1);
/* Small probability event, but we must examine it. */
if (atomic_cmpxchg((volatile long *) & pv->lock_status, 1, 0) == 0) {
/* pv->thread_id = GetCurrentThreadId(); */
(void) atomic_fetch_and_add(& pv->wait, -1);
return 0;
}
(void) WaitForSingleObject(pv->sync, INFINITE);
(void) atomic_fetch_and_add(& pv->wait, -1);
}
return 0;
}
/**
* Try acquire a mutex lock.
* @param m The pointer of the mutex object.
* @return If the function succeeds, the return value is 0.
* If the function fails, the return value is -1,
* with errno set to indicate the error (ENOMEM or EBUSY).
*/
int pthread_mutex_trylock(pthread_mutex_t *m)
{
arch_mutex *pv;
if (*m == NULL) {
int rc = arch_mutex_init(m, 1);
if (rc != 0) return rc;
}
pv = (arch_mutex *) *m;
if (spin_lock_with_count(& pv->lock_status, pv->spin_count)) {
/* pv->thread_id = GetCurrentThreadId(); */
return 0;
}
return EBUSY;
}
/**
* Release a mutex lock.
* @param m The pointer of the mutex object.
* @return If the function succeeds, the return value is 0.
* If the function fails, the return value is -1,
* with errno set to indicate the error (EINVAL).
*/
int pthread_mutex_unlock(pthread_mutex_t *m)
{
arch_mutex *pv = (arch_mutex *) *m;
if (pv != NULL) {
/* pv->thread_id = 0; */
atomic_set(& pv->lock_status, 0);
if (atomic_read(& pv->wait))
SetEvent(pv->sync);
return 0;
}
return EINVAL;
}
/**
* Destroy a mutex lock.
* @param m The pointer of the mutex object.
* @return Always return 0.
*/
int pthread_mutex_destroy(pthread_mutex_t *m)
{
arch_mutex *pv = (arch_mutex *) *m;
if (pv != NULL) {
if (pv->sync != NULL) CloseHandle(pv->sync);
free(pv);
}
return 0;
}
| 28.69555 | 93 | 0.677548 | [
"object"
] |
5a4f2912d0940797b0cc578da10af5b187bbd2b2 | 5,586 | c | C | samples/STM32L476GDISCOVERY/Src/Eve/dependencies/esd_core/Ft_Esd_Utility.c | kaetemi/nuklear_eve | 080f0ead495ffd599a966391537f4dba597a2010 | [
"MIT"
] | 4 | 2019-10-08T03:51:05.000Z | 2022-02-11T12:59:43.000Z | dependencies/esd_core/Ft_Esd_Utility.c | ftdi-paul-jiao/nuklear_eve-1 | 30c585edd0d34f086d625fece755babce3f5f9f5 | [
"MIT"
] | 4 | 2019-05-28T03:17:27.000Z | 2019-07-03T01:35:33.000Z | dependencies/esd_core/Ft_Esd_Utility.c | ftdi-paul-jiao/nuklear_eve-1 | 30c585edd0d34f086d625fece755babce3f5f9f5 | [
"MIT"
] | 3 | 2019-07-02T07:07:58.000Z | 2019-08-05T06:29:05.000Z |
#include <FT_Platform.h>
#include "Ft_Esd_Utility.h"
#include "FT_Gpu_Hal.h"
#include "FT_Gpu.h"
#include "Ft_Esd.h"
#include "FT_Esd_Dl.h"
#include "Ft_Esd_GpuAlloc.h"
#include "Ft_Esd_TouchTag.h"
#include "Ft_Esd_CoCmd.h"
#include "Ft_Esd_Core.h"
extern EVE_HalContext *Ft_Esd_Host;
extern Ft_Esd_GpuAlloc *Ft_Esd_GAlloc;
#ifndef NDEBUG
static ft_uint32_t s_FlashErrorLast = ~0;
#endif
//A function to enable spinner when frame is rendered.
ESD_FUNCTION(Ft_Esd_Spinner_Popup, DisplayName = "Pop-up Spinner", Category = EsdUtilities)
void Ft_Esd_Spinner_Popup()
{
Esd_CurrentContext->SpinnerPopup = FT_TRUE;
}
#if defined(EVE_FLASH_AVAILABLE)
#ifdef ESD_SIMULATION
extern void Esd_SetFlashStatus__ESD(int status);
extern void Esd_SetFlashSize__ESD(int size);
#else
#define Esd_SetFlashStatus__ESD(status) \
do \
{ \
} while (false)
#define Esd_SetFlashSize__ESD(status) \
do \
{ \
} while (false)
#endif
void Esd_AttachFlashFast()
{
// Wait for flash status to move on from FLASH_STATUS_INIT
uint32_t flashStatus;
while (!(flashStatus = Ft_Gpu_Hal_Rd32(Ft_Esd_Host, REG_FLASH_STATUS)))
{
#ifndef NDEBUG
eve_printf_debug("Waiting for REG_FLASH_STATUS (%u)\n", flashStatus);
#endif
}
// No need to continue if flash is okay
if (flashStatus < FLASH_STATUS_FULL)
{
ft_uint32_t error;
Esd_SetFlashStatus__ESD(flashStatus);
flashStatus = Ft_Gpu_CoCmd_FlashAttach(Ft_Esd_Host);
Esd_SetFlashStatus__ESD(flashStatus);
Esd_SetFlashSize__ESD(Ft_Gpu_Hal_Rd32(Ft_Esd_Host, REG_FLASH_SIZE));
flashStatus = Ft_Gpu_CoCmd_FlashFast(Ft_Esd_Host, &error);
Esd_SetFlashStatus__ESD(flashStatus);
#ifndef NDEBUG
if (error != s_FlashErrorLast)
{
s_FlashErrorLast = error;
switch (error)
{
case 0:
eve_printf_debug("Flash OK\n");
break;
case FLASH_ERROR_NOTATTACHED: // 0xE001 :
eve_printf_debug("Flash is not attached\n");
break;
case FLASH_ERROR_HEADERMISSING: // 0xE002:
eve_printf_debug("No header detected in sector 0. Is flash blank?\n");
break;
case FLASH_ERROR_HEADERCRCFAILED: // 0xE003:
eve_printf_debug("Sector 0 flash data failed integrity check\n");
break;
case FLASH_ERROR_FIRMWAREMISMATCH: // 0xE004:
eve_printf_debug("Flash device/blob mismatch. Was correct blob loaded?\n");
break;
case FLASH_ERROR_FULLSPEEDFAILED: // 0xE005:
eve_printf_debug("Failed full-speed flash test. Check board wiring\n");
break;
default:
eve_printf_debug("Unknown flash error (%u)\n", error);
}
}
#endif
}
}
#else
#define Esd_AttachFlashFast() eve_noop()
#endif
void Esd_BeginLogo()
{
Ft_Esd_GpuAlloc_Reset(Ft_Esd_GAlloc);
Ft_Esd_GpuAlloc_Alloc(Ft_Esd_GAlloc, RAM_G_SIZE, 0); // Block allocation
Ft_Gpu_CoCmd_StartFrame(Ft_Esd_Host);
Ft_Gpu_CoCmd_DlStart(Ft_Esd_Host);
Ft_Gpu_CoCmd_SendCmd(Ft_Esd_Host, CLEAR_COLOR_RGB(255, 255, 255));
Ft_Gpu_CoCmd_SendCmd(Ft_Esd_Host, CLEAR(1, 0, 0));
Ft_Gpu_CoCmd_SendCmd(Ft_Esd_Host, DISPLAY());
Ft_Gpu_CoCmd_Swap(Ft_Esd_Host);
Ft_Gpu_CoCmd_DlStart(Ft_Esd_Host);
Ft_Gpu_CoCmd_SendCmd(Ft_Esd_Host, CLEAR_COLOR_RGB(255, 255, 255));
Ft_Gpu_CoCmd_SendCmd(Ft_Esd_Host, CLEAR(1, 0, 0));
Ft_Gpu_CoCmd_SendCmd(Ft_Esd_Host, DISPLAY());
Ft_Gpu_CoCmd_Swap(Ft_Esd_Host);
Ft_Gpu_CoCmd_DlStart(Ft_Esd_Host);
Ft_Gpu_CoCmd_SendCmd(Ft_Esd_Host, CLEAR_COLOR_RGB(255, 255, 255));
Ft_Gpu_CoCmd_SendCmd(Ft_Esd_Host, CLEAR(1, 0, 0));
Ft_Gpu_CoCmd_SendCmd(Ft_Esd_Host, DISPLAY());
// Ft_Gpu_CoCmd_MemSet(Ft_Esd_Host, 0, 0xFF, RAM_G_SIZE);
Ft_Gpu_CoCmd_EndFrame(Ft_Esd_Host);
Ft_Gpu_Hal_WaitCmdFifoEmpty(Ft_Esd_Host);
Ft_Gpu_CoCmd_StartFrame(Ft_Esd_Host);
Ft_Gpu_CoCmd_Logo(Ft_Esd_Host);
Ft_Gpu_CoCmd_EndFrame(Ft_Esd_Host);
Ft_Gpu_Hal_WaitLogo_Finish(Ft_Esd_Host);
EVE_sleep(3000);
}
void Esd_EndLogo()
{
Ft_Gpu_CoCmd_StartFrame(Ft_Esd_Host);
Ft_Gpu_CoCmd_DlStart(Ft_Esd_Host);
Ft_Gpu_CoCmd_SendCmd(Ft_Esd_Host, CLEAR_COLOR_RGB(255, 255, 255));
Ft_Gpu_CoCmd_SendCmd(Ft_Esd_Host, CLEAR(1, 0, 0));
Ft_Gpu_CoCmd_SendCmd(Ft_Esd_Host, DISPLAY());
Ft_Gpu_CoCmd_Swap(Ft_Esd_Host);
Ft_Gpu_CoCmd_EndFrame(Ft_Esd_Host);
Ft_Gpu_Hal_WaitCmdFifoEmpty(Ft_Esd_Host);
Ft_Esd_GpuAlloc_Reset(Ft_Esd_GAlloc);
}
void Esd_ShowLogo()
{
Esd_CurrentContext->ShowLogo = FT_TRUE;
}
/// Run calibrate procedure
ft_bool_t Esd_Calibrate()
{
EVE_HalContext *phost = Ft_Esd_Host;
ft_uint32_t result;
ft_uint32_t transMatrix[6];
#if defined(EVE_SCREEN_CAPACITIVE)
Ft_Gpu_Hal_Wr8(phost, REG_CTOUCH_EXTENDED, CTOUCH_MODE_COMPATIBILITY);
#endif
eve_printf_debug("App_CoPro_Widget_Calibrate: Start Frame\n");
Ft_Gpu_CoCmd_StartFrame(phost);
Ft_Gpu_CoCmd_DlStart(phost);
Ft_Gpu_CoCmd_SendCmd(phost, CLEAR_COLOR_RGB(64, 64, 64));
Ft_Gpu_CoCmd_SendCmd(phost, CLEAR(1, 1, 1));
Ft_Gpu_CoCmd_SendCmd(phost, COLOR_RGB(0xff, 0xff, 0xff));
// Ft_Gpu_CoCmd_Text(phost, (Ft_Esd_Host->Parameters.Display.Width / 2), (Ft_Esd_Host->Parameters.Display.Height / 2), 27, OPT_CENTER, "Please Tap on the dot");
result = Ft_Gpu_CoCmd_Calibrate(phost);
eve_printf_debug("App_CoPro_Widget_Calibrate: End Frame\n");
Ft_Gpu_CoCmd_EndFrame(phost);
// Print the configured values
Ft_Gpu_Hal_RdMem(phost, REG_TOUCH_TRANSFORM_A, (ft_uint8_t *)transMatrix, 4 * 6); //read all the 6 coefficients
eve_printf_debug("Touch screen transform values are A 0x%x,B 0x%x,C 0x%x,D 0x%x,E 0x%x, F 0x%x\n",
transMatrix[0], transMatrix[1], transMatrix[2], transMatrix[3], transMatrix[4], transMatrix[5]);
return result != 0;
}
/* end of file */
| 30.194595 | 161 | 0.754207 | [
"transform"
] |
5a51dda320e83cc1d8018134e4f421e3255057c9 | 37,063 | c | C | battlestar/cmd.c | httpsgithu/bsd-games | 25801c56e3826662a773eaa78da9db8d45d74aa9 | [
"BSD-3-Clause"
] | 50 | 2016-08-04T02:44:12.000Z | 2022-03-20T15:23:02.000Z | battlestar/cmd.c | Gmyers67/bsd-games | 511ca9eb1fe71d3ab1948c0e3b61336150ff389e | [
"BSD-3-Clause"
] | 9 | 2020-07-24T06:12:58.000Z | 2021-11-16T14:16:50.000Z | battlestar/cmd.c | Gmyers67/bsd-games | 511ca9eb1fe71d3ab1948c0e3b61336150ff389e | [
"BSD-3-Clause"
] | 10 | 2016-05-21T17:04:07.000Z | 2022-03-07T22:08:57.000Z | // This file is free software, distributed under the BSD license.
#include "battlestar.h"
//{{{ ouch -------------------------------------------------------------
const char ouch [NUMOFINJURIES][24] = {
"some minor abrasions",
"some minor lacerations",
"a minor puncture wound",
"a minor amputation",
"a sprained wrist",
"a fractured ankle",
"a broken arm",
"a few broken ribs",
"a broken leg",
"a broken back",
"a large loss of blood",
"a fractured skull",
"a broken neck"
};
//}}}-------------------------------------------------------------------
// Parsed command line variables, in parse.c
extern struct Word words [NWORDS];
extern uint8_t wordcount;
extern uint8_t wordnumber;
//----------------------------------------------------------------------
bool moveplayer (location_t thataway, enum CommandId token)
{
++wordnumber;
if ((!game_state (CANTMOVE) && !game_state (LAUNCHED))
|| object_is_at (LAND, position)
|| (fuel > 0 && game_state (LAUNCHED))) {
if (!thataway) {
puts ("You can't go this way.");
return false;
}
position = thataway;
direction = compass_direction (token);
++ourtime;
} else {
if (game_state (CANTMOVE) && !game_state (LAUNCHED))
puts ("You aren't able to move; you better drop something.");
else
puts ("You are out of fuel; now you will drift in space forever!");
}
return true;
}
void news (void)
{
if (ourtime > 64 && position < OUTSIDE_BATTLESTAR) {
puts ("An explosion of shuddering magnitude splinters bulkheads and\n"
"ruptures the battlestar's hull. You are sucked out into the\n"
"frozen void of space and killed.");
die();
}
if (ourtime > 48 && position < OUTSIDE_BATTLESTAR)
puts ("Explosions rock the battlestar.");
if (ourtime > snooze) {
puts ("You drop from exhaustion...");
zzz();
}
if (ourtime > snooze - 5)
puts ("You're getting tired.");
if (ourtime > (rythmn + CYCLE)) {
if (game_state (IS_NIGHT)) {
convert (TODAY);
if (is_outside() && ourtime - rythmn - CYCLE < 10) {
puts ("Dew lit sunbeams stretch out from a watery sunrise and herald the dawn.\n"
"You awake from a misty dream-world into stark reality.\nIt is day.");
}
} else {
convert (TONIGHT);
remove_object_from (BATHGOD, POOLS);
if (is_outside() && ourtime - rythmn - CYCLE < 10) {
puts ("The dying sun sinks into the ocean, leaving a blood-stained sunset.\n"
"The sky slowly fades from orange to violet to black.\n"
"A few stars flicker on, and it is night.\n"
"The world seems completely different at night.");
}
}
rythmn = ourtime - ourtime % CYCLE;
}
if (!game_state (IS_WIZARD)
&& (object_is_at (TALISMAN, INVENTORY) || object_is_at (TALISMAN, WEARING))
&& (object_is_at (MEDALION, INVENTORY) || object_is_at (MEDALION, WEARING))
&& (object_is_at (AMULET, INVENTORY) || object_is_at (AMULET, WEARING))) {
set_game_state (IS_WIZARD);
puts ("The three amulets glow and reenforce each other in power.\nYou are now a wizard.");
}
if (object_is_at (ELF, position)) {
printf ("%s\n", c_objinfo[ELF].desc);
fight (ELF, nrand(30));
}
if (object_is_at (DARK_LORD, position)) {
printf ("%s\n", c_objinfo[DARK_LORD].desc);
fight (DARK_LORD, 100);
}
if (object_is_at (WOODSMAN, position)) {
printf ("%s\n", c_objinfo[WOODSMAN].desc);
fight (WOODSMAN, 50);
}
switch (position) {
case 246:
case 257: // entering a cave
case 267:
case 274:
set_game_state (CANTSEE);
break;
case SEA_CAVE_ENTRANCE:
case 216: // leaving a cave
case 230:
case CAVE_ENTRANCE:
case HUGE_CHASM:
clear_game_state (CANTSEE);
break;
}
if (object_is_at (GIRL, position))
set_game_state (MET_GIRL);
if (game_state (MET_GIRL) && CYCLE * 1.5 - ourtime < 10) {
create_object_at (GIRLTALK, GARDEN);
create_object_at (LAMPON, GARDEN);
create_object_at (ROPE, GARDEN);
}
if (position == DOCK && (visited_location (position) || ourtime > CYCLE)) {
remove_object_from (GIRL, DOCK);
remove_object_from (MAN, DOCK);
}
if (game_state (MET_GIRL) && ourtime - CYCLE * 1.5 > 10) {
remove_object_from (GIRLTALK, GARDEN);
remove_object_from (LAMPON, GARDEN);
remove_object_from (ROPE, GARDEN);
clear_game_state (MET_GIRL);
}
if (object_is_at (DRENIAN, position)) {
puts ("Oh my God, you're being shot at by an alien spacecraft!");
fflush (stdout);
sleep (1);
if (!visual()) {
unsigned hurt = nrand (NUMOFINJURIES);
suffer_injury (hurt);
puts ("Laser blasts sear the cockpit, and the alien veers off in a victory roll.");
puts ("The starfighter shudders under a terrible explosion.");
printf ("I'm afraid you have suffered %s.\n", ouch[hurt]);
} else
remove_object_from (DRENIAN, position);
}
if (is_fatally_injured()) {
puts ("I'm afraid you have suffered fatal injuries.");
die();
}
if (player_carrying() > player_max_weight() || player_encumber() > player_max_cumber())
set_game_state (CANTMOVE);
else
clear_game_state (CANTMOVE);
}
void crash (void)
{
--fuel;
if (location[position].dir.flyhere && (!object_is_at (LAND, position) || fuel >= 2)) // need 2 fuel to land
return;
if (!location[position].dir.flyhere)
puts ("You're flying too low. We're going to crash!");
else {
puts ("You're out of fuel. We'll have to crash land!");
if (!location[position].dir.down) {
puts ("Your starfighter strikes the ground and explodes into fiery fragments.");
puts ("Thick black smoke billows up from the wreckage.");
die();
}
position = location[position].dir.down;
}
clear_game_state (LAUNCHED);
create_object_at (CRASH, position);
ourtime += nrand(CYCLE / 4);
puts ("The starfighter explodes into the ground and you lose consciousness...");
zzz();
unsigned hurt1 = nrand (NUMOFINJURIES-MINOR_PUNCTURE)+MINOR_PUNCTURE;
unsigned hurt2 = nrand (NUMOFINJURIES-MINOR_PUNCTURE)+MINOR_PUNCTURE;
suffer_injury (hurt1);
suffer_injury (hurt2);
suffer_injury (ABRASIONS); // abrasions
suffer_injury (LACERATIONS); // lacerations
printf ("I'm afraid you have suffered %s and %s.\n", ouch[hurt1], ouch[hurt2]);
}
static bool is_wearable (enum ObjectId oid)
{
static const uint16_t c_wearable[] = {
AMULET, BRACELET, COMPASS, GRENADE, HELM,
KNIFE, LASER, LEVIS, MAIL, MEDALION,
PAJAMAS, RING, ROBE, ROPE, SHOES,
SWORD, TALISMAN
};
for (unsigned i = 0; i < ArraySize (c_wearable); ++i)
if (c_wearable[i] == oid)
return true;
return false;
}
int wearit (void)
{
int firstnumber = wordnumber;
++wordnumber;
while (wordnumber <= wordcount && (words[wordnumber].type == OBJECT || words[wordnumber].type == NOUNS) && words[wordnumber].value != DOOR) {
int value = words[wordnumber].value;
if (value >= 0 && !c_objinfo[value].shdesc)
break;
if (value < 0) {
puts ("Wear what?");
return firstnumber;
}
if (!is_wearable (value)) {
printf ("You can't wear %s%s!\n", A_OR_AN_OR_BLANK(value), c_objinfo[value].shdesc);
return firstnumber;
}
if (object_is_at (value, INVENTORY)) {
move_object_to (value, INVENTORY, WEARING);
++ourtime;
printf ("You are now wearing %s%s.\n", A_OR_AN_OR_THE(value), c_objinfo[value].shdesc);
} else if (object_is_at (value, WEARING))
printf ("You are already wearing the %s.\n", c_objinfo[value].shdesc);
else
printf ("You aren't holding the %s.\n", c_objinfo[value].shdesc);
if (wordnumber < wordcount - 1 && words[++wordnumber].value == AND)
++wordnumber;
else
return firstnumber;
}
puts ("Don't be ridiculous.");
return firstnumber;
}
int put (void)
{ // synonyms = {buckle, strap, tie}
if (words[wordnumber + 1].value == ON) {
words[++wordnumber].value = PUTON;
words[wordnumber].type = VERB;
return process_command();
}
if (words[wordnumber + 1].value == DOWN) {
words[++wordnumber].value = DROP;
words[wordnumber].type = VERB;
return process_command();
}
puts ("I don't understand what you want to put.");
return -1;
}
int draw (void)
{ // synonyms = {pull, carry}
return take (WEARING);
}
int use (void)
{
++wordnumber;
if (words[wordnumber].value == AMULET
&& object_is_at (AMULET, INVENTORY)
&& position >= FIRST_ISLAND_LAND) {
if (position == FINAL) {
puts ("The amulet won't work in here.");
return -1;
}
puts ("The amulet begins to glow.");
if (object_is_at (MEDALION, INVENTORY)) {
puts ("The medallion comes to life too.");
if (position == ABOVE_SEA_CAVE) {
set_game_state (UNCOVERED_SEA_CAVE);
puts ("The waves subside and it is possible to descend to the sea cave now.");
++ourtime;
return -1;
}
}
puts ("A light mist falls over your eyes and the sound of purling water trickles in");
puts ("your ears. When the mist lifts you are standing beside a cool stream.");
if (position == CAVE_STREAM_BANK)
position = END_OF_THE_ROAD;
else
position = CAVE_STREAM_BANK;
++ourtime;
clear_game_state (CANTSEE);
return 0;
} else if (words[wordnumber].value == COMPASS) {
if (!object_is_at (COMPASS, INVENTORY) && !object_is_at (COMPASS, WEARING))
puts ("You don't have a compass.");
else
printf ("Your compass points %s.\n", truedirec (NORTH, '-'));
} else
puts ("There is no apparent use.");
return -1;
}
int follow (void)
{
if (position == MINE_CHAMBER && object_is_at (DARK_LORD, FINAL)) {
puts ("The Dark Lord leaps away and runs down secret tunnels and corridors.\n"
"You chase him through the darkness and splash in pools of water.\n"
"You have cornered him. His laser sword extends as he steps forward.");
position = FINAL;
fight (DARK_LORD, 75);
create_object_at (TALISMAN, position);
return 0;
} else if (position == POOLS && object_is_at (GODDESS, POOLS)) {
puts ("The goddess leads you down a steamy tunnel and into a high, wide chamber.\n"
"She sits down on a throne.");
move_object_to (GODDESS, POOLS, GODDESS_THRONE_ROOM);
position = GODDESS_THRONE_ROOM;
set_game_state (CANTSEE);
return 0;
} else
puts ("There is no one to follow.");
return -1;
}
void dig (void)
{
if (!object_is_at (SHOVEL, INVENTORY)) {
puts ("You don't have a shovel.");
return;
}
puts ("Ok");
++ourtime;
if (position != SECRET_THICKET)
puts ("Nothing happens.");
else if (!game_state (DUG)) {
set_game_state (DUG);
create_object_at (DEADWOOD, position);
create_object_at (COMPASS, position);
create_object_at (KNIFE, position);
create_object_at (MACE, position);
}
}
int jump (void)
{
switch (position) {
default: puts ("Nothing happens."); return -1;
case ALONG_THE_SHORE:
case COAST_ROAD_TURN:
case ALONG_HIGH_CLIFFS:
case ROAD_TURNAROUND: position = TIDE_POOLS; break;
case HUGE_CHASM: position = FINAL; break;
case BRIDGE_OVER_LAGOON: position = IN_THE_LAGOON; break;
case CLIFF_WATERFALL: position = WIDER_CANYON; break;
case HANGAR_GALLERY: position = MAIN_HANGAR; break;
}
puts ("Ahhhhhhh...");
suffer_injury (BROKEN_LEG);
suffer_injury (BROKEN_RIBS);
suffer_injury (BROKEN_ARM);
for (unsigned n = 0; n < NUMOFOBJECTS; ++n)
move_object_to (n, INVENTORY, position);
return 0;
}
void bury (void)
{
if (!object_is_at (SHOVEL, INVENTORY)) {
puts ("You aren't holding a shovel.");
return;
}
static const uint16_t c_buryable[] = { MAID, DEADWOOD };
while (words[++wordnumber].type != OBJECT && words[wordnumber].type != NOUNS && wordnumber < wordcount)
continue;
int value = words[wordnumber].value;
if (words[wordnumber].type == NOUNS && (object_is_at (value, position) || value == MAID)) {
switch (value) {
case MAID:
words[wordnumber].type = OBJECT;
for (unsigned i = 0; i < ArraySize(c_buryable); ++i)
if (object_is_at (c_buryable[i], INVENTORY) || object_is_at (c_buryable[i], position))
value = c_buryable[i];
break;
case TIMER: game_score.power += 7; game_score.ego -= min_u (game_score.ego,10); // fallthrough
case AMULET:
case MEDALION:
case TALISMAN: words[wordnumber].type = OBJECT; break;
default: puts ("Wha..?"); break;
}
}
if (words[wordnumber].type == OBJECT && position >= FIRST_ISLAND_LAND
&& (object_is_at (value, INVENTORY) || object_is_at (value, position))) {
puts ("Buried.");
if (object_is_at (value, INVENTORY))
remove_object_from (value, INVENTORY);
remove_object_from (value, position);
for (unsigned i = 0; i < ArraySize(c_buryable); ++i) {
if (c_buryable[i] == value) {
game_score.ego += 2;
printf ("The %s should rest easier now.\n", c_objinfo[value].shdesc);
}
}
} else
puts ("It doesn't seem to work.");
}
void drink (void)
{
if (!object_is_at (POTION, INVENTORY)) {
puts ("You have nothing to drink.");
return;
}
puts ("The cool liquid runs down your throat but turns to fire and you choke.\n"
"The heat reaches your limbs and tingles your spirit.\n"
"You feel like falling asleep.");
remove_object_from (POTION, INVENTORY);
cure_all_injuries();
++ourtime;
zzz();
}
int shoot (void)
{
int firstnumber = wordnumber;
if (!object_is_at (LASER, INVENTORY)) {
puts ("You aren't holding a blaster.");
return firstnumber;
}
++wordnumber;
while (wordnumber <= wordcount && words[wordnumber].type == OBJECT) {
int value = words[wordnumber].value;
printf ("%s:\n", c_objinfo[value].shdesc);
if (object_is_at (value, position)) {
remove_object_from (value, position);
++ourtime;
printf ("The %s explode%s\n", c_objinfo[value].shdesc, (is_plural_object(value) ? "." : "s."));
if (value == BOMB)
die();
} else
printf ("I don't see any %s around here.\n", c_objinfo[value].shdesc);
if (wordnumber < wordcount - 1 && words[++wordnumber].value == AND)
++wordnumber;
else
return firstnumber;
}
// The blaster's only useful purpose is to destroy locked doors.
if (wordnumber > wordcount || words[wordnumber].value != DOOR) {
puts ("Shoot what?");
return firstnumber;
}
++ourtime;
switch (position) {
case CAVE_DOOR:
case CAVE_ENTRANCE:
puts ("The door is unhinged.");
set_game_state (OPENED_CAVE_DOOR);
break;
case KITCHEN_DOOR:
puts ("The wooden door splinters.");
set_game_state (OPENED_KITCHEN_DOOR);
break;
case DINING_ROOM_DOOR:
puts ("The laser blast has no effect on the door.");
break;
case LASER_ROOM:
puts ("The blast hits the door and it explodes into flame.\n"
"The magnesium burns so rapidly that we have no chance to escape.");
die();
default:
puts ("Nothing happens.");
}
return firstnumber;
}
int take (location_t fromloc)
{
int firstnumber = wordnumber;
if (wordnumber < wordcount && words[wordnumber + 1].value == OFF) {
++wordnumber;
words[wordnumber].value = TAKEOFF;
words[wordnumber].type = VERB;
return process_command();
} else {
++wordnumber;
while (wordnumber <= wordcount && words[wordnumber].type == OBJECT) {
int value = words[wordnumber].value;
printf ("%s:\n", c_objinfo[value].shdesc);
bool heavy = (player_carrying() + c_objinfo[value].weight) <= player_max_weight();
bool bulky = (player_encumber() + c_objinfo[value].cumber) <= player_max_cumber();
if ((object_is_at (value, fromloc) || game_state (IS_WIZARD)) && heavy && bulky && !object_is_at (value, INVENTORY)) {
create_object_at (value, INVENTORY);
++ourtime;
if (object_is_at (value, fromloc))
printf ("Taken.\n");
else
printf ("Zap! Taken from thin air.\n");
remove_object_from (value, fromloc);
if (value == MEDALION && win)
--win;
} else if (object_is_at (value, INVENTORY))
printf ("You're already holding %s%s.\n", A_OR_AN_OR_BLANK(value), c_objinfo[value].shdesc);
else if (!object_is_at (value, fromloc))
printf ("I don't see any %s around here.\n", c_objinfo[value].shdesc);
else if (!heavy)
printf ("The %s %stoo heavy.\n", c_objinfo[value].shdesc, IS_OR_ARE(value));
else
printf ("The %s %stoo cumbersome to hold.\n", c_objinfo[value].shdesc, IS_OR_ARE(value));
if (wordnumber < wordcount - 1 && words[++wordnumber].value == AND)
++wordnumber;
else
return firstnumber;
}
}
if (wordnumber > wordcount || words[wordnumber].type != NOUNS) {
puts ("You've got to be kidding.");
return firstnumber;
}
// special cases with their own returns
switch (words[wordnumber].value) {
case SWORD:
if (object_is_at (SWORD, fromloc)) {
words[wordnumber--].type = OBJECT;
return take(fromloc);
}
if (object_is_at (TWO_HANDED, fromloc)) {
words[wordnumber].value = TWO_HANDED;
words[wordnumber--].type = OBJECT;
return take(fromloc);
}
words[wordnumber].value = BROAD;
words[wordnumber--].type = OBJECT;
return take(fromloc);
case MAID:
if (object_is_at (MAID, fromloc)) {
words[wordnumber].value = MAID;
words[wordnumber--].type = OBJECT;
return take(fromloc);
} else if (object_is_at (DEADWOOD, fromloc)) {
words[wordnumber].value = DEADWOOD;
words[wordnumber--].type = OBJECT;
return take(fromloc);
} else
puts ("It doesn't seem to work.");
break;
case AMULET:
if (object_is_at (AMULET, position)) {
puts ("The amulet is warm to the touch, and its beauty catches your breath.\n"
"A mist falls over your eyes, but then it is gone. Sounds seem clearer\n"
"and sharper but far away as if in a dream. The sound of purling water\n"
"reaches you from afar. The mist falls again, and your heart leaps in horror.\n"
"The gold freezes your hands and fathomless darkness engulfs your soul.");
}
words[wordnumber--].type = OBJECT;
return take(fromloc);
case MEDALION:
if (object_is_at (MEDALION, position)) {
puts ("The medallion is warm, and it rekindles your spirit with the warmth of life.\n"
"Your amulet begins to glow as the medallion is brought near to it,\n"
"and together they radiate.");
}
words[wordnumber--].type = OBJECT;
return take(fromloc);
case TALISMAN:
if (object_is_at (TALISMAN, position))
puts ("The talisman is cold to the touch, and it sends a chill down your spine.");
words[wordnumber--].type = OBJECT;
return take(fromloc);
case GODDESS:
if (!object_is_at (BATHGOD, position))
puts ("She is not here.");
else if (object_is_at (AMULET, WEARING) || object_is_at (AMULET, INVENTORY)) {
puts ("She offers a delicate hand, and you help her out of the sparkling springs.\n"
"Water droplets like liquid silver bedew her golden skin, but when they part\n"
"from her, they fall as teardrops. She wraps a single cloth around her and\n"
"ties it at the waist. Around her neck hangs a golden amulet.\n"
"She bids you to follow her, and walks away.");
++game_score.pleasure;
remove_object_from (BATHGOD, position);
create_object_at (GODDESS, position);
} else
puts ("She moves away from you.");
break;
default:
puts ("It doesn't seem to work.");
break;
}
return firstnumber;
}
int throw_object (const char *name)
{
int first = wordnumber;
location_t deposit = 0;
if (drop(name) != -1) {
switch (words[wordnumber].value) {
default:
deposit = relative_destination (words[wordnumber].value);
break;
case UP:
if (position == FINAL && !game_state (ROPE_IN_PIT))
deposit = 0;
else
deposit = location[position].dir.up;
break;
case DOWN:
deposit = location[position].dir.down;
break;
}
wordnumber = first + 1;
while (wordnumber <= wordcount) {
int value = words[wordnumber].value;
if (deposit && object_is_at (value, position)) {
remove_object_from (value, position);
if (value == GRENADE) {
puts ("A thundering explosion nearby sends up a cloud of smoke and shrapnel.");
for (unsigned o = 0; o < NUMOFOBJECTS; ++o)
remove_object_from (o, deposit);
create_object_at (CHAR, deposit);
} else
create_object_at (value, deposit);
if (value == ROPE && position == FINAL)
set_game_state (ROPE_IN_PIT);
switch (deposit) {
case CAVE_DOOR:
case CAVE_ENTRANCE:
puts ("The stone door is unhinged.");
set_game_state (OPENED_CAVE_DOOR);
break;
case KITCHEN_DOOR:
puts ("The wooden door is blown open.");
set_game_state (OPENED_KITCHEN_DOOR);
break;
case DINING_ROOM_DOOR:
puts ("The door is not damaged.");
}
} else if (value == GRENADE && object_is_at (value, position)) {
puts ("You are blown into shreds when your grenade explodes.");
die();
}
if (wordnumber < wordcount - 1 && words[++wordnumber].value == AND)
++wordnumber;
else
return first;
}
return first;
}
return first;
}
int drop (const char *name)
{
int firstnumber = wordnumber;
++wordnumber;
while (wordnumber <= wordcount && (words[wordnumber].type == OBJECT || words[wordnumber].type == NOUNS)) {
int value = words[wordnumber].value;
if (value == MAID) { // special case
words[wordnumber].type = OBJECT;
if (object_is_at (MAID, INVENTORY) || object_is_at (MAID, position))
value = MAID;
else if (object_is_at (DEADWOOD, INVENTORY) || object_is_at (DEADWOOD, position))
value = DEADWOOD;
}
if (words[wordnumber].type == NOUNS && value == DOOR) {
if (*name == 'K')
puts ("You hurt your foot.");
else
puts ("You're not holding a door.");
} else if (c_objinfo[value].shdesc == NULL) {
if (*name == 'K')
puts ("That's not for kicking!");
else
puts ("You don't have that.");
} else {
printf ("%s:\n", c_objinfo[value].shdesc);
if (object_is_at (value, INVENTORY)) {
move_object_to (value, INVENTORY, position);
if (value == BOMB) {
puts ("The bomb explodes. A blinding white light and immense concussion obliterate us.");
die();
}
++ourtime;
if (*name == 'K')
puts ("Drop kicked.");
else
printf ("%s.\n", name);
if (game_state (IS_WIZARD) && (value == AMULET || value == MEDALION || value == TALISMAN)) {
clear_game_state (IS_WIZARD);
puts ("You no longer feel wizardly.");
}
} else {
if (*name != 'K') {
printf ("You aren't holding the %s.\n", c_objinfo[value].shdesc);
if (object_is_at (value, position)) {
if (*name == 'T')
puts ("Kicked instead.");
else if (*name == 'G')
puts ("Given anyway.");
}
} else if (object_is_at (value, position))
puts ("Kicked.");
else if (object_is_at (value, WEARING))
puts ("Not while it's being worn.");
else
puts ("Not found.");
}
}
if (wordnumber < wordcount - 1 && words[++wordnumber].value == AND)
++wordnumber;
else
return firstnumber;
}
puts ("Do what?");
return -1;
}
int takeoff (void)
{
wordnumber = take (WEARING);
return drop("Dropped");
}
int puton (void)
{
wordnumber = take (position);
return wearit();
}
static bool is_edible (enum ObjectId oid)
{
static const uint16_t c_edible[] = { PAPAYAS, PINEAPPLE, KIWI, COCONUTS, MANGO };
for (unsigned i = 0; i < ArraySize(c_edible); ++i)
if (c_edible[i] == oid)
return true;
return false;
}
int eat (void)
{
int firstnumber = wordnumber;
++wordnumber;
while (wordnumber <= wordcount) {
int value = words[wordnumber].value;
if (value < 0 || value >= NUMOFOBJECTS) {
puts ("Eat what?");
return firstnumber;
}
if (words[wordnumber].type != OBJECT || c_objinfo[value].shdesc == NULL) {
puts ("You can't eat that!");
return firstnumber;
}
if (!is_edible (value))
printf ("You can't eat %s%s!\n", A_OR_AN_OR_BLANK(value), c_objinfo[value].shdesc);
else if (!object_is_at (value, INVENTORY))
printf ("You aren't holding the %s.\n", c_objinfo[value].shdesc);
else if (ourtime < ate - CYCLE)
puts ("You're stuffed.");
else if (!object_is_at (KNIFE, INVENTORY))
puts ("You need a knife.");
else {
remove_object_from (value, INVENTORY);
ate = max_i (ourtime, ate) + CYCLE / 3;
snooze += CYCLE / 10;
++ourtime;
printf ("You ate %s%s. You can explore a little longer now.", A_OR_AN_OR_BLANK(value), c_objinfo[value].shdesc);
}
if (wordnumber < wordcount - 1 && words[++wordnumber].value == AND)
++wordnumber;
else
return firstnumber;
}
return firstnumber;
}
void kiss (void)
{
while (words[++wordnumber].type != NOUNS && wordnumber <= wordcount)
continue;
// The goddess must be "taken" first if bathing. This will remove her from the bath and move her into the throne room.
if (words[wordnumber].type == NOUNS && words[wordnumber].value == GODDESS && object_is_at (BATHGOD, position)) {
words[--wordnumber].value = TAKE;
process_command();
return;
}
if (!object_is_at (words[wordnumber].value, position))
puts ("She is not here.");
else if (words[wordnumber].value == NATIVE_GIRL) {
++game_score.pleasure;
puts ("You kiss her.\nHer lips are warm and her body robust. She pulls you down to the ground.");
} else if (words[wordnumber].value == GODDESS) {
++game_score.pleasure;
switch (godready++) {
case 0: puts ("You try to kiss her. She avoids your advances."); break;
case 1: puts ("You try to kiss her. She leans away with a smile."); break;
case 2: puts ("She turns her head and the kiss lands on her cheek."); break;
default: puts ("Her lips feel like fire upon yours. You melt with pleasure."); break;
}
} else
puts ("I'd prefer not to.");
}
void love (void)
{
while (words[++wordnumber].type != NOUNS && wordnumber <= wordcount)
continue;
if (!object_is_at (words[wordnumber].value, position))
puts ("Where's your lover?");
else if (words[wordnumber].value == NATIVE_GIRL) {
puts ("The girl peels off her sarong and indulges you.");
game_score.pleasure += 5;
printf ("Girl:\n");
ourtime += 10;
printf ("Loved.\n");
zzz();
} else if (words[wordnumber].value == GODDESS) {
if (game_state (LOVED_GODDESS))
puts ("Loved.");
else if (godready < 3)
puts ("You wish!");
else {
puts ("She cuddles up to you, and speaks softly:\n\n"
"'That was my sister's amulet. The lovely goddess Purl, was she. The Empire\n"
"captured her just after the Darkness came. My other sister, Vert, was\n"
"killed by the Dark Lord himself. He took her amulet and warped its power.\n"
"Your quest was foretold by my father before he died, but to get the Dark\n"
"Lord's amulet you must use cunning and skill. I will leave you my amulet,\n"
"which you may use as you wish. As for me, I am the last goddess of the\n"
"waters. My father was the Island King, and the rule is rightfully mine.'\n\n"
"She pulls the throne out into a large bed.");
game_score.pleasure += 50;
++game_score.power;
++game_score.ego;
if (is_injured()) {
puts ("Her kisses revive you; your wounds are healed.\n");
cure_all_injuries();
}
printf ("Goddess:\n");
if (!game_state (LOVED_GODDESS)) {
set_game_state (LOVED_GODDESS);
create_object_at (MEDALION, position);
}
ourtime += 10;
printf ("Loved.\n");
zzz();
}
} else
puts ("It doesn't seem to work.");
}
bool zzz (void)
{
gametime_t oldtime = ourtime;
if (snooze - ourtime >= 3*CYCLE/4)
return false;
ourtime += 3*CYCLE/4 - (snooze - ourtime);
printf ("<zzz>");
for (gametime_t n = 0; n < ourtime - oldtime; ++n)
printf (".");
printf ("\n");
snooze += 3 * (ourtime - oldtime);
if (game_state (LAUNCHED)) {
fuel -= min_u (fuel, (ourtime - oldtime));
if (location[position].dir.down) {
position = location[position].dir.down;
crash();
} else
clear_game_state (LAUNCHED);
}
if (is_outside() && nrand(2)) {
puts ("You are awakened abruptly by the sound of someone nearby.");
unsigned c = nrand(4);
if (c == 0)
create_object_at (DEADWOOD, position);
else if (c == 1)
create_object_at (HALBERD, position);
else if (count_objects_at (INVENTORY)) {
unsigned n;
do
n = nrand (NUMOFOBJECTS);
while (!object_is_at (n, INVENTORY));
move_object_to (n, INVENTORY, position);
puts ("A fiendish little Elf is stealing your treasures!");
fight (ELF, 10);
}
}
return true;
}
void chime (void)
{
gametime_t cycletime = (ourtime%CYCLE)*7/CYCLE;
if (!is_outside())
puts ("I can't tell the time in here.");
else if ((ourtime/CYCLE+1)%2) {
static const char c_day_times[] =
"just after sunrise\0"
"early morning\0"
"late morning\0"
"near noon\0"
"early afternoon\0"
"late afternoon\0"
"near sunset";
printf ("It is %s.\n", zstrn (c_day_times, cycletime, 7));
} else {
static const char c_night_times[] =
"It is just after sunset.\0"
"It is early evening.\0"
"The evening is getting old.\0"
"It is near midnight.\0"
"These are the wee hours of the morning.\0"
"The night is waning.\0"
"It is almost morning.";
puts (zstrn (c_night_times, cycletime, 7));
}
}
int give (void)
{
int firstnumber = wordnumber;
while (words[++wordnumber].type != OBJECT
&& wordnumber <= wordcount
&& words[wordnumber].value != AMULET
&& words[wordnumber].value != MEDALION
&& words[wordnumber].value != TALISMAN)
continue;
int obj = -1, person = 0, last1 = 0, last2 = 0;
if (wordnumber <= wordcount) {
obj = words[wordnumber].value;
if (obj == EVERYTHING)
words[wordnumber].type = -1;
last1 = wordnumber;
}
wordnumber = firstnumber;
while ((words[++wordnumber].type != NOUNS || words[wordnumber].value == obj) && wordnumber <= wordcount) {}
if (words[wordnumber].type == NOUNS) {
person = words[wordnumber].value;
last2 = wordnumber;
}
// Setting wordnumber to last1 - 1 looks wrong if last1 is 0, e.g.,
// plain 'give'. However, detecting this case is liable to detect
// 'give foo' as well, which would give a confusing error. We
// need to make sure the -1 value can cause no problems if it arises.
// If in the below we get to the drop("Given") then drop will look
// at word 0 for an object to give, and fail, which is OK; then
// result will be -1 and we get to the end, where wordnumber gets
// set to something more sensible. If we get to "I don't think
// that is possible" then again wordnumber is set to something
// sensible. The wordnumber we leave with still isn't right if
// you include words the game doesn't know in your command, but
// that's no worse than what other commands than give do in
// the same place.
int result = -1;
wordnumber = last1 - 1;
if (person && object_is_at (person, position)) {
if (person == GODDESS && godready < 2 && !(obj == RING || obj == BRACELET))
puts ("The goddess won't look at you.");
else
result = drop("Given");
} else {
puts ("I don't think that is possible.");
wordnumber = max_i (last1, last2) + 1;
return 0;
}
if (result != -1 && (object_is_at (obj, position) || obj == AMULET || obj == MEDALION || obj == TALISMAN)) {
remove_object_from (obj, position);
++ourtime;
++game_score.ego;
switch (person) {
case NATIVE_GIRL:
puts ("She accepts it shyly.");
game_score.ego += 2;
break;
case GODDESS:
if (obj == RING || obj == BRACELET) {
puts ("She takes the charm and puts it on.\n"
"A little kiss on the cheek is your reward.");
game_score.ego += 5;
godready += 3;
}
if (obj == AMULET || obj == MEDALION || obj == TALISMAN) {
game_score.ego += 5;
game_score.power -= min_u (game_score.power, 5);
if (++win >= 3) {
puts ("The powers of the earth are now legitimate. You have destroyed the Darkness\n"
"and restored the goddess to her throne. The entire island celebrates with\n"
"dancing and spring feasts. As a measure of her admiration, the goddess weds\n"
"you in the late summer and crowns you Prince Liverwort, Lord of Fungus.");
remove_object_from (MEDALION, position);
live();
}
}
break;
case TIMER:
if (obj == COINS) {
puts ("He fingers the coins for a moment and then looks up agape. 'Kind you are and\n"
"I mean to repay you as best I can.' Grabbing a pencil and cocktail napkin...\n\n"
"+-----------------------------------------------------------------------------+\n"
"| xxxxxxxx\\ |\n"
"| xxxxx\\ CLIFFS |\n"
"| FOREST xxx\\ |\n"
"| \\\\ x\\ OCEAN |\n"
"| || x\\ |\n"
"| || ROAD x\\ |\n"
"| || x\\ |\n"
"| SECRET || ......... |\n"
"| - + - || ........ |\n"
"| ENTRANCE || ... BEACH |\n"
"| || ... E |\n"
"| || ... | |\n"
"| // ... N <-- + --- S |\n"
"| PALM GROVE // ... | |\n"
"| // ... W |\n"
"+-----------------------------------------------------------------------------+\n"
"\n'This map shows a secret entrance to the catacombs.\n"
"You will know when you arrive because I left an old pair of shoes there.'");
}
break;
}
}
wordnumber = max_i (last1, last2) + 1;
return firstnumber;
}
bool launch (void)
{
if (!object_is_at (STARFIGHTER, position) || game_state (CANTLAUNCH)) {
puts ("Can't launch.");
return false;
}
if (fuel <= 4) {
puts ("Not enough fuel to launch.");
return false;
}
remove_object_from (STARFIGHTER, position);
position = location[position].dir.up;
set_game_state (LAUNCHED);
++ourtime;
fuel -= 4;
puts ("You climb into the starfighter and prepare for launch.\n"
"With a touch of your thumb the turbo engines ignite,\n"
"thrusting you back into your seat.");
return true;
}
bool land (void)
{
if (!game_state (LAUNCHED) || !object_is_at (LAND, position) || !location[position].dir.down) {
puts ("You can't land here.");
return false;
}
clear_game_state (LAUNCHED);
position = location[position].dir.down;
create_object_at (STARFIGHTER, position);
fuel -= min_u (fuel, 2);
++ourtime;
puts ("You land.");
return true;
}
int drive (void)
{
if (!object_is_at (CAR, position)) {
puts ("There is nothing to drive here.");
return -1;
}
puts ("You hop in the car and turn the key.\n"
"There is a perceptible grating noise,\n"
"and an explosion knocks you unconscious...");
remove_object_from (CAR, position);
create_object_at (CRASH, position);
suffer_injury (BROKEN_ARM);
suffer_injury (BROKEN_RIBS);
ourtime += 15;
zzz();
return 0;
}
int ride (void)
{
if (!object_is_at (HORSE, position)) {
puts ("There is no horse here.");
return -1;
}
puts ("You climb onto the stallion and kick it in the guts.\n"
"The indignant steed launches forward through bush and fern.\n"
"You are thrown and the horse gallops off.");
location_t oldpos = position;
while (!(position = nrand(NUMOFROOMS+1)) || !is_outside()
|| !visited_location(position) || location[position].dir.flyhere) {}
move_object_to (HORSE, oldpos, position);
if (location[position].dir.north)
position = location[position].dir.north;
else if (location[position].dir.south)
position = location[position].dir.south;
else if (location[position].dir.east)
position = location[position].dir.east;
else
position = location[position].dir.west;
return 0;
}
// synonyms = {strike, smoke} for matches, cigars
void light (void)
{
if (!object_is_at (MATCHES, INVENTORY)) {
puts ("You're out of matches.");
return;
}
if (!matchcount) // reset if picked up another book of matches
matchcount = 20;
++ourtime;
if (!--matchcount)
remove_object_from (MATCHES, INVENTORY);
set_game_state (MATCH_LIGHT);
puts ("Your match splutters to life.");
if (position == BUNGALOW_PORCH) {
puts ("The whole bungalow explodes with an intense blast.");
die();
}
}
// synonyms = {open, unlock}
void dooropen (void)
{
++wordnumber;
if (wordnumber > wordcount || words[wordnumber].type != NOUNS || words[wordnumber].value != DOOR)
puts ("That doesn't open.");
else if (position == CAVE_DOOR || position == CAVE_ENTRANCE) {
if (game_state (OPENED_CAVE_DOOR))
puts ("The door is already open.");
else
puts ("The door does not budge.");
} else if (position == KITCHEN_DOOR) {
if (game_state (OPENED_KITCHEN_DOOR))
puts ("The door is gone.");
else
puts ("The door is locked tight.");
} else if (position == DINING_ROOM_DOOR)
puts ("That's one immovable door.");
else if (position == LASER_ROOM)
puts ("The door is already ajar.");
else
puts ("What door?");
}
| 32.228696 | 145 | 0.629604 | [
"object"
] |
5a5a118e146f77192f01f2f827ff2bb6cfce2522 | 1,549 | h | C | samples/01_video_encode_shared/Encode_Device.h | zzlee/tegra_multimedia_api | 350dfc806b250b238226855b254f865a14630cf8 | [
"Unlicense"
] | null | null | null | samples/01_video_encode_shared/Encode_Device.h | zzlee/tegra_multimedia_api | 350dfc806b250b238226855b254f865a14630cf8 | [
"Unlicense"
] | null | null | null | samples/01_video_encode_shared/Encode_Device.h | zzlee/tegra_multimedia_api | 350dfc806b250b238226855b254f865a14630cf8 | [
"Unlicense"
] | null | null | null | #ifndef _ENCODE_DEVICE_H_
#define _ENCODE_DEVICE_H_
#include "video_encode.h"
#include <queue>
#include <vector>
typedef unsigned long ULONG;
struct EncodeParams
{
ULONG nType;
ULONG nWidth;
ULONG nHeight;
double dFrameRate;
ULONG nRecordMode;
ULONG nBitRate;
ULONG nTargetUsage;
ULONG nGOP;
ULONG nCodecProfile;
ULONG nCodecLevel;
ULONG nBFrameNumber;
ULONG nInputFormat;
};
struct FrameInfo
{
uint8_t *pData;
ULONG nDataSize;
ULONG nMaxDataSize;
bool bIsKeyFrame;
bool bIsUsed;
};
class CNvTegraEncode
{
public:
CNvTegraEncode();
~CNvTegraEncode();
std::queue<FrameInfo *> m_FrameInfoQueue;
std::vector<FrameInfo> m_FrameInfoArray;
pthread_mutex_t m_OutputMutex;
bool m_bFirstOutput;
int Create();
void Release();
int SetFormat(EncodeParams nParams);
int EncodeFrame(uint8_t *pSrcBuffer, uint8_t **pDestBuffer, ULONG *pDestBufferSize, bool *pbIsKeyFrame);
int InsertKeyFrame();
int GetFreeIndex();
void ResizeBuffer(FrameInfo *pFrameInfo, ULONG nSize);
uint8_t *pConverterBuffer;
uint8_t *pInputBuffer;
uint8_t *pOutputBuffer;
unsigned int iInputSize;
unsigned int iConvertSize;
private:
context_t m_nCtx;
unsigned int m_nFrameCount;
unsigned int m_nQueueIndex;
bool m_bIsEndOfEncode;
unsigned int m_nChangeFormat; // 0:dont change 1:YV12 to I420 2: YUY2 to I420
void FrameRateConvert(double dFrameRate, unsigned int *pFrameRateNum, unsigned int *pFrameRateDen);
};
#endif
| 22.449275 | 108 | 0.718528 | [
"vector"
] |
5a6b2db00e9cff1770505b7fe1e2e5f5470beefb | 1,576 | h | C | src/ast/forall_substitutor.h | cforall/resolv-proto | 4eb7c0b9f4e75b940205e808e14fa57f13541246 | [
"BSD-3-Clause"
] | 2 | 2019-05-13T10:26:02.000Z | 2019-05-13T15:04:42.000Z | src/ast/forall_substitutor.h | cforall/resolv-proto | 4eb7c0b9f4e75b940205e808e14fa57f13541246 | [
"BSD-3-Clause"
] | null | null | null | src/ast/forall_substitutor.h | cforall/resolv-proto | 4eb7c0b9f4e75b940205e808e14fa57f13541246 | [
"BSD-3-Clause"
] | null | null | null | #pragma once
// Copyright (c) 2015 University of Waterloo
//
// The contents of this file are covered under the licence agreement in
// the file "LICENCE" distributed with this repository.
#include <algorithm>
#include <unordered_map>
#include <vector>
#include "forall.h"
#include "type.h"
#include "type_mutator.h"
#include "data/list.h"
#include "data/range.h"
class Decl;
/// Replaces unsourced polymorphic type variables by fresh variables bound to a specified source.
class ForallSubstitutor : public TypeMutator<ForallSubstitutor> {
std::vector<const Forall*> ctx; ///< Forall clauses being substituted into
public:
using TypeMutator<ForallSubstitutor>::visit;
using TypeMutator<ForallSubstitutor>::operator();
ForallSubstitutor( const Forall* base ) : ctx{ base } {}
bool visit( const PolyType* orig, const Type*& r ) {
// Break early if not unbound
if ( orig->id() != 0 ) return true;
// Check for existing variable with given name in destination forall(s) and substitute
for ( const Forall* forall : reversed(ctx) ) {
if ( const PolyType* rep = forall->get( orig->name() ) ) {
r = rep;
return true;
}
}
return true;
}
/// Substitute a function declaration's types according to the substitution map;
/// Uses src to produce new IDs for nested forall clauses
Decl* operator() ( const Decl* d, unsigned& src );
/// Substitute a list of types
List<Type> operator() ( const List<Type>& ts ) {
List<Type> rs;
rs.reserve( ts.size() );
for ( const Type* t : ts ) { rs.push_back( (*this)( t ) ); }
return rs;
}
};
| 27.649123 | 97 | 0.693528 | [
"vector"
] |
5a81c743456d295731fda2b593776c26c0f880e0 | 4,211 | h | C | Source/AppAuthTV/OIDTVTokenRequest.h | mattio/AppAuth-iOS | e191b1beadf3041259652e6e464eaceff16e5fbb | [
"Apache-2.0"
] | 1,360 | 2016-02-18T22:51:22.000Z | 2022-03-30T23:42:29.000Z | Source/AppAuthTV/OIDTVTokenRequest.h | mattio/AppAuth-iOS | e191b1beadf3041259652e6e464eaceff16e5fbb | [
"Apache-2.0"
] | 642 | 2016-02-18T23:23:33.000Z | 2022-03-31T17:02:54.000Z | Source/AppAuthTV/OIDTVTokenRequest.h | mattio/AppAuth-iOS | e191b1beadf3041259652e6e464eaceff16e5fbb | [
"Apache-2.0"
] | 720 | 2016-02-18T02:39:06.000Z | 2022-03-31T07:56:19.000Z | /*! @file OIDTVTokenRequest.h
@brief AppAuth iOS SDK
@copyright
Copyright 2020 Google Inc.
@copydetails
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.
*/
#import "OIDTokenRequest.h"
#import <Foundation/Foundation.h>
@class OIDServiceConfiguration;
@class OIDTVServiceConfiguration;
NS_ASSUME_NONNULL_BEGIN
@interface OIDTVTokenRequest : OIDTokenRequest
/*! @brief The device code received from the authorization server.
@remarks device_code
@see https://tools.ietf.org/html/rfc8628#section-3.4
*/
@property(nonatomic, readonly) NSString *deviceCode;
/*! @internal
@brief Unavailable. Please use
@c initWithConfiguration:deviceCode:clientID:clientSecret:additionalParameters:
or @c initWithCoder:.
*/
- (instancetype)init NS_UNAVAILABLE;
/*! @internal
@brief Unavailable. Please use
@c initWithConfiguration:deviceCode:clientID:clientSecret:additionalParameters:
or @c initWithCoder:.
*/
- (instancetype)initWithConfiguration:(OIDServiceConfiguration *)configuration
grantType:(NSString *)grantType
authorizationCode:(nullable NSString *)code
redirectURL:(nullable NSURL *)redirectURL
clientID:(NSString *)clientID
clientSecret:(nullable NSString *)clientSecret
scopes:(nullable NSArray<NSString *> *)scopes
refreshToken:(nullable NSString *)refreshToken
codeVerifier:(nullable NSString *)codeVerifier
additionalParameters:
(nullable NSDictionary<NSString *, NSString *> *)additionalParameters
NS_UNAVAILABLE;
/*! @internal
@brief Unavailable. Please use
@c initWithConfiguration:deviceCode:clientID:clientSecret:additionalParameters:
or @c initWithCoder:.
*/
- (instancetype)initWithConfiguration:(OIDServiceConfiguration *)configuration
grantType:(NSString *)grantType
authorizationCode:(nullable NSString *)code
redirectURL:(nullable NSURL *)redirectURL
clientID:(NSString *)clientID
clientSecret:(nullable NSString *)clientSecret
scope:(nullable NSString *)scope
refreshToken:(nullable NSString *)refreshToken
codeVerifier:(nullable NSString *)codeVerifier
additionalParameters:
(nullable NSDictionary<NSString *, NSString *> *)additionalParameters
NS_UNAVAILABLE;
/*! @brief Designated initializer.
@param configuration The service's configuration.
@param deviceCode The device verification code received from the authorization server.
@param clientID The client identifier.
@param clientSecret The client secret (nullable).
@param additionalParameters The client's additional token request parameters.
*/
- (instancetype)initWithConfiguration:(OIDTVServiceConfiguration *)configuration
deviceCode:(NSString *)deviceCode
clientID:(NSString *)clientID
clientSecret:(nullable NSString *)clientSecret
additionalParameters:
(nullable NSDictionary<NSString *, NSString *> *)additionalParameters
NS_DESIGNATED_INITIALIZER;
/*! @brief Designated initializer for NSSecureCoding.
@param aDecoder Unarchiver object to decode
*/
- (instancetype)initWithCoder:(NSCoder *)aDecoder NS_DESIGNATED_INITIALIZER;
@end
NS_ASSUME_NONNULL_END
| 41.284314 | 90 | 0.663025 | [
"object"
] |
5a8335aa423eed0544b2c92a51cedb39f7acf94f | 876 | c | C | usr.bin/pascal/pdx/mappings/srcfile.c | weiss/original-bsd | b44636d7febc9dcf553118bd320571864188351d | [
"Unlicense"
] | 114 | 2015-01-18T22:55:52.000Z | 2022-02-17T10:45:02.000Z | usr.bin/pascal/pdx/mappings/srcfile.c | JamesLinus/original-bsd | b44636d7febc9dcf553118bd320571864188351d | [
"Unlicense"
] | null | null | null | usr.bin/pascal/pdx/mappings/srcfile.c | JamesLinus/original-bsd | b44636d7febc9dcf553118bd320571864188351d | [
"Unlicense"
] | 29 | 2015-11-03T22:05:22.000Z | 2022-02-08T15:36:37.000Z | /*-
* Copyright (c) 1980, 1993
* The Regents of the University of California. All rights reserved.
*
* %sccs.include.redist.c%
*/
#ifndef lint
static char sccsid[] = "@(#)srcfile.c 8.1 (Berkeley) 06/06/93";
#endif /* not lint */
/*
* get the source file name associated with a given address
*/
#include "defs.h"
#include "mappings.h"
#include "object.h"
#include "filetab.h"
char *srcfilename(addr)
ADDRESS addr;
{
register ADDRESS i, j, k;
ADDRESS a;
FILETAB *ftp;
if (addr < filetab[0].addr) {
return(NIL);
}
i = 0;
j = nlhdr.nfiles - 1;
while (i < j) {
k = (i + j) / 2;
ftp = &filetab[k];
if ((a = ftp->addr) == addr) {
return(ftp->filename);
} else if (addr > a) {
i = k + 1;
} else {
j = k - 1;
}
}
if (addr >= filetab[i].addr) {
return(filetab[i].filename);
} else {
return(filetab[i-1].filename);
}
/*NOTREACHED*/
}
| 17.176471 | 69 | 0.5879 | [
"object"
] |
5a90ff37208854e54d842c85e66154004f13b643 | 3,917 | h | C | src/include/symbols.h | chucktilbury/plang | b889299b20dedfe35de3e8c651f272d963b4d216 | [
"MIT"
] | null | null | null | src/include/symbols.h | chucktilbury/plang | b889299b20dedfe35de3e8c651f272d963b4d216 | [
"MIT"
] | null | null | null | src/include/symbols.h | chucktilbury/plang | b889299b20dedfe35de3e8c651f272d963b4d216 | [
"MIT"
] | null | null | null | /**
* @file symbols.h
* @brief Header file for symbols.c
*/
#ifndef __SYMBOLS_H__
#define __SYMBOLS_H__
#include <stdint.h>
typedef enum {
SYM_NO_ERROR = 300, // Success
SYM_EXISTS, // Failed to add because the name already exists
SYM_NOT_FOUND, // Failed to find the name.
SYM_CONTEXT_ERROR, // Sym table context could not be closed.
SYM_ERROR, // Covers things like an invalid state. Normally fatal.
} symbol_error_t;
typedef enum {
// no assignment type is allowed, trying to assign to something
// generates a syntax error.
SYM_NO_ASSIGN_TYPE = 325,
// These are used when the assignment type is a literal constant.
SYM_INT_ASSIGN_TYPE,
SYM_UINT_ASSIGN_TYPE,
SYM_FLOAT_ASSIGN_TYPE,
SYM_BOOL_ASSIGN_TYPE,
SYM_STRING_ASSIGN_TYPE,
// These indicate that an indirection is needed to retrieve a value
// for the name.
SYM_DICT_ASSIGN_TYPE,
SYM_MAP_ASSIGN_TYPE,
SYM_LIST_ASSIGN_TYPE,
// These two are handled the same except that the SYM_INHERIT_TYPE
// type has a pointer to the symbol that the class inherited from
// in the value union. The SYM_CLASS_TYPE means that there is no
// base class.
SYM_CLASS_ASSIGN_TYPE,
SYM_INHERIT_ASSIGN_TYPE,
// The assigment type is an expression, which could be any type and the
// actual assignment type is in the expression data structure.
SYM_EXPR_ASSIGN_TYPE,
} assignment_type_t;
typedef enum {
SYM_NO_NAME_TYPE = 350,
SYM_CLASS_NAME_TYPE,
SYM_METHOD_NAME_TYPE,
SYM_VAR_NAME_TYPE,
SYM_CONST_NAME_TYPE,
SYM_IMPORT_NAME_TYPE,
// name is a system-wide serial number and is only accessed at the top of
// the symbol table stack.
SYM_ANON_NAME_TYPE,
} name_type_t;
typedef enum {
// If the scope is not specified, then the scope is private.
SYM_PUBLIC_SCOPE_TYPE = 375,
SYM_PRIVATE_SCOPE_TYPE,
SYM_PROTECTED_SCOPE_TYPE,
} symbol_scope_t;
// When a context is opened, this data structure is stored in the current
// context. A pointer to the previous context is stored and the next
// context is NULL. The previous context's next pointer is updated to
// point to this context. This allows the resolver to move back and forth in
// the contexts that have been saved. No symbol is saved by opening a context.
typedef struct _symbol_context_t {
struct _symbol_t* sym; // tree that holds symbols for this context
struct _symbol_context_t* prev; // pointer to the symbol that holds the previous context
struct _symbol_context_t* next; // pointer to the symbol that holds the next context
} symbol_context_t;
typedef struct _symbol_t {
// symbol attributes
const char* name; // search name of the symbol.
name_type_t name_type;
assignment_type_t assign_type;
symbol_scope_t scope;
// constant value, if any
union {
// These hold a literally defined value that is connected to the name.
uint64_t uint_val;
int64_t int_val;
double float_val;
char* str_val;
// When the assignment object is a user-defined type or a variable,
// this points to the symbol table entry.
struct _symbol_t* symbol;
// TODO: add data structure for expressions.
} const_val;
// pointers for the tree
struct _symbol_t* left;
struct _symbol_t* right;
symbol_context_t* context;
} symbol_t;
// defined in symbols.c
void init_symbol_table();
symbol_t* create_symbol(const char* name);
symbol_error_t store_symbol(symbol_t* sym);
symbol_t* find_symbol(const char* name);
symbol_error_t open_symbol_context(const char* name);
symbol_error_t close_symbol_context();
symbol_t* get_symbol_context();
void dump_symbol_table();
// defined in resolver.c
symbol_t* open_resolver(const char* name);
symbol_t* resolve_symbol(const char* name);
symbol_t* close_resolver();
#endif
| 33.767241 | 92 | 0.721471 | [
"object"
] |
5a9dfe7b92c5fe7b1c06eac01b0d48f7df174a7b | 2,874 | h | C | Train/Pods/TTPLAPIManager/Classes/APIBase.h | Pradeepkn/StationApp | 2ac210f59c755009f2cd281f366a4995bb97d6ac | [
"MIT"
] | null | null | null | Train/Pods/TTPLAPIManager/Classes/APIBase.h | Pradeepkn/StationApp | 2ac210f59c755009f2cd281f366a4995bb97d6ac | [
"MIT"
] | null | null | null | Train/Pods/TTPLAPIManager/Classes/APIBase.h | Pradeepkn/StationApp | 2ac210f59c755009f2cd281f366a4995bb97d6ac | [
"MIT"
] | null | null | null | //
// APIBase.h
//
//
// Created by Subramanian on 11/10/14.
// Copyright (c) 2014 Tarento Technologies Pvt Ltd. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <AFNetworking/AFNetworking.h>
/*!
@discussion This is an API base model. Every API classes should be a subclass
of
PIAPIBase class.
## Version information
__Version__: 1.0
__Found__: 11/10/14
__Last update__: 11/10/14
__Developer__: Subramanian, Tarento Technologies Pvt Ltd.
*/
@interface APIBase : NSObject
/// @name Getter methods
/*!
@abstract Returns the base URL to be used for API calls
@discussion Every api has base url. Whenever need to request different server
apis.
then need to override this method on the specific API class with the proper
base url.
@return Returns the base URL in string format.
@since 1.0+
*/
- (NSString *)baseURL;
/*!
@abstract Returns the URL to be used for the API request
@discussion This method will return the part of the API request. This part will
append
with the base url.
@return Returns the URL part in string format.
@since 1.0+
*/
- (NSString *)urlForAPIRequest;
/*!
@abstract Returns the api authendication username
@discussion This will return the username in string format which is requeired
for API authendication.
@return Returns username in string format.
@since 1.0+
*/
- (NSString *)apiAuthenticationUsername;
/*!
@abstract Returns the api authendication password
@discussion This will return the password in string format which is requeired
for API authendication.
@return Returns password in string format.
@since 1.0+
*/
- (NSString *)apiAuthenticationPassword;
/*!
@abstract Returns the API parameters.
@discussion This will return the 'NSMutableDictionary'. It contains the list of
parameters which is required for API reqeust
@return Returns the API parameters in string format.
@since 1.0+
*/
- (NSMutableDictionary *)requestParameters;
/*!
@abstract Returns the API request type GET/POST
@discussion Mostly we are using two type to API request GET and POST. This will
return the type of request which we are going to make.
@return Returns the API request type GET/POST in string format
@since 1.0+
*/
- (NSString *)requestType;
/*!
@abstract Parse the API response and store it on respective API models.
@discussion Once got the API response from the request. APIManager will call
this method with the response of the API in the 'NSDictionary' format.
@param responseDictionary API response datas are serialized and gave as a
'NSDictionary' from the APIManager
@since 1.0+
*/
- (NSDictionary *)customHTTPHeaders;
- (NSString *)customRawBody;
- (void)parseAPIResponse:(NSDictionary *)responseDictionary;
- (NSString *)localFileName;
- (void)updateMultipartFormData:(id<AFMultipartFormData>)formData;
@end
| 22.107692 | 80 | 0.73904 | [
"model"
] |
bff2920eba2c6b9df0188b48f8ac5a66482b781c | 8,747 | h | C | include/city/CityRouteNetwork.h | etri/dtsim | 927c8e05c08c74ed376ec233ff677cd35b29e6f0 | [
"BSD-3-Clause"
] | null | null | null | include/city/CityRouteNetwork.h | etri/dtsim | 927c8e05c08c74ed376ec233ff677cd35b29e6f0 | [
"BSD-3-Clause"
] | null | null | null | include/city/CityRouteNetwork.h | etri/dtsim | 927c8e05c08c74ed376ec233ff677cd35b29e6f0 | [
"BSD-3-Clause"
] | null | null | null | /*
* Note: This license has also been called the "New BSD License"
* or "Modified BSD License".
*
* Copyright (c) 2021 Electronics and Telecommunications Research
* Institute All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* CityRouteNetwork.h
*
* $Revision: $
* $LastChangedDate: $
*/
#ifndef CITY_ROUTE_NETWORK_H_
#define CITY_ROUTE_NETWORK_H_
#include <vector>
#include <unordered_map>
#include <memory>
#include <queue>
#include "CitySpace.h"
#include "CityJunction.h"
#include "CityRoad.h"
#include "CityGeometry.h"
#include "CityCoordinate.h"
#include "CityRouter.h"
#include "CityRouteCache.h"
namespace dtsim {
class Edge;
/**
* \class Vertex
*
* \brief
* Vertex represents a junction in the route network.
*/
class Vertex {
private:
/// a numeric identifer read from the NODE shape file
double _nodeid;
/// geographic coordinates
double _latitude, _longitude;
/// uses to filter out what have visited to choose its successors
bool _visited;
/// uses for only A* to recalculate the distance to this vertex
bool _moved;
/// uses for only A* to filter out what have passed to get a shortest path
bool _passed;
// all edges to this vertex
std::vector<Edge*> _edges;
/// vertices connected to edges outgoing from this vertex
std::vector<Vertex*> _successors;
/// vertices connected to edges incoming to this vertex
std::vector<Vertex*> _predecessors;
public:
/**
* Constructor
*
* @param nodeid the numeric identifier of a junction represened by this vertex
* @param latitude the X-axis value
* @param longitude the Y-axis value
*/
Vertex(double nodeid, double latitude, double longitude);
~Vertex() {}
/// Returns the node identifer
double nodeid() const {
return _nodeid;
}
/// Returns the X-axis value
double getLatitude() const {
return _latitude;
}
/// Returns the Y-axis value
double getLongitude() const {
return _longitude;
}
/// Returns true if two coorindates are same or false if different
bool isSameCoordinate(double latitude, double longitude) {
return (_latitude == latitude && _longitude == longitude);
}
/// Returns the state whether it has visited
bool visited() const {
return _visited;
}
void visited(bool value) {
_visited = value;
}
/// Returns the state whether it has moved to the open list
bool moved() const {
return _moved;
}
void moved(bool value) {
_moved = value;
}
/// Returns the state whether it has passed
bool passed() const {
return _passed;
}
void passed(bool value) {
_passed = value;
}
/// Returns the list of edges connected to this
std::vector<Edge*> edges() const {
return _edges;
}
int edgeCount() const {
return _edges.size();
}
/// Adds an input vertex to the list of successors
void putSuccessors(Vertex* v) {
_successors.push_back(v);
}
/// Adds an vertex to the list of predecessors
void putPredecessors(Vertex* v) {
_predecessors.push_back(v);
}
/// Returns the successors of this vertex
void getSuccessors(std::vector<Vertex*>& out) const;
/// Returns the predecessors of this vertex
void getPredecessors(std::vector<Vertex*>& out) const;
/// Retrieves the edge from this to the specified vertex
Edge* findEdge(Vertex* target);
/// Adds the specified edge to the list of edges
void doAddEdge(Edge* e);
};
/**
* \class Edge
*
* \brief
* Edge represents a road in the route network.
*/
class Edge {
private:
Vertex* _source;
Vertex* _target;
// an edge identifier
double _edgeid;
/// a distance from source to target
double _weight;
/// means whether it has passed or not
bool _visited;
public:
/** Constructor
*
* @param source the source vertex
* @param target the target vertex
* @param edgeId the edge identifier
*/
Edge(Vertex* source, Vertex* target, double edgeId);
/** Constructor
*
* @param source the source vertex
* @param target the target vertex
* @param edgeId the edge identifier
* @param weight the distance from soruce to target
*/
Edge(Vertex* source, Vertex* target, double edgeId, double weight);
~Edge() {}
/// Returns the edge ID
double getEdgeId() const {
return _edgeid;
}
/// Sets the edge ID
void setEdgeId(double edgeId) {
_edgeid = edgeId;
}
/// Returns the source vertex
Vertex* source() const {
return _source;
}
/// Returns the target vertex
Vertex* target() const {
return _target;
}
/// Sets the source vertex
void source(Vertex* vSource) {
_source = vSource;
}
/// Sets the target vertex
void target(Vertex* vTarget) {
_target = vTarget;
}
/// Returns the weight
double weight() const {
return _weight;
}
/// Sets the weight
void weight(double wgt) {
_weight = wgt;
}
/// Returns the state whether it has visited or not
bool visited() const {
return _visited;
}
/// Sets the state to the specified value
void visited(bool value) {
_visited = value;
}
};
/**
* \class CityRouteNetwork
*
* \brief
* Road network implementation
*
* CityRouteNetwork describes a road network that is composed of junctions and roads.
* Junction is depicted as a vertex and Road as an edge. It is used to get the shortest path
* between the specified vertices
*/
class CityRouteNetwork: public CitySpace {
private:
typedef typename std::unordered_map<double, std::pair<Vertex*, CityJunction*>> VerticesMap;
typedef typename VerticesMap::iterator VerticesMapIterator;
/// all vertices on this network
VerticesMap vertices;
/// all edges on this network
std::vector<Edge*> edges;
std::unordered_map<double, Edge*> edgeMap;
/// CityRouteCache object
CityRouteCache* cacheMap;
/// parallel CityRouters
std::vector<CityRouter<Vertex, Edge>*> routers;
std::mutex qLock;
std::queue<CityRouter<Vertex, Edge>*> waitQ;
public:
static std::string DEFAULT_SEARCH_ALGORITHM;
/**
* Creates a CityRouteNetwork consisting of the specified vertices and edges
*
* @param name road network name
* @param context CityContext
*/
CityRouteNetwork(std::string& name, CityContext* context);
~CityRouteNetwork();
void build(std::vector<CityJunction*>& junctions, std::vector<CityRoad*>& roads);
Edge* findEdge(CityJunction* source, CityJunction* target);
/// Update the weight of the specified edge
void updateEdge(double edgeId, double newWeight);
CityRouter<Vertex, Edge>* getRouter();
void putRouter(CityRouter<Vertex, Edge>* r);
/// Gets the shortest path between start and goal junctions and puts them into out
void getShortestPath(double startJunctionId, double endJunctionId, std::vector<CityJunction*>& junctions);
void getShortestPath(double startJunctionId, double endJunctionId, std::vector<CityRoad*>& roads);
void getShortestPath(double startJunctionId, double endJunctionId, std::vector<std::unique_ptr<CityCoordinateSequence>>& roadCoordSeqs, std::vector<std::vector<double>>& roadDistances);
void getShortestPath(double startJunctionId, double endJunctionId, std::vector<std::pair<double, std::pair<std::unique_ptr<CityCoordinateSequence>, std::vector<double>>>>& roadDistances);
// debug
void printPath(double start, double goal, std::vector<CityJunction*>& paths);
};
} /* namespace */
#endif /* CITY_ROUTE_NETWORK_H_ */
| 24.991429 | 188 | 0.721847 | [
"object",
"shape",
"vector"
] |
bff2950a3ad65a585eaabe71a809c4d892e78def | 2,650 | h | C | source/PanCamera.h | Osumi-Akari/energytycoon | 25d18a0ee4a9f8833e678af297734602918a92e9 | [
"Unlicense"
] | null | null | null | source/PanCamera.h | Osumi-Akari/energytycoon | 25d18a0ee4a9f8833e678af297734602918a92e9 | [
"Unlicense"
] | null | null | null | source/PanCamera.h | Osumi-Akari/energytycoon | 25d18a0ee4a9f8833e678af297734602918a92e9 | [
"Unlicense"
] | null | null | null | #ifndef PANCAMERA_H
#define PANCAMERA_H
/*-----------------------------------------------------------------------------------------------*/
class EventData;
/*-----------------------------------------------------------------------------------------------*/
const float cMouseWheelZoomSteps = 450.0f; //!< Mousewheel zoom speed
const float cMouseRotationSteps = 175.0f; //!< Mouse rotation speed
/*-----------------------------------------------------------------------------------------------*/
//! Smooth move 'unit'
class SmoothMove {
public:
//! Create with default values
SmoothMove(void) :
mAmount(0.0), mTimePassed(0.0)
{}
float mAmount; //!< fixed
float mTimePassed; //!< time passed
};
/*-----------------------------------------------------------------------------------------------*/
//! Camera for the game
class PanCamera {
public:
//! Create it
PanCamera(Ogre::SceneManager* pSceneManager, Ogre::RenderWindow* pRenderWindow);
//! Set the aspect ratio
void setAspectRatio(float pRatio);
//! Set the map borders
void setMapSize(float pTerrainWidth, float pTerrainHeight);
//! move up
void moveUp(float pTimeElapsed);
//! move down
void moveDown(float pTimeElapsed);
//! move left
void moveLeft(float pTimeElapsed);
//! move right
void moveRight(float pTimeElapsed);
//! zoom in
void zoomIn(float pTimeElapsed);
//! zoom out
void zoomOut(float pTimeElapsed);
//! rotate left
void rotateLeft(float pTimeElapsed);
//! rotate right
void rotateRight(float pTimeElapsed);
//! Return OGRE camera ptr
Ogre::Camera* getCam(void);
//! Get current height
float getHeight(void);
//! update camera (smooth out moves)
void update(float pTimeElapsed);
//! add a zoom unit to the stack
void addZoom(float pTimeElapsed);
//! add a rotate unit to the stack
void addRotate(float pTimeElapsed);
private:
//! move to event (e.g. message ticker click)
void eventMoveTo(EventData* pData);
//! zoom event (main panel)
void eventZoom(EventData* pData);
//! rotate event (main panel)
void eventRotate(EventData* pData);
//! Event handler if graphic options change
void graphicOptionsChange(EventData* pData);
Ogre::Camera* mCamera; //!< OGRE camera
Ogre::SceneNode* mCameraNode; //!< OGRE node
Ogre::RenderWindow* mWindow; //!< OGRE render window
int mTerrainWidth; //!< Terrain width used in game logic
int mTerrainHeight; //!< Terrain height
std::vector<SmoothMove> mZoomers; //!< zoom stack
std::vector<SmoothMove> mRotators; //!< rotate stack
};
/*-----------------------------------------------------------------------------------------------*/
#endif // PANCAMERA_H
| 24.311927 | 99 | 0.580377 | [
"render",
"vector"
] |
bffad87c37cae5dd556d002d899b3bb0595f8ea2 | 591 | h | C | src/comparefiles.h | kamchatka-volcano/lunchtoast | ca974db4d924d3ae7624d2c3fbeff0c0ea555a6b | [
"MS-PL"
] | 1 | 2021-05-20T22:00:38.000Z | 2021-05-20T22:00:38.000Z | src/comparefiles.h | kamchatka-volcano/lunchtoast | ca974db4d924d3ae7624d2c3fbeff0c0ea555a6b | [
"MS-PL"
] | null | null | null | src/comparefiles.h | kamchatka-volcano/lunchtoast | ca974db4d924d3ae7624d2c3fbeff0c0ea555a6b | [
"MS-PL"
] | null | null | null | #pragma once
#include "testaction.h"
#include "alias_filesystem.h"
#include "filenamereader.h"
#include <vector>
#include <regex>
class CompareFiles : public TestAction
{
public:
CompareFiles(FilenameGroup lhs,
FilenameGroup rhs,
TestActionType actionType);
TestActionResult process() override;
TestActionType type() const override;
private:
bool compareFiles(const fs::path& lhs, const fs::path& rhs, std::string& failedComparisonInfo) const;
private:
FilenameGroup lhs_;
FilenameGroup rhs_;
TestActionType actionType_;
};
| 21.888889 | 105 | 0.708968 | [
"vector"
] |
bffba6ff9cad7c703a8a4ab8e17e32b5deb6c531 | 8,132 | h | C | media/base/mock_filters.h | creativeprogramming/chromium | c4625eefca763df86471d798ee5a4a054b4716ae | [
"BSD-3-Clause"
] | 1 | 2019-06-12T19:56:26.000Z | 2019-06-12T19:56:26.000Z | media/base/mock_filters.h | changbai1980/chromium | c4625eefca763df86471d798ee5a4a054b4716ae | [
"BSD-3-Clause"
] | null | null | null | media/base/mock_filters.h | changbai1980/chromium | c4625eefca763df86471d798ee5a4a054b4716ae | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2009 The Chromium Authors. All rights reserved. Use of this
// source code is governed by a BSD-style license that can be found in the
// LICENSE file.
//
// A new breed of mock media filters, this time using gmock! Feel free to add
// actions if you need interesting side-effects (i.e., copying data to the
// buffer passed into MockDataSource::Read()).
//
// Don't forget you can use StrictMock<> and NiceMock<> if you want the mock
// filters to fail the test or do nothing when an unexpected method is called.
// http://code.google.com/p/googlemock/wiki/CookBook#Nice_Mocks_and_Strict_Mocks
#ifndef MEDIA_BASE_MOCK_FILTERS_H_
#define MEDIA_BASE_MOCK_FILTERS_H_
#include "media/base/factory.h"
#include "media/base/filters.h"
#include "testing/gmock/include/gmock/gmock.h"
namespace media {
// Use this template to test for object destruction by setting expectations on
// the method OnDestroy().
//
// TODO(scherkus): not sure about the naming... perhaps contribute this back
// to gmock itself!
template<class MockClass>
class Destroyable : public MockClass {
public:
Destroyable() {}
MOCK_METHOD0(OnDestroy, void());
protected:
virtual ~Destroyable() {
OnDestroy();
}
private:
DISALLOW_COPY_AND_ASSIGN(Destroyable);
};
class MockDataSource : public DataSource {
public:
MockDataSource() {}
// MediaFilter implementation.
MOCK_METHOD0(Stop, void());
MOCK_METHOD1(SetPlaybackRate, void(float playback_rate));
MOCK_METHOD1(Seek, void(base::TimeDelta time));
// DataSource implementation.
MOCK_METHOD1(Initialize, bool(const std::string& url));
const MediaFormat& media_format() { return media_format_; }
MOCK_METHOD2(Read, size_t(uint8* data, size_t size));
MOCK_METHOD1(GetPosition, bool(int64* position_out));
MOCK_METHOD1(SetPosition, bool(int64 position));
MOCK_METHOD1(GetSize, bool(int64* size_out));
MOCK_METHOD0(IsSeekable, bool());
protected:
virtual ~MockDataSource() {}
private:
MediaFormat media_format_;
DISALLOW_COPY_AND_ASSIGN(MockDataSource);
};
class MockDemuxer : public Demuxer {
public:
MockDemuxer() {}
// MediaFilter implementation.
MOCK_METHOD0(Stop, void());
MOCK_METHOD1(SetPlaybackRate, void(float playback_rate));
MOCK_METHOD1(Seek, void(base::TimeDelta time));
// Demuxer implementation.
MOCK_METHOD1(Initialize, bool(DataSource* data_source));
MOCK_METHOD0(GetNumberOfStreams, size_t());
MOCK_METHOD1(GetStream, scoped_refptr<DemuxerStream>(int stream_id));
protected:
virtual ~MockDemuxer() {}
private:
DISALLOW_COPY_AND_ASSIGN(MockDemuxer);
};
class MockDemuxerStream : public DemuxerStream {
public:
MockDemuxerStream() {}
// Sets the mime type of this object's media format, which is usually checked
// to determine the type of decoder to create.
explicit MockDemuxerStream(const std::string& mime_type) {
media_format_.SetAsString(MediaFormat::kMimeType, mime_type);
}
// DemuxerStream implementation.
const MediaFormat& media_format() { return media_format_; }
MOCK_METHOD1(Read, void(Callback1<Buffer*>::Type* read_callback));
MOCK_METHOD1(QueryInterface, void*(const char* interface_id));
protected:
virtual ~MockDemuxerStream() {}
private:
MediaFormat media_format_;
DISALLOW_COPY_AND_ASSIGN(MockDemuxerStream);
};
class MockVideoDecoder : public VideoDecoder {
public:
MockVideoDecoder() {}
// MediaFilter implementation.
MOCK_METHOD0(Stop, void());
MOCK_METHOD1(SetPlaybackRate, void(float playback_rate));
MOCK_METHOD1(Seek, void(base::TimeDelta time));
// VideoDecoder implementation.
MOCK_METHOD1(Initialize, bool(DemuxerStream* demuxer_stream));
const MediaFormat& media_format() { return media_format_; }
MOCK_METHOD1(Read, void(Callback1<VideoFrame*>::Type* read_callback));
protected:
virtual ~MockVideoDecoder() {}
private:
MediaFormat media_format_;
DISALLOW_COPY_AND_ASSIGN(MockVideoDecoder);
};
class MockAudioDecoder : public AudioDecoder {
public:
MockAudioDecoder() {}
// MediaFilter implementation.
MOCK_METHOD0(Stop, void());
MOCK_METHOD1(SetPlaybackRate, void(float playback_rate));
MOCK_METHOD1(Seek, void(base::TimeDelta time));
// AudioDecoder implementation.
MOCK_METHOD1(Initialize, bool(DemuxerStream* demuxer_stream));
const MediaFormat& media_format() { return media_format_; }
MOCK_METHOD1(Read, void(Callback1<Buffer*>::Type* read_callback));
protected:
virtual ~MockAudioDecoder() {}
private:
MediaFormat media_format_;
DISALLOW_COPY_AND_ASSIGN(MockAudioDecoder);
};
class MockVideoRenderer : public VideoRenderer {
public:
MockVideoRenderer() {}
// MediaFilter implementation.
MOCK_METHOD0(Stop, void());
MOCK_METHOD1(SetPlaybackRate, void(float playback_rate));
MOCK_METHOD1(Seek, void(base::TimeDelta time));
// VideoRenderer implementation.
MOCK_METHOD1(Initialize, bool(VideoDecoder* decoder));
protected:
virtual ~MockVideoRenderer() {}
private:
DISALLOW_COPY_AND_ASSIGN(MockVideoRenderer);
};
class MockAudioRenderer : public AudioRenderer {
public:
MockAudioRenderer() {}
// MediaFilter implementation.
MOCK_METHOD0(Stop, void());
MOCK_METHOD1(SetPlaybackRate, void(float playback_rate));
MOCK_METHOD1(Seek, void(base::TimeDelta time));
// AudioRenderer implementation.
MOCK_METHOD1(Initialize, bool(AudioDecoder* decoder));
MOCK_METHOD1(SetVolume, void(float volume));
protected:
virtual ~MockAudioRenderer() {}
private:
DISALLOW_COPY_AND_ASSIGN(MockAudioRenderer);
};
// FilterFactory that returns canned instances of mock filters. You can set
// expectations on the filters and then pass the factory into a pipeline.
class MockFilterFactory : public FilterFactory {
public:
MockFilterFactory()
: creation_successful_(true),
data_source_(new MockDataSource()),
demuxer_(new MockDemuxer()),
video_decoder_(new MockVideoDecoder()),
audio_decoder_(new MockAudioDecoder()),
video_renderer_(new MockVideoRenderer()),
audio_renderer_(new MockAudioRenderer()) {
}
virtual ~MockFilterFactory() {}
// Controls whether the Create() method is successful or not.
void set_creation_successful(bool creation_successful) {
creation_successful_ = creation_successful;
}
// Mock accessors.
MockDataSource* data_source() const { return data_source_; }
MockDemuxer* demuxer() const { return demuxer_; }
MockVideoDecoder* video_decoder() const { return video_decoder_; }
MockAudioDecoder* audio_decoder() const { return audio_decoder_; }
MockVideoRenderer* video_renderer() const { return video_renderer_; }
MockAudioRenderer* audio_renderer() const { return audio_renderer_; }
protected:
MediaFilter* Create(FilterType filter_type, const MediaFormat& media_format) {
if (!creation_successful_) {
return NULL;
}
switch (filter_type) {
case FILTER_DATA_SOURCE:
return data_source_;
case FILTER_DEMUXER:
return demuxer_;
case FILTER_VIDEO_DECODER:
return video_decoder_;
case FILTER_AUDIO_DECODER:
return audio_decoder_;
case FILTER_VIDEO_RENDERER:
return video_renderer_;
case FILTER_AUDIO_RENDERER:
return audio_renderer_;
default:
NOTREACHED() << "Unknown filter type: " << filter_type;
}
return NULL;
}
private:
bool creation_successful_;
scoped_refptr<MockDataSource> data_source_;
scoped_refptr<MockDemuxer> demuxer_;
scoped_refptr<MockVideoDecoder> video_decoder_;
scoped_refptr<MockAudioDecoder> audio_decoder_;
scoped_refptr<MockVideoRenderer> video_renderer_;
scoped_refptr<MockAudioRenderer> audio_renderer_;
DISALLOW_COPY_AND_ASSIGN(MockFilterFactory);
};
// Helper gmock action that calls InitializationComplete() on behalf of the
// provided filter.
ACTION_P(InitializationComplete, filter) {
filter->host()->InitializationComplete();
}
// Helper gmock action that calls Error() on behalf of the provided filter.
ACTION_P2(Error, filter, error) {
filter->host()->Error(error);
}
} // namespace media
#endif // MEDIA_BASE_MOCK_FILTERS_H_
| 29.042857 | 80 | 0.747787 | [
"object"
] |
8708f97113071a148809695d56cbc37952b762e3 | 10,263 | h | C | tests/testsupport.h | n-marion/zDNN | 5966eddb57292e1d794c07ec7f2b9a126e7d4022 | [
"Apache-2.0"
] | 10 | 2021-09-11T11:28:23.000Z | 2022-03-26T03:18:22.000Z | site/zDNN/tests/testsupport.h | IBM/ai-on-z-101 | f2271134b04a66627f324fd536de2a0cf5a7975b | [
"Apache-2.0"
] | 1 | 2022-03-03T19:16:03.000Z | 2022-03-03T19:16:03.000Z | site/zDNN/tests/testsupport.h | IBM/ai-on-z-101 | f2271134b04a66627f324fd536de2a0cf5a7975b | [
"Apache-2.0"
] | 3 | 2021-10-01T15:35:38.000Z | 2022-02-04T22:38:09.000Z | // SPDX-License-Identifier: Apache-2.0
/*
* Copyright IBM Corp. 2021
*
* 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 TESTS_TESTSUPPORT_H_
#define TESTS_TESTSUPPORT_H_
#include "convert.h"
#include "unity.h"
#include "zdnn.h"
#include "zdnn_private.h"
// NOTE: ZDNN_CONFIG_NO_NNPA is not defined until after "zdnn_private.h"
#ifdef ZDNN_CONFIG_NO_NNPA
// when ZDNN_CONFIG_NO_NNPA is set we might need the scaffolded conversion
// routines
#include "convert.h"
#endif
#include <float.h>
#include <stddef.h>
#define AIU_METHOD_STR_LENGTH 32
extern float ZERO_ARRAY[1];
#define NO_CONCAT 0xFFFFFFFF
// "default" failure when non of the ZDNN_STATUS's si appropriate,
// likely due to something's wrong with the testcase itself
#define GENERAL_TESTCASE_FAILURE 0xDEADBEEF
// Generate path string to a pregenerated offset file
#define OFFSET_FILE(layout, d4, d3, d2, d1) \
"resources/offset_files/" #layout "_" #d4 "x" #d3 "x" #d2 "x" #d1 ".txt"
typedef enum offset_mode {
NO_OFFSETS, // Don't generate offsets. Not a valid mode.
QUICK_OFFSETS, // Fast but not always correct. Best for small dims.
// see https://jsw.ibm.com/browse/ZAI-206 for details.
FILE_OFFSETS // Load pre-generated offsets (see stick_fe.py).
} offset_mode;
uint64_t get_offsets_from_file(const char *file_name, size_t *array);
size_t *alloc_offsets(zdnn_ztensor *ztensor, offset_mode mode,
const char *path);
size_t *alloc_rnn_output_offsets(const zdnn_ztensor *ztensor);
void *alloc_and_convert_float_values(zdnn_data_types type, uint64_t num_values,
bool repeat_first_value, float *values);
zdnn_ztensor *alloc_ztensor_with_values(uint32_t *shape,
zdnn_data_layouts pre_tfrmd_layout,
zdnn_data_types type,
zdnn_concat_info info,
int repeat_first_value, ...);
void free_ztensor_buffers(uint32_t num_ztensors, ...);
// Struct for floating point value tolerance information.
typedef struct fp_tolerance {
uint32_t ulps; // unit in the last place
uint32_t epsilon_mult; // epsilon multiplier
} fp_tolerance;
extern fp_tolerance tol_bfloat, tol_fp16, tol_fp32;
void assert_ztensor_values(zdnn_ztensor *ztensor,
bool repeat_first_expected_value, void *values);
void assert_ztensor_values_adv(zdnn_ztensor *ztensor,
bool repeat_first_expected_value, void *values,
fp_tolerance tol);
unsigned char *create_and_fill_fp_data(zdnn_tensor_desc *desc);
unsigned char *create_and_fill_random_fp_data(zdnn_ztensor *ztensor);
void gen_random_float_array(int size, float arr[]);
void gen_random_float_array_neg(int size, float arr[]);
void gen_random_float_array_pos_neg(int size, float arr[]);
void gen_float_array_zeros(int size, float arr[]);
void copy_to_array(int size, float input[], float output[]);
void fill_everyother_with_zero_float_array(int size, float arr[]);
void fill_all_with_zero_float_array(int size, float arr[]);
#define SEQUENTIAL_FILL_INTERVAL 1.0F
#define SEQUENTIAL_FILL_MAX 1024.0F // sacrifice BFLOAT, 256 is too small
// "OK" tolerance values.
//
// As everything gets converted to DLFLOAT16 and back, some data types will fare
// better dealing with precision loss than others, thus the different values
// among the data types.
//
// Some ops may need higher/lower tolerance than these defaults.
#define MAX_ULPS_BFLOAT 8
#define MAX_ULPS_FP16 8
#define MAX_ULPS_FLOAT (16384 * 8)
#define MAX_ULPS_DLFLOAT16 8
#define MAX_EPSILON_MULT_BFLOAT 8
#define MAX_EPSILON_MULT_FP16 8
#define MAX_EPSILON_MULT_FLOAT (5120 * 8)
#define MAX_EPSILON_MULT_DLFLOAT16 8
// epsilon = 2 ^ (num_mantissa_bits - 1)
#define EPSILON_BFLOAT 0.00390625F // 2 ^ -8
#define EPSILON_FP16 0.00048828125F // 2 ^ -11
#define EPSILON_FLOAT 0.000000059604644775390625F // 2 ^ -24, FLT_EPSILON
#define EPSILON_DLFLOAT16 0.0009765625F // 2 ^ -10
bool almost_equal_bfloat_adv(uint16_t actual, uint16_t expected,
fp_tolerance tol);
bool almost_equal_fp16_adv(uint16_t actual, uint16_t expected,
fp_tolerance tol);
bool almost_equal_float_adv(float actual, float expected, fp_tolerance tol);
bool almost_equal_dlf16_adv(uint16_t actual, uint16_t expected,
fp_tolerance tol);
bool almost_equal_bfloat(uint16_t actual, uint16_t expected);
bool almost_equal_fp16(uint16_t actual, uint16_t expected);
bool almost_equal_float(float actual, float expected);
bool almost_equal_dlf16(uint16_t actual, uint16_t expected);
// in some cases we can't use the single-precision float values as-is for
// calculating expected results. these macros convert a given single-precision
// value to its "representable-by-AIU" value w.r.t. its pre-transformed data
// type
#define CLEANSE_BFLOAT(x) \
cnvt_1_dlf16_to_fp32( \
cnvt_1_fp32_to_dlf16(cnvt_1_bfloat_to_fp32((cnvt_1_fp32_to_bfloat(x)))))
#define CLEANSE_FP16(x) \
cnvt_1_dlf16_to_fp32( \
cnvt_1_fp32_to_dlf16(cnvt_1_fp16_to_fp32((cnvt_1_fp32_to_fp16(x)))))
#define CLEANSE_FP32(x) cnvt_1_dlf16_to_fp32(cnvt_1_fp32_to_dlf16(x))
// Max/min absolute values for some of the test random float generators
#define LARGEST_RANDOM_FP 5.0F
#define SMALLEST_RANDOM_FP 0.00006F
// -----------------------------------------------------------------------------
// Max values by type (to create NNPA overflow)
// -----------------------------------------------------------------------------
#define MAX_FP32 FLT_MAX
//#define MAX_FP32 3.4028234663852885981170418348452e+38
#define MAX_FP16 ((float)65504) // 2^15 * (1 + 1023/1024)
#define MAX_BFLOAT FLT_MAX
#define MAX_DLF16 ((float)8581545984) // 2^32 * (1 + 511/512)
#if defined(ZDNN_CONFIG_SIMULATION)
#define NUM_PRE_TFRMD_TYPES 1
#else
#define NUM_PRE_TFRMD_TYPES 3
#endif
#define NUM_TFRMD_TYPES 1
extern zdnn_data_types pre_tfrmd_types[NUM_PRE_TFRMD_TYPES];
extern zdnn_data_types tfrmd_types[NUM_TFRMD_TYPES];
#define NUM_PREV_LAYERS 2
#define NUM_BIASES_USAGES 2
#define NUM_NO_VCONCAT_INFOS 3
extern zdnn_concat_info prev_layers[NUM_PREV_LAYERS];
extern zdnn_concat_info biases_usages[NUM_BIASES_USAGES];
extern zdnn_concat_info no_vconcat_infos[NUM_NO_VCONCAT_INFOS];
void stdout_to_pipe();
void stderr_to_pipe();
void restore_stdout(char *buf, int buf_size);
void restore_stderr(char *buf, int buf_size);
/* The following defines a macro to verify the hardware environment for our
* tests to successfully run in. Most tests require the proper HW environment
* to succeed. Even some of the others, like "..._fail" tests, are looking for
* a specific error, but can't rely on the root cause of that error without
* the proper HW environment. In the event the proper HW environment is not
* available, we will ignore or skip those tests.
*
* When an NNPA build occurs (ZDNN_CONFIG_NO_NNPA wasn't defined) we require
* that NNPA hardware be available, otherwise we must skip tests.
*
* When we have a non-NNPA build, we require that NNPA hardware is not
* available, otherwise we must skip tests.
*
* Simply invoke it in the Unity "setup" proc or within specific tests.
*/
#ifndef ZDNN_CONFIG_NO_NNPA
#define VERIFY_HW_ENV \
if (!zdnn_is_nnpa_installed()) \
TEST_IGNORE_MESSAGE("NNPA build but NNPA hardware not available");
#else
#define VERIFY_HW_ENV \
if (zdnn_is_nnpa_installed()) \
TEST_IGNORE_MESSAGE("Non-NNPA build but NNPA Scaffold is not setup");
#endif
/**********************************************************
* Enhanced Unity Functions/Macros
**********************************************************/
// standard error message string buffer for all tests to send down to Unity
#define ERROR_MESSAGE_STR_LENGTH 512
extern char error_message[ERROR_MESSAGE_STR_LENGTH];
#define TEST_FAIL_MESSAGE_FORMATTED(f, ...) \
snprintf(error_message, ERROR_MESSAGE_STR_LENGTH, (f), __VA_ARGS__); \
TEST_FAIL_MESSAGE(error_message);
#define TEST_ASSERT_MESSAGE_FORMATTED(cond, f, ...) \
snprintf(error_message, ERROR_MESSAGE_STR_LENGTH, (f), __VA_ARGS__); \
TEST_ASSERT_MESSAGE((cond), error_message);
#define FUNCNAME_BANNER_LENGTH 256
extern zdnn_data_types test_datatype;
void UnityDefaultTestRunWithDataType(UnityTestFunction Func,
const char *FuncName,
const int FuncLineNum);
void UnityDefaultTestRunWithTfrmdDataType(UnityTestFunction Func,
const char *FuncName,
const int FuncLineNum);
// Macro to run test func() against all pre-transformed data-types
#define RUN_TEST_ALL_DATATYPES(func) \
UnityDefaultTestRunWithDataType(func, #func, __LINE__);
// Macro to run test func() against all transformed data-types
#define RUN_TEST_ALL_TFRMD_DATATYPES(func) \
UnityDefaultTestRunWithTfrmdDataType(func, #func, __LINE__);
#endif /* TESTS_TESTSUPPORT_H_ */
| 41.550607 | 80 | 0.67261 | [
"shape"
] |
870beefee4820a5e373ad998fc8eeb499a2f38d0 | 1,496 | h | C | Engine/src/Scene/Components/LuaScriptComponent.h | mfkiwl/Cross-Platform-Game-Engine | 72e6c1adc4fc78fdd0e326cc47ed819d6aa06d3b | [
"MIT"
] | null | null | null | Engine/src/Scene/Components/LuaScriptComponent.h | mfkiwl/Cross-Platform-Game-Engine | 72e6c1adc4fc78fdd0e326cc47ed819d6aa06d3b | [
"MIT"
] | null | null | null | Engine/src/Scene/Components/LuaScriptComponent.h | mfkiwl/Cross-Platform-Game-Engine | 72e6c1adc4fc78fdd0e326cc47ed819d6aa06d3b | [
"MIT"
] | null | null | null | #pragma once
#include "cereal/cereal.hpp"
#include "sol/sol.hpp"
#include <vector>
#include <filesystem>
#include "Core/Application.h"
#include "Utilities/FileUtils.h"
class Entity;
struct LuaScriptComponent
{
LuaScriptComponent() = default;
LuaScriptComponent(const std::filesystem::path& filepath) : absoluteFilepath(filepath) { }
LuaScriptComponent(const LuaScriptComponent&) = default;
~LuaScriptComponent();
std::filesystem::path absoluteFilepath;
bool created = false;
std::optional<std::pair<int, std::string>> ParseScript(Entity entity);
void OnCreate();
void OnDestroy();
void OnUpdate(float deltaTime);
void OnFixedUpdate();
private:
friend cereal::access;
template<typename Archive>
void save(Archive& archive) const
{
std::string relativePath;
if (!absoluteFilepath.empty())
relativePath = FileUtils::RelativePath(absoluteFilepath, Application::GetOpenDocumentDirectory()).string();
archive(cereal::make_nvp("Script", relativePath));
}
template<typename Archive>
void load(Archive& archive)
{
std::string relativePath;
archive(cereal::make_nvp("Script", relativePath));
if (!relativePath.empty())
absoluteFilepath = std::filesystem::absolute(Application::GetOpenDocumentDirectory() / relativePath);
}
Ref<sol::environment> m_SolEnvironment;
Ref<sol::protected_function> m_OnCreateFunc;
Ref<sol::protected_function> m_OnDestroyFunc;
Ref<sol::protected_function> m_OnUpdateFunc;
Ref<sol::protected_function> m_OnFixedUpdateFunc;
}; | 26.245614 | 110 | 0.763369 | [
"vector"
] |
870ca5221fe91f1e8988ad09e9e12d728fed3f52 | 11,373 | c | C | src/ld65/objfile.c | mikeakohn/cc65 | ca31e3af1effb268d36235495a11c2580b938682 | [
"Zlib"
] | 6 | 2018-11-28T15:42:20.000Z | 2022-01-05T18:59:11.000Z | src/ld65/objfile.c | mikeakohn/cc65 | ca31e3af1effb268d36235495a11c2580b938682 | [
"Zlib"
] | 1 | 2018-01-06T18:19:29.000Z | 2018-01-06T18:19:29.000Z | src/ld65/objfile.c | mikeakohn/cc65 | ca31e3af1effb268d36235495a11c2580b938682 | [
"Zlib"
] | 1 | 2022-01-05T18:59:16.000Z | 2022-01-05T18:59:16.000Z | /*****************************************************************************/
/* */
/* objfile.c */
/* */
/* Object file handling for the ld65 linker */
/* */
/* */
/* */
/* (C) 1998-2012, Ullrich von Bassewitz */
/* Roemerstrasse 52 */
/* D-70794 Filderstadt */
/* EMail: uz@cc65.org */
/* */
/* */
/* This software is provided 'as-is', without any expressed or implied */
/* warranty. In no event will the authors be held liable for any damages */
/* arising from the use of this software. */
/* */
/* Permission is granted to anyone to use this software for any purpose, */
/* including commercial applications, and to alter it and redistribute it */
/* freely, subject to the following restrictions: */
/* */
/* 1. The origin of this software must not be misrepresented; you must not */
/* claim that you wrote the original software. If you use this software */
/* in a product, an acknowledgment in the product documentation would be */
/* appreciated but is not required. */
/* 2. Altered source versions must be plainly marked as such, and must not */
/* be misrepresented as being the original software. */
/* 3. This notice may not be removed or altered from any source */
/* distribution. */
/* */
/*****************************************************************************/
#include <string.h>
/* common */
#include "fname.h"
#include "xmalloc.h"
/* ld65 */
#include "asserts.h"
#include "dbgsyms.h"
#include "error.h"
#include "exports.h"
#include "fileinfo.h"
#include "fileio.h"
#include "lineinfo.h"
#include "objdata.h"
#include "objfile.h"
#include "scopes.h"
#include "segments.h"
#include "spool.h"
/*****************************************************************************/
/* Code */
/*****************************************************************************/
static unsigned GetModule (const char* Name)
/* Get a module name index from the file name */
{
/* Make a module name from the file name */
const char* Module = FindName (Name);
if (*Module == 0) {
Error ("Cannot make module name from `%s'", Name);
}
return GetStringId (Module);
}
static void ObjReadHeader (FILE* Obj, ObjHeader* H, const char* Name)
/* Read the header of the object file checking the signature */
{
H->Version = Read16 (Obj);
if (H->Version != OBJ_VERSION) {
Error ("Object file `%s' has wrong version, expected %08X, got %08X",
Name, OBJ_VERSION, H->Version);
}
H->Flags = Read16 (Obj);
H->OptionOffs = Read32 (Obj);
H->OptionSize = Read32 (Obj);
H->FileOffs = Read32 (Obj);
H->FileSize = Read32 (Obj);
H->SegOffs = Read32 (Obj);
H->SegSize = Read32 (Obj);
H->ImportOffs = Read32 (Obj);
H->ImportSize = Read32 (Obj);
H->ExportOffs = Read32 (Obj);
H->ExportSize = Read32 (Obj);
H->DbgSymOffs = Read32 (Obj);
H->DbgSymSize = Read32 (Obj);
H->LineInfoOffs = Read32 (Obj);
H->LineInfoSize = Read32 (Obj);
H->StrPoolOffs = Read32 (Obj);
H->StrPoolSize = Read32 (Obj);
H->AssertOffs = Read32 (Obj);
H->AssertSize = Read32 (Obj);
H->ScopeOffs = Read32 (Obj);
H->ScopeSize = Read32 (Obj);
H->SpanOffs = Read32 (Obj);
H->SpanSize = Read32 (Obj);
}
void ObjReadFiles (FILE* F, unsigned long Pos, ObjData* O)
/* Read the files list from a file at the given position */
{
unsigned I;
unsigned FileCount;
/* Seek to the correct position */
FileSetPos (F, Pos);
/* Read the data */
FileCount = ReadVar (F);
CollGrow (&O->Files, FileCount);
for (I = 0; I < FileCount; ++I) {
CollAppend (&O->Files, ReadFileInfo (F, O));
}
}
void ObjReadSections (FILE* F, unsigned long Pos, ObjData* O)
/* Read the section data from a file at the given position */
{
unsigned I;
unsigned SectionCount;
/* Seek to the correct position */
FileSetPos (F, Pos);
/* Read the data */
SectionCount = ReadVar (F);
CollGrow (&O->Sections, SectionCount);
for (I = 0; I < SectionCount; ++I) {
CollAppend (&O->Sections, ReadSection (F, O));
}
}
void ObjReadImports (FILE* F, unsigned long Pos, ObjData* O)
/* Read the imports from a file at the given position */
{
unsigned I;
unsigned ImportCount;
/* Seek to the correct position */
FileSetPos (F, Pos);
/* Read the data */
ImportCount = ReadVar (F);
CollGrow (&O->Imports, ImportCount);
for (I = 0; I < ImportCount; ++I) {
CollAppend (&O->Imports, ReadImport (F, O));
}
}
void ObjReadExports (FILE* F, unsigned long Pos, ObjData* O)
/* Read the exports from a file at the given position */
{
unsigned I;
unsigned ExportCount;
/* Seek to the correct position */
FileSetPos (F, Pos);
/* Read the data */
ExportCount = ReadVar (F);
CollGrow (&O->Exports, ExportCount);
for (I = 0; I < ExportCount; ++I) {
CollAppend (&O->Exports, ReadExport (F, O));
}
}
void ObjReadDbgSyms (FILE* F, unsigned long Pos, ObjData* O)
/* Read the debug symbols from a file at the given position */
{
unsigned I;
unsigned DbgSymCount;
/* Seek to the correct position */
FileSetPos (F, Pos);
/* Read the asm debug symbols */
DbgSymCount = ReadVar (F);
CollGrow (&O->DbgSyms, DbgSymCount);
for (I = 0; I < DbgSymCount; ++I) {
CollAppend (&O->DbgSyms, ReadDbgSym (F, O, I));
}
/* Read the hll debug symbols */
DbgSymCount = ReadVar (F);
CollGrow (&O->HLLDbgSyms, DbgSymCount);
for (I = 0; I < DbgSymCount; ++I) {
CollAppend (&O->HLLDbgSyms, ReadHLLDbgSym (F, O, I));
}
}
void ObjReadLineInfos (FILE* F, unsigned long Pos, ObjData* O)
/* Read the line infos from a file at the given position */
{
unsigned I;
unsigned LineInfoCount;
/* Seek to the correct position */
FileSetPos (F, Pos);
/* Read the data */
LineInfoCount = ReadVar (F);
CollGrow (&O->LineInfos, LineInfoCount);
for (I = 0; I < LineInfoCount; ++I) {
CollAppend (&O->LineInfos, ReadLineInfo (F, O));
}
}
void ObjReadStrPool (FILE* F, unsigned long Pos, ObjData* O)
/* Read the string pool from a file at the given position */
{
unsigned I;
/* Seek to the correct position */
FileSetPos (F, Pos);
/* Read the data */
O->StringCount = ReadVar (F);
O->Strings = xmalloc (O->StringCount * sizeof (O->Strings[0]));
for (I = 0; I < O->StringCount; ++I) {
O->Strings[I] = ReadStr (F);
}
}
void ObjReadAssertions (FILE* F, unsigned long Pos, ObjData* O)
/* Read the assertions from a file at the given offset */
{
unsigned I;
unsigned AssertionCount;
/* Seek to the correct position */
FileSetPos (F, Pos);
/* Read the data */
AssertionCount = ReadVar (F);
CollGrow (&O->Assertions, AssertionCount);
for (I = 0; I < AssertionCount; ++I) {
CollAppend (&O->Assertions, ReadAssertion (F, O));
}
}
void ObjReadScopes (FILE* F, unsigned long Pos, ObjData* O)
/* Read the scope table from a file at the given offset */
{
unsigned I;
unsigned ScopeCount;
/* Seek to the correct position */
FileSetPos (F, Pos);
/* Read the data */
ScopeCount = ReadVar (F);
CollGrow (&O->Scopes, ScopeCount);
for (I = 0; I < ScopeCount; ++I) {
CollAppend (&O->Scopes, ReadScope (F, O, I));
}
}
void ObjReadSpans (FILE* F, unsigned long Pos, ObjData* O)
/* Read the span table from a file at the given offset */
{
unsigned I;
unsigned SpanCount;
/* Seek to the correct position */
FileSetPos (F, Pos);
/* Read the data */
SpanCount = ReadVar (F);
CollGrow (&O->Spans, SpanCount);
for (I = 0; I < SpanCount; ++I) {
CollAppend (&O->Spans, ReadSpan (F, O, I));
}
}
void ObjAdd (FILE* Obj, const char* Name)
/* Add an object file to the module list */
{
/* Create a new structure for the object file data */
ObjData* O = NewObjData ();
/* The magic was already read and checked, so set it in the header */
O->Header.Magic = OBJ_MAGIC;
/* Read and check the header */
ObjReadHeader (Obj, &O->Header, Name);
/* Initialize the object module data structure */
O->Name = GetModule (Name);
/* Read the string pool from the object file */
ObjReadStrPool (Obj, O->Header.StrPoolOffs, O);
/* Read the files list from the object file */
ObjReadFiles (Obj, O->Header.FileOffs, O);
/* Read the line infos from the object file */
ObjReadLineInfos (Obj, O->Header.LineInfoOffs, O);
/* Read the imports list from the object file */
ObjReadImports (Obj, O->Header.ImportOffs, O);
/* Read the object file exports and insert them into the exports list */
ObjReadExports (Obj, O->Header.ExportOffs, O);
/* Read the object debug symbols from the object file */
ObjReadDbgSyms (Obj, O->Header.DbgSymOffs, O);
/* Read the assertions from the object file */
ObjReadAssertions (Obj, O->Header.AssertOffs, O);
/* Read the segment list from the object file. This must be late, since
** the expressions stored in the code may reference segments or imported
** symbols.
*/
ObjReadSections (Obj, O->Header.SegOffs, O);
/* Read the scope table from the object file. Scopes reference segments, so
** we must read them after the sections.
*/
ObjReadScopes (Obj, O->Header.ScopeOffs, O);
/* Read the spans from the object file */
ObjReadSpans (Obj, O->Header.SpanOffs, O);
/* Mark this object file as needed */
O->Flags |= OBJ_REF;
/* Done, close the file (we read it only, so no error check) */
fclose (Obj);
/* Insert the imports and exports to the global lists */
InsertObjGlobals (O);
/* Insert the object into the list of all used object files */
InsertObjData (O);
/* All references to strings are now resolved, so we can delete the module
** string pool.
*/
FreeObjStrings (O);
}
| 30.328 | 79 | 0.529324 | [
"object"
] |
872bcb440130b0e81d2cd8231d5a0b756441bd00 | 8,256 | c | C | ObitSystem/Obit/src/ObitGPUImage.c | sarrvesh/Obit | e4ce6029e9beb2a8c0316ee81ea710b66b2b7986 | [
"Linux-OpenIB"
] | 5 | 2019-08-26T06:53:08.000Z | 2020-10-20T01:08:59.000Z | ObitSystem/Obit/src/ObitGPUImage.c | sarrvesh/Obit | e4ce6029e9beb2a8c0316ee81ea710b66b2b7986 | [
"Linux-OpenIB"
] | null | null | null | ObitSystem/Obit/src/ObitGPUImage.c | sarrvesh/Obit | e4ce6029e9beb2a8c0316ee81ea710b66b2b7986 | [
"Linux-OpenIB"
] | 8 | 2017-08-29T15:12:32.000Z | 2022-03-31T12:16:08.000Z | /* $Id: $ */
/*--------------------------------------------------------------------*/
/*; Copyright (C) 2014 */
/*; Associated Universities, Inc. Washington DC, USA. */
/*; */
/*; 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., 675 Massachusetts Ave, Cambridge, */
/*; MA 02139, USA. */
/*; */
/*; Correspondence this software should be addressed as follows: */
/*; Internet email: bcotton@nrao.edu. */
/*; Postal address: William Cotton */
/*; National Radio Astronomy Observatory */
/*; 520 Edgemont Road */
/*; Charlottesville, VA 22903-2475 USA */
/*--------------------------------------------------------------------*/
#include "ObitGPUImage.h"
#include "ObitGPUFArray.h"
#include "ObitGPUFInterpolate.h"
/*-------- Obit: Merx mollis mortibus nuper ------------------*/
/**
* \file ObitGPUImage.c
*
* ObitGPUImage GPU enhanced Image utilities
*
* Image utililties using a GPU.
*
*/
/*---------------Public functions---------------------------*/
/**
* Fill the pixels in outImage by interpolation to the corresponding
* locations in inImage.
* There is no interpolation between planes
* GPU Implementation
* The GPU should be assigned and reset externally to this routine.
* \param finterp GPU Interpolator
* \param inImage Image to be interpolated
* \param outImage Image to be written. Must be previously instantiated.
* \param inPlane desired plane in inImage, 1-rel pixel numbers on planes 3-7
* \param outPlane desired plane in outImage
* \param hwidth interpolation halfwidth (1 or 2 usually OK, 4 max)
* \param err Error stack, returns if not empty.
*/
void
ObitGPUImageInterpolateImageXY (ObitGPUFInterpolate *finterp,
ObitImage *inImage, ObitImage *outImage,
olong *inPlane, olong *outPlane,
ObitErr *err)
{
ObitIOSize IOBy;
ObitImageDesc *tmpDesc=NULL;
olong iblc[IM_MAXDIM], itrc[IM_MAXDIM], oblc[IM_MAXDIM], otrc[IM_MAXDIM];
gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};
ObitInfoType type;
olong i, j;
odouble RAPnt, DecPnt;
ofloat fblank = ObitMagicF();
gchar *today=NULL;
gchar *routine = "ObitGPUImageInterpolateImageXY";
/* error checks */
g_assert (ObitErrIsA(err));
if (err->error) return;
g_assert (ObitImageIsA(inImage));
g_assert (ObitImageIsA(outImage));
g_assert (inPlane!=NULL);
g_assert (outPlane!=NULL);
for (i=0; i<IM_MAXDIM; i++) iblc[i] = 1;
for (i=0; i<IM_MAXDIM; i++) itrc[i] = 0;
for (i=0; i<IM_MAXDIM; i++) oblc[i] = 1;
for (i=0; i<IM_MAXDIM; i++) otrc[i] = 0;
/* Do I/O by plane and all of plane */
IOBy = OBIT_IO_byPlane;
dim[0] = 1;
ObitInfoListPut (inImage->info, "IOBy", OBIT_long, dim, (gpointer)&IOBy, err);
ObitInfoListPut (outImage->info, "IOBy", OBIT_long, dim, (gpointer)&IOBy, err);
/* Get any previous blc, trc */
ObitInfoListGetTest (inImage->info, "BLC", &type, dim, iblc);
ObitInfoListGetTest (inImage->info, "TRC", &type, dim, itrc);
dim[0] = 7;
for (i=0; i<5; i++) iblc[i+2] = itrc[i+2] = inPlane[i];
ObitInfoListPut (inImage->info, "BLC", OBIT_long, dim, iblc, err);
ObitInfoListPut (inImage->info, "TRC", OBIT_long, dim, itrc, err);
for (i=0; i<5; i++) oblc[i+2] = otrc[i+2] = outPlane[i];
ObitInfoListPut (outImage->info, "BLC", OBIT_long, dim, oblc, err);
ObitInfoListPut (outImage->info, "TRC", OBIT_long, dim, otrc, err);
/* Open images */
if ((ObitImageOpen (inImage, OBIT_IO_ReadOnly, err)
!= OBIT_IO_OK) || (err->error>0)) { /* error test */
Obit_log_error(err, OBIT_Error, "%s: ERROR opening image %s",
routine, inImage->name);
return;
}
if ((ObitImageOpen (outImage, OBIT_IO_ReadWrite, err)
!= OBIT_IO_OK) || (err->error>0)) { /* error test */
Obit_log_error(err, OBIT_Error, "%s: ERROR opening image %s",
routine, outImage->name);
return;
}
/* Adjust output descriptor on first plane - copy from input */
if ((outPlane[0]==1) && (outPlane[1]==1) && (outPlane[2]==1) && (outPlane[3]==1)
&& (outPlane[4]==1)) {
/* Copy of old descriptor */
tmpDesc = ObitImageDescCopy (outImage->myDesc, tmpDesc, err);
/* update Descriptive stuff from input */
ObitImageDescCopyDesc (inImage->myDesc, outImage->myDesc, err);
if (err->error) Obit_traceback_msg (err, routine, inImage->name);
/* Creation date today */
today = ObitToday();
strncpy (outImage->myDesc->date, today, IMLEN_VALUE-1);
if (today) g_free(today);
/* Precess pointing position if necessary */
if (inImage->myDesc->equinox!=tmpDesc->equinox) {
ObitImageDescGetPoint (inImage->myDesc, &RAPnt, &DecPnt);
if ((fabs(inImage->myDesc->equinox-1950.0)<0.01) &&
(fabs(tmpDesc->equinox-2000.0)<0.01))
ObitSkyGeomBtoJ (&RAPnt, &DecPnt);
else if ((fabs(inImage->myDesc->equinox-2000.0)<0.01) &&
(fabs(tmpDesc->equinox-1950.0)<0.01))
ObitSkyGeomJtoB (&RAPnt, &DecPnt);
outImage->myDesc->obsra = RAPnt;
outImage->myDesc->obsdec = DecPnt;
}
/* restore first two planes geometry */
outImage->myDesc->epoch = tmpDesc->epoch;
outImage->myDesc->equinox = tmpDesc->equinox;
for (j=0; j<2; j++) {
outImage->myDesc->inaxes[j] = tmpDesc->inaxes[j];
outImage->myDesc->cdelt[j] = tmpDesc->cdelt[j];
outImage->myDesc->crota[j] = tmpDesc->crota[j];
outImage->myDesc->crpix[j] = tmpDesc->crpix[j];
outImage->myDesc->crval[j] = tmpDesc->crval[j];
for (i=0; i<IMLEN_KEYWORD; i++) outImage->myDesc->ctype[j][i] = tmpDesc->ctype[j][i];
}
tmpDesc = ObitImageDescUnref(tmpDesc);
}
/* Read input plane */
if ((ObitImageRead (inImage,NULL , err)
!= OBIT_IO_OK) || (err->error>0)) { /* error test */
Obit_log_error(err, OBIT_Error, "%s: ERROR reading image %s",
routine, inImage->name);
return;
}
/* Convert pure zero to fblank */
ObitFArrayInClip (inImage->image, -1.0e-25, 1.0e-25, fblank);
/* Interpolate */
ObitGPUFInterpolateImage(finterp, inImage->image, outImage->image, err);
if (err->error) Obit_traceback_msg (err, routine, inImage->name);
/* Write output */
if ((ObitImageWrite (outImage, NULL, err)
!= OBIT_IO_OK) || (err->error>0)) { /* error test */
Obit_log_error(err, OBIT_Error, "%s: ERROR writing image %s",
routine, outImage->name);
return;
}
/* Close */
if ((ObitImageClose (outImage, err)
!= OBIT_IO_OK) || (err->error>0)) { /* error test */
Obit_log_error(err, OBIT_Error, "%s: ERROR closing image %s",
routine, outImage->name);
return;
}
if ((ObitImageClose (inImage, err)
!= OBIT_IO_OK) || (err->error>0)) { /* error test */
Obit_log_error(err, OBIT_Error, "%s: ERROR closing image %s",
routine, inImage->name);
return;
}
if ((ObitImageClose (outImage, err)
!= OBIT_IO_OK) || (err->error>0)) { /* error test */
Obit_log_error(err, OBIT_Error, "%s: ERROR closing image %s",
routine, outImage->name);
return;
}
} /* end ObitGPUImageInterpolateImageXY */
| 41.28 | 91 | 0.58406 | [
"geometry"
] |
872ea8ec24f1d0a82d055dce0fcb80ad62e5a9b3 | 10,996 | h | C | aws-cpp-sdk-rum/include/aws/rum/model/UpdateAppMonitorRequest.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-rum/include/aws/rum/model/UpdateAppMonitorRequest.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-rum/include/aws/rum/model/UpdateAppMonitorRequest.h | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-12-30T04:25:33.000Z | 2021-12-30T04:25:33.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/rum/CloudWatchRUM_EXPORTS.h>
#include <aws/rum/CloudWatchRUMRequest.h>
#include <aws/rum/model/AppMonitorConfiguration.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace CloudWatchRUM
{
namespace Model
{
/**
*/
class AWS_CLOUDWATCHRUM_API UpdateAppMonitorRequest : public CloudWatchRUMRequest
{
public:
UpdateAppMonitorRequest();
// Service request name is the Operation name which will send this request out,
// each operation should has unique request name, so that we can get operation's name from this request.
// Note: this is not true for response, multiple operations may have the same response name,
// so we can not get operation's name from response.
inline virtual const char* GetServiceRequestName() const override { return "UpdateAppMonitor"; }
Aws::String SerializePayload() const override;
/**
* <p>A structure that contains much of the configuration data for the app monitor.
* If you are using Amazon Cognito for authorization, you must include this
* structure in your request, and it must include the ID of the Amazon Cognito
* identity pool to use for authorization. If you don't include
* <code>AppMonitorConfiguration</code>, you must set up your own authorization
* method. For more information, see <a
* href="https://docs.aws.amazon.com/monitoring/CloudWatch-RUM-get-started-authorization.html">Authorize
* your application to send data to Amazon Web Services</a>.</p>
*/
inline const AppMonitorConfiguration& GetAppMonitorConfiguration() const{ return m_appMonitorConfiguration; }
/**
* <p>A structure that contains much of the configuration data for the app monitor.
* If you are using Amazon Cognito for authorization, you must include this
* structure in your request, and it must include the ID of the Amazon Cognito
* identity pool to use for authorization. If you don't include
* <code>AppMonitorConfiguration</code>, you must set up your own authorization
* method. For more information, see <a
* href="https://docs.aws.amazon.com/monitoring/CloudWatch-RUM-get-started-authorization.html">Authorize
* your application to send data to Amazon Web Services</a>.</p>
*/
inline bool AppMonitorConfigurationHasBeenSet() const { return m_appMonitorConfigurationHasBeenSet; }
/**
* <p>A structure that contains much of the configuration data for the app monitor.
* If you are using Amazon Cognito for authorization, you must include this
* structure in your request, and it must include the ID of the Amazon Cognito
* identity pool to use for authorization. If you don't include
* <code>AppMonitorConfiguration</code>, you must set up your own authorization
* method. For more information, see <a
* href="https://docs.aws.amazon.com/monitoring/CloudWatch-RUM-get-started-authorization.html">Authorize
* your application to send data to Amazon Web Services</a>.</p>
*/
inline void SetAppMonitorConfiguration(const AppMonitorConfiguration& value) { m_appMonitorConfigurationHasBeenSet = true; m_appMonitorConfiguration = value; }
/**
* <p>A structure that contains much of the configuration data for the app monitor.
* If you are using Amazon Cognito for authorization, you must include this
* structure in your request, and it must include the ID of the Amazon Cognito
* identity pool to use for authorization. If you don't include
* <code>AppMonitorConfiguration</code>, you must set up your own authorization
* method. For more information, see <a
* href="https://docs.aws.amazon.com/monitoring/CloudWatch-RUM-get-started-authorization.html">Authorize
* your application to send data to Amazon Web Services</a>.</p>
*/
inline void SetAppMonitorConfiguration(AppMonitorConfiguration&& value) { m_appMonitorConfigurationHasBeenSet = true; m_appMonitorConfiguration = std::move(value); }
/**
* <p>A structure that contains much of the configuration data for the app monitor.
* If you are using Amazon Cognito for authorization, you must include this
* structure in your request, and it must include the ID of the Amazon Cognito
* identity pool to use for authorization. If you don't include
* <code>AppMonitorConfiguration</code>, you must set up your own authorization
* method. For more information, see <a
* href="https://docs.aws.amazon.com/monitoring/CloudWatch-RUM-get-started-authorization.html">Authorize
* your application to send data to Amazon Web Services</a>.</p>
*/
inline UpdateAppMonitorRequest& WithAppMonitorConfiguration(const AppMonitorConfiguration& value) { SetAppMonitorConfiguration(value); return *this;}
/**
* <p>A structure that contains much of the configuration data for the app monitor.
* If you are using Amazon Cognito for authorization, you must include this
* structure in your request, and it must include the ID of the Amazon Cognito
* identity pool to use for authorization. If you don't include
* <code>AppMonitorConfiguration</code>, you must set up your own authorization
* method. For more information, see <a
* href="https://docs.aws.amazon.com/monitoring/CloudWatch-RUM-get-started-authorization.html">Authorize
* your application to send data to Amazon Web Services</a>.</p>
*/
inline UpdateAppMonitorRequest& WithAppMonitorConfiguration(AppMonitorConfiguration&& value) { SetAppMonitorConfiguration(std::move(value)); return *this;}
/**
* <p>Data collected by RUM is kept by RUM for 30 days and then deleted. This
* parameter specifies whether RUM sends a copy of this telemetry data to Amazon
* CloudWatch Logs in your account. This enables you to keep the telemetry data for
* more than 30 days, but it does incur Amazon CloudWatch Logs charges.</p>
*/
inline bool GetCwLogEnabled() const{ return m_cwLogEnabled; }
/**
* <p>Data collected by RUM is kept by RUM for 30 days and then deleted. This
* parameter specifies whether RUM sends a copy of this telemetry data to Amazon
* CloudWatch Logs in your account. This enables you to keep the telemetry data for
* more than 30 days, but it does incur Amazon CloudWatch Logs charges.</p>
*/
inline bool CwLogEnabledHasBeenSet() const { return m_cwLogEnabledHasBeenSet; }
/**
* <p>Data collected by RUM is kept by RUM for 30 days and then deleted. This
* parameter specifies whether RUM sends a copy of this telemetry data to Amazon
* CloudWatch Logs in your account. This enables you to keep the telemetry data for
* more than 30 days, but it does incur Amazon CloudWatch Logs charges.</p>
*/
inline void SetCwLogEnabled(bool value) { m_cwLogEnabledHasBeenSet = true; m_cwLogEnabled = value; }
/**
* <p>Data collected by RUM is kept by RUM for 30 days and then deleted. This
* parameter specifies whether RUM sends a copy of this telemetry data to Amazon
* CloudWatch Logs in your account. This enables you to keep the telemetry data for
* more than 30 days, but it does incur Amazon CloudWatch Logs charges.</p>
*/
inline UpdateAppMonitorRequest& WithCwLogEnabled(bool value) { SetCwLogEnabled(value); return *this;}
/**
* <p>The top-level internet domain name for which your application has
* administrative authority.</p>
*/
inline const Aws::String& GetDomain() const{ return m_domain; }
/**
* <p>The top-level internet domain name for which your application has
* administrative authority.</p>
*/
inline bool DomainHasBeenSet() const { return m_domainHasBeenSet; }
/**
* <p>The top-level internet domain name for which your application has
* administrative authority.</p>
*/
inline void SetDomain(const Aws::String& value) { m_domainHasBeenSet = true; m_domain = value; }
/**
* <p>The top-level internet domain name for which your application has
* administrative authority.</p>
*/
inline void SetDomain(Aws::String&& value) { m_domainHasBeenSet = true; m_domain = std::move(value); }
/**
* <p>The top-level internet domain name for which your application has
* administrative authority.</p>
*/
inline void SetDomain(const char* value) { m_domainHasBeenSet = true; m_domain.assign(value); }
/**
* <p>The top-level internet domain name for which your application has
* administrative authority.</p>
*/
inline UpdateAppMonitorRequest& WithDomain(const Aws::String& value) { SetDomain(value); return *this;}
/**
* <p>The top-level internet domain name for which your application has
* administrative authority.</p>
*/
inline UpdateAppMonitorRequest& WithDomain(Aws::String&& value) { SetDomain(std::move(value)); return *this;}
/**
* <p>The top-level internet domain name for which your application has
* administrative authority.</p>
*/
inline UpdateAppMonitorRequest& WithDomain(const char* value) { SetDomain(value); return *this;}
/**
* <p>The name of the app monitor to update.</p>
*/
inline const Aws::String& GetName() const{ return m_name; }
/**
* <p>The name of the app monitor to update.</p>
*/
inline bool NameHasBeenSet() const { return m_nameHasBeenSet; }
/**
* <p>The name of the app monitor to update.</p>
*/
inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; }
/**
* <p>The name of the app monitor to update.</p>
*/
inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = std::move(value); }
/**
* <p>The name of the app monitor to update.</p>
*/
inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); }
/**
* <p>The name of the app monitor to update.</p>
*/
inline UpdateAppMonitorRequest& WithName(const Aws::String& value) { SetName(value); return *this;}
/**
* <p>The name of the app monitor to update.</p>
*/
inline UpdateAppMonitorRequest& WithName(Aws::String&& value) { SetName(std::move(value)); return *this;}
/**
* <p>The name of the app monitor to update.</p>
*/
inline UpdateAppMonitorRequest& WithName(const char* value) { SetName(value); return *this;}
private:
AppMonitorConfiguration m_appMonitorConfiguration;
bool m_appMonitorConfigurationHasBeenSet;
bool m_cwLogEnabled;
bool m_cwLogEnabledHasBeenSet;
Aws::String m_domain;
bool m_domainHasBeenSet;
Aws::String m_name;
bool m_nameHasBeenSet;
};
} // namespace Model
} // namespace CloudWatchRUM
} // namespace Aws
| 44.160643 | 169 | 0.705166 | [
"model"
] |
873293170b54b73fb751316f610f301ad9ac6d9e | 1,092 | h | C | Win/Win32/include/log/stringhelper.h | Bing4Autodesk/CEF3 | 5dbe1658b34e95e6fbdc13ef1c508cca4cead3e5 | [
"MIT"
] | 3 | 2015-06-07T07:09:50.000Z | 2017-06-09T17:12:22.000Z | Win/Win32/include/log/stringhelper.h | Bing4Autodesk/CEF3 | 5dbe1658b34e95e6fbdc13ef1c508cca4cead3e5 | [
"MIT"
] | null | null | null | Win/Win32/include/log/stringhelper.h | Bing4Autodesk/CEF3 | 5dbe1658b34e95e6fbdc13ef1c508cca4cead3e5 | [
"MIT"
] | 1 | 2019-01-04T03:22:03.000Z | 2019-01-04T03:22:03.000Z | // -*- C++ -*-
// Module: Log4CPLUS
// File: stringhelper.h
/** @file */
#ifndef LOG4CPLUS_HELPERS_STRINGHELPER_HEADER_
#define LOG4CPLUS_HELPERS_STRINGHELPER_HEADER_
#include "platform.h"
#include <algorithm>
#include <vector>
#include <iterator>
namespace log4cplus {
/**
* Returns <code>s</code> in upper case.
*/
std::string toUpper(const std::string& s);
char toUpper(char);
/**
* Returns <code>s</code> in lower case.
*/
std::string toLower(const std::string& s);
char toLower(char);
typedef std::back_insert_iterator<std::vector<std::string> > OutputIter;
void tokenize(const std::string& s, char c, OutputIter result, bool collapseTokens = true);
void convertIntegerToString(std::string & str, int intValue);
std::string convertIntegerToString(int intValue);
//!Join a list of items into a string.
typedef std::vector<std::string, std::allocator<std::string> >::iterator Iterator;
void join(std::string& result, Iterator start, Iterator last, std::string const& sep);
} // namespace log4cplus
#endif // LOG4CPLUS_HELPERS_STRINGHELPER_HEADER_
| 23.234043 | 92 | 0.717033 | [
"vector"
] |
873d19cd05b1ce2fc117c2b0440f61862d0b4c33 | 4,061 | c | C | deps/mozjs/incs/nss/nss/lib/libpkix/pkix/checker/pkix_namechainingchecker.c | ktrzeciaknubisa/jxcore-binary-packaging | 5759df084be10a259a4a4f1b38c214c6084a7c0f | [
"Apache-2.0"
] | 2,494 | 2015-02-11T04:34:13.000Z | 2022-03-31T14:21:47.000Z | deps/mozjs/incs/nss/nss/lib/libpkix/pkix/checker/pkix_namechainingchecker.c | ktrzeciaknubisa/jxcore-binary-packaging | 5759df084be10a259a4a4f1b38c214c6084a7c0f | [
"Apache-2.0"
] | 685 | 2015-02-11T17:14:26.000Z | 2021-04-13T09:58:39.000Z | deps/mozjs/incs/nss/nss/lib/libpkix/pkix/checker/pkix_namechainingchecker.c | ktrzeciaknubisa/jxcore-binary-packaging | 5759df084be10a259a4a4f1b38c214c6084a7c0f | [
"Apache-2.0"
] | 442 | 2015-02-12T13:45:46.000Z | 2022-03-21T05:28:05.000Z | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
* pkix_namechainingchecker.c
*
* Functions for name chaining validation
*
*/
#include "pkix_namechainingchecker.h"
/* --Private-Functions-------------------------------------------- */
/*
* FUNCTION: pkix_NameChainingChecker_Check
* (see comments for PKIX_CertChainChecker_CheckCallback in pkix_checker.h)
*/
PKIX_Error *
pkix_NameChainingChecker_Check(
PKIX_CertChainChecker *checker,
PKIX_PL_Cert *cert,
PKIX_List *unresolvedCriticalExtensions,
void **pNBIOContext,
void *plContext)
{
PKIX_PL_X500Name *prevSubject = NULL;
PKIX_PL_X500Name *currIssuer = NULL;
PKIX_PL_X500Name *currSubject = NULL;
PKIX_Boolean result;
PKIX_ENTER(CERTCHAINCHECKER, "pkix_NameChainingChecker_Check");
PKIX_NULLCHECK_THREE(checker, cert, pNBIOContext);
*pNBIOContext = NULL; /* we never block on pending I/O */
PKIX_CHECK(PKIX_CertChainChecker_GetCertChainCheckerState
(checker, (PKIX_PL_Object **)&prevSubject, plContext),
PKIX_CERTCHAINCHECKERGETCERTCHAINCHECKERSTATEFAILED);
PKIX_CHECK(PKIX_PL_Cert_GetIssuer(cert, &currIssuer, plContext),
PKIX_CERTGETISSUERFAILED);
if (prevSubject){
PKIX_CHECK(PKIX_PL_X500Name_Match
(prevSubject, currIssuer, &result, plContext),
PKIX_X500NAMEMATCHFAILED);
if (!result){
PKIX_ERROR(PKIX_NAMECHAININGCHECKFAILED);
}
} else {
PKIX_ERROR(PKIX_NAMECHAININGCHECKFAILED);
}
PKIX_CHECK(PKIX_PL_Cert_GetSubject(cert, &currSubject, plContext),
PKIX_CERTGETSUBJECTFAILED);
PKIX_CHECK(PKIX_CertChainChecker_SetCertChainCheckerState
(checker, (PKIX_PL_Object *)currSubject, plContext),
PKIX_CERTCHAINCHECKERSETCERTCHAINCHECKERSTATEFAILED);
cleanup:
PKIX_DECREF(prevSubject);
PKIX_DECREF(currIssuer);
PKIX_DECREF(currSubject);
PKIX_RETURN(CERTCHAINCHECKER);
}
/*
* FUNCTION: pkix_NameChainingChecker_Initialize
* DESCRIPTION:
*
* Creates a new CertChainChecker and stores it at "pChecker", where it will
* be used by pkix_NameChainingChecker_Check to check that the issuer name
* of the certificate matches the subject name in the checker's state. The
* X500Name pointed to by "trustedCAName" is used to initialize the checker's
* state.
*
* PARAMETERS:
* "trustedCAName"
* Address of X500Name representing the trusted CA Name used to
* initialize the state of this checker. Must be non-NULL.
* "pChecker"
* Address where object pointer will be stored. Must be non-NULL.
* "plContext"
* Platform-specific context pointer.
* THREAD SAFETY:
* Thread Safe (see Thread Safety Definitions in Programmer's Guide)
* RETURNS:
* Returns NULL if the function succeeds.
* Returns a CertChainChecker Error if the function fails in a non-fatal way.
* Returns a Fatal Error if the function fails in an unrecoverable way.
*/
PKIX_Error *
pkix_NameChainingChecker_Initialize(
PKIX_PL_X500Name *trustedCAName,
PKIX_CertChainChecker **pChecker,
void *plContext)
{
PKIX_ENTER(CERTCHAINCHECKER, "PKIX_NameChainingChecker_Initialize");
PKIX_NULLCHECK_TWO(pChecker, trustedCAName);
PKIX_CHECK(PKIX_CertChainChecker_Create
(pkix_NameChainingChecker_Check,
PKIX_FALSE,
PKIX_FALSE,
NULL,
(PKIX_PL_Object *)trustedCAName,
pChecker,
plContext),
PKIX_CERTCHAINCHECKERCREATEFAILED);
cleanup:
PKIX_RETURN(CERTCHAINCHECKER);
}
| 33.286885 | 78 | 0.654026 | [
"object"
] |
874f88539b13f86afdebf8f436de70733d88ab97 | 2,345 | h | C | src/prod/src/Hosting2/ComGuestServiceInstance.h | AnthonyM/service-fabric | c396ea918714ea52eab9c94fd62e018cc2e09a68 | [
"MIT"
] | 1 | 2018-03-15T02:09:21.000Z | 2018-03-15T02:09:21.000Z | src/prod/src/Hosting2/ComGuestServiceInstance.h | AnthonyM/service-fabric | c396ea918714ea52eab9c94fd62e018cc2e09a68 | [
"MIT"
] | null | null | null | src/prod/src/Hosting2/ComGuestServiceInstance.h | AnthonyM/service-fabric | c396ea918714ea52eab9c94fd62e018cc2e09a68 | [
"MIT"
] | null | null | null | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#pragma once
namespace Hosting2
{
class ComGuestServiceInstance :
public IFabricStatelessServiceInstance,
protected Common::ComUnknownBase,
Common::TextTraceComponent<Common::TraceTaskCodes::Hosting>
{
DENY_COPY(ComGuestServiceInstance)
COM_INTERFACE_LIST1(
ComGuestServiceInstance,
IID_IFabricStatelessServiceInstance,
IFabricStatelessServiceInstance)
public:
ComGuestServiceInstance(
std::wstring const & serviceName,
std::wstring const & serviceTypeName,
Common::Guid const & partitionId,
FABRIC_INSTANCE_ID instanceId,
std::vector<ServiceModel::EndpointDescription> const & endpointdescriptions);
virtual ~ComGuestServiceInstance();
HRESULT STDMETHODCALLTYPE BeginOpen(
/* [in] */ IFabricStatelessServicePartition *partition,
/* [in] */ IFabricAsyncOperationCallback *callback,
/* [retval][out] */ IFabricAsyncOperationContext **context);
HRESULT STDMETHODCALLTYPE EndOpen(
/* [in] */ IFabricAsyncOperationContext *context,
/* [retval][out] */ IFabricStringResult **serviceAddress);
HRESULT STDMETHODCALLTYPE BeginClose(
/* [in] */ IFabricAsyncOperationCallback *callback,
/* [retval][out] */ IFabricAsyncOperationContext **context);
HRESULT STDMETHODCALLTYPE EndClose(
/* [in] */ IFabricAsyncOperationContext *context);
void STDMETHODCALLTYPE Abort(void);
private:
HRESULT SetupEndpointAddresses();
class EndpointsJsonWrapper;
private:
std::wstring const serviceName_;
std::wstring const serviceTypeName_;
std::wstring const traceId_;
std::wstring endpointsAsJsonStr_;
Common::Guid const partitionId_;
::FABRIC_INSTANCE_ID const instanceId_;
std::vector<ServiceModel::EndpointDescription> endpointDescriptions_;
};
}
| 36.076923 | 98 | 0.620043 | [
"vector"
] |
87546eb7f7960e33cbbf5ca998e2616f64a048be | 1,669 | h | C | core/Lava.h | Satoshi-Yoda/VulkanCore | a737fedd4c2fa996b4f9c3a7df7411dfc0100fb9 | [
"MIT"
] | null | null | null | core/Lava.h | Satoshi-Yoda/VulkanCore | a737fedd4c2fa996b4f9c3a7df7411dfc0100fb9 | [
"MIT"
] | null | null | null | core/Lava.h | Satoshi-Yoda/VulkanCore | a737fedd4c2fa996b4f9c3a7df7411dfc0100fb9 | [
"MIT"
] | null | null | null | #pragma once
#include <memory>
#include <mutex>
#include <vector>
#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
#include <vk_mem_alloc.h>
#define GLM_FORCE_RADIANS
#include <glm/glm.hpp>
#include "../batch/Batch.h"
#include "../batch/BatchLayout.h"
#include "../graphic/Graphic.h"
#include "../graphic/GraphicLayout.h"
#include "../rectangle/Rectangle.h"
#include "../rectangle/RectangleLayout.h"
#include "Crater.h"
#include "Mountain.h"
#include "Rocks.h"
using std::shared_ptr;
using std::unique_ptr;
using std::vector;
using glm::vec2;
using glm::vec3;
using glm::vec4;
using glm::mat4;
using glm::radians;
struct UniformBufferObject {
vec2 scale;
vec2 shift;
};
class Batch;
class Graphic;
class Rectangle;
// TODO now lava contains all possible drawable objects in engine. But scene contains only used ones. Maybe it can be merged to single entity.
class Lava {
public:
Lava(Ash &ash, Mountain &mountain, Rocks &rocks, Crater &crater);
~Lava();
VkBuffer uniformBuffer;
VmaAllocation uniformBuffersAllocation;
VmaAllocationInfo uniformBuffersAllocationInfo;
vector<unique_ptr<Batch>> batches;
vector<shared_ptr<Graphic>> graphics;
vector<shared_ptr<Rectangle>> rectangles;
void addBatch(unique_ptr<Batch> batch);
void addRectangle(shared_ptr<Rectangle> rectangle);
void addGraphic(shared_ptr<Graphic> graphic);
private:
Ash& ash;
Mountain& mountain;
Rocks& rocks;
Crater& crater;
public:
BatchLayout batchLayout { ash, mountain, rocks, crater };
RectangleLayout rectangleLayout { ash, mountain, rocks, crater };
GraphicLayout graphicLayout { ash, mountain, rocks, crater };
private:
void createUniformBuffers();
};
| 21.960526 | 142 | 0.753146 | [
"vector"
] |
8757e054007fa7d5d41c51013d32bac06a4e7ddc | 4,032 | h | C | include/toml++/impl/yaml_formatter.h | Tachi107/tomlplusplus | 4bd9bda09f5ad28da9c9e8dd4d64bdcc73a667e4 | [
"MIT"
] | 1 | 2021-05-23T08:33:00.000Z | 2021-05-23T08:33:00.000Z | include/toml++/impl/yaml_formatter.h | Tachi107/tomlplusplus | 4bd9bda09f5ad28da9c9e8dd4d64bdcc73a667e4 | [
"MIT"
] | null | null | null | include/toml++/impl/yaml_formatter.h | Tachi107/tomlplusplus | 4bd9bda09f5ad28da9c9e8dd4d64bdcc73a667e4 | [
"MIT"
] | null | null | null | //# This file is a part of toml++ and is subject to the the terms of the MIT license.
//# Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>
//# See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
// SPDX-License-Identifier: MIT
#pragma once
#include "preprocessor.h"
#if TOML_ENABLE_FORMATTERS
#include "formatter.h"
#include "header_start.h"
TOML_NAMESPACE_START
{
/// \brief A wrapper for printing TOML objects out to a stream as formatted YAML.
///
/// \availability This class is only available when #TOML_ENABLE_FORMATTERS is enabled.
///
/// \detail \cpp
/// auto some_toml = toml::parse(R"(
/// [fruit]
/// apple.color = "red"
/// apple.taste.sweet = true
///
/// [fruit.apple.texture]
/// smooth = true
/// )"sv);
/// std::cout << toml::yaml_formatter{ some_toml } << "\n";
/// \ecpp
///
/// \out
/// fruit:
/// apple:
/// color: red
/// taste:
/// sweet: true
/// texture:
/// smooth: true
/// \eout
class yaml_formatter : impl::formatter
{
private:
/// \cond
using base = impl::formatter;
TOML_API
void print_yaml_string(const value<std::string>&);
TOML_API
void print(const toml::table&, bool = false);
TOML_API
void print(const toml::array&, bool = false);
TOML_API
void print();
static constexpr impl::formatter_constants constants = {
//
format_flags::quote_dates_and_times | format_flags::indentation, // mandatory
format_flags::allow_multi_line_strings, // ignored
".inf"sv,
"-.inf"sv,
".NAN"sv,
"true"sv,
"false"sv
};
/// \endcond
public:
/// \brief The default flags for a yaml_formatter.
static constexpr format_flags default_flags = constants.mandatory_flags //
| format_flags::allow_literal_strings //
| format_flags::allow_unicode_strings //
| format_flags::allow_octal_integers //
| format_flags::allow_hexadecimal_integers;
/// \brief Constructs a YAML formatter and binds it to a TOML object.
///
/// \param source The source TOML object.
/// \param flags Format option flags.
TOML_NODISCARD_CTOR
explicit yaml_formatter(const toml::node& source, format_flags flags = default_flags) noexcept
: base{ &source, nullptr, constants, { flags, " "sv } }
{}
#if defined(DOXYGEN) || (TOML_ENABLE_PARSER && !TOML_EXCEPTIONS)
/// \brief Constructs a YAML formatter and binds it to a toml::parse_result.
///
/// \availability This constructor is only available when exceptions are disabled.
///
/// \attention Formatting a failed parse result will simply dump the error message out as-is.
/// This will not be valid YAML, but at least gives you something to log or show up in diagnostics:
/// \cpp
/// std::cout << toml::yaml_formatter{ toml::parse("a = 'b'"sv) } // ok
/// << "\n\n"
/// << toml::yaml_formatter{ toml::parse("a = "sv) } // malformed
/// << "\n";
/// \ecpp
/// \out
/// a: b
///
/// Error while parsing key-value pair: encountered end-of-file
/// (error occurred at line 1, column 5)
/// \eout
/// Use the library with exceptions if you want to avoid this scenario.
///
/// \param result The parse result.
/// \param flags Format option flags.
TOML_NODISCARD_CTOR
explicit yaml_formatter(const toml::parse_result& result, format_flags flags = default_flags) noexcept
: base{ nullptr, &result, constants, { flags, " "sv } }
{}
#endif
/// \brief Prints the bound TOML object out to the stream as YAML.
friend std::ostream& operator<<(std::ostream& lhs, yaml_formatter& rhs)
{
rhs.attach(lhs);
rhs.print();
rhs.detach();
return lhs;
}
/// \brief Prints the bound TOML object out to the stream as YAML (rvalue overload).
friend std::ostream& operator<<(std::ostream& lhs, yaml_formatter&& rhs)
{
return lhs << rhs; // as lvalue
}
};
}
TOML_NAMESPACE_END;
#include "header_end.h"
#endif // TOML_ENABLE_FORMATTERS
| 28.8 | 104 | 0.647569 | [
"object"
] |
875ae424bbf9854d6ad942020b84422f337e7940 | 7,720 | h | C | Project/zoolib/Pixels/BigRegion.h | zoolib/zoolib_cxx | f52d45d90fe093599def6c509d2351a0769d676e | [
"MIT"
] | 13 | 2015-01-28T21:05:09.000Z | 2021-11-03T22:21:11.000Z | Project/zoolib/Pixels/BigRegion.h | zoolib/zoolib_cxx | f52d45d90fe093599def6c509d2351a0769d676e | [
"MIT"
] | null | null | null | Project/zoolib/Pixels/BigRegion.h | zoolib/zoolib_cxx | f52d45d90fe093599def6c509d2351a0769d676e | [
"MIT"
] | 4 | 2018-11-16T08:33:33.000Z | 2021-12-11T19:40:46.000Z | // Copyright (c) 2000 Andrew Green and Learning in Motion, Inc.
// MIT License. http://www.zoolib.org
/************************************************************************
Copyright (c) 1987, 1988 X Consortium
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
X CONSORTIUM 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.
Except as contained in this notice, the name of the X Consortium shall not be
used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from the X Consortium.
Copyright 1987, 1988 by Digital Equipment Corporation, Maynard, Massachusetts.
All Rights Reserved
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name of Digital not be
used in advertising or publicity pertaining to distribution of the
software without specific, written prior permission.
DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
SOFTWARE.
************************************************************************/
#ifndef __ZooLib_Pixels_BigRegion_h__
#define __ZooLib_Pixels_BigRegion_h__ 1
#include "zconfig.h"
#include "zoolib/PairwiseCombiner_T.h"
#include "zoolib/Pixels/Geom.h"
#include <vector>
namespace ZooLib {
namespace Pixels {
// =================================================================================================
#pragma mark - BigRegion
// AG 98-08-13. BigRegion provides a region-type facility that works with 32 bit coordinates.
// The implementation is ripped from the XFree86 source.
class BigRegion
{
public:
static BigRegion sRects(const RectPOD* iRects, size_t iCount, bool iAlreadySorted);
BigRegion();
BigRegion(const BigRegion& iOther);
BigRegion(const RectPOD& iBounds);
BigRegion(const PointPOD& iSize);
~BigRegion();
BigRegion& operator=(const BigRegion& iOther);
BigRegion& operator=(const RectPOD& iBounds);
BigRegion Inset(const PointPOD& iInset) const
{ return this->Inset(iInset.h, iInset.v); }
BigRegion Inset(Ord iInsetH, Ord iInsetV) const
{
BigRegion tempRgn(*this);
tempRgn.MakeInset(iInsetH, iInsetV);
return tempRgn;
}
void MakeInset(const PointPOD& iInset)
{ this->MakeInset(iInset.h, iInset.v); }
void MakeInset(Ord iInsetH, Ord iInsetV);
bool Contains(const PointPOD& iPoint) const;
bool Contains(Ord iH, Ord iV) const;
void MakeEmpty();
bool IsEmpty() const;
RectPOD Bounds() const;
bool IsSimpleRect() const;
void Decompose(std::vector<RectPOD>& oRects) const;
typedef bool (*DecomposeProc)(const RectPOD& iRect, void* iRefcon);
Ord Decompose(DecomposeProc iProc, void* iRefcon) const;
bool operator==(const BigRegion& iOther) const;
bool operator!=(const BigRegion& iOther) const
{ return ! (*this == iOther); }
BigRegion& operator+=(const PointPOD& iOffset);
BigRegion operator+(const PointPOD& iOffset) const
{
BigRegion newRegion(*this);
return newRegion += iOffset;
}
BigRegion& operator-=(const PointPOD& iOffset)
{ return *this += sPointPOD(-iOffset.h, -iOffset.v); }
BigRegion operator-(const PointPOD& iOffset) const
{
BigRegion newRegion(*this);
return newRegion -= iOffset;
}
BigRegion& operator|=(const BigRegion& iOther);
BigRegion operator|(const BigRegion& iOther) const
{
BigRegion newRegion(*this);
return newRegion |= iOther;
}
BigRegion& operator&=(const BigRegion& iOther);
BigRegion operator&(const BigRegion& iOther) const
{
BigRegion newRegion(*this);
return newRegion &= iOther;
}
BigRegion& operator-=(const BigRegion& iOther);
BigRegion operator-(const BigRegion& iOther) const
{
BigRegion newRegion(*this);
return newRegion -= iOther;
}
BigRegion& operator^=(const BigRegion& iOther);
BigRegion operator^(const BigRegion& iOther) const
{
BigRegion newRegion(*this);
return newRegion ^= iOther;
}
static void sUnion(const BigRegion& iSource1, const BigRegion& iSource2,
BigRegion& oDestination);
static void sIntersection(const BigRegion& iSource1, const BigRegion& iSource2,
BigRegion& oDestination);
static void sDifference(const BigRegion& iSource1, const BigRegion& iSource2,
BigRegion& oDestination);
static void sExclusiveOr(const BigRegion& iSource1, const BigRegion& iSource2,
BigRegion& oDestination);
protected:
static void spSpaceCheck(BigRegion& ioRegion, RectPOD*& oRect);
static void spReallocate(BigRegion& ioRegion, RectPOD*& oRect);
static void spCopy(const BigRegion& iSource, BigRegion& oDestination);
static void spSetExtents(BigRegion& ioRegion);
static void spUnionNonOverlapping(BigRegion& ioRegion,
RectPOD* r, RectPOD* rEnd, Ord y1, Ord y2);
static void spUnionOverlapping(BigRegion& ioRegion,
RectPOD* r1, RectPOD* r1End,
RectPOD* r2, RectPOD* r2End,
Ord y1, Ord y2);
static void spIntersectionOverlapping(BigRegion& ioRegion,
RectPOD* r1, RectPOD* r1End,
RectPOD* r2, RectPOD* r2End,
Ord y1, Ord y2);
static void spDifferenceNonOverlapping(BigRegion& ioRegion,
RectPOD* r, RectPOD* rEnd,
Ord y1, Ord y2);
static void spDifferenceOverlapping(BigRegion& ioRegion,
RectPOD* r1, RectPOD* r1End,
RectPOD* r2, RectPOD* r2End,
Ord y1, Ord y2);
typedef void (*NonOverlappingFuncPtr)(BigRegion& ioRegion,
RectPOD* r, RectPOD* rEnd, Ord y1, Ord y2);
typedef void (*OverlappingFuncPtr)(BigRegion& ioRegion,
RectPOD* r1, RectPOD* r1End,
RectPOD* r2, RectPOD* r2End,
Ord y1, Ord y2);
static void spRegionOp(BigRegion& ioNewRegion,
const BigRegion& iRegion1, const BigRegion& iRegion2,
OverlappingFuncPtr iOverlapFunc,
NonOverlappingFuncPtr iNonOverlapFunc1,
NonOverlappingFuncPtr iNonOverlapFunc2);
static Ord spCoalesce(BigRegion& ioRegion, Ord prevStart, Ord curStart);
RectPOD* fRects;
size_t fNumRectsAllocated;
size_t fNumRects;
RectPOD fExtent;
};
// =================================================================================================
#pragma mark - BigRegionAccumulator
class BigRegionUnioner_t
{
public:
void operator()(BigRegion& ioRgn, const BigRegion& iOther) const
{ ioRgn |= iOther; }
};
typedef PairwiseCombiner_T<BigRegion, BigRegionUnioner_t, std::vector<BigRegion> >
BigRegionAccumulator;
} // namespace Pixels
} // namespace ZooLib
#endif // __BigRegion_h__
| 32.57384 | 100 | 0.732772 | [
"vector"
] |
8765223da96a2101d4de32c70066f911ae5f88b1 | 3,155 | h | C | internals/cpp-src/src/ReadTrimmer.h | Weeks-UNC/shapemapper2 | e51a311c5219122307e250165eea6219a6a16019 | [
"MIT"
] | 16 | 2019-06-02T20:20:14.000Z | 2022-02-14T21:02:23.000Z | internals/cpp-src/src/ReadTrimmer.h | uaauaguga/shapemapper2 | e51a311c5219122307e250165eea6219a6a16019 | [
"MIT"
] | 28 | 2018-10-18T14:59:54.000Z | 2022-02-21T14:29:30.000Z | internals/cpp-src/src/ReadTrimmer.h | uaauaguga/shapemapper2 | e51a311c5219122307e250165eea6219a6a16019 | [
"MIT"
] | 10 | 2019-01-18T00:07:06.000Z | 2022-02-23T16:34:43.000Z | /** @file
* @brief Trim FASTQ reads by windowed mean phred score. Utility functions.
*/
/*-----------------------------------------------------------------------
* This file is a part of ShapeMapper, and is licensed under the terms *
* of the MIT license. Copyright 2018 Steven Busan. *
*----------------------------------------------------------------------*/
#ifndef SHAPEMAPPER_READTRIMMER_H
#define SHAPEMAPPER_READTRIMMER_H
#include <string>
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <boost/tuple/tuple.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/newline.hpp>
#include <boost/iostreams/filter/gzip.hpp>
namespace BF = boost::filesystem;
namespace BI = boost::iostreams;
// "Utility" function implementations
namespace read_trimmer { namespace detail {
int charToPhred(char c) {
int ascii_value = (int) c;
int phred_score = ascii_value - 33;
// Do some sanity checks, and throw exception if needed.
if (phred_score < 0 or phred_score > 93) {
throw std::invalid_argument(
"Phred score of " + std::to_string(phred_score) + " for char " + std::to_string(c) +
" is out of expected range 0-93. Input quality score lines may have unprintable characters.");
}
return phred_score;
}
/**
* Return the leftmost index of the first window (scanning left-to-right) with mean
* phred score below min_phred.
* Returns -1 if all positions pass
*/
int locateLowQualityWindow(const std::string &phred_scores,
unsigned int window_size,
unsigned int min_phred) {
std::vector<unsigned int> scores(phred_scores.length());
for (int i = 0; i < phred_scores.length(); ++i) {
try {
scores[i] = charToPhred(phred_scores[i]);
} catch (std::invalid_argument) {
throw std::invalid_argument(
"ERROR: Phred score string contains whitespace or non-printable characters. Check line endings.");
}
}
int low_qual_index = -1;
for (int i = 0; i < scores.size() - window_size; i++) {
int sum = 0;
for (int j = 0; j < window_size; j++) {
sum += scores[i + j];
}
float mean = (float) sum / (float) window_size;
if (mean < min_phred) {
low_qual_index = i;
break;
}
}
return low_qual_index;
}
/**
* Count lines in file. (probably only works correctly for platform-specific line-endings.)
*/
// TODO: move to a utility namespace outside read_trimmer
// Used in tests
int
countLines(std::string filename) {
std::ifstream f(filename);
int c = 0;
std::string line;
while (std::getline(f, line)) {
c++;
}
return c;
}
}}
#endif //SHAPEMAPPER_READTRIMMER_H
| 32.864583 | 122 | 0.558796 | [
"vector"
] |
8767253147fc21ed662ec10a4a7505e45bb41291 | 6,530 | h | C | aws-cpp-sdk-medialive/include/aws/medialive/model/TimecodeConfig.h | zokir/aws-sdk-cpp | 7afa97a3961923dfe39e4d452590a8828acccf86 | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-medialive/include/aws/medialive/model/TimecodeConfig.h | zokir/aws-sdk-cpp | 7afa97a3961923dfe39e4d452590a8828acccf86 | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-medialive/include/aws/medialive/model/TimecodeConfig.h | zokir/aws-sdk-cpp | 7afa97a3961923dfe39e4d452590a8828acccf86 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/medialive/MediaLive_EXPORTS.h>
#include <aws/medialive/model/TimecodeConfigSource.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace MediaLive
{
namespace Model
{
/**
* Placeholder documentation for TimecodeConfig<p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/medialive-2017-10-14/TimecodeConfig">AWS
* API Reference</a></p>
*/
class AWS_MEDIALIVE_API TimecodeConfig
{
public:
TimecodeConfig();
TimecodeConfig(Aws::Utils::Json::JsonView jsonValue);
TimecodeConfig& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* Identifies the source for the timecode that will be associated with the events
* outputs.
-Embedded (embedded): Initialize the output timecode with timecode from
* the the source. If no embedded timecode is detected in the source, the system
* falls back to using "Start at 0" (zerobased).
-System Clock (systemclock): Use
* the UTC time.
-Start at 0 (zerobased): The time of the first frame of the event
* will be 00:00:00:00.
*/
inline const TimecodeConfigSource& GetSource() const{ return m_source; }
/**
* Identifies the source for the timecode that will be associated with the events
* outputs.
-Embedded (embedded): Initialize the output timecode with timecode from
* the the source. If no embedded timecode is detected in the source, the system
* falls back to using "Start at 0" (zerobased).
-System Clock (systemclock): Use
* the UTC time.
-Start at 0 (zerobased): The time of the first frame of the event
* will be 00:00:00:00.
*/
inline bool SourceHasBeenSet() const { return m_sourceHasBeenSet; }
/**
* Identifies the source for the timecode that will be associated with the events
* outputs.
-Embedded (embedded): Initialize the output timecode with timecode from
* the the source. If no embedded timecode is detected in the source, the system
* falls back to using "Start at 0" (zerobased).
-System Clock (systemclock): Use
* the UTC time.
-Start at 0 (zerobased): The time of the first frame of the event
* will be 00:00:00:00.
*/
inline void SetSource(const TimecodeConfigSource& value) { m_sourceHasBeenSet = true; m_source = value; }
/**
* Identifies the source for the timecode that will be associated with the events
* outputs.
-Embedded (embedded): Initialize the output timecode with timecode from
* the the source. If no embedded timecode is detected in the source, the system
* falls back to using "Start at 0" (zerobased).
-System Clock (systemclock): Use
* the UTC time.
-Start at 0 (zerobased): The time of the first frame of the event
* will be 00:00:00:00.
*/
inline void SetSource(TimecodeConfigSource&& value) { m_sourceHasBeenSet = true; m_source = std::move(value); }
/**
* Identifies the source for the timecode that will be associated with the events
* outputs.
-Embedded (embedded): Initialize the output timecode with timecode from
* the the source. If no embedded timecode is detected in the source, the system
* falls back to using "Start at 0" (zerobased).
-System Clock (systemclock): Use
* the UTC time.
-Start at 0 (zerobased): The time of the first frame of the event
* will be 00:00:00:00.
*/
inline TimecodeConfig& WithSource(const TimecodeConfigSource& value) { SetSource(value); return *this;}
/**
* Identifies the source for the timecode that will be associated with the events
* outputs.
-Embedded (embedded): Initialize the output timecode with timecode from
* the the source. If no embedded timecode is detected in the source, the system
* falls back to using "Start at 0" (zerobased).
-System Clock (systemclock): Use
* the UTC time.
-Start at 0 (zerobased): The time of the first frame of the event
* will be 00:00:00:00.
*/
inline TimecodeConfig& WithSource(TimecodeConfigSource&& value) { SetSource(std::move(value)); return *this;}
/**
* Threshold in frames beyond which output timecode is resynchronized to the input
* timecode. Discrepancies below this threshold are permitted to avoid unnecessary
* discontinuities in the output timecode. No timecode sync when this is not
* specified.
*/
inline int GetSyncThreshold() const{ return m_syncThreshold; }
/**
* Threshold in frames beyond which output timecode is resynchronized to the input
* timecode. Discrepancies below this threshold are permitted to avoid unnecessary
* discontinuities in the output timecode. No timecode sync when this is not
* specified.
*/
inline bool SyncThresholdHasBeenSet() const { return m_syncThresholdHasBeenSet; }
/**
* Threshold in frames beyond which output timecode is resynchronized to the input
* timecode. Discrepancies below this threshold are permitted to avoid unnecessary
* discontinuities in the output timecode. No timecode sync when this is not
* specified.
*/
inline void SetSyncThreshold(int value) { m_syncThresholdHasBeenSet = true; m_syncThreshold = value; }
/**
* Threshold in frames beyond which output timecode is resynchronized to the input
* timecode. Discrepancies below this threshold are permitted to avoid unnecessary
* discontinuities in the output timecode. No timecode sync when this is not
* specified.
*/
inline TimecodeConfig& WithSyncThreshold(int value) { SetSyncThreshold(value); return *this;}
private:
TimecodeConfigSource m_source;
bool m_sourceHasBeenSet;
int m_syncThreshold;
bool m_syncThresholdHasBeenSet;
};
} // namespace Model
} // namespace MediaLive
} // namespace Aws
| 37.745665 | 115 | 0.71026 | [
"model"
] |
876a68e9dd0778dd5c2b7ef68e68225231de7ce1 | 1,708 | h | C | IA20-CommonLib/src/ia20/commonlib/logger/StackTrace.h | InvenireAude/IA20-BuilderTools | 7ef0116bd2d1db83e3d3583c9059d5b2ee5462d6 | [
"Apache-2.0"
] | null | null | null | IA20-CommonLib/src/ia20/commonlib/logger/StackTrace.h | InvenireAude/IA20-BuilderTools | 7ef0116bd2d1db83e3d3583c9059d5b2ee5462d6 | [
"Apache-2.0"
] | null | null | null | IA20-CommonLib/src/ia20/commonlib/logger/StackTrace.h | InvenireAude/IA20-BuilderTools | 7ef0116bd2d1db83e3d3583c9059d5b2ee5462d6 | [
"Apache-2.0"
] | null | null | null | /*
* File: IA20-CommonLib/src/commonlib/logger/StackTrace.h
*
* Copyright (C) 2021, Albert Krzymowski
*
* 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.
*/
/* IA20_COPYRIGHT */
/* ChangeLog:
*
*/
#ifndef _IA20_StackTrace_H_
#define _IA20_StackTrace_H_
#include "../types.h"
#include "../config.h"
#include <vector>
#include <iostream>
#include "../threads/Mutex.h"
namespace IA20{
/*************************************************************************/
/** The StackTrace class.
*/
class StackTrace {
public:
class Entry{
public:
Entry(const char *sFun,
const char *sFile,
int iLine);
Entry(const Entry& e);
const char *sFun;
const char *sFile;
int iLine;
};
size_t getSize()const;
bool empty() const;
const Entry &top() const;
void addEntry(const char *sFun,
const char *sFile,
int iLine);
void removeEntry();
void printStack(std::ostream& os);
StackTrace() throw();
virtual ~StackTrace() throw();
protected:
typedef std::vector<Entry> TStackEntries;
TStackEntries lstStackTrace;
Mutex theLock;
};
#ifdef __GLIBC__
void PrintTrace(std::ostream& os);
#endif
}
#endif /*STACKTRACE_H_*/
| 18.365591 | 75 | 0.654567 | [
"vector"
] |
8772b1dba5722d6a07b0caad237743f23e2fb791 | 1,178 | h | C | VS/Graphics/VS_ShaderRef.h | vectorstorm/vectorstorm | 7306214108b23fa97d4a1a598197bbaa52c17d3a | [
"Zlib"
] | 19 | 2017-04-03T09:06:21.000Z | 2022-03-05T19:06:07.000Z | VS/Graphics/VS_ShaderRef.h | vectorstorm/vectorstorm | 7306214108b23fa97d4a1a598197bbaa52c17d3a | [
"Zlib"
] | 2 | 2019-05-24T14:40:07.000Z | 2020-04-15T01:10:23.000Z | VS/Graphics/VS_ShaderRef.h | vectorstorm/vectorstorm | 7306214108b23fa97d4a1a598197bbaa52c17d3a | [
"Zlib"
] | 2 | 2020-03-08T07:14:49.000Z | 2020-03-09T10:39:52.000Z | /*
* VS_ShaderRef.h
* VectorStorm
*
* Created by Trevor Powell on 11/11/2019
* Copyright 2019 Trevor Powell. All rights reserved.
*
*/
#ifndef VS_SHADERREF_H
#define VS_SHADERREF_H
#include "VS_Shader.h"
// #include "VS/Utils/VS_Cache.h"
// [NOTE] TO SELF:
//
// I wanted to hook shaders into the vsCache system, but it turns out that the
// vsCache setup doesn't work with shaders, where I need to map *multiple*
// strings and other settings to an object; vsCache is pretty strongly
// opinionated about mapping just a single string to a single object.
//
// So in retrospect, no, I'm not going to be able to just wrap vsShader
// in the vsCache system and call it a day; I'm going to need to architect
// something similar but custom for this particular system. And that's what
// the vsShaderRef is for; it's an object that can hold a vsShader pointer
// and lets the owner destroy it, without destroying the shared shader object.
//
// [TODO]: Needs reference counting on the vsShader object.
class vsShaderRef
{
vsShader *m_shader;
public:
vsShaderRef( vsShader *shader );
vsShader* GetShader() { return m_shader; }
};
#endif // VS_SHADERREF_H
| 27.395349 | 78 | 0.728353 | [
"object"
] |
8777eccddcc5adc87db7784f6718ccf2c8852fc5 | 1,849 | h | C | grasp_generation/graspitmodified_lm/Coin-3.1.3/include/Inventor/lists/SoCallbackList.h | KraftOreo/EBM_Hand | 9ab1722c196b7eb99b4c3ecc85cef6e8b1887053 | [
"MIT"
] | null | null | null | grasp_generation/graspitmodified_lm/Coin-3.1.3/include/Inventor/lists/SoCallbackList.h | KraftOreo/EBM_Hand | 9ab1722c196b7eb99b4c3ecc85cef6e8b1887053 | [
"MIT"
] | null | null | null | grasp_generation/graspitmodified_lm/Coin-3.1.3/include/Inventor/lists/SoCallbackList.h | KraftOreo/EBM_Hand | 9ab1722c196b7eb99b4c3ecc85cef6e8b1887053 | [
"MIT"
] | null | null | null | #ifndef COIN_LISTS_SOCALLBACKLIST_H
#define COIN_LISTS_SOCALLBACKLIST_H
/**************************************************************************\
*
* This file is part of the Coin 3D visualization library.
* Copyright (C) by Kongsberg Oil & Gas Technologies.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* ("GPL") version 2 as published by the Free Software Foundation.
* See the file LICENSE.GPL at the root directory of this source
* distribution for additional information about the GNU GPL.
*
* For using Coin with software that can not be combined with the GNU
* GPL, and for taking advantage of the additional benefits of our
* support services, please contact Kongsberg Oil & Gas Technologies
* about acquiring a Coin Professional Edition License.
*
* See http://www.coin3d.org/ for more information.
*
* Kongsberg Oil & Gas Technologies, Bygdoy Alle 5, 0257 Oslo, NORWAY.
* http://www.sim.no/ sales@sim.no coin-support@coin3d.org
*
\**************************************************************************/
// NB: make sure the ifdef-test above wrapping this includefile is
// _not_ checking on and setting the same define-string as the other
// SoCallbackList.h file in misc/.
#include <Inventor/lists/SbPList.h>
typedef void SoCallbackListCB(void * userdata, void * callbackdata);
class COIN_DLL_API SoCallbackList {
public:
SoCallbackList(void);
~SoCallbackList();
void addCallback(SoCallbackListCB * f, void * userData = NULL);
void removeCallback(SoCallbackListCB * f, void * userdata = NULL);
void clearCallbacks(void);
int getNumCallbacks(void) const;
void invokeCallbacks(void * callbackdata);
private:
SbPList funclist;
SbPList datalist;
};
#endif // !COIN_LISTS_SOCALLBACKLIST_H
| 34.240741 | 76 | 0.686858 | [
"3d"
] |
eea1b179c79e1eb48892fcf40202458c591d7469 | 2,564 | h | C | src/include/wrap/argv.h | on-keyday/utils | 5364370eadfe909407ffded678bebfdd2b0f3995 | [
"MIT"
] | null | null | null | src/include/wrap/argv.h | on-keyday/utils | 5364370eadfe909407ffded678bebfdd2b0f3995 | [
"MIT"
] | null | null | null | src/include/wrap/argv.h | on-keyday/utils | 5364370eadfe909407ffded678bebfdd2b0f3995 | [
"MIT"
] | null | null | null | /*
utils - utility library
Copyright (c) 2021-2022 on-keyday (https://github.com/on-keyday)
Released under the MIT license
https://opensource.org/licenses/mit-license.php
*/
// argv - wrap argv to utf8
// need to link libutils
#pragma once
#include "../platform/windows/dllexport_header.h"
#include "../utf/convert.h"
#include "light/string.h"
#include "light/vector.h"
namespace utils {
namespace wrap {
template <class Char = char, class String = wrap::string, template <class...> class Vector = wrap::vector>
struct ArgvVector {
Vector<Char*> argv_;
Vector<String> holder_;
template <class T>
bool translate(T&& t) {
for (auto&& v : t) {
if (!push_back(v)) {
return false;
}
}
return true;
}
template <class Begin, class End>
bool translate(Begin begin, End end) {
for (auto i = begin; i != end; i++) {
if (!push_back(*i)) {
return false;
}
}
return true;
}
template <class V>
bool push_back(V&& v) {
String result;
if (!utf::convert(v, result)) {
return false;
}
holder_.push_back(std::move(result));
return true;
}
void clear() {
argv_.clear();
holder_.clear();
}
template <class Int = int>
void arg(Int& argc, Char**& argv) {
argv_.clear();
for (size_t i = 0; i < holder_.size(); i++) {
argv_.push_back(const_cast<Char*>(holder_[i].c_str()));
}
argv_.push_back(nullptr);
argv = argv_.data();
argc = static_cast<Int>(holder_.size());
}
};
struct DLL U8Arg {
#ifdef _WIN32
private:
ArgvVector<> replaced;
int* argcplace = nullptr;
char*** argvplace = nullptr;
int argcvalue = 0;
char** argvvalue = nullptr;
public:
explicit U8Arg(int& argc, char**& argv);
~U8Arg();
#else
explicit constexpr U8Arg(int&, char**&) {}
constexpr ~U8Arg() {}
#endif
};
} // namespace wrap
} // namespace utils
| 27.869565 | 114 | 0.453588 | [
"vector"
] |
eea3cedd783f7ae06cf7982038fd4fcabc9248eb | 12,326 | h | C | src/QMCTools/ppconvert/src/common/Blitz.h | bwvdg/qmcpack | cd09fc54b36de2579c9802f5e64b7ec15506f3c3 | [
"NCSA"
] | null | null | null | src/QMCTools/ppconvert/src/common/Blitz.h | bwvdg/qmcpack | cd09fc54b36de2579c9802f5e64b7ec15506f3c3 | [
"NCSA"
] | 1 | 2020-04-10T15:33:28.000Z | 2020-04-10T15:35:59.000Z | src/QMCTools/ppconvert/src/common/Blitz.h | bwvdg/qmcpack | cd09fc54b36de2579c9802f5e64b7ec15506f3c3 | [
"NCSA"
] | 1 | 2019-07-23T17:44:39.000Z | 2019-07-23T17:44:39.000Z | //////////////////////////////////////////////////////////////////////////////////////
// This file is distributed under the University of Illinois/NCSA Open Source License.
// See LICENSE file in top directory for details.
//
// Copyright (c) 2016 Jeongnim Kim and QMCPACK developers.
//
// File developed by: Paul R. C. Kent, kentpr@ornl.gov, Oak Ridge National Laboratory
// Mark A. Berrill, berrillma@ornl.gov, Oak Ridge National Laboratory
//
// File created by: Paul R. C. Kent, kentpr@ornl.gov, Oak Ridge National Laboratory
//////////////////////////////////////////////////////////////////////////////////////
#ifndef MYBLITZ_H
#define MYBLITZ_H
#include <complex>
#include <string.h>
#include "blitz/array.h"
#include "blitz/tinyvec-et.h"
using namespace blitz;
typedef double scalar;
// #define NDIM 3
using namespace blitz;
typedef TinyVector<scalar,1> Vec1;
typedef TinyVector<scalar,2> Vec2;
typedef TinyVector<scalar,3> Vec3;
typedef TinyVector<scalar,4> Vec4;
typedef TinyMatrix<scalar,2,2> Mat2;
typedef TinyMatrix<scalar,3,3> Mat3;
typedef TinyVector<std::complex<double>,3> cVec3;
typedef TinyMatrix<std::complex<double>,3,3> cMat3;
//typedef TinyVector<scalar,NDIM> dVec;
//typedef TinyVector<int,NDIM> dVecInt;
/* #ifdef MAC */
/* // extern "C" double isnan (double x); */
/* #define isnan(x) __isnand(x) */
/* #define fpclassify(x) __fpclassifyd(x) */
/* #define isnormal(x) __isnormald(x) */
/* #define isinf(x) __isinfd(x) */
/* #endif */
// using blitz::Array;
template <class T, int size>
inline TinyVector<T,size> operator-(TinyVector<T,size> v)
{
TinyVector<T,size> minusv;
for (int i=0; i<size; i++)
minusv[i] = -v[i];
return (minusv);
}
// template <class T, int size>
// inline bool operator==(TinyVector<T,size> v1,TinyVector<T,size> v2)
// {
// bool equals=true;
// for (int i=0; i<size; i++)
// equals = (v1[i]==v2[i]) && equals;
// return (equals);
// }
inline Vec2 operator*(const Vec2 &v, scalar s)
{
Vec2 result;
result[0] = s*v[0];
result[1] = s*v[1];
return (result);
}
inline Vec2 operator*(scalar s, const Vec2 &v)
{
return (v * s);
}
inline Vec2 operator+(const Vec2 &v1, const Vec2 &v2)
{
Vec2 result;
result[0] = v1[0]+v2[0];
result[1] = v1[1]+v2[1];
return (result);
}
inline Vec2 operator-(const Vec2 &v1, const Vec2 &v2)
{
Vec2 result;
result[0] = v1[0]-v2[0];
result[1] = v1[1]-v2[1];
return (result);
}
inline Vec3 operator*(scalar s, const Vec3 &v)
{
Vec3 result;
result[0] = s*v[0];
result[1] = s*v[1];
result[2] = s*v[2];
return (result);
}
inline Vec3 operator*(const Vec3 &v, scalar s)
{
Vec3 result;
result[0] = s*v[0];
result[1] = s*v[1];
result[2] = s*v[2];
return (result);
}
inline Vec3 operator+(const Vec3 &v1, const Vec3 &v2)
{
Vec3 result;
result[0] = v1[0]+v2[0];
result[1] = v1[1]+v2[1];
result[2] = v1[2]+v2[2];
return (result);
}
inline Vec3 operator-(const Vec3 &v1, const Vec3 &v2)
{
Vec3 result;
result[0] = v1[0]-v2[0];
result[1] = v1[1]-v2[1];
result[2] = v1[2]-v2[2];
return (result);
}
inline Vec4 operator*(scalar s, const Vec4 &v)
{
Vec4 result;
result[0] = s*v[0];
result[1] = s*v[1];
result[2] = s*v[2];
result[3] = s*v[3];
return (result);
}
inline Vec4 operator*(const Vec4 &v, scalar s)
{
Vec4 result;
result[0] = s*v[0];
result[1] = s*v[1];
result[2] = s*v[2];
result[3] = s*v[3];
return (result);
}
inline Vec4 operator+(const Vec4 &v1, const Vec4 &v2)
{
Vec4 result;
result[0] = v1[0]+v2[0];
result[1] = v1[1]+v2[1];
result[2] = v1[2]+v2[2];
result[3] = v1[3]+v2[3];
return (result);
}
inline Vec4 operator-(const Vec4 &v1, const Vec4 &v2)
{
Vec4 result;
result[0] = v1[0]-v2[0];
result[1] = v1[1]-v2[1];
result[2] = v1[2]-v2[2];
result[3] = v1[3]-v2[3];
return (result);
}
inline Mat3 operator*(scalar s, const Mat3 &M)
{
Mat3 sM;
sM(0,0)=s*M(0,0); sM(0,1)=s*M(0,1); sM(0,2)=s*M(0,2);
sM(1,0)=s*M(1,0); sM(1,1)=s*M(1,1); sM(1,2)=s*M(1,2);
sM(2,0)=s*M(2,0); sM(2,1)=s*M(2,1); sM(2,2)=s*M(2,2);
return (sM);
}
inline Mat3 operator*(const Mat3 &A, const Mat3 &B)
{
Mat3 C;
C(0,0) = A(0,0)*B(0,0)+A(0,1)*B(1,0)+A(0,2)*B(2,0);
C(0,1) = A(0,0)*B(0,1)+A(0,1)*B(1,1)+A(0,2)*B(2,1);
C(0,2) = A(0,0)*B(0,2)+A(0,1)*B(1,2)+A(0,2)*B(2,2);
C(1,0) = A(1,0)*B(0,0)+A(1,1)*B(1,0)+A(1,2)*B(2,0);
C(1,1) = A(1,0)*B(0,1)+A(1,1)*B(1,1)+A(1,2)*B(2,1);
C(1,2) = A(1,0)*B(0,2)+A(1,1)*B(1,2)+A(1,2)*B(2,2);
C(2,0) = A(2,0)*B(0,0)+A(2,1)*B(1,0)+A(2,2)*B(2,0);
C(2,1) = A(2,0)*B(0,1)+A(2,1)*B(1,1)+A(2,2)*B(2,1);
C(2,2) = A(2,0)*B(0,2)+A(2,1)*B(1,2)+A(2,2)*B(2,2);
return C;
}
inline Mat3 operator+(const Mat3 &A, const Mat3 &B)
{
Mat3 ApB;
for (int i=0; i<3; i++)
for (int j=0; j<3; j++)
ApB(i,j) = A(i,j) + B(i,j);
return (ApB);
}
inline Mat3 operator-(const Mat3 &A, const Mat3 &B)
{
Mat3 AmB;
for (int i=0; i<3; i++)
for (int j=0; j<3; j++)
AmB(i,j) = A(i,j) - B(i,j);
return (AmB);
}
inline Vec3 operator*(const Mat3& A, const Vec3 &v)
{
Vec3 Av;
Av[0] = A(0,0)*v[0] + A(0,1)*v[1] + A(0,2)*v[2];
Av[1] = A(1,0)*v[0] + A(1,1)*v[1] + A(1,2)*v[2];
Av[2] = A(2,0)*v[0] + A(2,1)*v[1] + A(2,2)*v[2];
return Av;
}
inline Vec3 operator*(const Vec3 &v, const Mat3 &A)
{
Vec3 vA;
vA[0] = A(0,0)*v[0] + A(1,0)*v[1] + A(2,0)*v[2];
vA[1] = A(0,1)*v[0] + A(1,1)*v[1] + A(2,1)*v[2];
vA[2] = A(0,2)*v[0] + A(1,2)*v[1] + A(2,2)*v[2];
return vA;
}
inline cMat3 operator+(const cMat3 &A, const cMat3 &B)
{
cMat3 ApB;
ApB(0,0)=A(0,0)+B(0,0); ApB(0,1)=A(0,1)+B(0,1); ApB(0,2)=A(0,2)+B(0,2);
ApB(1,0)=A(1,0)+B(1,0); ApB(1,1)=A(1,1)+B(1,1); ApB(1,2)=A(1,2)+B(1,2);
ApB(2,0)=A(2,0)+B(2,0); ApB(2,1)=A(2,1)+B(2,1); ApB(2,2)=A(2,2)+B(2,2);
return ApB;
}
inline cMat3 operator-(const cMat3 &A, const cMat3 &B)
{
cMat3 AmB;
AmB(0,0)=A(0,0)-B(0,0); AmB(0,1)=A(0,1)-B(0,1); AmB(0,2)=A(0,2)-B(0,2);
AmB(1,0)=A(1,0)-B(1,0); AmB(1,1)=A(1,1)-B(1,1); AmB(1,2)=A(1,2)-B(1,2);
AmB(2,0)=A(2,0)-B(2,0); AmB(2,1)=A(2,1)-B(2,1); AmB(2,2)=A(2,2)-B(2,2);
return AmB;
}
inline cMat3& operator+=(cMat3 &A, const cMat3 &B)
{
A(0,0)+=B(0,0); A(0,1)+=B(0,1); A(0,2)+=B(0,2);
A(1,0)+=B(1,0); A(1,1)+=B(1,1); A(1,2)+=B(1,2);
A(2,0)+=B(2,0); A(2,1)+=B(2,1); A(2,2)+=B(2,2);
return A;
}
inline cMat3& operator-=(cMat3 &A, const cMat3 &B)
{
A(0,0)-=B(0,0); A(0,1)-=B(0,1); A(0,2)-=B(0,2);
A(1,0)-=B(1,0); A(1,1)-=B(1,1); A(1,2)-=B(1,2);
A(2,0)-=B(2,0); A(2,1)-=B(2,1); A(2,2)-=B(2,2);
return A;
}
inline double operator*(const Vec3 &v1, const Vec3 &v2)
{
return (v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2]);
}
inline cMat3 operator*(std::complex<double> z, const Mat3 &A)
{
cMat3 zA;
zA(0,0)=z*A(0,0); zA(0,1)=z*A(0,1); zA(0,2)=z*A(0,2);
zA(1,0)=z*A(1,0); zA(1,1)=z*A(1,1); zA(1,2)=z*A(1,2);
zA(2,0)=z*A(2,0); zA(2,1)=z*A(2,1); zA(2,2)=z*A(2,2);
return zA;
}
inline cMat3 operator*(const Mat3 &A, std::complex<double> z)
{
return z*A;
}
inline cVec3 operator*(const cMat3 &A, const cVec3 &x)
{
cVec3 Ax;
Ax[0] = A(0,0)*x[0] + A(0,1)*x[1] + A(0,2)*x[2];
Ax[1] = A(1,0)*x[0] + A(1,1)*x[1] + A(1,2)*x[2];
Ax[2] = A(2,0)*x[0] + A(2,1)*x[1] + A(2,2)*x[2];
return Ax;
}
inline double distSqrd(Vec2 a,Vec2 b)
{
return dot(a-b,a-b);
}
inline double distSqrd(Vec3 a,Vec3 b)
{
return dot(a-b,a-b);
}
template<class T> class SymmArray
{
private:
blitz::Array<T,1> A;
int N;
inline int index(int row, int col) const
{ return ((row > col) ? ((row*(row+1)>>1)+col) : ((col*(col+1)>>1)+row)); }
public:
inline void resize(int n)
{
N = (n*(n+1))>>1;
A.resize(N);
}
inline int rows() const
{ return N; }
inline T operator()(int i, int j) const
{ return (A(index(i,j))); }
inline T& operator()(int i, int j)
{ return (A(index(i,j))); }
inline SymmArray<T> (const SymmArray<T> &B)
{
resize(B.N);
A=B.A;
}
inline SymmArray<T>& operator=(const SymmArray<T>& B)
{
A=B.A;
return *this;
}
inline SymmArray<T>()
{ N=0; }
};
inline
void Vec2Array (blitz::Array<Vec2,1> &vec, blitz::Array<double,1> &array)
{
assert (array.extent(0) == (2*vec.size()));
memcpy(array.data(), vec.data(),
array.size()*sizeof(double));
}
inline
void Vec2Array (blitz::Array<Vec3,1> &vec, blitz::Array<double,1> &array)
{
assert (array.extent(0) == (3*vec.size()));
for (int i=0; i<vec.size(); i++) {
array(3*i+0) = vec(i)[0];
array(3*i+1) = vec(i)[1];
array(3*i+2) = vec(i)[2];
}
// memcpy(array.data(), vec.data(),
// array.size()*sizeof(double));
}
inline
void Array2Vec (blitz::Array<double,1> &array, blitz::Array<Vec2,1> &vec)
{
assert (array.extent(0) == (2*vec.size()));
memcpy (vec.data(), array.data(),
array.size()*sizeof(double));
}
inline
void Array2Vec (blitz::Array<double,1> &array, blitz::Array<Vec3,1> &vec)
{
assert (array.extent(0) == (3*vec.size()));
memcpy (vec.data(), array.data(),
array.size()*sizeof(double));
}
inline
void Vec2Array (blitz::Array<Vec2,1> &vec, blitz::Array<double,2> &array)
{
assert (array.extent(0) == vec.size());
assert (array.extent(1) == 2);
memcpy(array.data(), vec.data(),
array.size()*sizeof(double));
}
inline
void Vec2Array (blitz::Array<Vec3,1> &vec, blitz::Array<double,2> &array)
{
assert (array.extent(0) == vec.size());
assert (array.extent(1) == 3);
for (int i=0; i<vec.size(); i++) {
array(i,0) = vec(i)[0];
array(i,1) = vec(i)[1];
array(i,2) = vec(i)[2];
}
// memcpy(array.data(), vec.data(),
// array.size()*sizeof(double));
}
inline
void Array2Vec (blitz::Array<double,2> &array, blitz::Array<Vec2,1> &vec)
{
assert (array.extent(0) == vec.size());
assert (array.extent(1) == 2);
memcpy (vec.data(), array.data(),
array.size()*sizeof(double));
}
inline
void Array2Vec (blitz::Array<double,2> &array, blitz::Array<Vec3,1> &vec)
{
assert (array.extent(0) == vec.size());
assert (array.extent(1) == 3);
memcpy(vec.data(), array.data(),
array.size()*sizeof(double));
}
inline blitz::Array<Vec3,1> operator+(const blitz::Array<Vec3,1> &array, Vec3 vec)
{
blitz::Array<Vec3,1> result(array.size());
for (int i=0; i<array.size(); i++)
result(i) = vec + array(i);
return result;
}
inline blitz::Array<Vec3,1> operator+(Vec3 vec, const blitz::Array<Vec3,1> &array)
{
blitz::Array<Vec3,1> result(array.size());
for (int i=0; i<array.size(); i++)
result(i) = vec + array(i);
return result;
}
template<typename T, int N>
inline bool operator==(const TinyVector<T,N> &a,
const TinyVector<T,N> &b)
{
bool equals = true;
for (int i=0; i<N; i++)
equals = equals && (a[i] == b[i]);
return equals;
}
template<typename T, int N>
inline bool operator!=(const TinyVector<T,N> &a,
const TinyVector<T,N> &b)
{
return !(a == b);
}
template<typename T1,typename T2>
inline void copy(const blitz::Array<T1,3> &src,
blitz::Array<T2,3> &dest)
{
assert (src.shape() == dest.shape());
for (int ix=0; ix<src.extent(0); ix++)
for (int iy=0; iy<src.extent(1); iy++)
for (int iz=0; iz<src.extent(2); iz++)
dest(ix,iy,iz) = src(ix,iy,iz);
}
inline std::complex<float> operator+(std::complex<float> z, double r)
{
return std::complex<float>(z.real()+r, z.imag());
}
inline double det(const Mat3 &A)
{
return (A(0,0)*(A(1,1)*A(2,2)-A(1,2)*A(2,1)) -
A(0,1)*(A(1,0)*A(2,2)-A(1,2)*A(2,0)) +
A(0,2)*(A(1,0)*A(2,1)-A(1,1)*A(2,0)));
}
inline Mat3 Inverse (const Mat3 &A)
{
Mat3 Ainv;
double dinv = 1.0/det (A);
Ainv(0,0) = dinv*(A(1,1)*A(2,2)-A(1,2)*A(2,1));
Ainv(1,0) = -dinv*(A(1,0)*A(2,2)-A(1,2)*A(2,0));
Ainv(2,0) = dinv*(A(1,0)*A(2,1)-A(1,1)*A(2,0));
Ainv(0,1) = -dinv*(A(0,1)*A(2,2)-A(0,2)*A(2,1));
Ainv(1,1) = dinv*(A(0,0)*A(2,2)-A(0,2)*A(2,0));
Ainv(2,1) = -dinv*(A(0,0)*A(2,1)-A(0,1)*A(2,0));
Ainv(0,2) = dinv*(A(0,1)*A(1,2)-A(0,2)*A(1,1));
Ainv(1,2) = -dinv*(A(0,0)*A(1,2)-A(0,2)*A(1,0));
Ainv(2,2) = dinv*(A(0,0)*A(1,1)-A(0,1)*A(1,0));
return Ainv;
}
inline Mat3
Transpose (const Mat3 &A)
{
Mat3 Atran;
Atran(0,0)=A(0,0); Atran(0,1)=A(1,0); Atran(0,2)=A(2,0);
Atran(1,0)=A(0,1); Atran(1,1)=A(1,1); Atran(1,2)=A(2,1);
Atran(2,0)=A(0,2); Atran(2,1)=A(1,2); Atran(2,2)=A(2,2);
return Atran;
}
#ifndef NAN
#define NAN sqrt(-1.0)
#endif
#endif
| 23.300567 | 88 | 0.556709 | [
"shape"
] |
eea525ef2d9183aa7a4eb717389e6ec11d51e52d | 1,821 | c | C | gempak/source/programs/util/maps/shp/shpwfld.c | oxelson/gempak | e7c477814d7084c87d3313c94e192d13d8341fa1 | [
"BSD-3-Clause"
] | 42 | 2015-06-03T15:26:21.000Z | 2022-02-28T22:36:03.000Z | gempak/source/programs/util/maps/shp/shpwfld.c | oxelson/gempak | e7c477814d7084c87d3313c94e192d13d8341fa1 | [
"BSD-3-Clause"
] | 60 | 2015-05-11T21:36:08.000Z | 2022-03-29T16:22:42.000Z | gempak/source/programs/util/maps/shp/shpwfld.c | oxelson/gempak | e7c477814d7084c87d3313c94e192d13d8341fa1 | [
"BSD-3-Clause"
] | 27 | 2016-06-06T21:55:14.000Z | 2022-03-18T18:23:28.000Z | #include "geminc.h"
#include "gemprm.h"
#include "shpprm.h"
void shp_wfld ( FILE *fp, shp_record *onerec, int *iret )
/************************************************************************
* shp_wfld *
* *
* This function writes one shape record's fields. *
* *
* shp_wfld ( fp, onerec, iret ) *
* *
* Input parameters: *
* *fp FILE Output file pointer *
* *onerec shp_record One shape record *
* *
* Output parameters: *
* *iret int Return code *
* 0 = Normal *
* -1 = Error *
** *
* Log: *
* R. Tian/SAIC 3/04 Initial coding *
***********************************************************************/
{
int ifld;
/*---------------------------------------------------------------------*/
*iret = 0;
for ( ifld = 0; ifld < onerec->numfld; ifld++ ) {
fprintf ( fp, "Field %s: %s\n", onerec->fields[ifld].name,
onerec->fields[ifld].data );
}
}
| 52.028571 | 73 | 0.213619 | [
"shape"
] |
eeab98d15596c4d880db96692cfc23b3451ceb2d | 4,523 | h | C | IGC/Compiler/FindInterestingConstants.h | scott-snyder/intel-graphics-compiler | 0977554d5aecf93b4a777f38e6c2e73e4dea313e | [
"MIT"
] | null | null | null | IGC/Compiler/FindInterestingConstants.h | scott-snyder/intel-graphics-compiler | 0977554d5aecf93b4a777f38e6c2e73e4dea313e | [
"MIT"
] | null | null | null | IGC/Compiler/FindInterestingConstants.h | scott-snyder/intel-graphics-compiler | 0977554d5aecf93b4a777f38e6c2e73e4dea313e | [
"MIT"
] | null | null | null | /*===================== begin_copyright_notice ==================================
Copyright (c) 2017 Intel Corporation
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
======================= end_copyright_notice ==================================*/
#pragma once
#include "Compiler/CodeGenContextWrapper.hpp"
#include "common/LLVMWarningsPush.hpp"
#include <llvm/Pass.h>
#include <llvm/IR/InstVisitor.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/InstrTypes.h>
#include <llvm/IR/Dominators.h>
#include "common/LLVMWarningsPop.hpp"
#include "llvm/Analysis/LoopInfo.h"
namespace IGC
{
struct InstructionStats
{
uint32_t instCount = 0;
uint32_t branchCount = 0;
uint32_t loopCount = 0;
uint32_t samplerCount = 0;
uint32_t extendedMath = 0;
uint32_t selectCount = 0;
uint32_t weight = 0;
};
class FindInterestingConstants : public llvm::FunctionPass, public llvm::InstVisitor<FindInterestingConstants>
{
public:
static char ID;
FindInterestingConstants();
~FindInterestingConstants() {}
virtual llvm::StringRef getPassName() const override
{
return "Find Interesting Constants";
}
virtual void getAnalysisUsage(llvm::AnalysisUsage& AU) const override
{
AU.addRequired<CodeGenContextWrapper>();
AU.addRequired<llvm::LoopInfoWrapperPass>();
}
virtual bool runOnFunction(llvm::Function& F) override;
bool doFinalization(llvm::Module&) override;
void visitLoadInst(llvm::LoadInst& I);
private:
CodeGenContext* m_context;
llvm::LoopInfo* m_LI;
unsigned int m_instCount;
unsigned int m_constFoldBranch;
unsigned int m_constFoldLoopBranch;
unsigned int m_samplerCount;
unsigned int m_extendedMath;
unsigned int m_selectCount;
unsigned int m_branchsize;
unsigned int m_loopSize;
std::unordered_map<unsigned int, std::vector<SConstantAddrValue>> m_InterestingConstants;
const llvm::DataLayout* m_DL;
std::unordered_set<llvm::Instruction*> visitedForFolding;
// Helper functions
bool isReverseOpInstPair(llvm::Intrinsic::ID intr1, llvm::Intrinsic::ID intr2);
void UpdateInstCount(llvm::Instruction* inst);
bool getConstantAddress(llvm::LoadInst& I, unsigned& bufIdOrGRFOffset, int& eltId, int& size_in_bytes);
bool FoldsToConst(llvm::Instruction* inst, llvm::Instruction* use, bool& propagate);
bool FoldsToZero(llvm::Instruction* inst, llvm::Instruction* use);
bool FoldsToSource(llvm::Instruction* inst, llvm::Instruction* use);
void FoldsToConstPropagate(llvm::Instruction* I);
void FoldsToZeroPropagate(llvm::Instruction* I);
void FoldsToSourcePropagate(llvm::Instruction* I);
bool allUsersVisitedForFolding(llvm::Instruction* binOperand, llvm::Instruction* binInst);
void CheckIfSampleBecomesDeadCode(llvm::Instruction* inst, llvm::Instruction* use);
unsigned int BranchSize(llvm::Instruction* I, llvm::BranchInst* Br, bool& isLoop);
void ResetStatCounters();
void addInterestingConstant(llvm::Type* loadTy, unsigned bufIdOrGRFOffset, unsigned eltId, int size_in_bytes, bool anyValue, uint32_t constValue, InstructionStats stats);
template<typename ContextT>
void copyInterestingConstants(ContextT* pShaderCtx);
};
}
| 41.87963 | 178 | 0.701083 | [
"vector"
] |
eead81f07af3fcc2303ddb026ab284d07f9194a7 | 507 | h | C | source/SC_EditMesh.h | FMalmberg/SolidchamferR20 | d241aa40206f9c373afd772fca052a7badee304a | [
"MIT"
] | 1 | 2020-06-29T21:30:34.000Z | 2020-06-29T21:30:34.000Z | source/SC_EditMesh.h | FMalmberg/SolidchamferR20 | d241aa40206f9c373afd772fca052a7badee304a | [
"MIT"
] | null | null | null | source/SC_EditMesh.h | FMalmberg/SolidchamferR20 | d241aa40206f9c373afd772fca052a7badee304a | [
"MIT"
] | 1 | 2020-07-08T06:41:06.000Z | 2020-07-08T06:41:06.000Z | #ifndef SC_EDIT_MESH_H
#define SC_EDIT_MESH_H
#include "c4d.h"
#include <vector>
//A wrapper class for polygon objects,
//allowing vertices and polygons to be inserted dynamically
class SC_EditMesh{
private:
PolygonObject* mesh;
std::vector<Vector> new_verts;
std::vector<CPolygon> new_polys;
public:
SC_EditMesh(PolygonObject* obj);
int AddVertex(Vector v);
int AddFace(CPolygon p);
void Commit();
Vector& Vertex(Int32 index);
CPolygon& Face(Int32 index);
};
#endif | 19.5 | 60 | 0.717949 | [
"mesh",
"vector"
] |
eebdc1ae671f69eaf7f8ea2893c08f3f2e7fea51 | 1,811 | h | C | FireCube/Rendering/Font.h | ashleygwinnell/firecube | ea6bec6bab98d922dce76610a739beb5f7f88b61 | [
"MIT"
] | 1 | 2020-03-31T20:41:48.000Z | 2020-03-31T20:41:48.000Z | FireCube/Rendering/Font.h | ashleygwinnell/firecube | ea6bec6bab98d922dce76610a739beb5f7f88b61 | [
"MIT"
] | null | null | null | FireCube/Rendering/Font.h | ashleygwinnell/firecube | ea6bec6bab98d922dce76610a739beb5f7f88b61 | [
"MIT"
] | null | null | null | #pragma once
#pragma warning(push)
#pragma warning(disable:4251)
#include <memory>
#include <vector>
#include <map>
#include "Math/Math.h"
#include "Core/Resource.h"
namespace FireCube
{
//Forward declarations.
class Font;
class Texture2D;
class vec2;
class vec3;
class vec4;
class UIText;
class FontImpl;
class FontFace;
/**
* @cond
* Stores information about a specific glyph.
*/
class FIRECUBE_API Glyph
{
public:
vec2 uv;
vec2 size;
vec2 bitmapOffset;
int advance;
};
/** @endcond */
/**
* @cond
* Stores information about a font page.
*/
class FIRECUBE_API FontPage
{
public:
Texture2D *tex;
vec2 curPos;
int textureSize;
};
/** @endcond */
/**
* This class holds the data needed to draw text with a specific font.
*/
class FIRECUBE_API Font : public Resource
{
FIRECUBE_OBJECT(Font)
public:
Font(Engine *engine);
~Font();
/**
* Loads a font.
* @param name The file to load.
*/
bool Load(const std::string &filename);
/**
* Generates a font face using an actual size
* @param pointSize The size of the font
*/
FontFace *GenerateFontFace(int pointSize);
static void Init();
private:
std::vector<char> data;
std::map<int, FontFace *> faces;
};
/**
* This class holds the data needed to draw text with a specific font and size.
*/
class FIRECUBE_API FontFace
{
friend class Font;
friend class Renderer;
friend class UIText;
public:
FontFace();
~FontFace();
/**
* @returns the kerning between two characters in pixels
*/
short GetKerning(unsigned int a, unsigned int b) const;
private:
bool AddChar(char c);
int pointSize;
std::vector<Glyph> glyph;
FontPage *page;
FontImpl *fontImpl;
std::map<unsigned int, short> kerning;
};
}
#pragma warning(pop)
| 16.768519 | 79 | 0.663722 | [
"vector"
] |
eec22af2841663ae23ab0957e49d34a80af3275f | 1,278 | h | C | Course work/Base.h | filtitov2001/Coursework_ConsoleCalc | 165ea2c259536cb4f2f227824d1c800391fadc48 | [
"MIT"
] | null | null | null | Course work/Base.h | filtitov2001/Coursework_ConsoleCalc | 165ea2c259536cb4f2f227824d1c800391fadc48 | [
"MIT"
] | null | null | null | Course work/Base.h | filtitov2001/Coursework_ConsoleCalc | 165ea2c259536cb4f2f227824d1c800391fadc48 | [
"MIT"
] | null | null | null | #ifndef _BASE_H
#define _BASE_H
#include <vector>
#include <string>
#include <iostream>
using namespace std;
class Base;
typedef void(Base::* T_SIGNAL) (string&);
typedef void(Base::* T_HENDLER) (string);
class Base {
private:
struct o_sh {
Base* p_Base;
T_SIGNAL p_signal;
T_HENDLER p_hendler;
};
Base* parent;
string name;
vector<o_sh*> connects;
protected:
int cl_num = 1;
int activity = 0;
vector<Base*> children;
public:
Base(Base* parent);
Base(Base* parent, string name);
void setStatus(int activity);
void printChildren();
void inputName(string name);
string getName();
void printTree(string space);
Base* searchParent(string name);
string getTrailItem(string objectPath, int iLevel);
Base* getObjectRoot();
Base* getTrailObjectRoot(string objectPath);
Base* getObject(string objectPath);
Base* getChild(string nameChild);
int getClassNumber();
void setConnect(T_SIGNAL p_signal, Base* p_ob_hend, T_HENDLER p_hendler);
void deleteConnect(T_SIGNAL p_signal, Base* p_ob_hend, T_HENDLER p_hendler);
void emitSignal(T_SIGNAL p_signal, string& command);
~Base();
};
#define SIGNAL_D(T, signal_f)(T_SIGNAL(&T::signal_f))
#define HENDLER_D(G,hendler_f) (T_HENDLER(&G::hendler_f))
#endif
| 20.612903 | 78 | 0.713615 | [
"vector"
] |
eec5b08a1478af32b76ca363070e7483d8333cba | 1,941 | h | C | Engine/Source/Runtime/HeadMountedDisplay/Public/XRRenderTargetManager.h | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Source/Runtime/HeadMountedDisplay/Public/XRRenderTargetManager.h | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Source/Runtime/HeadMountedDisplay/Public/XRRenderTargetManager.h | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "StereoRenderTargetManager.h"
/**
* Common IStereoRenderTargetManager implementation that can be used by HMD implementations in order to get default implementations for most methods.
*/
class HEADMOUNTEDDISPLAY_API FXRRenderTargetManager : public IStereoRenderTargetManager
{
public:
/**
* Updates viewport for direct rendering of distortion. Should be called on a game thread.
*
* @param bUseSeparateRenderTarget Set to true if a separate render target will be used. Can potentiallt be true even if ShouldUseSeparateRenderTarget() returned false earlier.
* @param Viewport The Viewport instance calling this method.
* @param ViewportWidget (optional) The Viewport widget containing the view. Can be used to access SWindow object.
*/
virtual void UpdateViewport(bool bUseSeparateRenderTarget, const class FViewport& Viewport, class SViewport* ViewportWidget = nullptr) override;
/**
* Calculates dimensions of the render target texture for direct rendering of distortion.
* This implementation calculates the size based on the current value of r.ScreenPercentage.
*/
virtual void CalculateRenderTargetSize(const class FViewport& Viewport, uint32& InOutSizeX, uint32& InOutSizeY) override;
/**
* Returns true, if render target texture must be re-calculated.
*/
virtual bool NeedReAllocateViewportRenderTarget(const class FViewport& Viewport) override;
protected:
/**
* Optional method called when the ViewportWidget is not null
*/
virtual void UpdateViewportWidget(bool bUseSeparateRenderTarget, const class FViewport& Viewport, class SViewport* ViewportWidget) {}
/**
* Optional method for custom present specific actions called at the end of UpdateViewport
*/
virtual void UpdateViewportRHIBridge(bool bUseSeparateRenderTarget, const class FViewport& Viewport, FRHIViewport* const ViewportRHI) {}
};
| 43.133333 | 177 | 0.789284 | [
"render",
"object"
] |
eec90b4ce3b12a220b236723c9f8441f91073ec2 | 1,567 | h | C | src/SparkMessage.h | ServError/Ignitron | 231635cb0cf58190682580ad9f633320ef84b325 | [
"BSD-3-Clause"
] | 10 | 2021-11-10T14:15:27.000Z | 2022-02-03T08:10:55.000Z | src/SparkMessage.h | ServError/Ignitron | 231635cb0cf58190682580ad9f633320ef84b325 | [
"BSD-3-Clause"
] | 6 | 2021-12-03T22:13:16.000Z | 2022-03-27T09:31:14.000Z | src/SparkMessage.h | ServError/Ignitron | 231635cb0cf58190682580ad9f633320ef84b325 | [
"BSD-3-Clause"
] | 4 | 2021-11-20T10:15:52.000Z | 2022-01-02T20:55:47.000Z | /*
* SparkDataControl.cpp
*
* Created on: 19.08.2021
* Author: stangreg
*/
#ifndef SPARK_MESSAGE_H // include guard
#define SPARK_MESSAGE_H
#include <array>
#include <vector>
#include <iomanip>
#include <sstream>
#include <Arduino.h>
#include "SparkHelper.h"
#include "SparkTypes.h"
#include "Common.h"
using ByteVector = std::vector<byte>;
class SparkMessage{
private:
byte cmd;
byte sub_cmd;
// data types to be confirmed
std::vector<ByteVector> split_data8;
std::vector<ByteVector> split_data7;
ByteVector data;
std::vector<ByteVector> final_message;
void start_message (byte cmd, byte sub_cmd);
std::vector<ByteVector> end_message();
//ByteVector end_message();
void add_bytes(ByteVector bytes_8);
void add_byte(byte by);
void add_string(std::string pack_str);
void add_long_string(std::string pack_str);
void add_prefixed_string(std::string pack_str);
void add_float (float flt);
void add_onoff (boolean onoff);
public:
SparkMessage();
// Command messages to send to Spark
std::vector<ByteVector> change_effect_parameter (std::string pedal, int param, float val);
std::vector<ByteVector> change_effect (std::string pedal1, std::string pedal2);
std::vector<ByteVector> change_hardware_preset (int preset_num);
std::vector<ByteVector> turn_effect_onoff (std::string pedal, boolean enable);
std::vector<ByteVector> create_preset (Preset preset_data);
std::vector<ByteVector> get_current_preset_num();
std::vector<ByteVector> get_current_preset();
std::vector<ByteVector> send_ack(byte seq, byte cmd);
};
#endif
| 23.742424 | 91 | 0.751755 | [
"vector"
] |
eecb8437d8b9eeedfae0b591cebd4d4f831ebb84 | 4,492 | c | C | bin/MirnaNetwork/miRanda-3.3a/src/miranda.c | zhoujj2013/lncfuntk | 65f6d18a2dbc2a09901a867583f5e2a84bdfb3a9 | [
"MIT"
] | null | null | null | bin/MirnaNetwork/miRanda-3.3a/src/miranda.c | zhoujj2013/lncfuntk | 65f6d18a2dbc2a09901a867583f5e2a84bdfb3a9 | [
"MIT"
] | 1 | 2018-09-30T00:55:00.000Z | 2018-09-30T00:55:00.000Z | bin/MirnaNetwork/miRanda-3.3a/src/miranda.c | zhoujj2013/lncfuntk | 65f6d18a2dbc2a09901a867583f5e2a84bdfb3a9 | [
"MIT"
] | 1 | 2019-11-17T15:42:51.000Z | 2019-11-17T15:42:51.000Z | /* miranda.c */
/* -------------------------------------------------------------------
* miRanda- An miRNA target scanner, aims to predict mRNA targets for microRNAs,
* using dynamic-programming alignment and thermodynamics
*
* Copyright (C) (2003) Memorial Sloan-Kettering Cancer Center, New York
*
* Distributed under the GNU Public License (GPL)
* See the files 'COPYING' and 'LICENSE' for details
*
* Authors: Anton Enright, Bino John, Chris Sander and Debora Marks
* Email: mirnatargets (at) cbio.mskcc.org - reaches all authors
*
* Written By: Anton Enright
*
* Please send bug reports to: miranda (at) cbio.mskcc.org
*
* If you use miRanda in your research please cite:
* Enright AJ, John B, Gaul U, Tuschl T, Sander C and Marks DS;
* (2003) Genome Biology; 5(1):R1.
*
* This software will be further developed under the open source model,
* coordinated by Anton Enright and Chris Sander:
* miranda (at) cbio.mskcc.org (reaches both).
*
* Copyright (C) (2003) Memorial Sloan-Kettering Cancer Center
*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
* -------------------------------------------------------------------
*/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "miranda.h"
void initialize_globals() {
initialize_bases(); /* Prepare the generic base lookup array*/
initialize_scores();
initialize_seqio_buffers();
}
void destroy_globals() {
destroy_seqio_buffers();
}
int main (int argc, char* argv[]) {
char filename1[200];
char filename2[200];
char pairs_file[200];
char fileout[200];
FILE* query_fp = 0;
FILE* reference_fp = 0;
FILE* fp_pairs = 0;
FILE* fpout = stdout;
int total_pairs = 0;
pair_struct* pairs = 0;
/* Set Default Parameter Values*/
length_5p_for_weighting = 8; /* The 5' sequence length to be weighed except for the last residue*/
scale = 4.0; /* The 5' miRNA scaling parameter*/
strict = 0; /* Strict seed model on/off*/
debug = 0; /* Debugging mode on/off*/
key_value_pairs = 0;
gap_open = -9.0; /* Gap-open Penalty*/
gap_extend = -4.0; /* Gap-extend Penalty*/
score_threshold = 140.0; /* SW Score Threshold for reporting hits*/
energy_threshold = 1.0; /* Energy Threshold (DG) for reporting hits*/
verbosity = 1; /* Verbose mode on/off*/
outfile = 0; /* Dump to file on/off*/
truncated = 0; /* Truncate sequences on/off*/
no_energy = 0; /* Turn off Vienna Energy Calcs - FASTER*/
restricted = 0; /* Perform restricted search space*/
parse_command_line(argc, argv, filename1, filename2, fileout, pairs_file);
if (gap_open > 0.0 || gap_extend > 0.0) {
fprintf(stderr, "Error: gap penalties may not be greater than 0\n");
return 1;
}
if (truncated < 0) {
fprintf(stderr, "Error: negative value give for UTR truncation\n");
return 1;
}
if ((query_fp = fopen(filename1, "r")) == NULL) {
fprintf(stderr, "Error: Cannot open file %s\n", filename1);
return 1;
}
if ((reference_fp = fopen(filename2, "r")) == NULL) {
fprintf(stderr, "Error: Cannot open file %s\n", filename2);
return 1;
}
fclose(reference_fp);
if ((outfile) && ((fpout = fopen(fileout, "w")) == NULL)) {
fprintf(stderr, "Error: Cannot create output file %s\n", fileout);
return 1;
}
if (restricted) {
if ((fp_pairs = fopen(pairs_file, "r")) == NULL) {
fprintf(stderr, "Error: Cannot open restrict pairs file %s\n", pairs_file);
return 1;
}
/* Initialize the pairs list for restriced searches*/
total_pairs = load_pairs(fp_pairs, &pairs);
fclose(fp_pairs);
}
initialize_globals();
print_parameters(filename1, filename2, fpout);
if (restricted && verbosity) {
printf("Performing Restricted Scan on:%d pairs\n", total_pairs);
}
find_targets(query_fp, fpout, pairs, total_pairs, filename2);
destroy_globals();
if (outfile) fclose(fpout);
fclose(query_fp);
return 0;
}
| 34.821705 | 100 | 0.676981 | [
"model"
] |
eed74725106252c1494f403a47ef8b04e3daf2bd | 3,257 | h | C | src/suns_parser.h | Boernsman/sunspec | a622e3c37f2c02c9927c063dd7e319053645b2ab | [
"BSD-3-Clause"
] | 17 | 2015-08-27T08:26:11.000Z | 2021-08-08T12:47:23.000Z | src/suns_parser.h | Boernsman/sunspec | a622e3c37f2c02c9927c063dd7e319053645b2ab | [
"BSD-3-Clause"
] | 3 | 2016-12-06T08:34:15.000Z | 2017-11-07T11:27:29.000Z | src/suns_parser.h | Boernsman/sunspec | a622e3c37f2c02c9927c063dd7e319053645b2ab | [
"BSD-3-Clause"
] | 5 | 2015-04-04T01:24:31.000Z | 2021-01-19T17:00:54.000Z |
/* -*- tab-width: 4; indent-tabs-mode: nil -*- */
/*
* suns_parser.h
*
* mostly glue code to interact with yacc
*
* Copyright (c) 2011-2012, John D. Blair <jdb@moship.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:
*
* * 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 John D. Blair nor his lackeys 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
* JOHN D. BLAIR 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 _SUNS_PARSER_H_
#define _SUNS_PARSER_H_
#include <stdio.h>
#include <stdlib.h>
#include "ezxml/ezxml.h"
#include "suns_model.h"
typedef struct suns_parser_state {
char *model_file;
FILE *input_file;
/* the rest of this is the parsed s-lang document
which describes the sunspec data models and all
of the test data blocks */
list_t *model_list; /* all models */
list_t *did_list; /* index of all dids (dids > models) */
list_t *define_list; /* global defines */
list_t *data_block_list; /* static test data blocks */
} suns_parser_state_t;
/* prototypes so compiling bison and flex output doesn't cause warnings */
/* crap, there are still warnings. sigh. */
void yyerror(const char *str);
int yylex(void);
int yywrap();
void suns_parser_init(void);
suns_dp_t * suns_model_find_dp_by_name(list_t *list, char *name);
suns_dp_t *suns_dp_find_in_model(suns_model_t *m, char *name);
int parser_getopt(int argc, char *argv[]);
int suns_parse_model_file(const char *file);
/* accessor used to access the global parser state */
suns_parser_state_t *suns_get_parser_state(void);
/* accessors used to access the parsed suns model definition file */
list_t *suns_get_model_list(void);
list_t *suns_get_did_list(void);
list_t *suns_get_data_block_list(void);
list_t *suns_get_define_list(void);
int suns_parse_xml_model_file(const char *file);
suns_dp_block_t *suns_ezxml_to_dp_block(ezxml_t b);
suns_dp_t *suns_ezxml_to_dp(ezxml_t p);
#endif /* _SUNS_PARSER_H_ */
| 36.188889 | 78 | 0.731962 | [
"model"
] |
eed82173113a9adfbdc1f40dfe5bcc7148747309 | 1,267 | h | C | src/EventSystem.h | WienerTakesAll/WienerTakesAll | 6accbf6f0ac04cf990134072474e71f2bc59e7d0 | [
"Apache-2.0"
] | 2 | 2018-01-07T02:26:22.000Z | 2018-04-06T16:07:01.000Z | src/EventSystem.h | WienerTakesAll/WienerTakesAll | 6accbf6f0ac04cf990134072474e71f2bc59e7d0 | [
"Apache-2.0"
] | 39 | 2018-01-12T00:21:12.000Z | 2018-04-13T12:08:20.000Z | src/EventSystem.h | WienerTakesAll/WienerTakesAll | 6accbf6f0ac04cf990134072474e71f2bc59e7d0 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <string>
#include <functional>
#include <vector>
#include <array>
#include "Event.h"
template<class T>
class EventSystem {
public:
EventSystem() = default;
~EventSystem() = default;
//Add a function to handle an event of name eventName. Also requires "this" pointer of object.
//Example Usage: add_event_handler("someEvent", &ExampleClass::ExampleFunction, this)
void add_event_handler(EventType event_type, std::function<void(T*, Event)> handle_function, T* this_pointer);
void remove_event_handler(EventType event_type);
//Takes a list of events and runs the specified function handlers
void handle_events(const std::vector<Event>& events);
//Construct and queue an event.
//Example Usage: queue_event("someEvent", "int_value", 10, "float_value", 5.5f, "string_value", "text")
void queue_event(Event&& queuedEvent);
//Send the accumulated events to a list.
//This should be used to congregate the events of all the systems before handling
void send_events(std::vector<Event>& reciever);
private:
std::vector<Event> event_queue_;
std::array<std::function<void(const Event&)>, static_cast<int>(EventType::EVENT_COUNT)> function_handlers_;
};
#include "EventSystem_impl.h"
| 33.342105 | 114 | 0.728493 | [
"object",
"vector"
] |
eed9f9b3f8de2aa01a08945b61b891094a0f6368 | 1,374 | h | C | lessons/Lesson5/ShoppingCart.h | maychan111/cpp-tdd | ed34561b5c9763e280fd871c1dcfc749f1ad1d7d | [
"MIT"
] | 2 | 2019-04-23T23:27:07.000Z | 2022-03-27T14:43:14.000Z | lessons/Lesson5/ShoppingCart.h | maychan111/cpp-tdd | ed34561b5c9763e280fd871c1dcfc749f1ad1d7d | [
"MIT"
] | null | null | null | lessons/Lesson5/ShoppingCart.h | maychan111/cpp-tdd | ed34561b5c9763e280fd871c1dcfc749f1ad1d7d | [
"MIT"
] | null | null | null | #pragma once
#include "Item.h"
#include "Discounts.h"
#include <vector>
#include <numeric>
#include <algorithm>
// http://en.cppreference.com/w/cpp/language/lambda
namespace Lesson5
{
class ShoppingCart
{
public:
template <typename ...Params>
void Add(Params&&... params)
{
_items.emplace_back(std::forward<Params>(params)...);
};
double Cost() const
{
return std::accumulate(std::begin(_items), std::end(_items), 0.0, [](double result, const Item& item)
{
return result + item._price * item._quantity;
});
}
double Cost(const Discounts& d)
{
return std::accumulate(std::begin(_items), std::end(_items), 0.0, [&d](double result, const Item& item)
{
return result + item._price * item._quantity * d.Lookup(item._name);
});
}
template <typename F>
double Cost(F func)
{
return std::accumulate(std::begin(_items), std::end(_items), 0.0, func);
}
bool Contains(const std::string& name) const
{
return std::find_if(std::begin(_items), std::end(_items), [&](auto item) { return name == item._name; }) != _items.end();
}
private:
std::vector<Item> _items;
};
} | 26.423077 | 133 | 0.534207 | [
"vector"
] |
eeda930a0130f5937687074ba4ed62c2de07e73f | 2,721 | h | C | EpicForceEngine/MagnumEngineLib/MagnumCore/GXVertexBuffer.h | MacgyverLin/MagnumEngine | 975bd4504a1e84cb9698c36e06bd80c7b8ced0ff | [
"MIT"
] | 1 | 2021-03-30T06:28:32.000Z | 2021-03-30T06:28:32.000Z | EpicForceEngine/MagnumEngineLib/MagnumCore/GXVertexBuffer.h | MacgyverLin/MagnumEngine | 975bd4504a1e84cb9698c36e06bd80c7b8ced0ff | [
"MIT"
] | null | null | null | EpicForceEngine/MagnumEngineLib/MagnumCore/GXVertexBuffer.h | MacgyverLin/MagnumEngine | 975bd4504a1e84cb9698c36e06bd80c7b8ced0ff | [
"MIT"
] | null | null | null | #ifndef _GXVertexBuffer_h_
#define _GXVertexBuffer_h_
#include "GXDef.h"
#include "gldef.h"
namespace Magnum
{
/**
* GXVertexBuffer encapsulate a the Index Buffer of Graphics Device
*/
class GXVertexBuffer
{
friend class GXContext;
private:
GXVertexBuffer(const GXVertexBuffer &vertexBuffer_);
GXVertexBuffer &operator = (const GXVertexBuffer &vertexBuffer_);
public:
enum Usage
{
STATIC,
DYNAMIC,
STREAM,
};
GXVertexBuffer(int vertexCount_, const Vector<GXVertexFormat> &formats_, Usage usage_ = STATIC);
virtual ~GXVertexBuffer();
const Vector<GXVertexFormat> &getFormats() const;
const Vector<int> &getOffsets() const;
int getVertexCount() const;
int getStreamCount() const;
unsigned int getVertexHandle() const;
Usage getUsage() const;
void setVertices(const char *buffer_, int to_, int count_);
template <class T>
void setVertices(const T *vertices_, int count_)
{
assert(count_<=vertexCount);
assert( sizeof(T) == stride );
setVertices(vertices_, 0, 0, count_);
}
template <class T>
void setVertices(const T *vertices_, int to_, int from_, int count_)
{
assert(to_ +count_<=vertexCount);
assert( sizeof(T) == stride );
int oldVertexBufferHandle;
int oldIndexBufferHandle;
glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &oldVertexBufferHandle);
glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &oldIndexBufferHandle);
glBindBuffer(GL_ARRAY_BUFFER, vertexBufferHandle);
glBufferSubData(GL_ARRAY_BUFFER, to_*sizeof(T), count_*sizeof(T), &vertices_[from_]);
glBindBuffer(GL_ARRAY_BUFFER, oldVertexBufferHandle);
::checkGLError("setVertices");
}
/*
template <class T>
void setVertices(int stream, const Vector<T> &vertices)
{
assert( getStreamSize(stream)==sizeof(T) );
}
template <class T>
void setVertices(int stream, const Vector<T> &vertices, int to, int from, int count)
{
assert( getStreamSize(stream)==sizeof(T) );
}
template <class T>
void setVertices(int stream, const Vector<T> &vertices, int offset, int stride)
{
assert( getStreamSize(stream)==sizeof(T) );
}
template <class T>
void setVertices(int stream, const Vector<T> &vertices, GXVertexFormat format, Vector4 trans, Vector4 scale)
{
assert( getStreamSize(stream)==sizeof(T) );
}
template <class T>
void setVertices(int stream, const Vector<T> &vertices, GXVertexFormat format, Vector4 trans, Vector4 scale, int offset, int stride, int to, int from, int count)
{
assert( getStreamSize(stream)==sizeof(T) );
}
*/
private:
void prepareFormat();
protected:
unsigned int vertexBufferHandle;
int vertexCount;
int GXPrimitiveCount;
Vector<GXVertexFormat> formats;
Vector<int> offsets;
int stride;
Usage usage;
};
};
#endif | 23.059322 | 162 | 0.733186 | [
"vector"
] |
eedba1a25ed949095d3e8bb6bbe3fe188465e124 | 3,356 | h | C | localization/lib/ndt_cpu/include/ndt_cpu/Octree.h | project-aslan/autoware.ai | d8ee1bfb4f36fb7f789f6f90b10c2f6007128d8b | [
"Apache-2.0"
] | 2 | 2021-01-29T18:07:18.000Z | 2021-08-16T16:11:22.000Z | localization/lib/ndt_cpu/include/ndt_cpu/Octree.h | project-aslan/autoware.ai | d8ee1bfb4f36fb7f789f6f90b10c2f6007128d8b | [
"Apache-2.0"
] | 1 | 2020-09-25T14:15:25.000Z | 2020-10-12T12:15:22.000Z | localization/lib/ndt_cpu/include/ndt_cpu/Octree.h | project-aslan/autoware.ai | d8ee1bfb4f36fb7f789f6f90b10c2f6007128d8b | [
"Apache-2.0"
] | null | null | null | // Originally included at Autoware.ai version 1.10.0
#ifndef OCTREE_H_
#define OCTREE_H_
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <float.h>
#include <vector>
#include <eigen3/Eigen/Dense>
#include <eigen3/Eigen/Geometry>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
/* The octree is built on top of a voxel grid to fasten the nearest neighbor search */
namespace cpu {
template <typename PointSourceType>
class Octree {
public:
Octree();
/* Input is a vector of boundaries and ptsum of the voxel grid
* Those boundaries is needed since the number of actually occupied voxels may be
* much smaller than reserved number of voxels */
void setInput(std::vector<Eigen::Vector3i> occupied_voxels, typename pcl::PointCloud<PointSourceType>::Ptr point_cloud);
void update(std::vector<Eigen::Vector3i> new_voxels, typename pcl::PointCloud<PointSourceType>::Ptr new_cloud);
Eigen::Matrix<float, 6, 1> nearestOctreeNode(PointSourceType q);
private:
typedef struct {
float lx, ux;
float ly, uy;
float lz, uz;
Eigen::Vector3d centroid;
int point_num;
} OctreeNode;
typedef struct {
int lower_x, upper_x;
int lower_y, upper_y;
int lower_z, upper_z;
} OctreeLevelBoundaries;
typedef struct {
int x, y, z;
} OctreeLevelDim;
// Convert from 3d indexes and level of the tree node to the actual index in the array
int index2id(int idx, int idy, int idz, int level);
int index2id(int idx, int idy, int idz, OctreeLevelBoundaries bounds, OctreeLevelDim dims);
// Convert from the index in the array to the 3d indexes of the tree node
Eigen::Vector3i id2index(int id, int level);
Eigen::Vector3i id2index(int id, OctreeLevelBoundaries bounds, OctreeLevelDim dims);
void buildLevel(int level);
bool isOccupied(int node_id, int level);
bool isOccupied(std::vector<unsigned int> occupancy, int node_id);
void setOccupied(int node_id, int level);
void setOccupied(std::vector<unsigned int> &occupancy, int node_id);
void updateBoundaries(std::vector<Eigen::Vector3i> new_voxels);
int roundUp(int input, int factor);
int roundDown(int input, int factor);
int div(int input, int divisor);
void updateOctreeContent(std::vector<Eigen::Vector3i> new_voxels, typename pcl::PointCloud<PointSourceType>::Ptr new_cloud);
double dist(OctreeNode node, PointSourceType q);
/* Three functions to search for the nearest neighbor of a point */
void initRange(PointSourceType q, double &min_range, int ¤t_nn_voxel);
void goUp(Eigen::Matrix<int, 4, 1 > tree_node, PointSourceType q, double &min_range, int ¤t_nn_voxel);
void goDown(Eigen::Matrix<int, 4, 1> tree_node, PointSourceType q, double &min_range, int ¤t_nn_voxel);
boost::shared_ptr<std::vector<std::vector<OctreeNode> > > octree_;
boost::shared_ptr<std::vector<OctreeLevelBoundaries> > reserved_size_;
boost::shared_ptr<std::vector<OctreeLevelDim> > dimension_;
/* Used for checking if an octree node is occupied or not
* If an octree node is occupied (containing some points),
* then the corresponding bit is set
*/
boost::shared_ptr<std::vector<std::vector<unsigned int> > > occupancy_check_;
int leaf_x_, leaf_y_, leaf_z_; // Number of voxels contained in each leaf
static const int MAX_BX_ = 8;
static const int MAX_BY_ = 8;
static const int MAX_BZ_ = 4;
};
}
#endif
| 31.074074 | 125 | 0.75149 | [
"geometry",
"vector",
"3d"
] |
eee26811487bb7b70ad4bdb174e1acac7b865390 | 26,684 | h | C | bob/ip/base/include/bob.ip.base/Affine.h | bioidiap/bob.ip.base | d0b4bff89390fa4ac22f4e16bf1e3aaf1d00d926 | [
"BSD-3-Clause"
] | 4 | 2017-10-30T10:52:47.000Z | 2020-08-21T05:33:33.000Z | bob/ip/base/include/bob.ip.base/Affine.h | bioidiap/bob.ip.base | d0b4bff89390fa4ac22f4e16bf1e3aaf1d00d926 | [
"BSD-3-Clause"
] | 5 | 2015-01-14T18:00:08.000Z | 2016-05-24T08:18:05.000Z | bob/ip/base/include/bob.ip.base/Affine.h | bioidiap/bob.ip.base | d0b4bff89390fa4ac22f4e16bf1e3aaf1d00d926 | [
"BSD-3-Clause"
] | 4 | 2015-07-16T14:57:09.000Z | 2018-03-15T09:23:28.000Z | /**
* @author Manuel Günther <manuel.guenther@idiap.ch>
* @date Thu Jun 26 09:33:10 CEST 2014
*
* This file defines functions and classes for affine image transformations
*
* Copyright (C) Idiap Research Institute, Martigny, Switzerland
*/
#ifndef BOB_IP_BASE_AFFINE_H
#define BOB_IP_BASE_AFFINE_H
#include <boost/shared_ptr.hpp>
#include <bob.core/assert.h>
#include <bob.core/check.h>
#include <bob.core/logging.h>
#include <boost/random.hpp>
#include <bob.core/random.h>
namespace bob { namespace ip { namespace base {
/** Implementation of the bi-linear interpolation of a source to a target image. */
template <typename T, bool mask>
void transform(
const blitz::Array<T,2>& source,
const blitz::Array<bool,2>& source_mask,
const blitz::TinyVector<double,2>& source_center,
blitz::Array<double,2>& target,
blitz::Array<bool,2>& target_mask,
const blitz::TinyVector<double,2>& target_center,
const blitz::TinyVector<double,2>& scaling_factor,
const double& rotation_angle
){
// This is the fastest version of the function that I can imagine...
// It handles two different coordinate systems: original image and new image
// transformation center in original image
const double original_center_y = source_center[0],
original_center_x = source_center[1];
// transformation center in new image:
const double new_center_y = target_center[0],
new_center_x = target_center[1];
// With these positions, we can define a mapping from the new image to the original image
const double sin_angle = -sin(rotation_angle * M_PI / 180.),
cos_angle = cos(rotation_angle * M_PI / 180.);
// we compute the distance in the source image, when going 1 pixel in the new image
const double col_dy = -sin_angle / scaling_factor[0],
col_dx = cos_angle / scaling_factor[1];
const double row_dy = cos_angle / scaling_factor[0],
row_dx = sin_angle / scaling_factor[1];
// Now, we iterate through the target image, and compute pixel positions in the source.
// For this purpose, get the (0,0) position of the target image in source image coordinates:
double origin_y = original_center_y - (new_center_y * cos_angle - new_center_x * sin_angle) / scaling_factor[0];
double origin_x = original_center_x - (new_center_x * cos_angle + new_center_y * sin_angle) / scaling_factor[1];
// WARNING: I am not sure, if this is correct, or if we rather need to do something like:
//double origin_y = original_center_y - (new_center_y * cos_angle / scaling_factor[0] - new_center_x * sin_angle / scaling_factor[1]);
//double origin_x = original_center_x - (new_center_x * cos_angle / scaling_factor[1] + new_center_y * sin_angle / scaling_factor[0]);
// Note: as long a single scale is used, or scaling is done without rotation, it should be the same.
// (at least, the tests pass with both ways)
// some helpers for the interpolation
int ox, oy;
double mx, my;
int h = source.extent(0)-1;
int w = source.extent(1)-1;
int size_y = target.extent(0), size_x = target.extent(1);
// Ok, so let's do it.
for (int y = 0; y < size_y; ++y){
// set the source image point to first point in row
double source_x = origin_x, source_y = origin_y;
// iterate over the row
for (int x = 0; x < size_x; ++x){
// We are at the desired pixel in the new image. Interpolate the old image's pixels:
double& res = target(y,x) = 0.;
// split each source x and y in integral and decimal digits
ox = std::floor(source_x);
oy = std::floor(source_y);
mx = source_x - ox;
my = source_y - oy;
// add the four values bi-linearly interpolated
if (mask){
bool& new_mask = target_mask(y,x) = true;
// upper left
if (ox >= 0 && oy >= 0 && ox <= w && oy <= h && source_mask(oy,ox)){
res += (1.-mx) * (1.-my) * source(oy,ox);
} else if ((1.-mx) * (1.-my) > 0.){
new_mask = false;
}
// upper right
if (ox >= -1 && oy >= 0 && ox < w && oy <= h && source_mask(oy,ox+1)){
res += mx * (1.-my) * source(oy,ox+1);
} else if (mx * (1.-my) > 0.){
new_mask = false;
}
// lower left
if (ox >= 0 && oy >= -1 && ox <= w && oy < h && source_mask(oy+1,ox)){
res += (1.-mx) * my * source(oy+1,ox);
} else if ((1.-mx) * my > 0.){
new_mask = false;
}
// lower right
if (ox >= -1 && oy >= -1 && ox < w && oy < h && source_mask(oy+1,ox+1)){
res += mx * my * source(oy+1,ox+1);
} else if (mx * my > 0.){
new_mask = false;
}
} else {
// upper left
if (ox >= 0 && oy >= 0 && ox <= w && oy <= h)
res += (1.-mx) * (1.-my) * source(oy,ox);
// upper right
if (ox >= -1 && oy >= 0 && ox < w && oy <= h)
res += mx * (1.-my) * source(oy,ox+1);
// lower left
if (ox >= 0 && oy >= -1 && ox <= w && oy < h)
res += (1.-mx) * my * source(oy+1,ox);
// lower right
if (ox >= -1 && oy >= -1 && ox < w && oy < h)
res += mx * my * source(oy+1,ox+1);
}
// done with this pixel...
// go to the next source pixel in the row
source_y += col_dy;
source_x += col_dx;
}
// at the end of the row, we shift the origin to the next line
origin_y += row_dy;
origin_x += row_dx;
}
// done!
}
/************************************************************************
************** Scaling functionality **********************************
************************************************************************/
/** helper function to compute the scale required by bob.ip.base.GeomNorm for the given image shapes */
static inline blitz::TinyVector<double,2> _get_scale_factor(const blitz::TinyVector<int,2>& src_shape, const blitz::TinyVector<int,2>& dst_shape){
double y_scale = (dst_shape[0]-1.) / (src_shape[0]-1.);
double x_scale = (dst_shape[1]-1.) / (src_shape[1]-1.);
return blitz::TinyVector<double,2>(y_scale, x_scale);
}
/**
* @brief Function which rescales a 2D blitz::array/image of a given type.
* The first dimension is the height (y-axis), whereas the second
* one is the width (x-axis).
* @param src The input blitz array
* @param dst The output blitz array. The new array is resized according
* to the dimensions of this dst array.
*/
template <typename T>
void scale(const blitz::Array<T,2>& src, blitz::Array<double,2>& dst){
blitz::TinyVector<double,2> offset(0,0);
blitz::Array<bool,2> src_mask, dst_mask;
// .. apply scale with (0,0) as offset and 0 as rotation angle
transform<T,false>(src, src_mask, offset, dst, dst_mask, offset, _get_scale_factor(src.shape(), dst.shape()), 0.);
}
/**
* @brief Function which rescales a 2D blitz::array/image of a given type.
* The first dimension is the height (y-axis), whereas the second
* one is the width (x-axis).
* @param src The input blitz array
* @param src_mask The input blitz boolean mask array
* @param dst The output blitz array. The new array is resized according
* to the dimensions of this dst array.
* @param dst_mask The output blitz boolean mask array
*/
template <typename T>
void scale(const blitz::Array<T,2>& src, const blitz::Array<bool,2>& src_mask, blitz::Array<double,2>& dst, blitz::Array<bool,2>& dst_mask){
blitz::TinyVector<double,2> offset(0,0);
// .. apply scale with (0,0) as offset and 0 as rotation angle
transform<T,true>(src, src_mask, offset, dst, dst_mask, offset, _get_scale_factor(src.shape(), dst.shape()), 0.);
}
/**
* @brief Function which rescales a 3D blitz::array/image of a given type.
* The first dimension is the number of color plane, the second is the
* height (y-axis), whereas the third one is the width (x-axis).
* @param src The input blitz array
* @param dst The output blitz array. The new array is resized according
* to the dimensions of this dst array.
*/
template <typename T>
void scale(const blitz::Array<T,3>& src, blitz::Array<double,3>& dst)
{
// Check number of planes
bob::core::array::assertSameDimensionLength(src.extent(0), dst.extent(0));
for (int p = 0; p < dst.extent(0); ++p){
const blitz::Array<T,2> src_slice = src(p, blitz::Range::all(), blitz::Range::all());
blitz::Array<double,2> dst_slice =dst(p, blitz::Range::all(), blitz::Range::all());
// Process one plane
scale(src_slice, dst_slice);
}
}
template <typename T>
void scale(const blitz::Array<T,3>& src, const blitz::Array<bool,3>& src_mask, blitz::Array<double,3>& dst, blitz::Array<bool,3>& dst_mask)
{
// Check number of planes
bob::core::array::assertSameDimensionLength(src.extent(0), dst.extent(0));
bob::core::array::assertSameDimensionLength(src.extent(0), src_mask.extent(0));
bob::core::array::assertSameDimensionLength(src_mask.extent(0), dst_mask.extent(0));
for (int p = 0; p < dst.extent(0); ++p){
const blitz::Array<T,2> src_slice = src(p, blitz::Range::all(), blitz::Range::all());
const blitz::Array<bool,2> src_mask_slice = src_mask(p, blitz::Range::all(), blitz::Range::all());
blitz::Array<double,2> dst_slice = dst(p, blitz::Range::all(), blitz::Range::all());
blitz::Array<bool,2> dst_mask_slice = dst_mask(p, blitz::Range::all(), blitz::Range::all());
// Process one plane
scale(src_slice, src_mask_slice, dst_slice, dst_mask_slice);
}
}
/**
* @brief Function which returns the shape of an output blitz::array
* when rescaling an input image with the given scale factor.
* @param src The input blitz array shape
* @param scale_factor The scaling factor to apply
* @return A blitz::TinyVector containing the shape of the rescaled image
*/
template <int D>
blitz::TinyVector<int, D> getScaledShape(const blitz::TinyVector<int, D> src_shape, const double scale_factor){
blitz::TinyVector<int, D> dst_shape = src_shape;
dst_shape(D-2) = floor(dst_shape(D-2) * scale_factor + 0.5);
dst_shape(D-1) = floor(dst_shape(D-1) * scale_factor + 0.5);
return dst_shape;
}
/************************************************************************
************** Rotating functionality *********************************
************************************************************************/
/**
* @brief Function which rotates a 2D blitz::array/image of a given type with the given angle in degrees.
* The first dimension is the height (y-axis), whereas the second
* one is the width (x-axis).
* @param src The input blitz array
* @param dst The output blitz array
* @param rotation_angle The angle in degrees to rotate the image with
*/
template <typename T>
void rotate(const blitz::Array<T,2>& src, blitz::Array<double,2>& dst, const double rotation_angle){
// rotation offset is the center of the image
blitz::TinyVector<double,2> src_offset((src.extent(0)-1.)/2.,(src.extent(1)-1.)/2.);
blitz::TinyVector<double,2> dst_offset((dst.extent(0)-1.)/2.,(dst.extent(1)-1.)/2.);
blitz::Array<bool,2> src_mask, dst_mask;
// .. apply scale with (0,0) as offset and 0 as rotation angle
transform<T,false>(src, src_mask, src_offset, dst, dst_mask, dst_offset, blitz::TinyVector<double,2>(1., 1.), rotation_angle);
}
/**
* @brief Function which rotates a 2D blitz::array/image of a given type with the given angle in degrees.
* The first dimension is the height (y-axis), whereas the second
* one is the width (x-axis).
* @param src The input blitz array
* @param src_mask The input blitz boolean mask array
* @param dst The output blitz array
* @param dst_mask The output blitz boolean mask array
* @param rotation_angle The angle in degrees to rotate the image with
*/
template <typename T>
void rotate(const blitz::Array<T,2>& src, const blitz::Array<bool,2>& src_mask, blitz::Array<double,2>& dst, blitz::Array<bool,2>& dst_mask, const double rotation_angle){
// rotation offset is the center of the image
blitz::TinyVector<double,2> src_offset((src.extent(0)-1.)/2.,(src.extent(1)-1.)/2.);
blitz::TinyVector<double,2> dst_offset((dst.extent(0)-1.)/2.,(dst.extent(1)-1.)/2.);
// .. apply scale with (0,0) as offset and 0 as rotation angle
transform<T,true>(src, src_mask, src_offset, dst, dst_mask, dst_offset, blitz::TinyVector<double,2>(1., 1.), rotation_angle);
}
/**
* @brief Function which rotates a 3D blitz::array/image of a given type.
* The first dimension is the number of color plane, the second is the
* height (y-axis), whereas the third one is the width (x-axis).
* @param src The input blitz array
* @param dst The output blitz array
* @param rotation_angle The angle in degrees to rotate the image with
*/
template <typename T>
void rotate(const blitz::Array<T,3>& src, blitz::Array<double,3>& dst, const double rotation_angle)
{
// Check number of planes
bob::core::array::assertSameDimensionLength(src.extent(0), dst.extent(0));
for (int p = 0; p < dst.extent(0); ++p){
const blitz::Array<T,2> src_slice = src(p, blitz::Range::all(), blitz::Range::all());
blitz::Array<double,2> dst_slice = dst(p, blitz::Range::all(), blitz::Range::all());
// Process one plane
rotate(src_slice, dst_slice, rotation_angle);
}
}
template <typename T>
void rotate(const blitz::Array<T,3>& src, const blitz::Array<bool,3>& src_mask, blitz::Array<double,3>& dst, blitz::Array<bool,3>& dst_mask, const double rotation_angle)
{
// Check number of planes
bob::core::array::assertSameDimensionLength(src.extent(0), dst.extent(0));
bob::core::array::assertSameDimensionLength(src.extent(0), src_mask.extent(0));
bob::core::array::assertSameDimensionLength(src_mask.extent(0), dst_mask.extent(0));
for (int p = 0; p < dst.extent(0); ++p){
const blitz::Array<T,2> src_slice = src(p, blitz::Range::all(), blitz::Range::all());
const blitz::Array<bool,2> src_mask_slice = src_mask(p, blitz::Range::all(), blitz::Range::all());
blitz::Array<double,2> dst_slice = dst(p, blitz::Range::all(), blitz::Range::all());
blitz::Array<bool,2> dst_mask_slice = dst_mask(p, blitz::Range::all(), blitz::Range::all());
// Process one plane
rotate(src_slice, src_mask_slice, dst_slice, dst_mask_slice, rotation_angle);
}
}
/**
* @brief Function which returns the shape of an output blitz::array
* when rotating an input image with the given rotation angle.
* @param src_shape The input blitz array shape
* @param rotation_angle The angle in degrees to rotate the image with
* @return A blitz::TinyVector containing the shape of the rotated image
*/
template <int D>
blitz::TinyVector<int, D> getRotatedShape(const blitz::TinyVector<int, D> src_shape, const double rotation_angle){
blitz::TinyVector<int, D> dst_shape = src_shape;
// compute rotation shape
double rad_angle = rotation_angle * M_PI / 180.;
const double absCos = std::abs(cos(rad_angle));
const double absSin = std::abs(sin(rad_angle));
dst_shape(D-2) = floor(src_shape[D-2] * absCos + src_shape[D-1] * absSin + 0.5);
dst_shape(D-1) = floor(src_shape[D-1] * absCos + src_shape[D-2] * absSin + 0.5);
return dst_shape;
}
/************************************************************************
************** Other functionalities **********************************
************************************************************************/
/**
* @brief Function which extracts a rectangle of maximal area from a
* 2D mask of booleans (i.e. a 2D blitz array).
* @warning The function assumes that the true values on the mask form
* a convex area.
* @param mask The 2D input blitz array mask.
* @result A blitz::TinyVector which contains in the following order:
* 0/ The y-coordinate of the top left corner
* 1/ The x-coordinate of the top left corner
* 2/ The height of the rectangle
* 3/ The width of the rectangle
*/
const blitz::TinyVector<int,4> maxRectInMask(const blitz::Array<bool,2>& mask);
/**
* @brief Function which extracts an image with a nearest neighbour
* technique, a boolean mask being given.
* a/ The columns of the image are firstly extrapolated wrt. to the
* nearest neighbour on the same column.
* b/ The rows of the image are the extrapolate wrt. to the
* closest neighbour on the same row.
* The first dimension is the height (y-axis), whereas the second one
* is the width (x-axis).
* @param src_mask The 2D input blitz array mask.
* @param img The 2D input/output blitz array/image.
* @warning The function assumes that the true values on the mask form
* a convex area.
* @warning img is used as both an input and output, in order to provide
* high performance. A copy might be done by the user before calling
* the function if required.
*/
template <typename T>
void extrapolateMask( const blitz::Array<bool,2>& src_mask, blitz::Array<T,2>& img){
// Check input and output size
bob::core::array::assertSameShape(src_mask, img);
bob::core::array::assertZeroBase(src_mask);
bob::core::array::assertZeroBase(img);
// TODO: check that the input mask is convex
// Determine the "full of false" columns
blitz::firstIndex i;
blitz::secondIndex j;
blitz::Array<bool,1> column_true(blitz::any(src_mask(j,i), j) );
int true_min_index=blitz::first(column_true);
int true_max_index=blitz::last(column_true);
if (true_min_index < 0 || true_max_index < 0){
throw std::runtime_error("The given mask is invalid as it contains only 'False' values.");
}
// Extrapolate the "non false" columns
for(int jj=true_min_index; jj<=true_max_index; ++jj)
{
blitz::Array<bool,1> src_col( src_mask( blitz::Range::all(), jj) );
int i_first = blitz::first(src_col);
if( i_first>0)
{
blitz::Range r_first(0,i_first-1);
img(r_first,jj) = img(i_first,jj);
}
int i_last=blitz::last(src_col);
if( i_last+1<src_mask.extent(0))
{
blitz::Range r_last(i_last+1,src_mask.extent(0)-1);
img(r_last,jj) = img(i_last,jj);
}
}
// Extrapolate the rows
if(true_min_index>0)
{
blitz::Range r_left(0,true_min_index-1);
for(int i=0; i<src_mask.extent(0); ++i)
img(i,r_left) = img(i,true_min_index);
}
if(true_max_index+1<src_mask.extent(1))
{
blitz::Range r_right(true_max_index+1,src_mask.extent(1)-1);
for(int i=0; i<src_mask.extent(0); ++i)
img(i,r_right) = img(i,true_max_index);
}
}
/**
* brief Color version of mask extrapolation
*/
template <typename T>
void extrapolateMask(const blitz::Array<bool,2>& mask, blitz::Array<T,3>& img){
blitz::Range a = blitz::Range::all();
for (int i = 0; i < img.extent(0); ++i){
blitz::Array<T,2> slice(img(i,a,a));
extrapolateMask(mask(a,a), slice);
}
}
template <typename T>
void _copy(blitz::Array<T,2>& img, const blitz::TinyVector<int,2>& to, const blitz::TinyVector<int,2>& from, double random_factor, boost::mt19937& rng){
T value = img(from);
if (random_factor){
value = static_cast<T>(bob::core::random::normal_distribution<double>(1., random_factor)(rng) * value);
}
img(to) = value;
}
template <typename T>
void _copy(blitz::Array<T,3>& img, const blitz::TinyVector<int,2>& to, const blitz::TinyVector<int,2>& from, double random_factor, boost::mt19937& rng){
blitz::Array<T,1> pixel(img(blitz::Range::all(), from[0], from[1]));
if (random_factor){
double factor = bob::core::random::normal_distribution<double>(1., random_factor)(rng);
for (int i = 0; i < img.extent(0); ++i)
pixel(i) = static_cast<T>(pixel(i) * factor);
}
img(blitz::Range::all(), to[0], to[1]) = pixel;
}
/**
* @brief Function which fills unmasked pixel areas of an image with pixel values from the border of the masked part of the image
* by adding some random noise.
* @param src_mask The 2D input blitz array mask.
* @param img The 2D input/output blitz array/image.
* @param rng The random number generatir to consider
* @param random_factor The standard deviation of a normal distribution to multiply pixel values with
* @param neighbors The (maximum) number of additional neighboring border values to choose from
* @warning The function assumes that the true values on the mask form
* a convex area.
* @warning img is used as both an input and output, in order to provide
* high performance. A copy might be done by the user before calling
* the function if required.
*/
template <typename T, int N>
void extrapolateMaskRandom(const blitz::Array<bool,2>& mask, blitz::Array<T,N>& img, boost::mt19937& rng, double random_factor = 0.01, int neighbors = 5){
// Check input and output size
blitz::TinyVector<int,2> shape(img.extent(N-2), img.extent(N-1));
bob::core::array::assertSameShape(mask, shape);
// get the masked center
int miny = mask.extent(0)-1, maxy = 0, minx = mask.extent(1)-1, maxx = 0;
for (int y = 0; y < mask.extent(0); ++y)
for (int x = 0; x < mask.extent(1); ++x)
if (mask(y,x)){
miny = std::min(miny, y);
maxy = std::max(maxy, y);
minx = std::min(minx, x);
maxx = std::max(maxx, x);
}
int center_y = (miny + maxy)/2;
int center_x = (minx + maxx)/2;
if (!mask(center_y, center_x)) throw std::runtime_error("The center of the masked area is not masked. Is your mask convex?");
blitz::Array<bool,2> filled_mask(mask.shape());
filled_mask = mask;
// the four directions to go (in this order):
// right, down, left, up
int directions_y[] = {0, 1, 0, -1};
int directions_x[] = {1, 0, -1, 0};
// the border values for the four directions
int border[] = {img.extent(1), img.extent(0), 1, 1};
bool at_border[4] = {false};
// the current maxima
int maxima_y[4], maxima_x[4];
for (int i = 0; i < 4; ++i){
maxima_y[i] = center_y + directions_y[i];
maxima_x[i] = center_x + directions_x[i];
}
// the current index (i.e., direction) to go
int current_index = 0;
int current_dir_y = directions_y[current_index];
int current_dir_x = directions_x[current_index];
// we start from the center
int current_pos_y = center_y;
int current_pos_x = center_x;
// go from the mask center in all directions, using a spiral
while (!at_border[0] || !at_border[1] || !at_border[2] || !at_border[3]){
// check that we haven't reached our limits yet
if (current_dir_y * current_pos_y + current_dir_x * current_pos_x >= maxima_y[current_index] * current_dir_y + maxima_x[current_index] * current_dir_x){
// increase the maxima
maxima_y[current_index] += current_dir_y;
maxima_x[current_index] += current_dir_x;
// check if we are at the border
if (current_pos_y * current_dir_y + current_pos_x * current_dir_x >= border[current_index]){
at_border[current_index] = true;
}
// change direction
current_index = (current_index + 1) % 4;
current_dir_y = directions_y[current_index];
current_dir_x = directions_x[current_index];
}
// check if we have to write a value
if (current_pos_y >= 0 && current_pos_y < img.extent(0) && current_pos_x >= 0 && current_pos_x < img.extent(1) && !mask(current_pos_y, current_pos_x)){
// fill with pixel from the inner part of the spiral
int next_index = (current_index + 1) % 4;
int next_dir_y = directions_y[next_index];
int next_dir_x = directions_x[next_index];
// .. get valid border pixel (e.g. that has been set before)
int valid_y = current_pos_y + next_dir_y;
int valid_x = current_pos_x + next_dir_x;
while (valid_y * next_dir_y + valid_x * next_dir_x < border[next_index] && !filled_mask(valid_y, valid_x)){
valid_y += next_dir_y;
valid_x += next_dir_x;
}
// check if we have found some part that is not connected anywhere
if (valid_y * next_dir_y + valid_x * next_dir_x >= border[next_index]){
bob::core::warn << "Could not find valid pixel in direction (" << next_dir_y << ", " << next_dir_x << ") at pixel position (" << current_pos_y << ", " << current_pos_x << "); is your mask convex?";
} else {
// choose one of the next pixels
std::vector<blitz::TinyVector<int,2> > locations;
if (neighbors >= 1){
for (int c = -neighbors; c <= neighbors; ++c){
int pos_y = valid_y + c * current_dir_y;
int pos_x = valid_x + c * current_dir_x;
if (pos_y >= 0 && pos_y < img.extent(0) && pos_x >= 0 && pos_x < img.extent(1) && filled_mask(pos_y, pos_x)){
locations.push_back(blitz::TinyVector<int,2>(pos_y, pos_x));
}
}
} else { // neighbors == 1
locations.push_back(blitz::TinyVector<int,2>(valid_y, valid_x));
}
// choose random location
blitz::TinyVector<int,2> location;
if (!locations.size()){
bob::core::warn << "Could not find valid pixel in range " << neighbors << " close to the border at pixel position (" << current_pos_y << ", " << current_pos_x << "); is your mask convex?";
location = blitz::TinyVector<int,2>(current_pos_y, current_pos_x);
} else {
location = locations[boost::uniform_int<int>(0, locations.size()-1)(rng)];
}
// copy pixel value
_copy(img, blitz::TinyVector<int,2>(current_pos_y, current_pos_x), location, random_factor, rng);
filled_mask(current_pos_y, current_pos_x) = true;
}
} // write value
// move one step towards the current direction
current_pos_y += current_dir_y;
current_pos_x += current_dir_x;
} // while
}
} } } // namespaces
#endif // BOB_IP_BASE_AFFINE_H
| 43.530179 | 207 | 0.61951 | [
"shape",
"vector",
"transform",
"3d"
] |
eeeea4a3e526b9d23c76d6dbad6a93536902b0ea | 5,819 | h | C | src/vicsetup/libvicsetup/luks2.h | harshanavkis/sgx-lkl | 539b65af777fb832031fa98a098d32575fac88f0 | [
"MIT"
] | 244 | 2018-01-08T19:11:43.000Z | 2022-03-24T06:11:32.000Z | src/vicsetup/libvicsetup/luks2.h | harshanavkis/sgx-lkl | 539b65af777fb832031fa98a098d32575fac88f0 | [
"MIT"
] | 614 | 2018-04-16T05:30:20.000Z | 2021-04-23T12:58:56.000Z | src/vicsetup/libvicsetup/luks2.h | harshanavkis/sgx-lkl | 539b65af777fb832031fa98a098d32575fac88f0 | [
"MIT"
] | 95 | 2018-02-05T03:41:50.000Z | 2022-01-06T23:09:49.000Z | #ifndef _VIC_LUKS2_H
#define _VIC_LUKS2_H
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
#include "vic.h"
#include "lukscommon.h"
#include "defs.h"
#include "hash.h"
#define LUKS2_LABEL_SIZE 48
#define LUKS2_SALT_SIZE 64
#define LUKS2_CSUM_ALG_SIZE 32
#define LUKS2_CSUM_SIZE 64
VIC_PACK_BEGIN
typedef struct luks2_hdr
{
char magic[LUKS_MAGIC_SIZE]; /* LUKS2_MAGIC_1ST or LUKS2_MAGIC_2ND */
uint16_t version; /* Version 2 */
uint64_t hdr_size; /* size including JSON area [ bytes ] */
uint64_t seqid; /* sequence ID , increased on update */
char label[LUKS2_LABEL_SIZE]; /* ASCII label or empty */
char csum_alg[LUKS2_CSUM_ALG_SIZE]; /* checksum algorithm , "sha256" */
uint8_t salt[LUKS2_SALT_SIZE]; /* salt , unique for every header */
char uuid[VIC_UUID_STRING_SIZE]; /* UUID of device */
char subsystem[LUKS2_LABEL_SIZE]; /* owner subsystem label or empty */
uint64_t hdr_offset; /* offset from device start [bytes] */
char _padding[184]; /* must be zeroed */
uint8_t csum[LUKS2_CSUM_SIZE]; /* header checksum */
char _padding4096[7*512]; /* Padding , must be zeroed */
/* luks2_ext_hdr follows */
}
luks2_hdr_t;
VIC_PACK_END
VIC_STATIC_ASSERT(sizeof(luks2_hdr_t) == 4096);
#define LUKS2_TYPE_SIZE 32
#define LUKS2_ENCRYPTION_SIZE 32
#define LUKS2_NUM_KEYSLOTS 64
#define LUKS2_NUM_SEGMENTS 1
#define LUKS2_NUM_DIGESTS (LUKS2_NUM_KEYSLOTS + LUKS2_NUM_SEGMENTS)
#define LUKS2_NUM_CONFIGS 1
#define LUKS2_DIGEST_SIZE VIC_MAX_HASH_SIZE
#define LUKS2_INTEGRITY_SIZE 32
typedef struct luks2_keyslot
{
char type[LUKS2_TYPE_SIZE];
uint64_t key_size;
struct
{
char type[LUKS2_TYPE_SIZE];
uint8_t salt[LUKS_SALT_SIZE];
/* For type 'pbkdf2' */
char hash[VIC_HASH_SPEC_SIZE];
uint64_t iterations;
/* For type 'argon2i' or 'argon2id' */
uint64_t time;
uint64_t memory;
uint64_t cpus;
}
kdf;
struct
{
char type[LUKS2_TYPE_SIZE];
char hash[VIC_HASH_SPEC_SIZE];
uint64_t stripes;
}
af;
struct
{
char type[LUKS2_TYPE_SIZE];
char encryption[LUKS2_ENCRYPTION_SIZE];
uint64_t key_size;
uint64_t offset;
uint64_t size;
}
area;
}
luks2_keyslot_t;
typedef struct luks2_segment
{
/* only "crypt" supported */
char type[LUKS2_TYPE_SIZE];
/* offset in bytes */
uint64_t offset;
/* starting offset for the initialization vector */
uint64_t iv_tweak;
/* (uint64_t)-1 indicates dynamic */
uint64_t size;
/* example: "aes-xts-plain64" */
char encryption[LUKS2_ENCRYPTION_SIZE];
/* 512, 1024, 2048, 4096 */
uint64_t sector_size;
/* Data integrity type */
struct
{
char type[LUKS2_INTEGRITY_SIZE];
char journal_encryption[LUKS2_ENCRYPTION_SIZE];
char journal_integrity[LUKS2_INTEGRITY_SIZE];
}
integrity;
}
luks2_segment_t;
typedef struct luks2_digest
{
/* Example: "pbkdf2" */
char type[LUKS2_TYPE_SIZE];
/* Keyslots that are used are non-zero in this array */
uint8_t keyslots[LUKS2_NUM_KEYSLOTS];
/* Segments that are used are non-zero in this array */
uint8_t segments[LUKS2_NUM_SEGMENTS];
/* Example: "sha256" */
char hash[VIC_HASH_SPEC_SIZE];
uint64_t iterations;
uint8_t salt[LUKS_SALT_SIZE];
uint8_t digest[LUKS2_DIGEST_SIZE];
}
luks2_digest_t;
typedef struct luks2_config
{
uint64_t json_size;
uint64_t keyslots_size;
}
luks2_config_t;
typedef struct _luks2_ext_hdr
{
/* Primary header */
luks2_hdr_t phdr;
/* Secondary header */
luks2_hdr_t shdr;
/* Binary representation of JSON objects */
luks2_keyslot_t keyslots[LUKS2_NUM_KEYSLOTS];
luks2_segment_t segments[LUKS2_NUM_SEGMENTS];
luks2_digest_t digests[LUKS2_NUM_DIGESTS];
luks2_config_t config;
/* JSON script (associated with primary header) */
size_t json_size;
char json_data[];
}
luks2_ext_hdr_t;
VIC_STATIC_ASSERT(sizeof(luks2_hdr_t) == 4096);
int luks2_read_hdr(vic_blockdev_t* device, luks2_hdr_t** hdr_out);
int luks2_dump_hdr(const luks2_hdr_t* hdr);
vic_result_t luks2_recover_master_key(
vic_blockdev_t* device,
const char* pwd,
size_t pwd_size,
vic_key_t* master_key,
size_t* master_key_bytes);
vic_result_t luks2_format(
vic_blockdev_t* device,
const char* label,
const char* subsystem,
const char* cipher,
const char* uuid,
const char* hash,
uint64_t iterations,
const vic_key_t* master_key,
size_t master_key_bytes,
const char* integrity);
vic_result_t luks2_add_key(
vic_blockdev_t* device,
const char* keyslot_cipher,
const char* kdf_type,
vic_kdf_t* kdf,
const char* pwd,
size_t pwd_size,
const char* new_pwd,
size_t new_pwd_size);
vic_result_t luks2_add_key_by_master_key(
vic_blockdev_t* device,
const char* keyslot_cipher,
const char* kdf_type,
vic_kdf_t* kdf,
const vic_key_t* master_key,
size_t master_key_bytes,
const char* pwd,
size_t pwd_size);
vic_result_t luks2_change_key(
vic_blockdev_t* device,
const char* old_pwd,
size_t old_pwd_size,
const char* new_pwd,
size_t new_pwd_size);
vic_result_t luks2_remove_key(
vic_blockdev_t* device,
const char* pwd,
size_t pwd_size);
vic_result_t luks2_stat(vic_blockdev_t* device, vic_luks_stat_t* buf);
vic_result_t luks2_open(
vic_blockdev_t* device,
const char* path,
const char* name,
const vic_key_t* master_key,
size_t master_key_bytes);
vic_result_t luks2_open_by_passphrase(
vic_blockdev_t* dev,
luks2_hdr_t* hdr,
const char* path,
const char* name,
const char* pwd,
size_t pwd_size);
#endif /* _VIC_LUKS2_H */
| 23.946502 | 75 | 0.698402 | [
"vector"
] |
e10819edf1e3a642720a4aab716c192fec2b9c18 | 246 | c | C | tests/transform/replace/replace_metadata_5/sample/main.c | dvm-system/tsar-test | b3047eaa2ad8e4d6c0ab2a86f61a596736dbd762 | [
"Apache-2.0"
] | null | null | null | tests/transform/replace/replace_metadata_5/sample/main.c | dvm-system/tsar-test | b3047eaa2ad8e4d6c0ab2a86f61a596736dbd762 | [
"Apache-2.0"
] | 11 | 2021-01-28T21:06:08.000Z | 2021-02-24T09:49:35.000Z | tests/transform/replace/replace_metadata_5/sample/main.c | zoocide/tsar-test-template | b3047eaa2ad8e4d6c0ab2a86f61a596736dbd762 | [
"Apache-2.0"
] | null | null | null | struct STy { int X; };
int bar(struct STy *S) { return S->X; }
int foo(int X, int Y) {
#pragma spf metadata replace(bar({.X=X}, Y))
return X;
}
int baz() {
struct STy S;
#pragma spf transform replace with(foo)
bar(&S);
return S.X;
}
| 15.375 | 44 | 0.601626 | [
"transform"
] |
e10ce5143e9e0543d872def28da7df82ded9105d | 438 | h | C | NinjaVsZombie/NinjaVsZombies - final/source/ImmovableBox.h | Cabrra/SPG-Project | 7602de287b750c882f9fe9e2bc57e0492d36a76f | [
"MIT"
] | null | null | null | NinjaVsZombie/NinjaVsZombies - final/source/ImmovableBox.h | Cabrra/SPG-Project | 7602de287b750c882f9fe9e2bc57e0492d36a76f | [
"MIT"
] | null | null | null | NinjaVsZombie/NinjaVsZombies - final/source/ImmovableBox.h | Cabrra/SPG-Project | 7602de287b750c882f9fe9e2bc57e0492d36a76f | [
"MIT"
] | null | null | null | #pragma once
#include "Unbreakable.h"
class Hook;
class ImmovableBox:
public Unbreakable
{
Hook* m_hook = nullptr;
public:
ImmovableBox();
~ImmovableBox();
virtual void Update(float elapsedTime) override;
virtual void Render(void) override;
virtual int GetType(void) const override { return ENT_IMMOVABLE; }
virtual void HandleCollision(const IEntity* pOther) override;
void SetHook(Hook* hook) { m_hook = hook; }
}; | 21.9 | 70 | 0.737443 | [
"render"
] |
e1175fc26b84ee1457ddf7cb882518e5e53ce179 | 1,324 | h | C | eagleeye/processnode/AdaptorNode.h | MirrorYu/eagleeye | c251e7b3bc919673b41360212c38d5fda85bbe2f | [
"Apache-2.0"
] | 12 | 2020-09-21T02:24:11.000Z | 2022-03-10T03:02:03.000Z | eagleeye/processnode/AdaptorNode.h | nihui/eagleeye | eeb69204b7322e79904a4406b44d61a1a30a5c9a | [
"Apache-2.0"
] | 1 | 2020-11-30T08:22:50.000Z | 2020-11-30T08:22:50.000Z | eagleeye/processnode/AdaptorNode.h | nihui/eagleeye | eeb69204b7322e79904a4406b44d61a1a30a5c9a | [
"Apache-2.0"
] | 3 | 2020-03-16T12:10:55.000Z | 2021-07-20T09:58:15.000Z | #ifndef _EAGLEEYE_ADAPTORNODE_H_
#define _EAGLEEYE_ADAPTORNODE_H_
#include "eagleeye/common/EagleeyeMacro.h"
#include "eagleeye/framework/pipeline/AnyNode.h"
#include "eagleeye/basic/Array.h"
#include "eagleeye/basic/Matrix.h"
namespace eagleeye{
/**
* @brief define condition function type
*
*/
typedef void (*AdaptorFunc)(std::vector<AnySignal*> input_sigs, std::vector<AnySignal*> output_sigs);
class AdaptorNode:public AnyNode{
public:
typedef AdaptorNode Self;
typedef AnyNode Superclass;
AdaptorNode(int input_sigs_num, int output_sigs_num, AdaptorFunc func);
virtual ~AdaptorNode();
EAGLEEYE_CLASSIDENTITY(AdaptorNode);
template<class TargetT>
void configureOutputSignal(int port_index){
assert(port_index < this->getNumberOfOutputSignals());
// 设置输出端口(端口0)及携带数据类型(TargetT)
this->setOutputPort(new TargetT, port_index);
}
/**
* @brief execute image process
*
*/
virtual void executeNodeInfo();
/**
* @brief make self check
* @note judge whether some preliminary conditions have been satisfied.
*/
virtual bool selfcheck(){
return true;
}
private:
AdaptorNode(const AdaptorNode&);
void operator=(const AdaptorNode&);
AdaptorFunc m_adaptor_func;
};
}
#endif | 24.981132 | 101 | 0.694109 | [
"vector"
] |
e118300fa338468765dd0c14fd61989ebdb06018 | 6,224 | c | C | external/source/exploits/drunkpotato/Common_Src_Files/LocalNegotiator.c | OsmanDere/metasploit-framework | b7a014a5d22d3b57157e301d4af57e3a31ad03a9 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 26,932 | 2015-01-01T00:04:51.000Z | 2022-03-31T22:51:38.000Z | external/source/exploits/drunkpotato/Common_Src_Files/LocalNegotiator.c | Kilo-411/metasploit-framework | aaf27d7fa51390895dea63c58cb3b76e959d36f8 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 11,048 | 2015-01-01T00:05:44.000Z | 2022-03-31T21:49:52.000Z | external/source/exploits/drunkpotato/Common_Src_Files/LocalNegotiator.c | Kilo-411/metasploit-framework | aaf27d7fa51390895dea63c58cb3b76e959d36f8 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 12,593 | 2015-01-01T01:01:20.000Z | 2022-03-31T22:13:32.000Z | /**
This module is a plain C class emulation. The POC written by decoder was in cpp and used some classes
in particular for the local negotiator.
See https://stackoverflow.com/questions/40992945/convert-a-cpp-class-cpp-file-into-a-c-structure-c-file
for how I emulated a class in pure C.
The local negotiator is an object used to handle security an client-server negotiation data. In this
exploit, it is used by elevatorService.c (Rogue WinRM service) in order to store security context
obtained when BITS shoots the Rogue WinRM service, and is required by this service to authenticate.
*/
#include "pch.h"
/**
Constructor of the LocalNegotiator class. Setup the addresses of class methods,
and initialize some arguments
@param LocalNegotiator* this Address of the instantiated object.
*/
void Init(LocalNegotiator* this)
{
/* Cleaning everything. This is not very useful as we calloc-ed LocalNegotiator,
but this is in the case somebody would reuse this function or change the code elswhere.*/
ZeroMemory(this, sizeof(LocalNegotiator));
// linking of class methods
this->destruct = &destructNegotiator;
this->processNtlmBytes = &processNtlmBytes;
this->handleType1 = &HandleType1;
this->handleType3 = &HandleType3;
this->returnType2 = &ReturnType2;
// Initialization of attributes
this->phContext = (PCtxtHandle)calloc(1, sizeof(CtxtHandle));
this->authResult = -1;
return;
}
/**
destructor of the LocalNegotiator Class. Free allocated memory
@param LocalNegotiator* this Address of the instantiated object.
*/
void destructNegotiator(LocalNegotiator* this)
{
free(this->phContext);
this->phContext = NULL;
free(this);
return;
}
/**
This static function is a router which process NTLM request bytes according to if it is a
NTLM 1 or 3 request (for calling a security context through handleType in localNegotiator
object.
@param LocalNegotiator* this Address of negotiator object
@param char* ntlmBytes Address of buffer hosting raw bytes of NTLM request
@param unsigned short len Length of previous buffer argument
@return int Error code. 0 for success.
*/
static int processNtlmBytes(LocalNegotiator* this, char* ntlmBytes, unsigned short len)
{
int messageType = ntlmBytes[8];
switch (messageType)
{
case 1:
//NTLM type 1 message
dprintf("[processNtlmBytes] -- handleType1 start --");
this->handleType1(this, ntlmBytes, len);
dprintf("[processNtlmBytes] -- handleType1 end --");
break;
case 3:
//NTLM type 3 message
dprintf("[processNtlmBytes] -- handleType3 start --");
this->handleType3(this, ntlmBytes, len);
dprintf("[processNtlmBytes] -- handleType3 end --");
break;
default:
dprintf("[processNtlmBytes] ERROR: unknown NTLM message type...");
return -1;
break;
}
return 0;
}
/**
Process the data sent by the first request of BITS server (ntlmBytes)
by creating a security context stored in the local negotiator instance.
@param LocalNegotiator* this Address of the instantiated object.
@param char* ntlmBytes packet sent by BITS server
@param unsigned short len length of packet sent by BITS (length of prev argument)
@return int Error code. 0 for success.
*/
static int HandleType1(LocalNegotiator* this, char* ntlmBytes, unsigned short len)
{
int status = -1;
LPSTR lpPackageName = "Negotiate";
TimeStamp ptsExpiry;
TimeStamp tsContextExpiry;
ULONG fContextAttr;
status = AcquireCredentialsHandleA
(
NULL,
lpPackageName,
SECPKG_CRED_INBOUND,
NULL,
NULL,
0,
NULL,
&this->hCred,
&ptsExpiry
);
if (status != SEC_E_OK)
{
dprintf("[HandleType1] ERROR: AcquireCredentialsHandleA return value: 0x%x", status);
return -1;
}
InitTokenContextBuffer(&this->secClientBufferDesc, &this->secClientBuffer);
InitTokenContextBuffer(&this->secServerBufferDesc, &this->secServerBuffer);
this->secClientBuffer.cbBuffer = len;
this->secClientBuffer.pvBuffer = ntlmBytes;
status = AcceptSecurityContext
(
&this->hCred,
NULL,
&this->secClientBufferDesc,
ASC_REQ_ALLOCATE_MEMORY | ASC_REQ_CONNECTION,
//STANDARD_CONTEXT_ATTRIBUTES,
SECURITY_NATIVE_DREP,
this->phContext,
&this->secServerBufferDesc,
&fContextAttr,
&tsContextExpiry
);
dprintf("[HandleType1] Result of AcceptSecurityContext() = status: 0x%x--", status);
return status;
}
/**
Process the data sent by the second request of BITS server, when it answer to the challenge-response
proposed by the rogue WinRM service (elevatorService.c) by creating a security context stored in the
local negotiator instance. This security context will be used later to steal a SYSTEM token.
@param LocalNegotiator* this Address of the instantiated object.
@param char* ntlmBytes packet sent by BITS server
@param unsigned short len length of packet sent by BITS (length of prev argument)
@return int Error code. 0 for success.
*/
static int HandleType3(LocalNegotiator* this, char* ntlmBytes, unsigned short len)
{
InitTokenContextBuffer(&this->secClientBufferDesc, &this->secClientBuffer);
InitTokenContextBuffer(&this->secServerBufferDesc, &this->secServerBuffer);
this->secClientBuffer.cbBuffer = len;
this->secClientBuffer.pvBuffer = ntlmBytes;
ULONG fContextAttr;
TimeStamp tsContextExpiry;
int status = AcceptSecurityContext
(
&this->hCred,
this->phContext,
&this->secClientBufferDesc,
ASC_REQ_ALLOCATE_MEMORY | ASC_REQ_CONNECTION,
//STANDARD_CONTEXT_ATTRIBUTES,
SECURITY_NATIVE_DREP,
this->phContext,
&this->secServerBufferDesc,
&fContextAttr,
&tsContextExpiry
);
this->authResult = status;
dprintf("[HandleType3] Result of AcceptSecurityContext() = status: 0x%x--", status);
return status;
}
static char* ReturnType2(LocalNegotiator* this, unsigned short* outbuffer_len)
{
*outbuffer_len = (unsigned short)this->secServerBuffer.cbBuffer;
return (char*)this->secServerBuffer.pvBuffer;
}
static void InitTokenContextBuffer(PSecBufferDesc pSecBufferDesc, PSecBuffer pSecBuffer)
{
pSecBuffer->BufferType = SECBUFFER_TOKEN;
pSecBuffer->cbBuffer = 0;
pSecBuffer->pvBuffer = NULL;
pSecBufferDesc->ulVersion = SECBUFFER_VERSION;
pSecBufferDesc->cBuffers = 1;
pSecBufferDesc->pBuffers = pSecBuffer;
}
| 27.785714 | 104 | 0.751767 | [
"object"
] |
e119add1f0bc20f5e13097c91e0c4b38be75cef8 | 4,891 | h | C | krembot/src/krembot/rgba_sensor.h | yiftachn/krembot_sim_fork | d3d1b050f9fff4c96bded298eadde5a9ca4dab6b | [
"MIT"
] | null | null | null | krembot/src/krembot/rgba_sensor.h | yiftachn/krembot_sim_fork | d3d1b050f9fff4c96bded298eadde5a9ca4dab6b | [
"MIT"
] | null | null | null | krembot/src/krembot/rgba_sensor.h | yiftachn/krembot_sim_fork | d3d1b050f9fff4c96bded298eadde5a9ca4dab6b | [
"MIT"
] | null | null | null | /*******************************************************************************
* Copyright (c) 2019, Elhay Rauper.
* All rights reserved.
*
* This code API is based on Robotican's Krembot library, which can be found here:
* https://github.com/robotican/krembot
*
* 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 Elhay Rauper 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 FOOTBOT_DIFFUSION_RGBA_SENSOR_H
#define FOOTBOT_DIFFUSION_RGBA_SENSOR_H
#include <stdint.h>
#include <string>
#include <argos3/plugins/robots/foot-bot/control_interface/ci_footbot_proximity_sensor.h>
#include <argos3/plugins/robots/generic/control_interface/ci_colored_blob_omnidirectional_camera_sensor.h>
#include <argos3/plugins/robots/foot-bot/control_interface/ci_footbot_light_sensor.h>
/* RGBA sensor location and ID number:
*
* 0
* 1 7
* 2 6
* 3 5
* 4
*/
/* footbot width is 17 cm and krembot width is 6.5 cm
* -> that cause different behavior when the robots based on this information
* a temporary solution - sense the distance in the same proportion
* and then, return it to the proportions of the original sensor
* (so that the robots' code works in the same way)
* */
using namespace argos;
struct RGBAResult
{
uint8_t Ambient = 0; /**< The Ambience of the light, (0-65535)*/
uint16_t Red = 0; /**< The Red value of the light, (0-65535)*/
uint16_t Green = 0; /**< The Green value of the light, (0-65535)*/
uint16_t Blue = 0; /**< The Blue value of the light, (0-65535)*/
uint16_t Proximity = 0; /**< The Raw value of the proximity sensor, (0-255)*/
float Distance = 0; /**< The calculated distance to the object, in cm*/
bool AmbientError = false;
bool RedError = false;
bool GreenError = false;
bool BlueError = false;
bool ProximityError = false;
};
struct HSVResult
{
double H, S, V;
};
enum Colors
{
Red,
Green,
Blue,
Yellow,
Magenta,
None
};
class RGBASensor
{
private:
uint8_t m_index = 0;
std::string m_name = "";
argos::CRange<argos::CRadians> m_ColorSensorAngularRange;
argos::CCI_FootBotProximitySensor * m_cProximity = nullptr;
argos::CCI_FootBotLightSensor * m_Light = nullptr;
argos::CCI_ColoredBlobOmnidirectionalCameraSensor * m_ColorCam = nullptr;
argos::CRange<Real> m_ProxRange;
argos::CRange<Real> m_DistRange;
static Real DISTANCE_RATIO_KREMBOT;
float footbotDistanceToKrembotDistanceProximity(argos::Real footbot_distance);
float footbotDistanceToKrembotDistanceColorCam(argos::Real footbot_distance);
public:
RGBASensor();
void init(const std::string name,
uint8_t index,
argos::CCI_FootBotProximitySensor * proximity,
argos::CCI_FootBotLightSensor * light,
argos::CCI_ColoredBlobOmnidirectionalCameraSensor * colorCam);
RGBAResult readRGBA();
HSVResult readHSV();
Colors readColor();
static HSVResult rgbToHSV(RGBAResult in);
void printRGBA();
void printHSV();
void printColor();
void print();
/*
* Mock-up functions
*/
inline void publish() { }
argos::CCI_ColoredBlobOmnidirectionalCameraSensor * getCamPtr()
{
return m_ColorCam;
}
static void set_DISTANCE_RATIO_KREMBOT(Real _DISTANCE_RATIO_KREMBOT);
};
#endif //FOOTBOT_DIFFUSION_RGBA_SENSOR_H
| 31.352564 | 106 | 0.69127 | [
"object"
] |
e12b8e80e40080e09cbb4b852fdc0a0f134fcb29 | 2,600 | h | C | include/bvh-parser.h | tyoungroy/bvh-parser | 3c3ab58c58d5b8c61c24ad19c3e181ec263408b4 | [
"Apache-2.0"
] | 22 | 2017-10-27T11:36:51.000Z | 2022-01-11T12:43:17.000Z | include/bvh-parser.h | tyoungroy/bvh-parser | 3c3ab58c58d5b8c61c24ad19c3e181ec263408b4 | [
"Apache-2.0"
] | null | null | null | include/bvh-parser.h | tyoungroy/bvh-parser | 3c3ab58c58d5b8c61c24ad19c3e181ec263408b4 | [
"Apache-2.0"
] | 7 | 2018-05-03T08:27:05.000Z | 2021-11-27T15:54:24.000Z | #ifndef BVH_PARSER_H
#define BVH_PARSER_H
#include "bvh.h"
#include "joint.h"
#include <algorithm>
#include <boost/filesystem.hpp>
#include <functional>
#include <locale>
#include <memory>
namespace bf = boost::filesystem;
namespace bvh {
/** Bvh Parser class that is responsible for parsing .bvh file */
class Bvh_parser {
public:
/** Parses single bvh file and stored data into bvh structure
* @param path The path to file to be parsed
* @param bvh The pointer to bvh object where parsed data will be stored
* @return 0 if success, -1 otherwise
*/
int parse(const bf::path& path, Bvh* bvh);
private:
/** Parses single hierarchy in bvh file
* @param file The input stream that is needed for reading file content
* @return 0 if success, -1 otherwise
*/
int parse_hierarchy(std::ifstream& file);
/** Parses joint and its children in bvh file
* @param file The input stream that is needed for reading file content
* @param parent The pointer to parent joint
* @param parsed The output parameter, here will be stored parsed joint
* @return 0 if success, -1 otherwise
*/
int parse_joint(std::ifstream& file, std::shared_ptr <Joint> parent,
std::shared_ptr <Joint>& parsed);
/** Parses order of channel for single joint
* @param file The input stream that is needed for reading file content
* @param joint The pointer to joint that channels order will be parsed
* @return 0 if success, -1 otherwise
*/
int parse_channel_order(std::ifstream& file, std::shared_ptr <Joint> joint);
/** Parses motion part data
* @param file The input stream that is needed for reading file content
* @return 0 if success, -1 otherwise
*/
int parse_motion(std::ifstream& file);
/** Trims the string, removes leading and trailing whitespace from it
* @param s The string, which leading and trailing whitespace will be
* trimmed
*/
inline void trim(std::string &s) {
s.erase( std::remove_if( s.begin(), s.end(),
std::bind( std::isspace<char>, std::placeholders::_1,
std::locale::classic() ) ), s.end() );
}
/** Converts the vector of float to string, ex. "el1, el2, el3"
* @param vector The data that will be converted to string
* @return The string that will be created from input data
*/
std::string vtos(const std::vector <float> &vector);
/** The path to file that was parsed previously */
bf::path path_;
/** The bvh object to store parsed data */
Bvh* bvh_;
};
} // namespace
#endif // BVH_PARSER_H
| 32.098765 | 78 | 0.671923 | [
"object",
"vector"
] |
e132d011411ab70e3b5bd89a4473ac4730e1663b | 3,250 | h | C | src/zerork/info_net.h | LLNL/zero-rk | b3e505efd77adc3eab3b1fce6283355f216112e3 | [
"BSD-3-Clause"
] | 23 | 2019-09-13T16:38:56.000Z | 2022-03-30T19:39:14.000Z | src/zerork/info_net.h | LLNL/zero-rk | b3e505efd77adc3eab3b1fce6283355f216112e3 | [
"BSD-3-Clause"
] | 4 | 2021-02-21T16:52:38.000Z | 2022-01-19T00:22:21.000Z | src/zerork/info_net.h | LLNL/zero-rk | b3e505efd77adc3eab3b1fce6283355f216112e3 | [
"BSD-3-Clause"
] | 15 | 2019-08-15T01:47:55.000Z | 2022-03-10T13:36:23.000Z | #ifndef ZERORK_INFO_NET_H
#define ZERORK_INFO_NET_H
#include "../CKconverter/CKReader.h"
#include "species.h"
#include "non_integer_reaction_network.h"
namespace zerork {
typedef struct
{
std::vector<int> index;
std::vector<double> alpha;
} EnhancedSpecies;
class info_net
{
public:
info_net(ckr::CKReader *ckrobj);
~info_net();
int getNumRxn() const {return nRxn;}
int getNumSteps() const {return nStep;}
int getTotalReactants() const {return totReactant;}
int getTotalProducts() const {return totProduct;}
int getMaxProductsInStep() const {return maxProductInStep;}
int getMaxReactantsInStep() const {return maxReactantInStep;}
int getNumEnhancedSpeciesOfStep(const int id) const
{return enhanced_species_of_step[id].index.size();}
int getEnhancementFactorsOfStep(const int id,
std::vector<int> *species_id,
std::vector<double> *alpha);
int getRxnIdxOfStep(int id) const {return rxnIdxOfStep[id]%nRxn;}
int getRxnDirOfStep(int id) const
{return ((rxnIdxOfStep[id]<nRxn) ? 1 : -1);}
int getStepIdxOfRxn(int id, int dir) const
{return ((dir > 0) ? stepIdxOfFwdRxn[id] : stepIdxOfRevRxn[id]);}
// getOrderOfStep and getNumProductsOfStep return zero if the step
// is a non-integer reaction
int getOrderOfStep(int id) const {return nReactantOfStep[id];}
int getNumProductsOfStep(int id) const {return nProductOfStep[id];}
// getRealOrderOfStep return the real number of the step for exact
// conversion of the rate constant
double getRealOrderOfStep(int id) const;
// bound check safe
int getSpecIdxOfStepReactant(const int stepId, const int reacId) const;
int getSpecIdxOfStepProduct(const int stepId, const int prodId) const;
int getReversibleFlagOfReaction(int id) const {return isReversible[id];}
int getThirdBodyFlagOfReaction(int id) const {return isThirdBody[id];}
int getFalloffFlagOfReaction(int id) const {return isFalloff[id];}
int getNonIntegerStoichFlagOfReaction(int id) const
{return isNonIntegerStoich[id];}
NonIntegerReactionNetwork getNonIntegerReactionNetwork() const
{return non_integer_network;}
void print(const species *spcList);
private:
// reaction index <-> step index maps
int nRxn;
int *stepIdxOfFwdRxn;
int *stepIdxOfRevRxn;
int *rxnIdxOfStep;
int setRxnStepIdxMaps(ckr::CKReader *ckrobj);
int SetEnhancedSpeciesList(ckr::CKReader *ckrobj);
// reaction participant species info:
int nStep;
int totProduct;
int totReactant;
int maxProductInStep;
int maxReactantInStep;
int *nReactantOfStep;
int *nProductOfStep;
int *addrReactantOfStep;
int *addrProductOfStep;
int *reactantSpcIdx;
int *productSpcIdx;
int *isReversible; // (0,1)
int *isThirdBody; // (0,1)
int *isFalloff; // (-1 = yes, M, 0 = no, spcId + 1 = yes, falloff species)
int *isEnhanced; // (0,1)
int *isNonIntegerStoich; // (0,1)
std::vector<EnhancedSpecies> enhanced_species_of_step;
NonIntegerReactionNetwork non_integer_network;
int setParticipants(ckr::CKReader *ckrobj);
int spcIdxOfString(ckr::CKReader &ckrobj, string spcName);
void setReactionFlags(ckr::CKReader *ckrobj);
};
} // namespace zerork
#endif
| 31.553398 | 79 | 0.726769 | [
"vector"
] |
e13b37722d0797f9e808dd73518d0ec6f50668ff | 649 | h | C | silk_engine/src/gfx/allocators/query_pool.h | GeorgeAzma/VulkanEngine | 0c2279682f526f428b44eae2a82be6933c74320d | [
"MIT"
] | 1 | 2022-02-11T12:49:49.000Z | 2022-02-11T12:49:49.000Z | silk_engine/src/gfx/allocators/query_pool.h | GeorgeAzma/VulkanEngine | 0c2279682f526f428b44eae2a82be6933c74320d | [
"MIT"
] | null | null | null | silk_engine/src/gfx/allocators/query_pool.h | GeorgeAzma/VulkanEngine | 0c2279682f526f428b44eae2a82be6933c74320d | [
"MIT"
] | null | null | null | #pragma once
class QueryPool
{
public:
QueryPool(VkQueryType query_type = VK_QUERY_TYPE_OCCLUSION, uint32_t query_count = 1, VkQueryPipelineStatisticFlags pipeline_statistic_flags = 0);
~QueryPool();
void begin(uint32_t index = 0, VkQueryControlFlags flags = VK_QUERY_CONTROL_PRECISE_BIT);
void end(uint32_t index = 0);
uint64_t getResult(uint32_t index = 0, bool wait = false);
operator const VkQueryPool& () const { return query_pool; }
private:
VkQueryPool query_pool = VK_NULL_HANDLE;
VkQueryType query_type;
VkQueryPipelineStatisticFlags pipeline_statistic_flags;
std::vector<VkBool32> queries;
std::vector<uint64_t> results;
}; | 29.5 | 147 | 0.793529 | [
"vector"
] |
e1439c6172966343ebe42b54b1299d22c728113c | 6,182 | h | C | src/c/convolution/Neuron.h | pcPowerJG/natural-network | 062840ee888b4fc374c9828e4197775485d18b61 | [
"MIT"
] | 3 | 2019-04-15T13:57:31.000Z | 2021-05-17T03:35:39.000Z | src/c/convolution/Neuron.h | pcPowerJG/natural-network | 062840ee888b4fc374c9828e4197775485d18b61 | [
"MIT"
] | null | null | null | src/c/convolution/Neuron.h | pcPowerJG/natural-network | 062840ee888b4fc374c9828e4197775485d18b61 | [
"MIT"
] | 1 | 2022-02-24T08:27:11.000Z | 2022-02-24T08:27:11.000Z | #pragma once
#include <iostream>
#include <vector>
#include <fstream>
#include <assert.h>
using namespace std;
struct Connection {
double weight;
double deltaWeight;
};
class Neuron;
typedef vector<Neuron> Layer;
class Neuron {
public:
Neuron(unsigned numOutputs, unsigned myIndex);
Neuron(vector<double> &outputWeights, unsigned myIndex);
Neuron();
Neuron(unsigned pX, unsigned pY, int c);
void setOutputVal(double val) { n_outputVal = val; }
double getOutputVal(void) const { return n_outputVal; }
void feedForward(const Layer &prevLayer);
void feedForward(vector<vector<Neuron>> &prevLayer, vector<vector<double>> &fW, double &bias);
void calcOutputGradients(double targetVal);
void calcHiddenGradients(const Layer &nextLayer);
double sumDOW(const Layer &nextLayer) const;
void updateInputWeights(Layer &prevLayer);
void updateInputWeights(vector<vector<Neuron>> &prevLayer, vector<vector<double>> &fW, double &bias, int currentLayerSize);
void updatePrevLayerGradient(vector<vector<Neuron>> &prevLayer, vector<vector<double>> &fW);
void setGradient(double grad) { n_gradient = grad; }
double getGradient() { return n_gradient; }
unsigned getConvX() { return convX; }
unsigned getConvY() { return convY; }
void setConvCoord(unsigned x, unsigned y) { convX = x; convY = y; }
void storeNeuron(vector<double> &weights);
void addGradient(double grad) { n_gradient += grad; }
private:
static double transferFunction(double x);
static double transferFunctionDerivative(double x);
static double randomWeight(void) { return rand() / (double(RAND_MAX)); }
static double eta; // 0.0 to 1.0
static double alpha; //0.0 to n
static int batchSize;
double n_outputVal;
int batchCount;
vector<Connection> n_outputWeights;
unsigned n_myIndex;
double n_gradient;
vector<double> storeGradient;
//conv neuron
unsigned posX, posY; //start pos on prev layer
double biasGrad;
//pool neuron
unsigned convX, convY;
};
double Neuron::eta = 0.015;
double Neuron::alpha = 0.5;
int Neuron::batchSize = 1;
void Neuron::updateInputWeights(Layer &prevLayer) {
for (unsigned n = 0; n < prevLayer.size(); n++) {
Neuron &neuron = prevLayer[n];
if (storeGradient.size() < n + 1) {
storeGradient.push_back(0.0);
}
storeGradient[n] += neuron.getOutputVal()*n_gradient;
batchCount++;
if (batchCount == ((batchSize - 1)*prevLayer.size()) + n + 1) {
neuron.n_outputWeights[n_myIndex].weight += eta * storeGradient[n] / batchSize;
storeGradient[n] = 0.0;
}
}
if (batchCount == batchSize * prevLayer.size()) {
batchCount = 0;
}
}
void Neuron::updateInputWeights(vector<vector<Neuron>> &prevLayer, vector<vector<double>> &fW, double &bias, int currentLayerSize) {
for (int y = 0; y < fW.size(); y++) {
for (int x = 0; x < fW[y].size(); x++) {
if (storeGradient.size() < (fW[0].size()*y) + x + 1) {
storeGradient.push_back(0.0);
}
storeGradient[(y*fW[0].size()) + x] += prevLayer[posY + y][posX + x].getOutputVal() * n_gradient;
batchCount++;
if (batchCount == (batchSize - 1)*(fW.size()*fW[0].size()) + (y*fW[0].size()) + x + 1) {
fW[y][x] += eta * storeGradient[(y*fW[0].size()) + x] / (batchSize);
storeGradient[(y*fW[0].size()) + x] = 0.0;
}
}
}
biasGrad += n_gradient;
if (batchCount == batchSize * fW.size() * fW[0].size()) {
bias += eta * biasGrad / (batchSize * currentLayerSize);
biasGrad = 0;
batchCount = 0;
}
}
double Neuron::sumDOW(const Layer &nextLayer) const {
double sum = 0.0;
for (unsigned n = 0; n < nextLayer.size() - 1; n++) {
sum += n_outputWeights[n].weight * nextLayer[n].n_gradient;
}
return sum;
}
void Neuron::calcHiddenGradients(const Layer &nextLayer) {
double dow = sumDOW(nextLayer);
n_gradient = dow * Neuron::transferFunctionDerivative(n_outputVal);
}
void Neuron::calcOutputGradients(double targetVals) {
//n_gradient = ((targetVals / n_outputVal) - ((1 - targetVals) / (1 - n_outputVal))) * Neuron::transferFunctionDerivative(n_outputVal); //sigmoid cross entropy cost func
//n_gradient = (targetVals - n_outputVal) * Neuron::transferFunctionDerivative(n_outputVal); //quad cost func
n_gradient = targetVals - n_outputVal; //cross entropy cost func for both sigmoid and tanh
}
double Neuron::transferFunction(double x) {
//return tanh(x);
return 1.0 / (1.0 + exp(-x));
}
double Neuron::transferFunctionDerivative(double x) {
//return 1.0-(x*x); //aprox. for domain
return x - (x*x);
}
void Neuron::feedForward(const Layer &prevLayer) {
double sum = 0.0;
for (unsigned n = 0; n < prevLayer.size(); n++) {
sum += prevLayer[n].getOutputVal() * prevLayer[n].n_outputWeights[n_myIndex].weight;
}
n_outputVal = Neuron::transferFunction(sum); //activation function
}
void Neuron::feedForward(vector<vector<Neuron>> &prevLayer, vector<vector<double>> &fW, double &bias) {
double sum = 0.0;
for (unsigned sY = 0; sY < fW.size(); sY++) {
for (unsigned sX = 0; sX < fW[0].size(); sX++) {
sum += prevLayer[sY + posY][sX + posX].getOutputVal() * fW[sY][sX];
}
}
sum += bias;
n_outputVal = Neuron::transferFunction(sum);
}
Neuron::Neuron(unsigned numOutputs, unsigned myIndex) {
for (unsigned c = 0; c < numOutputs; c++) {
n_outputWeights.push_back(Connection());
n_outputWeights.back().weight = randomWeight();
}
n_myIndex = myIndex;
batchCount = 0;
}
Neuron::Neuron() {
batchCount = 0;
}
Neuron::Neuron(unsigned pX, unsigned pY, int c) {
posX = pX;
posY = pY;
batchCount = 0;
biasGrad = 0;
}
Neuron::Neuron(vector<double> &outputWeights, unsigned myIndex) {
n_myIndex = myIndex;
batchCount = 0;
for (unsigned c = 0; c < outputWeights.size(); c++) {
n_outputWeights.push_back(Connection());
n_outputWeights.back().weight = outputWeights[c];
}
}
void Neuron::storeNeuron(vector<double> &weights) {
weights.clear();
for (int w = 0; w < n_outputWeights.size(); w++) {
weights.push_back(n_outputWeights[w].weight);
//weights.push_back(n_outputWeights[w].weight);
}
}
void Neuron::updatePrevLayerGradient(vector<vector<Neuron>> &prevLayer, vector<vector<double>> &fW) {
for (int y = 0; y < fW.size(); y++) {
for (int x = 0; x < fW[y].size(); x++) {
prevLayer[y + posY][x + posX].addGradient(n_gradient * fW[y][x]);
}
}
} | 35.325714 | 170 | 0.689097 | [
"vector"
] |
e15223e993ef32e13a5a3d154f0c9b8819bc1a43 | 2,991 | h | C | services/network/tcp_server_socket.h | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | services/network/tcp_server_socket.h | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | services/network/tcp_server_socket.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 SERVICES_NETWORK_TCP_SERVER_SOCKET_H_
#define SERVICES_NETWORK_TCP_SERVER_SOCKET_H_
#include <memory>
#include <vector>
#include "base/component_export.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "mojo/public/cpp/bindings/interface_request.h"
#include "net/base/ip_endpoint.h"
#include "net/traffic_annotation/network_traffic_annotation.h"
#include "services/network/public/mojom/tcp_socket.mojom.h"
namespace net {
class NetLog;
class ServerSocket;
class StreamSocket;
} // namespace net
namespace network {
class TCPConnectedSocket;
class COMPONENT_EXPORT(NETWORK_SERVICE) TCPServerSocket
: public mojom::TCPServerSocket {
public:
// A delegate interface that is notified when new connections are established.
class Delegate {
public:
Delegate() {}
~Delegate() {}
// Invoked when a new connection is accepted. The delegate should take
// ownership of |socket| and set up binding for |request|.
virtual void OnAccept(std::unique_ptr<TCPConnectedSocket> socket,
mojom::TCPConnectedSocketRequest request) = 0;
};
// Constructs a TCPServerSocket. |delegate| must outlive |this|. When a new
// connection is accepted, |delegate| will be notified to take ownership of
// the connection.
TCPServerSocket(Delegate* delegate,
net::NetLog* net_log,
const net::NetworkTrafficAnnotationTag& traffic_annotation);
~TCPServerSocket() override;
int Listen(const net::IPEndPoint& local_addr,
int backlog,
net::IPEndPoint* local_addr_out);
// TCPServerSocket implementation.
void Accept(mojom::SocketObserverPtr observer,
AcceptCallback callback) override;
void GetLocalAddress(GetLocalAddressCallback callback) override;
// Replaces the underlying socket implementation with |socket| in tests.
void SetSocketForTest(std::unique_ptr<net::ServerSocket> socket);
private:
struct PendingAccept {
PendingAccept(AcceptCallback callback, mojom::SocketObserverPtr observer);
~PendingAccept();
AcceptCallback callback;
mojom::SocketObserverPtr observer;
};
// Invoked when socket_->Accept() completes.
void OnAcceptCompleted(int result);
// Process the next Accept() from |pending_accepts_queue_|.
void ProcessNextAccept();
Delegate* const delegate_;
std::unique_ptr<net::ServerSocket> socket_;
int backlog_;
std::vector<std::unique_ptr<PendingAccept>> pending_accepts_queue_;
std::unique_ptr<net::StreamSocket> accepted_socket_;
net::NetworkTrafficAnnotationTag traffic_annotation_;
base::WeakPtrFactory<TCPServerSocket> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(TCPServerSocket);
};
} // namespace network
#endif // SERVICES_NETWORK_TCP_SERVER_SOCKET_H_
| 32.51087 | 80 | 0.748245 | [
"vector"
] |
e15f3b7b6990472cc0ff601fe767d6084e98f26f | 2,464 | h | C | src/interfaces/media/irestorableradiostationprovider.h | Maledictus/leechcraft | 79ec64824de11780b8e8bdfd5d8a2f3514158b12 | [
"BSL-1.0"
] | 120 | 2015-01-22T14:10:39.000Z | 2021-11-25T12:57:16.000Z | src/interfaces/media/irestorableradiostationprovider.h | Maledictus/leechcraft | 79ec64824de11780b8e8bdfd5d8a2f3514158b12 | [
"BSL-1.0"
] | 8 | 2015-02-07T19:38:19.000Z | 2017-11-30T20:18:28.000Z | src/interfaces/media/irestorableradiostationprovider.h | Maledictus/leechcraft | 79ec64824de11780b8e8bdfd5d8a2f3514158b12 | [
"BSL-1.0"
] | 33 | 2015-02-07T16:59:55.000Z | 2021-10-12T00:36:40.000Z | /**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2006-2014 Georg Rudoy
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt)
**********************************************************************/
#pragma once
#include <variant>
#include <QtPlugin>
#include "iradiostation.h"
template<typename>
class QFuture;
namespace Media
{
struct AudioInfo;
/** @brief Describes the data associated with a radio station restore.
*
* For now it can be just a list of AudioInfo structs.
*
* @sa AudioInfo
*/
using RadioRestoreVariant_t = std::variant<QList<AudioInfo>>;
/** @brief Describes the result of restoring a single radio station.
*
* The radio stations are identified by Media::RadioItemRole::RadioID.
*/
struct RadioRestoreResult
{
/** @brief The plugin this RadioRestoreResult corresponds to.
*/
QString PluginID_;
/** @brief The radio station this RadioRestoreResult describes.
*
* This field is equal to some Media::RadioItemRole::RadioID.
*/
QString RadioID_;
/** @brief The restore result itself.
*/
RadioRestoreVariant_t Restored_;
};
/** @brief A list of RadioRestoreResult structs.
*/
using RadiosRestoreResult_t = QList<RadioRestoreResult>;
/** @brief Interface for radio station providers able to restore the
* radio stations between LeechCraft runs.
*
* An example of such a provider could be the VKontakte streamer. The
* links to the songs die after a certain amount of time, but still
* it's desirable to allow restoring the list of tracks.
*
* @sa IRadioStationProvider
*/
class IRestorableRadioStationProvider
{
protected:
virtual ~IRestorableRadioStationProvider () {}
public:
/** @brief Initiates restoring the radio stations for the given
* IDs.
*
* The IDs are the ones exposed by the provider via the
* Media::RadioItemRole::RadioID model role.
*
* @param[in] ids The list of radio IDs to restore.
* @return The future providing a list of RadioRestoreResult
* structs.
*
* @sa RadioRestoreResult
*/
virtual QFuture<RadiosRestoreResult_t> RestoreRadioStations (const QStringList& ids) = 0;
};
}
Q_DECLARE_INTERFACE (Media::IRestorableRadioStationProvider, "org.LeechCraft.Media.IRestorableRadioStationProvider/1.0")
| 28.651163 | 120 | 0.686688 | [
"model"
] |
e15f8cd3c8c4fa7f3ca5563955b431612d76c954 | 413 | h | C | test/RandomHelpers.h | BBN-Q/libaps2 | 7787c821279deeca14108d7ac9a49992c64fffe9 | [
"Apache-2.0"
] | 4 | 2015-01-21T22:21:55.000Z | 2017-06-30T08:30:11.000Z | test/RandomHelpers.h | BBN-Q/libaps2 | 7787c821279deeca14108d7ac9a49992c64fffe9 | [
"Apache-2.0"
] | 71 | 2015-03-30T18:30:15.000Z | 2020-06-09T21:04:34.000Z | test/RandomHelpers.h | BBN-Q/libaps2 | 7787c821279deeca14108d7ac9a49992c64fffe9 | [
"Apache-2.0"
] | 5 | 2015-07-08T18:47:40.000Z | 2017-06-13T02:34:44.000Z | // Helper functions for generating random test data
//
// Original author: Colm Ryan
// Copyright 2016, Raytheon BBN Technologies
#include <random>
#include <vector>
static std::default_random_engine generator(std::random_device{}());
namespace RandomHelpers {
uint32_t random_address(uint32_t, uint32_t, uint32_t);
std::vector<uint32_t> random_data(size_t);
std::vector<int16_t> random_waveform(size_t);
}
| 21.736842 | 68 | 0.774818 | [
"vector"
] |
e162802ad4825971cacb174a84aff92f4f99a440 | 2,273 | h | C | src/Compucolor.Impl.Smc5027/Smc5027Emulator.h | nathanmentley/cc2emulator | 2eccca0ab7a8f306d21a2516106ef687d2b8e065 | [
"MIT"
] | null | null | null | src/Compucolor.Impl.Smc5027/Smc5027Emulator.h | nathanmentley/cc2emulator | 2eccca0ab7a8f306d21a2516106ef687d2b8e065 | [
"MIT"
] | null | null | null | src/Compucolor.Impl.Smc5027/Smc5027Emulator.h | nathanmentley/cc2emulator | 2eccca0ab7a8f306d21a2516106ef687d2b8e065 | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include <Compucolor/Logger/ILogger.h>
#include <Compucolor/Smc5027/ISmc5027Emulator.h>
namespace Compucolor::Impl::Smc5027 {
/**
* @brief
* @note
* @retval None
*/
class Smc5027Emulator: public Compucolor::Smc5027::ISmc5027Emulator {
public:
/**
* @brief
* @note
* @retval
*/
Smc5027Emulator(
std::shared_ptr<Logger::ILogger> logger
);
/**
* @brief
* @note
* @retval None
*/
virtual void Start() override;
/**
* @brief
* @note
* @retval None
*/
virtual void Stop() override;
/**
* @brief
* @note
* @param port:
* @retval
*/
virtual uint8_t Read(uint8_t port) override;
/**
* @brief
* @note
* @param port:
* @param data:
* @retval None
*/
virtual void Write(uint8_t port, uint8_t data) override;
/**
* @brief
* @note
* @retval None
*/
virtual void Reset() override;
/**
* @brief
* @note
* @retval
*/
virtual uint8_t GetCursorX() override;
/**
* @brief
* @note
* @retval
*/
virtual uint8_t GetCursorY() override;
/**
* @brief
* @note
* @retval
*/
virtual uint8_t FirstDisplayRow() override;
private:
static const uint8_t REGISTER_COUNT = 16;
std::shared_ptr<Logger::ILogger> _logger;
std::vector<uint8_t> _registers;
/**
* @brief
* @note
* @param port:
* @retval
*/
uint8_t ConvertPort(uint8_t port);
};
} | 23.43299 | 73 | 0.370436 | [
"vector"
] |
e16c80e8ce19a7a42149d23b71c85223c74e8156 | 3,842 | h | C | src/devices/bus/isa/mda.h | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 26 | 2015-03-31T06:25:51.000Z | 2021-12-14T09:29:04.000Z | src/devices/bus/isa/mda.h | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | null | null | null | src/devices/bus/isa/mda.h | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 10 | 2015-03-27T05:45:51.000Z | 2022-02-04T06:57:36.000Z | // license:BSD-3-Clause
// copyright-holders:Wilbert Pol, Miodrag Milanovic
#ifndef MAME_BUS_ISA_MDA_H
#define MAME_BUS_ISA_MDA_H
#pragma once
#include "isa.h"
#include "machine/pc_lpt.h"
#include "video/mc6845.h"
#include "emupal.h"
#include "screen.h"
//**************************************************************************
// TYPE DEFINITIONS
//**************************************************************************
// ======================> isa8_mda_device
class isa8_mda_device : public device_t,
public device_isa8_card_interface
{
public:
friend class isa8_hercules_device;
// construction/destruction
isa8_mda_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock);
virtual uint8_t io_read(offs_t offset);
virtual void io_write(offs_t offset, uint8_t data);
virtual uint8_t status_r();
virtual void mode_control_w(uint8_t data);
DECLARE_WRITE_LINE_MEMBER(hsync_changed);
DECLARE_WRITE_LINE_MEMBER(vsync_changed);
virtual MC6845_UPDATE_ROW( crtc_update_row );
protected:
isa8_mda_device(const machine_config &mconfig, device_type type, const char *tag, device_t *owner, uint32_t clock);
// device-level overrides
virtual void device_start() override;
virtual void device_reset() override;
// optional information overrides
virtual void device_add_mconfig(machine_config &config) override;
virtual const tiny_rom_entry *device_rom_region() const override;
required_device<mc6845_device> m_crtc;
optional_device<pc_lpt_device> m_lpt;
private:
WRITE_LINE_MEMBER(pc_cpu_line);
MC6845_UPDATE_ROW( mda_text_inten_update_row );
MC6845_UPDATE_ROW( mda_text_blink_update_row );
public:
int m_framecnt;
uint8_t m_mode_control;
int m_update_row_type;
uint8_t *m_chr_gen;
uint8_t m_vsync;
uint8_t m_hsync;
std::vector<uint8_t> m_videoram;
uint8_t m_pixel;
required_device<palette_device> m_palette;
};
// device type definition
DECLARE_DEVICE_TYPE(ISA8_MDA, isa8_mda_device)
// ======================> isa8_hercules_device
class isa8_hercules_device :
public isa8_mda_device
{
public:
// construction/destruction
isa8_hercules_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock);
virtual uint8_t io_read(offs_t offset) override;
virtual void io_write(offs_t offset, uint8_t data) override;
virtual uint8_t status_r() override;
virtual void mode_control_w(uint8_t data) override;
protected:
// device-level overrides
virtual void device_start() override;
virtual void device_reset() override;
// optional information overrides
virtual void device_add_mconfig(machine_config &config) override;
virtual const tiny_rom_entry *device_rom_region() const override;
private:
virtual MC6845_UPDATE_ROW( crtc_update_row ) override;
MC6845_UPDATE_ROW( hercules_gfx_update_row );
uint8_t m_configuration_switch; //hercules
};
// device type definition
DECLARE_DEVICE_TYPE(ISA8_HERCULES, isa8_hercules_device)
// ======================> isa8_ec1840_0002_device
class isa8_ec1840_0002_device :
public isa8_mda_device
{
public:
// construction/destruction
isa8_ec1840_0002_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock);
protected:
// device-level overrides
virtual void device_start() override;
virtual void device_reset() override;
// optional information overrides
virtual void device_add_mconfig(machine_config &config) override;
private:
virtual void mode_control_w(uint8_t data) override;
virtual MC6845_UPDATE_ROW( crtc_update_row ) override;
MC6845_UPDATE_ROW( mda_lowres_text_inten_update_row );
MC6845_UPDATE_ROW( mda_lowres_text_blink_update_row );
std::unique_ptr<uint8_t[]> m_soft_chr_gen;
};
// device type definition
DECLARE_DEVICE_TYPE(ISA8_EC1840_0002, isa8_ec1840_0002_device)
#endif // MAME_BUS_ISA_MDA_H
| 27.056338 | 116 | 0.757158 | [
"vector"
] |
e175e361c2cac6cf76a7184d7d1727f144b3f140 | 5,529 | c | C | C/vector.c | gizmo385/Utilities | 196b121f68653a26072be3413037a617d3bc1e5e | [
"MIT"
] | null | null | null | C/vector.c | gizmo385/Utilities | 196b121f68653a26072be3413037a617d3bc1e5e | [
"MIT"
] | null | null | null | C/vector.c | gizmo385/Utilities | 196b121f68653a26072be3413037a617d3bc1e5e | [
"MIT"
] | null | null | null | #include <stdlib.h>
#include <stdio.h>
#include "vector.h"
#include "utils.h"
/* Function prototypes */
int isInBounds( Vector *vector, int indexToCheck );
void resizeIfNecessary( Vector *vector );
/* Verifies that the supplied index is within the bounds of the vector
*
* Arguments:
* vector -- The vector to bound check
* index -- The index that is being tested
*
* Returns:
* 1 if the index is within the bounds of vector. 0 otherwise.
*/
int isInBounds( Vector *vector, int indexToCheck ) {
return ( indexToCheck < vector->capacity );
}
/*
* Resizes the vector if the size and the capacity are equal. It will increase the overall capacity
* of the vector by 25% upon resizing it.
*
* Arguments:
* vector -- The vector that you would like to resize
*/
void resizeIfNecessary( Vector *vector ) {
if( vector->size == vector->capacity ) {
int newCapacity = (vector->capacity * 1.25);
void** newElements = (void **)realloc( vector->elements, sizeof(void *) * newCapacity );
if( ! newElements ) {
free( vector->elements );
}
// Prevent unitialized pointers from being passed to free()
for( int i = vector->capacity; i < newCapacity; i++ ) {
newElements[i] = NULL;
}
vector->elements = newElements;
vector->capacity = newCapacity;
debug( E_DEBUG, "Resized vector to have capacity %d @ location %p\n", newCapacity,
vector->elements);
}
}
/*
* Creates a new vector that has a specific amount of specific previously allocated.
*
* Arguments:
* initalCapacity -- The amount of space to initially allocate for the elements.
*
* Returns:
* A pointer to a newly allocated Vector
*/
Vector *newVector( int initialCapacity ) {
Vector *vector = NULL;
if( initialCapacity >= 0 ) {
vector = (Vector *) malloc( sizeof(Vector) );
vector->capacity = initialCapacity;
vector->size = 0;
vector->elements = (void **) calloc( initialCapacity, sizeof(void *) );
for( int i = 0; i < vector->capacity; i++ ) {
vector->elements[i] = NULL;
}
}
return vector;
}
/*
* Adds an element to the supplied vector. In the case that the size == capacity, the vector will
* have to be resized to accomodate for the additional element.
*
* Arguments:
* vector -- The vector that the element is being added to
* element -- The element that is being added to the vector
*/
void vectorAdd( Vector *vector, void *element ) {
if( element == NULL ) {
debug( E_WARNING, "Cannot add a NULL element to the vector!\n" );
return;
}
resizeIfNecessary( vector );
vector->elements[ (vector->size) ] = element;
vector->size += 1;
}
/*
* Inserts an element into a specified index in a vector. If this falls outside the bounds of the
* vector, the function will fail and return a false value. Otherwise it will return true.
*
* Arguments:
* vector -- The vector that the item is being inserted into.
* element -- The element that is being inserted into the list.
* index -- The index that the element is being inserted into
*
* Returns:
* In the case that the element is successfully inserted, this will return 1. Otherwise, it will
* return 0.
*/
int vectorInsert( Vector *vector, void *element, int index ) {
if( isInBounds( vector, index ) ) {
vector->elements[index] = element;
return 1;
} else {
return 0;
}
}
/*
* Removes the element from the vector at the specified location.
*
* Arguments:
* vector -- The vector to remove from
* index -- The index of the element to remove
*/
void *vectorRemove( Vector *vector, int index ) {
if( isInBounds( vector, index ) ) {
void *removedElement = vector->elements[index];
vector->elements[index] = NULL;
vector->size -= 1;
return removedElement;
}
return NULL;
}
/*
* Returns whether or not the supplied vector is empty. This will return 1 when the vector is empty
* and will return 0 when the vector is not empty.
*
* Arguments:
* vector -- The vector to check for emptiness
*
* Returns:
* 1 in the case that the vector is empty, 0 otherwise.
*/
int vectorIsEmpty( Vector *vector ) {
return (vector->size == 0);
}
/*
* Returns the value at the specified index in the vector.
*
* Arguments:
* vector -- The vector the element is being retrieved from
* index -- The index to retrieve in the vector
*
* Returns:
* The element in the location or NULL if the index is out of bounds
*/
void *vectorGet( Vector *vector, int index ) {
if( isInBounds( vector, index ) ) {
return vector->elements[index];
} else {
debug( E_WARNING, "WARNING: GET called with index that is out of bounds.\n" );
return NULL;
}
}
/*
* Frees up the memory used by the vector.
*
* Arguments:
* vector -- The vector whose memory you would like to free
*/
void freeVector( Vector *vector ) {
for( int i = 0; i < vector->capacity; i++ ) {
void *itemToFree = vectorGet(vector, i);
if( itemToFree ) {
free( itemToFree );
}
}
free( vector->elements );
free( vector );
}
/*
* Frees up the structural memory used by the vector, but doesn't free the elements inside the
* vector.
*
* Arguments:
* vector -- The vector whose memory you would like to free
*/
void vectorFreeStructure( Vector *vector ) {
free( vector->elements );
free( vector );
}
| 27.371287 | 99 | 0.640441 | [
"vector"
] |
e186262a14bab38564b3746532203bd837d4004c | 5,392 | h | C | usr/src/cmd/picl/plugins/sun4u/lib/fruaccess/fru_access_impl.h | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | null | null | null | usr/src/cmd/picl/plugins/sun4u/lib/fruaccess/fru_access_impl.h | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | null | null | null | usr/src/cmd/picl/plugins/sun4u/lib/fruaccess/fru_access_impl.h | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | 1 | 2020-12-30T00:04:16.000Z | 2020-12-30T00:04:16.000Z | /*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License, Version 1.0 only
* (the "License"). You may not use this file except in compliance
* with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2003 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
#ifndef _FRU_ACCESS_IMPL_H
#define _FRU_ACCESS_IMPL_H
#pragma ident "%Z%%M% %I% %E% SMI"
#ifdef __cplusplus
extern "C" {
#endif
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dial.h>
#include <strings.h>
#include <libdevinfo.h>
#include <sys/systeminfo.h>
#include <picl.h>
#include <picltree.h>
#include <picldefs.h>
#include <syslog.h>
#include <errno.h>
#include <libfru.h>
#include <limits.h>
#include <fru_tag.h>
#include "fru_access.h"
#include "spd_data.h"
/* object types */
typedef enum {CONTAINER_TYPE, SECTION_TYPE, SEGMENT_TYPE, PACKET_TYPE} object_t;
#define TABLE_SIZE 64 /* hash table size */
/* container configuration file name */
#define FRU_CONTAINER_CONF "fru_container.conf"
#define CONTAINER_DIR "/usr/platform/sun4u/lib"
/* section header */
#define SECTION_HDR_TAG 0x08
#define SECTION_HDR_VER 0x0001
#define SECTION_HDR_LENGTH 0x06
#define SECTION_HDR_CRC8 0x00
#define SECTION_HDR_VER_BIT0 0x00
#define SECTION_HDR_VER_BIT1 0x01
#define READ_ONLY_SECTION 1 /* section is read-only */
#define GET_SEGMENT_DESCRIPTOR \
(seg_layout->descriptor[1]|seg_layout->descriptor[0] << 16)
#define GET_SECTION_HDR_VERSION \
(sec_hdr.headerversion[1]|sec_hdr.headerversion[0] << 8)
/* Segment Trailer Tag */
#define SEG_TRAILER_TAG 0x0C
/* defines fixed segment */
#define SEGMENT_FIXED 1
typedef union {
uint32_t all_bits;
struct {
unsigned read_only : 1;
unsigned unused : 8;
unsigned : 8;
unsigned : 8;
unsigned : 7;
} field;
} sectdescbit_t;
typedef enum {
ENC_STANDARD = 0, /* proper fruid data */
ENC_SPD /* serial presence detect data */
} sectencoding_t;
typedef struct {
sectdescbit_t description;
uint32_t address; /* for SEEPROMS this is the offset */
uint32_t size;
sectencoding_t encoding;
} sectioninfo_t;
typedef uint16_t headerrev_t;
#define MAX_NUMOF_SECTION 2
typedef struct {
headerrev_t header_ver;
int num_sections;
sectioninfo_t section_info[MAX_NUMOF_SECTION];
} container_info_t;
/* section header layout */
typedef struct {
uint8_t headertag; /* section header tag */
uint8_t headerversion[2]; /* header version (msb) */
uint8_t headerlength; /* header length */
uint8_t headercrc8; /* crc8 */
uint8_t segmentcount; /* total number of segment */
} section_layout_t;
/* segment header layout */
typedef struct {
uint16_t name; /* segment name */
uint16_t descriptor[2]; /* descriptor (msb) */
uint16_t offset; /* segment data offset */
uint16_t length; /* segment length */
} segment_layout_t;
/* segment information used in finding new offset for a new segment */
typedef struct {
int segnum; /* segment number */
int offset; /* segment offset */
int length; /* segment length */
int fixed; /* fixed or non-fixed segment */
} seg_info_t;
typedef uint64_t handle_t;
struct hash_obj;
/* packet hash object */
typedef struct {
handle_t segment_hdl; /* segment handle */
fru_tag_t tag;
int tag_size;
uint8_t *payload;
uint32_t paylen;
uint32_t payload_offset;
struct hash_obj *next;
} packet_obj_t;
/* segment hash object */
typedef struct {
handle_t section_hdl; /* section handle */
int num_of_packets; /* in a segment */
int trailer_offset;
segment_t segment;
struct hash_obj *pkt_obj_list; /* packet object list */
struct hash_obj *next;
} segment_obj_t;
/* section hash object */
typedef struct {
handle_t cont_hdl; /* container handle */
section_t section;
sectencoding_t encoding; /* standard or needing interpretation */
int num_of_segment; /* in a section */
struct hash_obj *seg_obj_list; /* points to segment objects list */
struct hash_obj *next;
} section_obj_t;
/* container hash object */
typedef struct {
char device_pathname[PATH_MAX]; /* device name */
int num_of_section; /* num of section in container */
struct hash_obj *sec_obj_list; /* points to section objects list */
} container_obj_t;
/* hash object */
typedef struct hash_obj {
int object_type;
handle_t obj_hdl;
union {
container_obj_t *cont_obj;
section_obj_t *sec_obj;
segment_obj_t *seg_obj;
packet_obj_t *pkt_obj;
} u;
struct hash_obj *next;
struct hash_obj *prev;
} hash_obj_t;
unsigned char compute_crc8(unsigned char *bytes, int length);
long compute_crc32(unsigned char *bytes, int length);
long compute_checksum32(unsigned char *bytes, int length);
#ifdef __cplusplus
}
#endif
#endif /* _FRU_ACCESS_IMPL_H */
| 25.433962 | 80 | 0.736276 | [
"object"
] |
e188f61af0539ac6f566680e2e15ec9721a515c8 | 2,049 | h | C | deps/memkind/test/allocator_perf_tool/FootprintSampling.h | shanicky/pmem-redis | cc54b5516d5106336a016cc36135141319a97690 | [
"BSD-3-Clause"
] | 107 | 2018-10-08T08:34:38.000Z | 2021-12-05T13:17:59.000Z | deps/memkind/test/allocator_perf_tool/FootprintSampling.h | shanicky/pmem-redis | cc54b5516d5106336a016cc36135141319a97690 | [
"BSD-3-Clause"
] | 13 | 2018-10-30T05:19:29.000Z | 2021-07-28T08:30:53.000Z | deps/memkind/test/allocator_perf_tool/FootprintSampling.h | shanicky/pmem-redis | cc54b5516d5106336a016cc36135141319a97690 | [
"BSD-3-Clause"
] | 37 | 2018-10-16T05:43:25.000Z | 2022-03-14T19:46:23.000Z | /*
* Copyright (C) 2015 - 2016 Intel Corporation.
* 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(s),
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice(s),
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE COPYRIGHT HOLDER(S) 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.
*/
#pragma once
#include <vector>
#include "Runnable.hpp"
#include "Numastat.hpp"
#include "FootprintTask.h"
#include "MemoryFootprintStats.hpp"
#include "Sample.hpp"
class FootprintSampling
: public Runnable
{
public:
FootprintSampling(void) : is_running(true) {}
~FootprintSampling(void);
void run();
void start() {is_running = true;}
void stop() {is_running = false;}
void register_task(FootprintTask* task) {tasks.push_back(task);}
MemoryFootprintStats get_memory_footprint_stats()
{
return MemoryFootprintStats::generate_stats(before_running_sample, samples);
}
private:
std::vector<FootprintTask*> tasks;
std::vector<Sample> samples;
bool is_running;
float before_running_sample;
};
| 33.590164 | 81 | 0.769156 | [
"vector"
] |
e1987ffcf8b6809e3c021eebeb4eb4df334f3ee6 | 1,652 | h | C | ui/views/animation/ink_drop.h | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 3 | 2018-02-22T18:06:56.000Z | 2021-08-28T12:49:27.000Z | ui/views/animation/ink_drop.h | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2016-07-11T15:19:20.000Z | 2017-04-02T20:38:55.000Z | ui/views/animation/ink_drop.h | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 6 | 2020-09-23T08:56:12.000Z | 2021-11-18T03:40:49.000Z | // Copyright 2015 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 UI_VIEWS_ANIMATION_INK_DROP_H_
#define UI_VIEWS_ANIMATION_INK_DROP_H_
#include <memory>
#include "base/macros.h"
#include "base/time/time.h"
#include "ui/compositor/layer_tree_owner.h"
#include "ui/events/event_handler.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
#include "ui/views/animation/ink_drop_state.h"
#include "ui/views/views_export.h"
namespace ui {
class Layer;
}
namespace views {
// Pure virtual base class that manages the lifetime and state of an ink drop
// ripple as well as visual hover state feedback.
class VIEWS_EXPORT InkDrop {
public:
virtual ~InkDrop() {}
// Gets the target state of the ink drop.
virtual InkDropState GetTargetInkDropState() const = 0;
// Animates from the current InkDropState to |ink_drop_state|.
virtual void AnimateToState(InkDropState ink_drop_state) = 0;
// Immediately snaps the InkDropState to ACTIVATED. This more specific
// implementation of the non-existent SnapToState(InkDropState) function is
// the only one available because it was the only InkDropState that clients
// needed to skip animations for.
virtual void SnapToActivated() = 0;
// Enables or disables the hover state.
virtual void SetHovered(bool is_hovered) = 0;
// Enables or disables the focus state.
virtual void SetFocused(bool is_focused) = 0;
protected:
InkDrop() {}
private:
DISALLOW_COPY_AND_ASSIGN(InkDrop);
};
} // namespace views
#endif // UI_VIEWS_ANIMATION_INK_DROP_H_
| 28.482759 | 77 | 0.758475 | [
"geometry"
] |
e19d7f3e0b1346a5b60c15b1b810f04b4ef7aad4 | 137,005 | c | C | source/AccessorySDK/Support/PrintFUtils.c | olli991/WirelessCarPlay | a6b51348a7df83c348d7467b2b1ccaa4e71bdc04 | [
"MIT"
] | 1 | 2020-03-10T15:53:34.000Z | 2020-03-10T15:53:34.000Z | source/AccessorySDK/Support/PrintFUtils.c | Vulpecula-nl/WirelessCarPlay | a6b51348a7df83c348d7467b2b1ccaa4e71bdc04 | [
"MIT"
] | null | null | null | source/AccessorySDK/Support/PrintFUtils.c | Vulpecula-nl/WirelessCarPlay | a6b51348a7df83c348d7467b2b1ccaa4e71bdc04 | [
"MIT"
] | 1 | 2021-08-30T14:20:33.000Z | 2021-08-30T14:20:33.000Z | /*
File: PrintFUtils.c
Package: Apple CarPlay Communication Plug-in.
Abstract: n/a
Version: 410.8
Disclaimer: IMPORTANT: This Apple software is supplied to you, by Apple Inc. ("Apple"), in your
capacity as a current, and in good standing, Licensee in the MFi Licensing Program. Use of this
Apple software is governed by and subject to the terms and conditions of your MFi License,
including, but not limited to, the restrictions specified in the provision entitled ”Public
Software”, and is further subject to your agreement to the following additional terms, and your
agreement that the use, installation, modification or redistribution of this Apple software
constitutes acceptance of these additional terms. If you do not agree with these additional terms,
please do not use, install, modify or redistribute this Apple software.
Subject to all of these terms and in consideration of your agreement to abide by them, Apple grants
you, for as long as you are a current and in good-standing MFi Licensee, a personal, non-exclusive
license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use,
reproduce, and modify the Apple Software in source form, and to use, reproduce, modify, and
redistribute the Apple Software, with or without modifications, in binary form. While you may not
redistribute the Apple Software in source form, should you redistribute the Apple Software in binary
form, you must retain this notice and the following text and disclaimers in all such redistributions
of the Apple Software. Neither the name, trademarks, service marks, or logos of Apple Inc. may be
used to endorse or promote products derived from the Apple Software without specific prior written
permission from Apple. Except as expressly stated in this notice, no other rights or licenses,
express or implied, are granted by Apple herein, including but not limited to any patent rights that
may be infringed by your derivative works or by other works in which the Apple Software may be
incorporated.
Unless you explicitly state otherwise, if you provide any ideas, suggestions, recommendations, bug
fixes or enhancements to Apple in connection with this software (“Feedback”), you hereby grant to
Apple a non-exclusive, fully paid-up, perpetual, irrevocable, worldwide license to make, use,
reproduce, incorporate, modify, display, perform, sell, make or have made derivative works of,
distribute (directly or indirectly) and sublicense, such Feedback in connection with Apple products
and services. Providing this Feedback is voluntary, but if you do provide Feedback to Apple, you
acknowledge and agree that Apple may exercise the license granted above without the payment of
royalties or further consideration to Participant.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR
IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR
IN COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION
AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT
(INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
Copyright (C) 1997-2015 Apple Inc. All Rights Reserved.
*/
// Microsoft deprecated standard C APIs like fopen so disable those warnings because the replacement APIs are not portable.
#if( !defined( _CRT_SECURE_NO_DEPRECATE ) )
#define _CRT_SECURE_NO_DEPRECATE 1
#endif
#include "PrintFUtils.h"
#include "ChecksumUtils.h"
#include "CommonServices.h"
#include "DebugServices.h"
#include "RandomNumberUtils.h"
#include "StringUtils.h"
#if( TARGET_HAS_STD_C_LIB )
#include <time.h>
#endif
#if( TARGET_OS_DARWIN )
#if( !TARGET_KERNEL && !COMMON_SERVICES_NO_CORE_SERVICES )
#include <CoreAudio/CoreAudio.h>
#endif
#endif
#if( TARGET_OS_POSIX )
#include <net/if.h>
#include <pthread.h>
#include <sys/time.h>
#include <time.h>
#include "MiscUtils.h"
#include "TimeUtils.h"
#endif
#if( DEBUG_CF_OBJECTS_ENABLED )
#include "CFUtils.h"
#endif
#include LIBDISPATCH_HEADER
#if( XPC_ENABLED )
#include XPC_HEADER
#endif
//===========================================================================================================================
// Constants
//===========================================================================================================================
// Enables limited %f floating-point output.
#if( !defined( PRINTF_ENABLE_FLOATING_POINT ) )
#if( !TARGET_OS_WINDOWS_KERNEL )
#define PRINTF_ENABLE_FLOATING_POINT 1
#else
#define PRINTF_ENABLE_FLOATING_POINT 0
#endif
#endif
//===========================================================================================================================
// Structures
//===========================================================================================================================
static const PrintFFormat kPrintFFormatDefault = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
typedef int ( *PrintFCallBack )( const char *inStr, size_t inSize, PrintFContext *inContext );
struct PrintFContext
{
PrintFCallBack callback;
char * str;
size_t usedSize;
size_t reservedSize;
PrintFUserCallBack userCallBack;
void * userContext;
};
typedef struct PrintFExtension PrintFExtension;
struct PrintFExtension
{
PrintFExtension * next;
PrintFExtensionHandler_f handler_f;
void * context;
char name[ 1 ]; // Variable length.
};
//===========================================================================================================================
// Prototypes
//===========================================================================================================================
static int PrintFWriteAddr( const uint8_t *inAddr, PrintFFormat *inFormat, char *outStr );
static int PrintFWriteAudioStreamBasicDescription( PrintFContext *inContext, const AudioStreamBasicDescription *inASBD );
static int PrintFWriteCEC( PrintFContext *ctx, const uint8_t *inData, size_t inLen );
static int PrintFWriteBits( uint64_t inX, PrintFFormat *inFormat, char *outStr );
#if( DEBUG_CF_OBJECTS_ENABLED )
static int PrintFWriteCFObject( PrintFContext *inContext, PrintFFormat *inFormat, CFTypeRef inObj, char *inBuffer );
#endif
#if( DEBUG_CF_OBJECTS_ENABLED && ( !CFLITE_ENABLED || CFL_XML ) )
static int PrintFWriteCFXMLObject( PrintFContext *inContext, PrintFFormat *inFormat, CFTypeRef inObj );
#endif
static int PrintFWriteFill( PrintFContext *inContext, int inC, size_t inCount, char *inBuf );
static int PrintFWriteFlags( PrintFContext *inContext, PrintFFormat *inFormat, const char *inDescriptors, uint64_t inX );
static int
PrintFWriteHex(
PrintFContext * inContext,
PrintFFormat * inFormat,
int inIndent,
const void * inData,
size_t inSize,
size_t inMaxSize );
static int PrintFWriteHexOneLine( PrintFContext *inContext, PrintFFormat *inFormat, const uint8_t *inData, size_t inSize );
static int PrintFWriteHexByteStream( PrintFContext *inContext, Boolean inUppercase, const uint8_t *inData, size_t inSize );
static int PrintFWriteMultiLineText( PrintFContext *inContext, PrintFFormat *inFormat, const char *inStr, size_t inLen );
static int PrintFWriteNumVersion( uint32_t inVersion, char *outStr );
static int PrintFWriteSingleLineText( PrintFContext *inContext, const char *inStr, size_t inLen );
static int PrintFWriteObfuscatedPtr( PrintFContext *inContext, const void *inPtr );
static void _PrintFWriteObfuscatedPtrInit( void *inArg );
static int PrintFWriteString( const char *inStr, PrintFFormat *inFormat, char *inBuf, const char **outStrPtr );
static int PrintFWriteText( PrintFContext *inContext, PrintFFormat *inFormat, const char *inText, size_t inSize );
static int PrintFWriteTimeDuration( uint64_t inSeconds, int inAltMode, char *inBuf );
static int
PrintFWriteTLV8(
PrintFContext * inContext,
PrintFFormat * inFormat,
const char * inDescriptors,
const uint8_t * inPtr,
size_t inLen );
static int PrintFWriteTXTRecord( PrintFContext *inContext, PrintFFormat *inFormat, const void *inPtr, size_t inLen );
static int PrintFWriteUnicodeString( const uint8_t *inStr, PrintFFormat *inFormat, char *inBuf );
static int PrintFWriteXMLEscaped( PrintFContext *inContext, const char *inPtr, size_t inLen );
#define print_indent( CONTEXT, N ) PrintFCore( ( CONTEXT ), "%*s", (int)( ( N ) * 4 ), "" )
static int PrintFCallBackFixedString( const char *inStr, size_t inSize, PrintFContext *inContext );
static int PrintFCallBackAllocatedString( const char *inStr, size_t inSize, PrintFContext *inContext );
static int PrintFCallBackUserCallBack( const char *inStr, size_t inSize, PrintFContext *inContext );
//===========================================================================================================================
// Globals
//===========================================================================================================================
MinimalMutexDefine( gPrintFUtilsLock );
static PrintFExtension * gExtensionList = NULL;
#if 0
#pragma mark -
#endif
//===========================================================================================================================
// PrintFRegisterExtension
//===========================================================================================================================
OSStatus PrintFRegisterExtension( const char *inName, PrintFExtensionHandler_f inHandler, void *inContext )
{
OSStatus err;
size_t len;
PrintFExtension * extension;
MinimalMutexEnsureInitialized( gPrintFUtilsLock );
MinimalMutexLock( gPrintFUtilsLock );
for( extension = gExtensionList; extension; extension = extension->next )
{
if( stricmp( extension->name, inName ) == 0 )
{
break;
}
}
require_action( !extension, exit, err = kDuplicateErr );
len = strlen( inName ) + 1;
extension = (PrintFExtension *) malloc( offsetof( PrintFExtension, name ) + len );
require_action( extension, exit, err = kNoMemoryErr );
extension->handler_f = inHandler;
extension->context = inContext;
memcpy( extension->name, inName, len );
extension->next = gExtensionList;
gExtensionList = extension;
err = kNoErr;
exit:
MinimalMutexUnlock( gPrintFUtilsLock );
return( err );
}
//===========================================================================================================================
// PrintFDeregisterExtension
//===========================================================================================================================
OSStatus PrintFDeregisterExtension( const char *inName )
{
PrintFExtension * curr;
PrintFExtension ** next;
MinimalMutexEnsureInitialized( gPrintFUtilsLock );
MinimalMutexLock( gPrintFUtilsLock );
for( next = &gExtensionList; ( curr = *next ) != NULL; next = &curr->next )
{
if( stricmp( curr->name, inName ) == 0 )
{
*next = curr->next;
free( curr );
MinimalMutexUnlock( gPrintFUtilsLock );
return( kNoErr );
}
}
MinimalMutexUnlock( gPrintFUtilsLock );
return( kNotFoundErr );
}
#if 0
#pragma mark -
#endif
#if( COMPILER_OBJC )
//===========================================================================================================================
// NSPrintF
//===========================================================================================================================
NSString * NSPrintF( const char *inFormat, ... )
{
NSString * result;
va_list args;
va_start( args, inFormat );
result = NSPrintV( inFormat, args );
va_end( args );
return( result );
}
//===========================================================================================================================
// NSPrintV
//===========================================================================================================================
NSString * NSPrintV( const char *inFormat, va_list inArgs )
{
NSString * result;
char * cptr = NULL;
VASPrintF( &cptr, inFormat, inArgs );
result = cptr ? @(cptr) : @"";
FreeNullSafe( cptr );
return( result );
}
#endif // COMPILER_OBJC
//===========================================================================================================================
// SNPrintF
//===========================================================================================================================
int SNPrintF( void *inBuf, size_t inMaxLen, const char *inFormat, ... )
{
int n;
va_list args;
va_start( args, inFormat );
n = VSNPrintF( inBuf, inMaxLen, inFormat, args );
va_end( args );
return( n );
}
//===========================================================================================================================
// VSNPrintF
//===========================================================================================================================
int VSNPrintF( void *inBuf, size_t inMaxLen, const char *inFormat, va_list inArgs )
{
int n;
PrintFContext context;
context.callback = PrintFCallBackFixedString;
context.str = (char *) inBuf;
context.usedSize = 0;
context.reservedSize = ( inMaxLen > 0 ) ? inMaxLen - 1 : 0;
n = PrintFCoreVAList( &context, inFormat, inArgs );
if( inMaxLen > 0 ) context.str[ context.usedSize ] = '\0';
return( n );
}
//===========================================================================================================================
// SNPrintF_Add
//===========================================================================================================================
#if( !defined( SNPRINTF_USE_ASSERTS ) )
#define SNPRINTF_USE_ASSERTS 1
#endif
OSStatus SNPrintF_Add( char **ioPtr, char *inEnd, const char *inFormat, ... )
{
char * const ptr = *ioPtr;
size_t len;
int n;
va_list args;
len = (size_t)( inEnd - ptr );
#if( SNPRINTF_USE_ASSERTS )
require_action( len > 0, exit, n = kNoSpaceErr );
#else
require_action_quiet( len > 0, exit, n = kNoSpaceErr );
#endif
va_start( args, inFormat );
n = VSNPrintF( ptr, len, inFormat, args );
va_end( args );
#if( SNPRINTF_USE_ASSERTS )
require( n >= 0, exit );
#else
require_quiet( n >= 0, exit );
#endif
if( n >= ( (int) len ) )
{
#if( SNPRINTF_USE_ASSERTS )
dlogassert( "Add '%s' format failed due to lack of space (%d vs %zu)", inFormat, n, len );
#endif
*ioPtr = inEnd;
n = kOverrunErr;
goto exit;
}
*ioPtr = ptr + n;
n = kNoErr;
exit:
return( n );
}
//===========================================================================================================================
// AppendPrintF
//===========================================================================================================================
int AppendPrintF( char **ioStr, const char *inFormat, ... )
{
int n;
va_list args;
char * tempStr;
va_start( args, inFormat );
n = ASPrintF( &tempStr, "%s%V", *ioStr ? *ioStr : "", inFormat, &args );
va_end( args );
require_quiet( n >= 0, exit );
if( *ioStr ) free( *ioStr );
*ioStr = tempStr;
exit:
return( n );
}
//===========================================================================================================================
// ASPrintF
//===========================================================================================================================
int ASPrintF( char **outStr, const char *inFormat, ... )
{
int n;
va_list args;
va_start( args, inFormat );
n = VASPrintF( outStr, inFormat, args );
va_end( args );
return( n );
}
//===========================================================================================================================
// VASPrintF
//===========================================================================================================================
int VASPrintF( char **outStr, const char *inFormat, va_list inArgs )
{
int n;
PrintFContext context;
int tmp;
context.callback = PrintFCallBackAllocatedString;
context.str = NULL;
context.usedSize = 0;
context.reservedSize = 0;
n = PrintFCoreVAList( &context, inFormat, inArgs );
if( n >= 0 )
{
tmp = context.callback( "", 1, &context );
if( tmp < 0 ) n = tmp;
}
if( n >= 0 ) *outStr = context.str;
else if( context.str ) free( context.str );
return( n );
}
//===========================================================================================================================
// CPrintF
//===========================================================================================================================
int CPrintF( PrintFUserCallBack inCallBack, void *inContext, const char *inFormat, ... )
{
int n;
va_list args;
va_start( args, inFormat );
n = VCPrintF( inCallBack, inContext, inFormat, args );
va_end( args );
return( n );
}
//===========================================================================================================================
// VCPrintF
//===========================================================================================================================
int VCPrintF( PrintFUserCallBack inCallBack, void *inContext, const char *inFormat, va_list inArgs )
{
int n;
PrintFContext context;
int tmp;
context.callback = PrintFCallBackUserCallBack;
context.str = NULL;
context.usedSize = 0;
context.reservedSize = 0;
context.userCallBack = inCallBack;
context.userContext = inContext;
n = PrintFCoreVAList( &context, inFormat, inArgs );
if( n >= 0 )
{
tmp = context.callback( "", 0, &context );
if( tmp < 0 ) n = tmp;
}
return( n );
}
#if( TARGET_HAS_C_LIB_IO )
//===========================================================================================================================
// FPrintF
//===========================================================================================================================
int FPrintF( FILE *inFile, const char *inFormat, ... )
{
int n;
va_list args;
va_start( args, inFormat );
n = VFPrintF( inFile, inFormat, args );
va_end( args );
return( n );
}
//===========================================================================================================================
// VFPrintF
//===========================================================================================================================
static int FPrintFCallBack( const char *inStr, size_t inSize, void *inContext );
int VFPrintF( FILE *inFile, const char *inFormat, va_list inArgs )
{
return( VCPrintF( FPrintFCallBack, inFile, inFormat, inArgs ) );
}
//===========================================================================================================================
// FPrintFCallBack
//===========================================================================================================================
static int FPrintFCallBack( const char *inStr, size_t inSize, void *inContext )
{
FILE * const file = (FILE *) inContext;
if( file ) fwrite( inStr, 1, inSize, file );
return( (int) inSize );
}
#endif // TARGET_HAS_C_LIB_IO
//===========================================================================================================================
// MemPrintF
//===========================================================================================================================
int MemPrintF( void *inBuf, size_t inMaxLen, const char *inFormat, ... )
{
int n;
va_list args;
va_start( args, inFormat );
n = VMemPrintF( inBuf, inMaxLen, inFormat, args );
va_end( args );
return( n );
}
//===========================================================================================================================
// VMemPrintF
//===========================================================================================================================
int VMemPrintF( void *inBuf, size_t inMaxLen, const char *inFormat, va_list inArgs )
{
int n;
PrintFContext context;
context.callback = PrintFCallBackFixedString;
context.str = (char *) inBuf;
context.usedSize = 0;
context.reservedSize = inMaxLen;
n = PrintFCoreVAList( &context, inFormat, inArgs );
return( n );
}
#if 0
#pragma mark -
#endif
//===========================================================================================================================
// PrintFCore
//===========================================================================================================================
int PrintFCore( PrintFContext *inContext, const char *inFormat, ... )
{
int n;
va_list args;
va_start( args, inFormat );
n = PrintFCoreVAList( inContext, inFormat, args );
va_end( args );
return( n );
}
//===========================================================================================================================
// PrintFCoreVAList
//===========================================================================================================================
#define kPrintFBufSize 300 // Enough space for a 256-byte domain name and some error text.
#define PrintFIsPrintable( C ) ( ( (C) >= 0x20 ) && ( (C) < 0x7F ) )
#define PrintFMakePrintable( C ) ( (char)( PrintFIsPrintable( (C) ) ? (C) : (C) ? '^' : '.' ) )
int PrintFCoreVAList( PrintFContext *inContext, const char *inFormat, va_list inArgs )
{
int total = 0;
const char * fmt = inFormat;
PrintFVAList vaArgs;
const char * src;
int err;
char buf[ kPrintFBufSize ];
char * p;
int c;
PrintFFormat F;
int i;
const char * digits;
const char * s;
const uint8_t * a;
int n;
size_t size;
size_t sizeMax;
uint64_t x;
unsigned int base;
uint32_t remain;
unsigned int extra;
#if( defined( va_copy ) )
va_copy( vaArgs.args, inArgs );
#else
vaArgs.args = inArgs; // Not portable and only works on va_list's that are pointers and not arrays.
#endif
for( c = *fmt; ; c = *++fmt )
{
// Non-conversion characters are copied directly to the output.
src = fmt;
while( ( c != '\0' ) && ( c != '%' ) ) c = *++fmt;
if( fmt != src )
{
i = (int)( fmt - src );
err = inContext->callback( src, (size_t) i, inContext );
if( err < 0 ) goto error;
total += i;
}
if( c == '\0' ) break;
F = kPrintFFormatDefault;
// Flags
for( ;; )
{
c = *++fmt;
if( c == '-' ) F.leftJustify = 1;
else if( c == '+' ) F.forceSign = 1;
else if( c == ' ' ) F.sign = ' ';
else if( c == '#' ) F.altForm += 1;
else if( c == '0' ) F.zeroPad = 1;
else if( c == '\'' ) F.group += 1;
else if( c == '?' ) F.suppress = !va_arg( vaArgs.args, int );
else break;
}
// Field Width
if( c == '*' )
{
i = va_arg( vaArgs.args, int );
if( i < 0 )
{
i = -i;
F.leftJustify = 1;
}
F.fieldWidth = (unsigned int) i;
c = *++fmt;
}
else
{
for( ; ( c >= '0' ) && ( c <= '9' ); c = *++fmt )
{
F.fieldWidth = ( 10 * F.fieldWidth ) + ( c - '0' );
}
}
// Precision
if( c == '.' )
{
c = *++fmt;
if( c == '*' )
{
F.precision = va_arg( vaArgs.args, unsigned int );
c = *++fmt;
}
else
{
for( ; ( c >= '0' ) && ( c <= '9' ); c = *++fmt )
{
F.precision = ( 10 * F.precision ) + ( c - '0' );
}
}
F.havePrecision = 1;
}
if( F.leftJustify ) F.zeroPad = 0;
// Length modifiers
for( ;; )
{
if( c == 'h' ) { ++F.hSize; c = *++fmt; }
else if( c == 'l' ) { ++F.lSize; c = *++fmt; }
else if( c == 'j' )
{
if( F.hSize || F.lSize ) { err = -1; goto error; }
// Disable unreachable code warnings because unreachable paths are reachable on some architectures.
begin_unreachable_code_paths()
if( sizeof( intmax_t ) == sizeof( long ) ) F.lSize = 1;
else if( sizeof( intmax_t ) == sizeof( int64_t ) ) F.lSize = 2;
else F.lSize = 0;
end_unreachable_code_paths()
c = *++fmt;
break;
}
else if( c == 'z' )
{
if( F.hSize || F.lSize ) { err = -1; goto error; };
// Disable unreachable code warnings because unreachable paths are reachable on some architectures.
begin_unreachable_code_paths()
if( sizeof( size_t ) == sizeof( long ) ) F.lSize = 1;
else if( sizeof( size_t ) == sizeof( int64_t ) ) F.lSize = 2;
else F.lSize = 0;
end_unreachable_code_paths()
c = *++fmt;
break;
}
else if( c == 't' )
{
if( F.hSize || F.lSize ) { err = -1; goto error; };
// Disable unreachable code warnings because unreachable paths are reachable on some architectures.
begin_unreachable_code_paths()
if( sizeof( ptrdiff_t ) == sizeof( long ) ) F.lSize = 1;
else if( sizeof( ptrdiff_t ) == sizeof( int64_t ) ) F.lSize = 2;
else F.lSize = 0;
end_unreachable_code_paths()
c = *++fmt;
break;
}
else break;
}
if( F.hSize > 2 ) { err = -1; goto error; };
if( F.lSize > 2 ) { err = -1; goto error; };
if( F.hSize && F.lSize ) { err = -1; goto error; };
// Conversions
digits = kHexDigitsUppercase;
switch( c )
{
// %d, %i, %u, %o, %b, %x, %X, %p: Number
case 'd':
case 'i': base = 10; goto canBeSigned;
case 'u': base = 10; goto notSigned;
case 'o': base = 8; goto notSigned;
case 'b': base = 2; goto notSigned;
case 'x': digits = kHexDigitsLowercase;
case 'X': base = 16; goto notSigned;
case 'p':
x = (uintptr_t) va_arg( vaArgs.args, void * );
F.precision = sizeof( void * ) * 2;
F.havePrecision = 1;
F.altForm = 1;
F.sign = 0;
base = 16;
c = 'x';
goto number;
canBeSigned:
if( F.lSize == 1 ) x = (uint64_t) va_arg( vaArgs.args, long );
else if( F.lSize == 2 ) x = (uint64_t) va_arg( vaArgs.args, int64_t );
else x = (uint64_t) va_arg( vaArgs.args, int );
if( F.hSize == 1 ) x = (uint64_t)(short)( x & 0xFFFF );
else if( F.hSize == 2 ) x = (uint64_t)(signed char)( x & 0xFF );
if( (int64_t) x < 0 ) { x = (uint64_t)( -(int64_t) x ); F.sign = '-'; }
else if( F.forceSign ) F.sign = '+';
goto number;
notSigned:
if( F.lSize == 1 ) x = va_arg( vaArgs.args, unsigned long );
else if( F.lSize == 2 ) x = va_arg( vaArgs.args, uint64_t );
else x = va_arg( vaArgs.args, unsigned int );
if( F.hSize == 1 ) x = (unsigned short)( x & 0xFFFF );
else if( F.hSize == 2 ) x = (unsigned char)( x & 0xFF );
F.sign = 0;
goto number;
number:
if( F.suppress ) continue;
if( ( base == 2 ) && ( F.altForm > 1 ) )
{
i = PrintFWriteBits( x, &F, buf );
s = buf;
}
else
{
if( !F.havePrecision )
{
if( F.zeroPad )
{
extra = 0;
if( F.altForm )
{
if( base == 8 ) extra += 1; // Make room for the leading "0".
else if( base != 10 ) extra += 2; // Make room for the leading "0x", "0b", etc.
}
if( F.sign ) extra += 1; // Make room for the leading "+" or "-".
F.precision = ( F.fieldWidth > extra ) ? ( F.fieldWidth - extra ) : 0;
}
if( F.precision < 1 ) F.precision = 1;
}
if( F.precision > ( sizeof( buf ) - 1 ) ) F.precision = sizeof( buf ) - 1;
p = buf + sizeof( buf );
i = 0;
if( F.group )
{
n = 0;
for( ;; )
{
Divide64x32( x, base, remain );
*--p = digits[ remain ]; ++i; ++n;
if( !x ) break;
if( ( n % 3 ) == 0 ) { *--p = ','; ++i; }
}
}
else
{
while( x )
{
Divide64x32( x, base, remain );
*--p = digits[ remain ]; ++i;
}
}
for( ; i < (int) F.precision; ++i ) *--p = '0';
if( F.altForm )
{
if( base == 8 ) { *--p = '0'; i += 1; }
else if( base != 10 ) { *--p = (char) c; *--p = '0'; i += 2; }
}
if( F.sign ) { *--p = F.sign; ++i; }
s = p;
}
break;
#if( PRINTF_ENABLE_FLOATING_POINT )
case 'f': // %f: Floating point
{
char fpFormat[ 9 ];
double dx;
i = 0;
fpFormat[ i++ ] = '%';
if( F.forceSign ) fpFormat[ i++ ] = '+';
if( F.altForm ) fpFormat[ i++ ] = '#';
if( F.zeroPad ) fpFormat[ i++ ] = '0';
fpFormat[ i++ ] = '*';
if( F.havePrecision )
{
fpFormat[ i++ ] = '.';
fpFormat[ i++ ] = '*';
}
fpFormat[ i++ ] = 'f';
fpFormat[ i ] = '\0';
i = (int) F.fieldWidth;
if( F.leftJustify ) i = -i;
dx = va_arg( vaArgs.args, double );
if( F.suppress ) continue;
if( F.havePrecision ) i = snprintf( buf, sizeof( buf ), fpFormat, i, (int) F.precision, dx );
else i = snprintf( buf, sizeof( buf ), fpFormat, i, dx );
if( i < 0 ) { err = i; goto error; }
s = buf;
break;
}
#endif
#if( TARGET_OS_WINDOWS && !defined( UNICODE ) && !defined( _UNICODE ) )
case 'T': // %T: TCHAR string (Windows only)
#endif
case 's': // %s: String
src = va_arg( vaArgs.args, const char * );
if( F.suppress ) continue;
if( !src && ( !F.havePrecision || ( F.precision != 0 ) ) ) { s = "<<NULL>>"; i = 8; break; }
if( F.group && F.havePrecision )
{
if( F.precision >= 2 ) F.precision -= 2;
else { F.precision = 0; F.group = '\0'; }
}
i = PrintFWriteString( src, &F, buf, &s );
if( F.group == 1 ) { F.prefix = '\''; F.suffix = '\''; }
else if( F.group == 2 ) { F.prefix = '"'; F.suffix = '"'; }
break;
#if( TARGET_OS_WINDOWS && ( defined( UNICODE ) || defined( _UNICODE ) ) )
case 'T': // %T: TCHAR string (Windows only)
#endif
case 'S': // %S: Unicode String
a = va_arg( vaArgs.args, uint8_t * );
if( F.suppress ) continue;
if( !a && ( !F.havePrecision || ( F.precision != 0 ) ) ) { s = "<<NULL>>"; i = 8; break; }
if( F.group && F.havePrecision )
{
if( F.precision >= 2 ) F.precision -= 2;
else { F.precision = 0; F.group = '\0'; }
}
i = PrintFWriteUnicodeString( a, &F, buf );
s = buf;
if( F.group == 1 ) { F.prefix = '\''; F.suffix = '\''; }
else if( F.group == 2 ) { F.prefix = '"'; F.suffix = '"'; }
break;
case '@': // %@: Cocoa/CoreFoundation Object
a = va_arg( vaArgs.args, uint8_t * );
if( F.suppress ) continue;
#if( DEBUG_CF_OBJECTS_ENABLED )
{
CFTypeRef cfObj;
cfObj = (CFTypeRef) a;
if( !cfObj ) cfObj = CFSTR( "<<NULL>>" );
if( F.group && F.havePrecision )
{
if( F.precision >= 2 ) F.precision -= 2;
else { F.precision = 0; F.group = '\0'; }
}
if( F.group == 1 ) { F.prefix = '\''; F.suffix = '\''; }
else if( F.group == 2 ) { F.prefix = '"'; F.suffix = '"'; }
#if( !CFLITE_ENABLED || CFL_XML )
if( F.altForm ) err = PrintFWriteCFXMLObject( inContext, &F, cfObj );
else
#endif
err = PrintFWriteCFObject( inContext, &F, cfObj, buf );
if( err < 0 ) goto error;
total += err;
continue;
}
#else
i = SNPrintF( buf, sizeof( buf ), "<<%%@=%p WITH CF OBJECTS DISABLED>>", a );
s = buf;
break;
#endif
case 'm': // %m: Error Message
{
OSStatus errCode;
errCode = va_arg( vaArgs.args, OSStatus );
if( F.suppress ) continue;
if( F.altForm )
{
if( PrintFIsPrintable( ( errCode >> 24 ) & 0xFF ) &&
PrintFIsPrintable( ( errCode >> 16 ) & 0xFF ) &&
PrintFIsPrintable( ( errCode >> 8 ) & 0xFF ) &&
PrintFIsPrintable( errCode & 0xFF ) )
{
if( F.altForm == 2 )
{
i = SNPrintF( buf, sizeof( buf ), "%-11d 0x%08X '%C' ",
(int) errCode, (unsigned int) errCode, (uint32_t) errCode );
}
else
{
i = SNPrintF( buf, sizeof( buf ), "%d/0x%X/'%C' ",
(int) errCode, (unsigned int) errCode, (uint32_t) errCode );
}
}
else
{
if( F.altForm == 2 )
{
i = SNPrintF( buf, sizeof( buf ), "%-11d 0x%08X '^^^^' ",
(int) errCode, (unsigned int) errCode, (uint32_t) errCode );
}
else
{
i = SNPrintF( buf, sizeof( buf ), "%d/0x%X ",
(int) errCode, (unsigned int) errCode, (uint32_t) errCode );
}
}
}
else
{
#if( DEBUG || DEBUG_EXPORT_ERROR_STRINGS )
i = 0;
#else
i = SNPrintF( buf, sizeof( buf ), "%d/0x%X ", (int) errCode, (unsigned int) errCode );
#endif
}
#if( DEBUG || DEBUG_EXPORT_ERROR_STRINGS )
DebugGetErrorString( errCode, &buf[ i ], sizeof( buf ) - ( (size_t) i ) );
#endif
s = buf;
for( i = 0; s[ i ]; ++i ) {}
break;
}
case 'H': // %H: Hex Dump
a = va_arg( vaArgs.args, uint8_t * );
size = (size_t) va_arg( vaArgs.args, int );
sizeMax = (size_t) va_arg( vaArgs.args, int );
if( F.suppress ) continue;
if( a || ( size == 0 ) )
{
if( size == kSizeCString ) size = strlen( (const char *) a );
if( F.precision == 0 ) err = PrintFWriteHexOneLine( inContext, &F, a, Min( size, sizeMax ) );
else if( F.precision == 1 ) err = PrintFWriteHex( inContext, &F, (int) F.fieldWidth, a, size, sizeMax );
else if( F.precision == 2 )
{
if( size <= 0 ) err = PrintFCore( inContext, "(0 bytes)\n" );
else if ( size <= 16 ) err = PrintFWriteHex( inContext, &F, 0, a, size, sizeMax );
else
{
err = PrintFCore( inContext, "\n" );
if( err < 0 ) goto error;
err = PrintFWriteHex( inContext, &F, (int) F.fieldWidth, a, size, sizeMax );
}
}
else if( F.precision == 3 ) err = PrintFWriteHexByteStream( inContext, false, a, Min( size, sizeMax ) );
else if( F.precision == 4 ) err = PrintFWriteHexByteStream( inContext, true, a, Min( size, sizeMax ) );
else err = PrintFCore( inContext, "<< BAD %%H PRECISION >>" );
if( err < 0 ) goto error;
total += err;
}
else
{
err = PrintFCore( inContext, "<<NULL %zu/%zu>>", size, sizeMax );
if( err < 0 ) goto error;
total += err;
}
continue;
case 'c': // %c: Character
c = va_arg( vaArgs.args, int );
if( F.suppress ) continue;
if( F.group )
{
buf[ 0 ] = '\'';
buf[ 1 ] = PrintFMakePrintable( c );
buf[ 2 ] = '\'';
i = 3;
}
else
{
buf[ 0 ] = (char) c;
i = 1;
}
s = buf;
break;
case 'C': // %C: FourCharCode
x = va_arg( vaArgs.args, uint32_t );
if( F.suppress ) continue;
i = 0;
if( F.group ) buf[ i++ ] = '\'';
buf[ i ] = (char)( ( x >> 24 ) & 0xFF ); buf[ i ] = PrintFMakePrintable( buf[ i ] ); ++i;
buf[ i ] = (char)( ( x >> 16 ) & 0xFF ); buf[ i ] = PrintFMakePrintable( buf[ i ] ); ++i;
buf[ i ] = (char)( ( x >> 8 ) & 0xFF ); buf[ i ] = PrintFMakePrintable( buf[ i ] ); ++i;
buf[ i ] = (char)( x & 0xFF ); buf[ i ] = PrintFMakePrintable( buf[ i ] ); ++i;
if( F.group ) buf[ i++ ] = '\'';
s = buf;
break;
case 'a': // %a: Address
a = va_arg( vaArgs.args, const uint8_t * );
if( F.suppress ) continue;
if( !a ) { s = "<<NULL>>"; i = 8; break; }
i = PrintFWriteAddr( a, &F, buf );
s = buf;
break;
case 'N': // %N Now (date/time string).
if( F.suppress ) continue;
#if( TARGET_OS_POSIX )
{
struct timeval now;
time_t nowTT;
struct tm * nowTM;
char dateTimeStr[ 24 ];
char amPMStr[ 8 ];
gettimeofday( &now, NULL );
nowTT = now.tv_sec;
nowTM = localtime( &nowTT );
if( F.altForm ) strftime( dateTimeStr, sizeof( dateTimeStr ), "%Y-%m-%d_%I-%M-%S", nowTM );
else strftime( dateTimeStr, sizeof( dateTimeStr ), "%Y-%m-%d %I:%M:%S", nowTM );
strftime( amPMStr, sizeof( amPMStr ), "%p", nowTM );
i = SNPrintF( buf, sizeof( buf ), "%s.%06u%c%s", dateTimeStr, now.tv_usec, F.altForm ? '-' : ' ', amPMStr );
s = buf;
}
#elif( TARGET_HAS_STD_C_LIB )
{
time_t now;
struct tm * nowTM;
buf[ 0 ] = '\0';
now = time( NULL );
nowTM = localtime( &now );
if( F.altForm ) i = (int) strftime( buf, sizeof( buf ), "%Y-%m-%d_%I-%M-%S-%p", nowTM );
else i = (int) strftime( buf, sizeof( buf ), "%Y-%m-%d %I:%M:%S %p", nowTM );
s = buf;
}
#elif( TARGET_OS_DARWIN_KERNEL || ( TARGET_OS_NETBSD && TARGET_KERNEL ) )
{
struct timeval now;
int64_t secs;
int year, month, day, hour, minute, second;
microtime( &now );
secs = now.tv_sec + ( INT64_C( 719163 ) * kSecondsPerDay ); // Seconds to 1970-01-01 00:00:00.
SecondsToYMD_HMS( secs, &year, &month, &day, &hour, &minute, &second );
if( F.altForm )
{
i = SNPrintF( buf, sizeof( buf ), "%04d-%02d-%02d_%02d-%02d-%02d.%06u-%s",
year, month, day, Hour24ToHour12( hour ), minute, second, now.tv_usec, Hour24ToAMPM( hour ) );
}
else
{
i = SNPrintF( buf, sizeof( buf ), "%04d-%02d-%02d %02d:%02d:%02d.%06u %s",
year, month, day, Hour24ToHour12( hour ), minute, second, now.tv_usec, Hour24ToAMPM( hour ) );
}
s = buf;
}
#else
s = "<<NO TIME>>";
i = 11;
#endif
break;
case 'U': // %U: UUID
a = va_arg( vaArgs.args, const uint8_t * );
if( F.suppress ) continue;
if( !a ) { s = "<<NULL>>"; i = 8; break; }
// Note: Windows and EFI treat some sections as 32-bit and 16-bit little endian values and those are the
// most common UUID's so default to that, but allow %#U to print big-endian UUIDs.
if( F.altForm == 0 )
{
i = SNPrintF( buf, sizeof( buf ), "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
a[ 3 ], a[ 2 ], a[ 1 ], a[ 0 ], a[ 5 ], a[ 4 ], a[ 7 ], a[ 6 ],
a[ 8 ], a[ 9 ], a[ 10 ], a[ 11 ], a[ 12 ], a[ 13 ], a[ 14 ], a[ 15 ] );
}
else
{
i = SNPrintF( buf, sizeof( buf ), "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
a[ 0 ], a[ 1 ], a[ 2 ], a[ 3 ], a[ 4 ], a[ 5 ], a[ 6 ], a[ 7 ],
a[ 8 ], a[ 9 ], a[ 10 ], a[ 11 ], a[ 12 ], a[ 13 ], a[ 14 ], a[ 15 ] );
}
s = buf;
break;
case 'v' : // %v: NumVersion
x = va_arg( vaArgs.args, unsigned int );
if( F.suppress ) continue;
i = PrintFWriteNumVersion( (uint32_t) x, buf );
s = buf;
break;
case 'V': // %V: Nested PrintF format string and va_list.
{
const char * nestedFormat;
va_list * nestedArgs;
nestedFormat = va_arg( vaArgs.args, const char * );
nestedArgs = va_arg( vaArgs.args, va_list * );
if( F.suppress ) continue;
if( !nestedFormat || !nestedArgs ) { s = "<<NULL>>"; i = 8; break; }
err = PrintFCoreVAList( inContext, nestedFormat, *nestedArgs );
if( err < 0 ) goto error;
total += err;
continue;
}
case 'n' : // %n: Receive the number of characters written so far.
p = va_arg( vaArgs.args, char * );
if( F.hSize == 1 ) *( (short *) p ) = (short) total;
else if( F.hSize == 2 ) *( (char *) p ) = (char) total;
else if( F.lSize == 1 ) *( (long *) p ) = (long) total;
else if( F.lSize == 2 ) *( (int64_t *) p ) = (long) total;
else *( (int *) p ) = total;
continue;
case '%': // %%: Literal %
if( F.suppress ) continue;
buf[ 0 ] = '%';
i = 1;
s = buf;
break;
case '{': // %{<extension>}
{
const char * extensionPtr;
size_t extensionLen;
PrintFExtension * extension;
extensionPtr = ++fmt;
while( ( c != '\0' ) && ( c != '}' ) ) c = *++fmt;
extensionLen = (size_t)( fmt - extensionPtr );
// %{asbd}: AudioStreamBasicDescription
if( strnicmpx( extensionPtr, extensionLen, "asbd" ) == 0 )
{
const AudioStreamBasicDescription * const absd = va_arg( vaArgs.args, const AudioStreamBasicDescription * );
if( F.suppress ) continue;
err = PrintFWriteAudioStreamBasicDescription( inContext, absd );
if( err < 0 ) goto error;
total += err;
continue;
}
// %{cec}: HDMI CEC message.
if( strnicmpx( extensionPtr, extensionLen, "cec" ) == 0 )
{
a = va_arg( vaArgs.args, uint8_t * );
size = (size_t) va_arg( vaArgs.args, int );
if( F.suppress ) continue;
err = PrintFWriteCEC( inContext, a, size );
if( err < 0 ) goto error;
total += err;
continue;
}
// %{dur}: Time Duration (e.g. 930232 seconds prints "10d 18h 23m 52s").
// %#{dur}: Time Duration (e.g. 930232 seconds prints "10d 18:23:52").
if( strnicmpx( extensionPtr, extensionLen, "dur" ) == 0 )
{
if( F.lSize == 1 ) x = va_arg( vaArgs.args, unsigned long );
else if( F.lSize == 2 ) x = va_arg( vaArgs.args, uint64_t );
else x = va_arg( vaArgs.args, unsigned int );
if( F.hSize == 1 ) x = (unsigned short)( x & 0xFFFF );
else if( F.hSize == 2 ) x = (unsigned char)( x & 0xFF );
if( F.suppress ) continue;
i = PrintFWriteTimeDuration( x, F.altForm, buf );
s = buf;
break;
}
// %{end}: End printing (used with ? for conditional suppression).
if( strnicmpx( extensionPtr, extensionLen, "end" ) == 0 )
{
if( F.suppress ) continue;
goto exit;
}
// %{fill}: Repeat a single character N times.
if( strnicmpx( extensionPtr, extensionLen, "fill" ) == 0 )
{
c = va_arg( vaArgs.args, int );
size = (size_t) va_arg( vaArgs.args, int );
if( F.suppress ) continue;
err = PrintFWriteFill( inContext, c, size, buf );
if( err < 0 ) goto error;
total += err;
continue;
}
// %{flags}: Bit flags (e.g. "0x43 <POWER LINK ERROR>").
if( strnicmpx( extensionPtr, extensionLen, "flags" ) == 0 )
{
if( F.lSize == 1 ) x = va_arg( vaArgs.args, unsigned long );
else if( F.lSize == 2 ) x = va_arg( vaArgs.args, uint64_t );
else x = va_arg( vaArgs.args, unsigned int );
if( F.hSize == 1 ) x = (unsigned short)( x & 0xFFFF );
else if( F.hSize == 2 ) x = (unsigned char)( x & 0xFF );
s = va_arg( vaArgs.args, const char * );
if( F.suppress ) continue;
err = PrintFWriteFlags( inContext, &F, s ? s : "\x00", x );
if( err < 0 ) goto error;
total += err;
continue;
}
// %{pid}: Process name (with optional numeric PID).
if( strnicmpx( extensionPtr, extensionLen, "pid" ) == 0 )
{
#if( TARGET_OS_POSIX )
pid_t pid;
if( sizeof( pid_t ) > sizeof( int ) ) pid = (pid_t) va_arg( vaArgs.args, int64_t );
else pid = (pid_t) va_arg( vaArgs.args, int );
if( F.suppress ) continue;
*buf = '\0';
GetProcessNameByPID( pid, buf, sizeof( buf ) );
if( F.altForm ) err = PrintFCore( inContext, "%s:%lld", buf, (int64_t) pid );
else err = PrintFCore( inContext, "%s", buf );
#else
err = PrintFCore( inContext, "<< ERROR: %%{pid} not supported on this platform >>" );
#endif
if( err < 0 ) goto error;
total += err;
continue;
}
// %{ptr}: Obfuscated pointer.
if( strnicmpx( extensionPtr, extensionLen, "ptr" ) == 0 )
{
a = va_arg( vaArgs.args, uint8_t * );
if( F.suppress ) continue;
err = PrintFWriteObfuscatedPtr( inContext, a );
if( err < 0 ) goto error;
total += err;
continue;
}
// %{sline}: Single line string. \r and \n are replaced with ⏎. Arg=ptr to string.
if( strnicmpx( extensionPtr, extensionLen, "sline" ) == 0 )
{
s = va_arg( vaArgs.args, const char * );
size = va_arg( vaArgs.args, size_t );
if( F.suppress ) continue;
if( size == kSizeCString ) size = strlen( s );
err = PrintFWriteSingleLineText( inContext, s, size );
if( err < 0 ) goto error;
total += err;
continue;
}
// %{text}: Multi-line text (with optional indenting).
if( strnicmpx( extensionPtr, extensionLen, "text" ) == 0 )
{
s = va_arg( vaArgs.args, const char * );
size = va_arg( vaArgs.args, size_t );
if( F.suppress ) continue;
if( size == kSizeCString ) size = strlen( s );
err = PrintFWriteMultiLineText( inContext, &F, s, size );
if( err < 0 ) goto error;
total += err;
continue;
}
// %{tlv8}: 8-bit Type-Length-Value (TLV) data.
if( strnicmpx( extensionPtr, extensionLen, "tlv8" ) == 0 )
{
s = va_arg( vaArgs.args, const char * );
a = va_arg( vaArgs.args, uint8_t * );
size = (size_t) va_arg( vaArgs.args, int );
if( F.suppress ) continue;
err = PrintFWriteTLV8( inContext, &F, s ? s : "\x00", a, size );
if( err < 0 ) goto error;
total += err;
continue;
}
// %{tpl}: EFI Task Priority Level (TPL).
// %{txt}: DNS TXT record name=value pairs.
if( strnicmpx( extensionPtr, extensionLen, "txt" ) == 0 )
{
a = va_arg( vaArgs.args, uint8_t * );
size = va_arg( vaArgs.args, size_t );
if( F.suppress ) continue;
err = PrintFWriteTXTRecord( inContext, &F, a, size );
if( err < 0 ) goto error;
total += err;
continue;
}
// %{xml}: XML-escaped text.
if( strnicmpx( extensionPtr, extensionLen, "xml" ) == 0 )
{
s = va_arg( vaArgs.args, const char * );
size = va_arg( vaArgs.args, size_t );
if( F.suppress ) continue;
err = PrintFWriteXMLEscaped( inContext, s, size );
if( err < 0 ) goto error;
total += err;
continue;
}
// %{xpc}: XPC Object.
if( strnicmpx( extensionPtr, extensionLen, "xpc" ) == 0 )
{
a = va_arg( vaArgs.args, uint8_t * );
if( F.suppress ) continue;
if( !a ) { s = "<<NULL>>"; i = 8; break; }
#if( XPC_ENABLED )
p = xpc_copy_description( (xpc_object_t) a );
if( !p ) { s = "<<NULL XPC DESC>>"; i = 17; break; }
err = PrintFWriteMultiLineText( inContext, &F, p, strlen( p ) );
free( p );
if( err < 0 ) goto error;
total += err;
continue;
#else
s = "<<NO XPC SUPPORT>>";
i = 18;
break;
#endif
}
// Search extensions.
MinimalMutexEnsureInitialized( gPrintFUtilsLock );
MinimalMutexLock( gPrintFUtilsLock );
for( extension = gExtensionList; extension; extension = extension->next )
{
if( strnicmpx( extensionPtr, extensionLen, extension->name ) == 0 )
{
break;
}
}
if( extension )
{
err = extension->handler_f( inContext, &F, &vaArgs, extension->context );
MinimalMutexUnlock( gPrintFUtilsLock );
if( err < 0 ) goto error;
total += err;
continue;
}
MinimalMutexUnlock( gPrintFUtilsLock );
// Unknown extension.
i = SNPrintF( buf, sizeof( buf ), "<<UNKNOWN PRINTF EXTENSION '%.*s'>>", (int) extensionLen, extensionPtr );
s = buf;
break;
}
default:
i = SNPrintF( buf, sizeof( buf ), "<<UNKNOWN FORMAT CONVERSION CODE %%%c>>", c );
s = buf;
break;
}
// Print the text with the correct padding, etc.
err = PrintFWriteText( inContext, &F, s, (size_t) i );
if( err < 0 ) goto error;
total += err;
}
exit:
return( total );
error:
return( err );
}
//===========================================================================================================================
// PrintFWriteAddr
//===========================================================================================================================
typedef struct
{
int32_t type;
union
{
uint8_t v4[ 4 ];
uint8_t v6[ 16 ];
} ip;
} mDNSAddrCompat;
static int PrintFWriteAddr( const uint8_t *inAddr, PrintFFormat *inFormat, char *outStr )
{
int n;
const uint8_t * a;
PrintFFormat * F;
a = inAddr;
F = inFormat;
if( ( F->altForm == 1 ) && ( F->precision == 4 ) ) // %#.4a - IPv4 address in host byte order
{
#if( TARGET_RT_BIG_ENDIAN )
n = SNPrintF( outStr, kPrintFBufSize, "%u.%u.%u.%u", a[ 0 ], a[ 1 ], a[ 2 ], a[ 3 ] );
#else
n = SNPrintF( outStr, kPrintFBufSize, "%u.%u.%u.%u", a[ 3 ], a[ 2 ], a[ 1 ], a[ 0 ] );
#endif
}
else if( ( F->altForm == 1 ) && ( F->precision == 6 ) ) // %#.6a - MAC address from host order uint64_t *.
{
#if( TARGET_RT_BIG_ENDIAN )
n = SNPrintF( outStr, kPrintFBufSize, "%02X:%02X:%02X:%02X:%02X:%02X",
a[ 2 ], a[ 3 ], a[ 4 ], a[ 5 ], a[ 6 ], a[ 7 ] );
#else
n = SNPrintF( outStr, kPrintFBufSize, "%02X:%02X:%02X:%02X:%02X:%02X",
a[ 5 ], a[ 4 ], a[ 3 ], a[ 2 ], a[ 1 ], a[ 0 ] );
#endif
}
else if( F->altForm == 1 ) // %#a: mDNSAddr
{
mDNSAddrCompat * ip;
ip = (mDNSAddrCompat *) inAddr;
if( ip->type == 4 )
{
a = ip->ip.v4;
n = SNPrintF( outStr, kPrintFBufSize, "%u.%u.%u.%u", a[ 0 ], a[ 1 ], a[ 2 ], a[ 3 ] );
}
else if( ip->type == 6 )
{
IPv6AddressToCString( ip->ip.v6, 0, 0, -1, outStr, 0 );
n = (int) strlen( outStr );
}
else
{
n = SNPrintF( outStr, kPrintFBufSize, "%s", "<< ERROR: %#a used with unsupported type: %d >>", ip->type );
}
}
else if( F->altForm == 2 ) // %##a: sockaddr
{
#if( defined( AF_INET ) )
int family;
family = ( (const struct sockaddr *) inAddr )->sa_family;
if( family == AF_INET )
{
const struct sockaddr_in * const sa4 = (const struct sockaddr_in *) a;
IPv4AddressToCString( ntoh32( sa4->sin_addr.s_addr ), (int) ntoh16( sa4->sin_port ), outStr );
n = (int) strlen( outStr );
}
#if( defined( AF_INET6 ) )
else if( family == AF_INET6 )
{
const struct sockaddr_in6 * const sa6 = (const struct sockaddr_in6 *) a;
IPv6AddressToCString( sa6->sin6_addr.s6_addr, sa6->sin6_scope_id, (int) ntoh16( sa6->sin6_port ), -1, outStr, 0 );
n = (int) strlen( outStr );
}
#endif
#if( defined( AF_LINK ) && defined( LLADDR ) )
else if( family == AF_LINK )
{
const struct sockaddr_dl * const sdl = (const struct sockaddr_dl *) a;
a = (const uint8_t *) LLADDR( sdl );
if( sdl->sdl_alen == 6 )
{
n = SNPrintF( outStr, kPrintFBufSize, "%02X:%02X:%02X:%02X:%02X:%02X",
a[ 0 ], a[ 1 ], a[ 2 ], a[ 3 ], a[ 4 ], a[ 5 ] );
}
else
{
n = SNPrintF( outStr, kPrintFBufSize, "<< AF_LINK %H >>", a, sdl->sdl_alen, sdl->sdl_alen );
}
}
#endif
else if( family == AF_UNSPEC )
{
n = SNPrintF( outStr, kPrintFBufSize, "<< AF_UNSPEC >>" );
}
else
{
n = SNPrintF( outStr, kPrintFBufSize, "<< ERROR: %%##a used with unknown family: %d >>", family );
}
#else
n = SNPrintF( outStr, kPrintFBufSize, "%s", "<< ERROR: %##a used without socket support >>" );
#endif
}
else
{
switch( F->precision )
{
case 2:
n = SNPrintF( outStr, kPrintFBufSize, "%u.%u.%u.%u", a[ 0 ] >> 4, a[ 0 ] & 0xF, a[ 1 ] >> 4, a[ 1 ] & 0xF );
break;
case 4:
n = SNPrintF( outStr, kPrintFBufSize, "%u.%u.%u.%u", a[ 0 ], a[ 1 ], a[ 2 ], a[ 3 ] );
break;
case 6:
n = SNPrintF( outStr, kPrintFBufSize, "%02X:%02X:%02X:%02X:%02X:%02X",
a[ 0 ], a[ 1 ], a[ 2 ], a[ 3 ], a[ 4 ], a[ 5 ] );
break;
case 8:
n = SNPrintF( outStr, kPrintFBufSize, "%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X",
a[ 0 ], a[ 1 ], a[ 2 ], a[ 3 ], a[ 4 ], a[ 5 ], a[ 6 ], a[ 7 ] );
break;
case 16:
IPv6AddressToCString( a, 0, 0, -1, outStr, 0 );
n = (int) strlen( outStr );
break;
default:
n = SNPrintF( outStr, kPrintFBufSize, "%s",
"<< ERROR: Must specify address size (i.e. %.4a=IPv4, %.6a=Enet, %.8a=Fibre, %.16a=IPv6) >>" );
break;
}
}
return( n );
}
//===========================================================================================================================
// PrintFWriteAudioStreamBasicDescription
//===========================================================================================================================
static int PrintFWriteAudioStreamBasicDescription( PrintFContext *inContext, const AudioStreamBasicDescription *inASBD )
{
int total = 0;
int n;
char buf[ 32 ];
const char * str;
uint32_t u32;
if( inASBD->mFormatID == kAudioFormatMPEG4AAC_ELD ) str = "ELD,";
else if( inASBD->mFormatID == kAudioFormatMPEG4AAC ) str = "AAC,";
else if( inASBD->mFormatID == kAudioFormatAppleLossless ) str = "ALAC,";
else if( inASBD->mFormatID == kAudioFormatLinearPCM ) str = "PCM,";
else { SNPrintF( buf, sizeof( buf ), "%C,", inASBD->mFormatID ); str = buf; }
n = PrintFCore( inContext, "%-5s %5u Hz", str, (uint32_t) inASBD->mSampleRate );
require_action_quiet( n >= 0, exit, total = n );
total += n;
if( inASBD->mBitsPerChannel > 0 )
{
n = PrintFCore( inContext, ", %2u-bit", inASBD->mBitsPerChannel );
require_action_quiet( n >= 0, exit, total = n );
total += n;
}
else if( inASBD->mFormatID == kAudioFormatAppleLossless )
{
if( inASBD->mFormatFlags == kAppleLosslessFormatFlag_16BitSourceData ) str = "16-bit";
else if( inASBD->mFormatFlags == kAppleLosslessFormatFlag_20BitSourceData ) str = "20-bit";
else if( inASBD->mFormatFlags == kAppleLosslessFormatFlag_24BitSourceData ) str = "24-bit";
else if( inASBD->mFormatFlags == kAppleLosslessFormatFlag_32BitSourceData ) str = "32-bit";
else str = "\?\?-bit";
n = PrintFCore( inContext, ", %s", str );
require_action_quiet( n >= 0, exit, total = n );
total += n;
}
if( inASBD->mChannelsPerFrame == 1 ) str = "Mono";
else if( inASBD->mChannelsPerFrame == 2 ) str = "Stereo";
else { SNPrintF( buf, sizeof( buf ), "%u ch", inASBD->mChannelsPerFrame ); str = buf; }
n = PrintFCore( inContext, ", %s", str );
require_action_quiet( n >= 0, exit, total = n );
total += n;
if( inASBD->mFormatFlags & kAudioFormatFlagIsNonInterleaved )
{
n = PrintFCore( inContext, ", Non-interleaved" );
require_action_quiet( n >= 0, exit, total = n );
total += n;
}
if( inASBD->mFormatID == kAudioFormatLinearPCM )
{
#if( TARGET_RT_LITTLE_ENDIAN )
if( inASBD->mFormatFlags & kLinearPCMFormatFlagIsBigEndian )
#else
if( !( inASBD->mFormatFlags & kLinearPCMFormatFlagIsBigEndian ) )
#endif
{
n = PrintFCore( inContext, ", Swapped" );
require_action_quiet( n >= 0, exit, total = n );
total += n;
}
if( inASBD->mFormatFlags & kAudioFormatFlagIsFloat )
{
n = PrintFCore( inContext, ", Float" );
require_action_quiet( n >= 0, exit, total = n );
total += n;
}
else if( ( inASBD->mBitsPerChannel > 0 ) && ( inASBD->mFormatFlags & kLinearPCMFormatFlagIsSignedInteger ) &&
( inASBD->mFormatFlags & kLinearPCMFormatFlagsSampleFractionMask ) )
{
u32 = ( inASBD->mFormatFlags & kLinearPCMFormatFlagsSampleFractionMask ) >> kLinearPCMFormatFlagsSampleFractionShift;
n = PrintFCore( inContext, ", %u.%u", inASBD->mBitsPerChannel - u32, u32 );
require_action_quiet( n >= 0, exit, total = n );
total += n;
}
}
if( inASBD->mFramesPerPacket > 1 )
{
n = PrintFCore( inContext, ", %u samples/packet", inASBD->mFramesPerPacket );
require_action_quiet( n >= 0, exit, total = n );
total += n;
}
exit:
return( total );
}
//===========================================================================================================================
// PrintFWriteBits
//===========================================================================================================================
static int PrintFWriteBits( uint64_t inX, PrintFFormat *inFormat, char *outStr )
{
#if( TYPE_LONGLONG_NATIVE )
static const uint64_t kBit0 = 1;
uint64_t x = inX;
#else
static const unsigned long kBit0 = 1;
unsigned long x = (unsigned long) inX;
#endif
int maxBit;
int bit;
char * dst;
char * lim;
dst = outStr;
lim = dst + kPrintFBufSize;
if( !inFormat->havePrecision )
{
if( inFormat->hSize == 1 ) inFormat->precision = 8 * sizeof( short );
else if( inFormat->hSize == 2 ) inFormat->precision = 8 * sizeof( char );
else if( inFormat->lSize == 1 ) inFormat->precision = 8 * sizeof( long );
else if( inFormat->lSize == 2 ) inFormat->precision = 8 * sizeof( int64_t );
else inFormat->precision = 8 * sizeof( int );
}
if( inFormat->precision > ( sizeof( kBit0 ) * 8 ) )
{
SNPrintF_Add( &dst, lim, "ERROR: << precision must be 0-%d >>", ( sizeof( kBit0 ) * 8 ) );
}
else
{
if( inFormat->precision < 1 ) inFormat->precision = 1;
maxBit = (int)( inFormat->precision - 1 );
if( inFormat->altForm == 2 )
{
for( bit = maxBit; bit >= 0; --bit )
{
if( x & ( kBit0 << bit ) )
{
SNPrintF_Add( &dst, lim, "%s%d", ( dst != outStr ) ? " " : "", bit );
}
}
}
else
{
for( bit = 0; bit <= maxBit; ++bit )
{
if( x & ( kBit0 << ( maxBit - bit ) ) )
{
SNPrintF_Add( &dst, lim, "%s%d", ( dst != outStr ) ? " " : "", bit );
}
}
}
}
return( (int)( dst - outStr ) );
}
//===========================================================================================================================
// PrintFWriteCEC
//===========================================================================================================================
#define CECAddressToString( X ) ( \
( (X) == 0 ) ? "TV" : \
( (X) == 1 ) ? "Record 1" : \
( (X) == 2 ) ? "Record 2" : \
( (X) == 3 ) ? "Tuner 1" : \
( (X) == 4 ) ? "Player1" : \
( (X) == 5 ) ? "Audio" : \
( (X) == 6 ) ? "Tuner 2" : \
( (X) == 7 ) ? "Tuner 3" : \
( (X) == 8 ) ? "Player 2" : \
( (X) == 9 ) ? "Record 3" : \
( (X) == 10 ) ? "Tuner 4" : \
( (X) == 11 ) ? "Player 3" : \
( (X) == 12 ) ? "Backup 1" : \
( (X) == 13 ) ? "Backup 2" : \
( (X) == 14 ) ? "Extra" : \
( (X) == 15 ) ? "Broadcast" : \
"?" )
static int PrintFWriteCEC( PrintFContext *ctx, const uint8_t *inData, size_t inLen )
{
int total = 0;
const uint8_t * src = inData;
const uint8_t * const end = src + inLen;
OSStatus err;
uint8_t srcAddr, dstAddr;
uint8_t opcode;
const char * label;
const char * params = NULL;
char labelBuf[ 32 ];
char paramsBuf[ 32 ];
size_t len;
require_action_quiet( ( end - src ) >= 1, exit, err = kUnderrunErr );
srcAddr = *src >> 4;
dstAddr = *src & 0xF;
src += 1;
if( ( end - src ) >= 1 )
{
opcode = *src++;
switch( opcode )
{
case 0x04: // ImageViewOn
label = "<Image View On>";
break;
case 0x0D: // TextViewOn
label = "<Text View On>";
break;
case 0x82: // ActiveSource
require_action_quiet( ( end - src ) >= 2, exit, err = kMalformedErr );
label = "<Active Source>";
SNPrintF( paramsBuf, sizeof( paramsBuf ), "%.2a", src );
params = paramsBuf;
break;
case 0x9D: // InactiveSource
label = "<Inactive Source>";
break;
case 0x85: // RequestActiveSource
label = "<Request Active Source>";
break;
case 0x80: // RoutingChange
require_action_quiet( ( end - src ) >= 4, exit, err = kMalformedErr );
label = "<Routing Change>";
SNPrintF( paramsBuf, sizeof( paramsBuf ), "%.2a -> %.2a", src, src + 2 );
params = paramsBuf;
break;
case 0x8F: // GivePowerStatus
label = "<Give Power Status>";
break;
case 0x90: // ReportPowerStatus
label = "<Report Power Status>";
break;
case 0x36: // Standby
label = "<Standby>";
break;
case 0x9F: // GetCECVersion
label = "<Get CEC Version>";
break;
case 0x9E: // CECVersion
label = "<CEC Version>";
require_action_quiet( ( end - src ) >= 1, exit, err = kMalformedErr );
if( src[ 0 ] == 4 ) params = "1.3a";
else if( src[ 0 ] == 5 ) params = "1.4";
else if( src[ 0 ] == 6 ) params = "2.0";
else
{
len = (size_t)( end - src );
SNPrintF( paramsBuf, sizeof( paramsBuf ), "Other %H", src, (int) len, (int) len );
params = paramsBuf;
}
break;
case 0x83: // GivePhysicalAddress
label = "<Give Physical Address>";
break;
case 0x84: // ReportPhysicalAddress
label = "<Report Physical Address>";
break;
case 0x8C: // GiveDeviceVendorID
label = "<Give Device Vendor ID>";
break;
case 0x87: // DeviceVendorID
label = "<Device Vendor ID>";
require_action_quiet( ( end - src ) >= 3, exit, err = kMalformedErr );
SNPrintF( paramsBuf, sizeof( paramsBuf ), "%02X-%02X-%02X", src[ 0 ], src[ 1 ], src[ 2 ] );
params = paramsBuf;
break;
case 0x86: // SetStreamPath
label = "<Set Stream Path>";
require_action_quiet( ( end - src ) >= 2, exit, err = kMalformedErr );
SNPrintF( paramsBuf, sizeof( paramsBuf ), "%.2a", src );
params = paramsBuf;
break;
case 0x46: // GetOSDName
label = "<Get OSD Name>";
break;
case 0x47: // SetOSDName
label = "<Set OSD Name>";
SNPrintF( paramsBuf, sizeof( paramsBuf ), "'%.*s'", (int)( end - src ), (const char *) src );
params = paramsBuf;
break;
case 0x32: // SetMenuLanguage
label = "<Set Menu Language>";
SNPrintF( paramsBuf, sizeof( paramsBuf ), "'%.*s'", (int)( end - src ), (const char *) src );
params = paramsBuf;
break;
case 0x8D: // MenuRequest
label = "<Menu Request>";
break;
case 0x8E: // MenuStatus
label = "<Menu Status>";
break;
case 0x44: // UserControlPressed
label = "<User Control Pressed>";
break;
case 0x45: // UserControlReleased
label = "<User Control Released>";
break;
case 0x00: // FeatureAbort
label = "<Feature Abort>";
break;
case 0x1A: // GiveDeckStatus
label = "<Give Deck Status>";
break;
case 0xA0: // VendorCommandWithID
label = "<Vendor Command with ID>";
break;
default:
SNPrintF( labelBuf, sizeof( labelBuf ), "<<? 0x%02X>>", opcode );
label = labelBuf;
break;
}
}
else
{
label = "<Poll>";
params = "";
}
if( !params )
{
len = (size_t)( end - src );
SNPrintF( paramsBuf, sizeof( paramsBuf ), "%H", src, (int) len, (int) len );
params = paramsBuf;
}
err = PrintFCore( ctx, "%-9s -> %9s: %s %s", CECAddressToString( srcAddr ), CECAddressToString( dstAddr ), label, params );
require_quiet( err >= 0, exit );
total += err;
err = kNoErr;
exit:
if( err ) total = PrintFCore( ctx, "<< MALFORMED CEC: %H >>", inData, (int) inLen, 64 );
return( total );
}
#if( DEBUG_CF_OBJECTS_ENABLED )
//===========================================================================================================================
// PrintFWriteCFObject
//===========================================================================================================================
typedef struct
{
PrintFContext * context;
PrintFFormat * format;
int indent;
int total; // Note: temporary total for a recursive operation.
OSStatus error;
} PrintFWriteCFObjectContext;
static int PrintFWriteCFObjectLevel( PrintFWriteCFObjectContext *inContext, CFTypeRef inObj, Boolean inPrintingArray );
static void PrintFWriteCFObjectApplier( const void *inKey, const void *inValue, void *inContext );
static int PrintFWriteCFObject( PrintFContext *inContext, PrintFFormat *inFormat, CFTypeRef inObj, char *inBuffer )
{
int total;
CFTypeID typeID;
const char * s;
int n;
typeID = CFGetTypeID( inObj );
// Boolean
if( typeID == CFBooleanGetTypeID() )
{
if( ( (CFBooleanRef) inObj ) == kCFBooleanTrue ) { s = "true"; n = 4; }
else { s = "false"; n = 5; }
total = PrintFWriteText( inContext, inFormat, s, (size_t) n );
}
// Number
else if( typeID == CFNumberGetTypeID() )
{
#if( !CFLITE_ENABLED || CFL_FLOATING_POINT_NUMBERS )
if( CFNumberIsFloatType( (CFNumberRef) inObj ) )
{
double dval = 0;
CFNumberGetValue( (CFNumberRef) inObj, kCFNumberDoubleType, &dval );
n = SNPrintF( inBuffer, kPrintFBufSize, "%f", dval );
}
else
#endif
{
int64_t s64 = 0;
CFNumberGetValue( (CFNumberRef) inObj, kCFNumberSInt64Type, &s64 );
n = SNPrintF( inBuffer, kPrintFBufSize, "%lld", s64 );
}
total = PrintFWriteText( inContext, inFormat, inBuffer, (size_t) n );
}
// String
else if( typeID == CFStringGetTypeID() )
{
CFStringRef const cfStr = (CFStringRef) inObj;
CFIndex cfLen;
size_t size;
cfLen = CFStringGetLength( cfStr );
size = (size_t) CFStringGetMaximumSizeForEncoding( cfLen, kCFStringEncodingUTF8 );
if( size > 0 )
{
char * cStr;
CFRange range;
CFIndex i;
cStr = (char *) malloc( size );
require_action_quiet( cStr, exit, total = kNoMemoryErr );
i = 0;
range = CFRangeMake( 0, cfLen );
CFStringGetBytes( cfStr, range, kCFStringEncodingUTF8, '^', false, (UInt8 *) cStr, (CFIndex) size, &i );
// Restrict the string length to the precision, but don't truncate in the middle of a UTF-8 character.
if( inFormat->havePrecision && ( i > (CFIndex) inFormat->precision ) )
{
for( i = (int) inFormat->precision; ( i > 0 ) && ( ( cStr[ i ] & 0xC0 ) == 0x80 ); --i ) {}
}
total = PrintFWriteText( inContext, inFormat, cStr, (size_t) i );
free( cStr );
}
else
{
// Note: this is needed because there may be field widths, etc. to fill.
total = PrintFWriteText( inContext, inFormat, "", 0 );
}
}
// Null
else if( typeID == CFNullGetTypeID() )
{
total = PrintFWriteText( inContext, inFormat, "Null", 4 );
}
#if( TARGET_OS_DARWIN && !COMMON_SERVICES_NO_CORE_SERVICES )
// URL
else if( typeID == CFURLGetTypeID() )
{
CFStringRef cfStr;
cfStr = CFURLGetString( (CFURLRef) inObj );
require_action_quiet( cfStr, exit, total = kUnknownErr );
total = PrintFWriteCFObject( inContext, inFormat, cfStr, inBuffer );
}
// UUID
else if( typeID == CFUUIDGetTypeID() )
{
CFUUIDBytes bytes;
bytes = CFUUIDGetUUIDBytes( (CFUUIDRef) inObj );
n = SNPrintF( inBuffer, kPrintFBufSize, "%#U", &bytes );
total = PrintFWriteText( inContext, inFormat, inBuffer, (size_t) n );
}
#endif
// Other
else
{
PrintFWriteCFObjectContext cfContext;
cfContext.context = inContext;
cfContext.format = inFormat;
cfContext.indent = (int) inFormat->fieldWidth;
cfContext.error = kNoErr;
total = PrintFWriteCFObjectLevel( &cfContext, inObj, false );
require_quiet( total >= 0, exit );
if( ( typeID == CFArrayGetTypeID() ) || ( typeID == CFDictionaryGetTypeID() ) )
{
n = inContext->callback( "\n", 1, inContext );
require_action_quiet( n > 0, exit, total = n );
total += n;
}
}
exit:
return( total );
}
//===========================================================================================================================
// PrintFWriteCFObjectLevel
//===========================================================================================================================
static int PrintFWriteCFObjectLevel( PrintFWriteCFObjectContext *inContext, CFTypeRef inObj, Boolean inPrintingArray )
{
int total = 0;
OSStatus err;
CFTypeID typeID;
CFIndex i, n;
CFTypeRef obj;
size_t size;
char buf[ 4 ];
typeID = CFGetTypeID( inObj );
// Array
if( typeID == CFArrayGetTypeID() )
{
err = print_indent( inContext->context, inContext->indent );
require_action_quiet( err >= 0, exit, total = err );
total += err;
n = CFArrayGetCount( (CFArrayRef) inObj );
if( n > 0 )
{
err = inContext->context->callback( "[\n", 2, inContext->context );
require_action_quiet( err >= 0, exit, total = err );
total += 2;
for( i = 0; i < n; )
{
obj = CFArrayGetValueAtIndex( (CFArrayRef) inObj, i );
++inContext->indent;
err = PrintFWriteCFObjectLevel( inContext, obj, true );
--inContext->indent;
require_action_quiet( err >= 0, exit, total = err );
total += err;
++i;
size = 0;
if( i < n ) buf[ size++ ] = ',';
buf[ size++ ] = '\n';
err = inContext->context->callback( buf, size, inContext->context );
require_action_quiet( err >= 0, exit, total = err );
total += 1;
}
err = print_indent( inContext->context, inContext->indent );
require_action_quiet( err >= 0, exit, total = err );
total += err;
err = inContext->context->callback( "]", 1, inContext->context );
require_action_quiet( err >= 0, exit, total = err );
total += 1;
}
else
{
err = inContext->context->callback( "[]", 2, inContext->context );
require_action_quiet( err >= 0, exit, total = err );
total += 2;
}
}
// Boolean
else if( typeID == CFBooleanGetTypeID() )
{
const char * boolStr;
err = print_indent( inContext->context, inContext->indent );
require_action_quiet( err >= 0, exit, total = err );
total += err;
if( ( (CFBooleanRef) inObj ) == kCFBooleanTrue ) { boolStr = "true"; size = 4; }
else { boolStr = "false"; size = 5; }
err = inContext->context->callback( boolStr, size, inContext->context );
require_action_quiet( err >= 0, exit, total = err );
total += (int) size;
}
// Data
else if( typeID == CFDataGetTypeID() )
{
int oldIndent;
oldIndent = inContext->indent;
size = (size_t) CFDataGetLength( (CFDataRef) inObj );
if( ( size <= 16 ) && !inPrintingArray )
{
inContext->indent = 0;
}
else
{
err = inContext->context->callback( "\n", 1, inContext->context );
require_action_quiet( err >= 0, exit, total = err );
total += 1;
inContext->indent = oldIndent + 1;
}
err = PrintFWriteHex( inContext->context, inContext->format, inContext->indent,
CFDataGetBytePtr( (CFDataRef) inObj ), size,
inContext->format->havePrecision ? inContext->format->precision : size );
require_action_quiet( err >= 0, exit, total = err );
total += err;
inContext->indent = oldIndent;
}
// Date
else if( typeID == CFDateGetTypeID() )
{
int year, month, day, hour, minute, second, micros;
err = print_indent( inContext->context, inContext->indent );
require_action_quiet( err >= 0, exit, total = err );
total += err;
CFDateGetComponents( (CFDateRef) inObj, &year, &month, &day, &hour, &minute, &second, µs );
err = PrintFCore( inContext->context, "%04d-%02d-%02d %02d:%02d:%02d.%06d",
year, month, day, hour, minute, second, micros );
require_action_quiet( err >= 0, exit, total = err );
total += err;
}
// Dictionary
else if( typeID == CFDictionaryGetTypeID() )
{
err = print_indent( inContext->context, inContext->indent );
require_action_quiet( err >= 0, exit, total = err );
total += err;
if( CFDictionaryGetCount( (CFDictionaryRef) inObj ) > 0 )
{
err = inContext->context->callback( "{\n", 2, inContext->context );
require_action_quiet( err >= 0, exit, total = err );
total += 2;
++inContext->indent;
inContext->total = total;
CFDictionaryApplyFunction( (CFDictionaryRef) inObj, PrintFWriteCFObjectApplier, inContext );
require_action_quiet( inContext->error >= 0, exit, total = inContext->error );
total = inContext->total;
--inContext->indent;
err = print_indent( inContext->context, inContext->indent );
require_action_quiet( err >= 0, exit, total = err );
total += err;
err = inContext->context->callback( "}", 1, inContext->context );
require_action_quiet( err >= 0, exit, total = err );
total += 1;
}
else
{
err = inContext->context->callback( "{}", 2, inContext->context );
require_action_quiet( err >= 0, exit, total = err );
total += 2;
}
}
// Number
else if( typeID == CFNumberGetTypeID() )
{
err = print_indent( inContext->context, inContext->indent );
require_action_quiet( err >= 0, exit, total = err );
total += err;
#if( !CFLITE_ENABLED || CFL_FLOATING_POINT_NUMBERS )
if( CFNumberIsFloatType( (CFNumberRef) inObj ) )
{
double dval = 0;
CFNumberGetValue( (CFNumberRef) inObj, kCFNumberDoubleType, &dval );
err = PrintFCore( inContext->context, "%f", dval );
}
else
#endif
{
int64_t s64 = 0;
CFNumberGetValue( (CFNumberRef) inObj, kCFNumberSInt64Type, &s64 );
err = PrintFCore( inContext->context, "%lld", s64 );
}
require_action_quiet( err >= 0, exit, total = err );
total += err;
}
// String
else if( typeID == CFStringGetTypeID() )
{
CFStringRef const cfStr = (CFStringRef) inObj;
err = print_indent( inContext->context, inContext->indent );
require_action_quiet( err >= 0, exit, total = err );
total += err;
err = inContext->context->callback( "\"", 1, inContext->context );
require_action_quiet( err >= 0, exit, total = err );
total += 1;
n = CFStringGetLength( cfStr );
size = (size_t) CFStringGetMaximumSizeForEncoding( n, kCFStringEncodingUTF8 );
if( size > 0 )
{
char * cStr;
CFRange range;
CFIndex converted;
cStr = (char *) malloc( size );
require_action_quiet( cStr, exit, total = kNoMemoryErr );
converted = 0;
range = CFRangeMake( 0, n );
CFStringGetBytes( cfStr, range, kCFStringEncodingUTF8, '^', false, (UInt8 *) cStr, (CFIndex) size, &converted );
err = inContext->context->callback( cStr, (size_t) converted, inContext->context );
free( cStr );
require_action_quiet( err >= 0, exit, total = err );
total += (int) converted;
}
err = inContext->context->callback( "\"", 1, inContext->context );
require_action_quiet( err >= 0, exit, total = err );
total += 1;
}
// Null
else if( typeID == CFNullGetTypeID() )
{
err = print_indent( inContext->context, inContext->indent );
require_action_quiet( err >= 0, exit, total = err );
total += err;
err = inContext->context->callback( "Null", 4, inContext->context );
require_action_quiet( err >= 0, exit, total = err );
total += 4;
}
#if( TARGET_OS_DARWIN && !COMMON_SERVICES_NO_CORE_SERVICES )
// URL
else if( typeID == CFURLGetTypeID() )
{
CFStringRef cfStr;
cfStr = CFURLGetString( (CFURLRef) inObj );
require_action_quiet( cfStr, exit, total = kUnknownErr );
err = PrintFWriteCFObjectLevel( inContext, cfStr, inPrintingArray );
require_action_quiet( err >= 0, exit, total = err );
total += err;
}
// UUID
else if( typeID == CFUUIDGetTypeID() )
{
CFUUIDBytes bytes;
err = print_indent( inContext->context, inContext->indent );
require_action_quiet( err >= 0, exit, total = err );
total += err;
bytes = CFUUIDGetUUIDBytes( (CFUUIDRef) inObj );
err = PrintFCore( inContext->context, "%#U", &bytes );
require_action_quiet( err >= 0, exit, total = err );
total += err;
}
#endif
// Unknown
else
{
err = print_indent( inContext->context, inContext->indent );
require_action_quiet( err >= 0, exit, total = err );
total += err;
#if( TARGET_OS_DARWIN && !COMMON_SERVICES_NO_CORE_SERVICES )
{
CFStringRef desc;
desc = CFCopyDescription( inObj );
if( desc )
{
err = PrintFCore( inContext->context, "%@", desc );
CFRelease( desc );
require_action_quiet( err >= 0, exit, total = err );
total += err;
goto exit;
}
}
#endif
err = PrintFCore( inContext->context, "<<UNKNOWN CF OBJECT TYPE: %d>>", (int) typeID );
require_action_quiet( err >= 0, exit, total = err );
total += err;
}
exit:
return( total );
}
//===========================================================================================================================
// PrintFWriteCFObjectApplier
//===========================================================================================================================
static void PrintFWriteCFObjectApplier( const void *inKey, const void *inValue, void *inContext )
{
int total;
PrintFWriteCFObjectContext * const context = (PrintFWriteCFObjectContext *) inContext;
CFTypeRef const value = (CFTypeRef) inValue;
OSStatus err;
CFTypeID typeID;
if( context->error ) return;
// Print the key.
err = PrintFWriteCFObjectLevel( context, (CFTypeRef) inKey, false );
require_action_quiet( err >= 0, exit, total = err );
total = err;
err = context->context->callback( " : ", 3, context->context );
require_action_quiet( err >= 0, exit, total = err );
total += 3;
// Print the value based on its type.
typeID = CFGetTypeID( value );
if( typeID == CFArrayGetTypeID() )
{
if( CFArrayGetCount( (CFArrayRef) inValue ) > 0 )
{
err = context->context->callback( "\n", 1, context->context );
require_action_quiet( err >= 0, exit, total = err );
total += 1;
err = PrintFWriteCFObjectLevel( context, value, true );
require_action_quiet( err >= 0, exit, total = err );
total += err;
err = context->context->callback( "\n", 1, context->context );
require_action_quiet( err >= 0, exit, total = err );
total += 1;
}
else
{
err = context->context->callback( "[]\n", 3, context->context );
require_action_quiet( err >= 0, exit, total = err );
total += 3;
}
}
else if( typeID == CFDictionaryGetTypeID() )
{
if( CFDictionaryGetCount( (CFDictionaryRef) inValue ) > 0 )
{
err = context->context->callback( "\n", 1, context->context );
require_action_quiet( err >= 0, exit, total = err );
total += 1;
err = PrintFWriteCFObjectLevel( context, value, false );
require_action_quiet( err >= 0, exit, total = err );
total += err;
err = context->context->callback( "\n", 1, context->context );
require_action_quiet( err >= 0, exit, total = err );
total += 1;
}
else
{
err = context->context->callback( "{}\n", 3, context->context );
require_action_quiet( err >= 0, exit, total = err );
total += 3;
}
}
else if( ( typeID == CFDataGetTypeID() ) && ( context->format->altForm != 2 ) )
{
err = PrintFWriteCFObjectLevel( context, value, false );
require_action_quiet( err >= 0, exit, total = err );
total += err;
}
else
{
int oldIndent;
oldIndent = context->indent;
context->indent = 0;
err = PrintFWriteCFObjectLevel( context, value, false );
require_action_quiet( err >= 0, exit, total = err );
total += err;
context->indent = oldIndent;
err = context->context->callback( "\n", 1, context->context );
require_action_quiet( err >= 0, exit, total = err );
total += 1;
}
exit:
context->total += total;
if( err < 0 ) context->error = err;
}
//===========================================================================================================================
// PrintFWriteCFXMLObject
//===========================================================================================================================
#if( !CFLITE_ENABLED || CFL_XML )
static int PrintFWriteCFXMLObject( PrintFContext *inContext, PrintFFormat *inFormat, CFTypeRef inObj )
{
int total = 0, err;
CFDataRef xmlData;
const char * xmlPtr;
size_t xmlLen;
xmlData = CFPropertyListCreateData( NULL, inObj, kCFPropertyListXMLFormat_v1_0, 0, NULL );
if( !xmlData )
{
err = PrintFCore( inContext, "<<PLIST NOT XML-ABLE>>" );
require_action_quiet( err >= 0, exit, total = err );
total += err;
goto exit;
}
xmlPtr = (const char *) CFDataGetBytePtr( xmlData );
xmlLen = (size_t) CFDataGetLength( xmlData );
err = PrintFWriteMultiLineText( inContext, inFormat, xmlPtr, xmlLen );
CFRelease( xmlData );
require_action_quiet( err >= 0, exit, total = err );
total += err;
exit:
return( total );
}
#endif // !CFLITE_ENABLED || CFL_XML
#endif // DEBUG_CF_OBJECTS_ENABLED
//===========================================================================================================================
// PrintFWriteFill
//===========================================================================================================================
static int PrintFWriteFill( PrintFContext *inContext, int inC, size_t inCount, char *inBuf )
{
int total = 0, n;
size_t len;
while( inCount > 0 )
{
len = Min( inCount, kPrintFBufSize );
memset( inBuf, inC, len );
inCount -= len;
n = inContext->callback( inBuf, len, inContext );
require_action_quiet( n >= 0, exit, total = n );
total += n;
}
exit:
return( total );
}
//===========================================================================================================================
// PrintFWriteFlags
//===========================================================================================================================
static int PrintFWriteFlags( PrintFContext *inContext, PrintFFormat *inFormat, const char *inDescriptors, uint64_t inX )
{
int total = 0, n;
uint64_t mask;
uint8_t i, bit;
const char * descPtr;
size_t len;
if( inFormat->altForm )
{
n = PrintFCore( inContext, "0x%llX ", inX );
require_action_quiet( n >= 0, exit, total = n );
total += n;
}
n = PrintFCore( inContext, "<" );
require_action_quiet( n >= 0, exit, total = n );
total += n;
for( i = 0; ( i < 64 ) && inX; ++i )
{
mask = UINT64_C( 1 ) << i;
if( !( inX & mask ) ) continue;
inX &= ~mask;
for( descPtr = inDescriptors; ; descPtr += ( len + 1 ) )
{
bit = (uint8_t)( *descPtr++ );
len = strlen( descPtr );
if( len == 0 ) break;
if( bit != i ) continue;
n = PrintFCore( inContext, " %s", descPtr );
require_action_quiet( n >= 0, exit, total = n );
total += n;
break;
}
}
n = PrintFCore( inContext, " >" );
require_action_quiet( n >= 0, exit, total = n );
total += n;
exit:
return( total );
}
//===========================================================================================================================
// PrintFWriteHex
//===========================================================================================================================
static int
PrintFWriteHex(
PrintFContext * inContext,
PrintFFormat * inFormat,
int inIndent,
const void * inData,
size_t inSize,
size_t inMaxSize )
{
int total = 0;
int err;
const uint8_t * start;
const uint8_t * ptr;
size_t size;
uint8_t hex1[ 64 ];
uint8_t hex2[ 64 ];
uint8_t * currHexPtr;
uint8_t * prevHexPtr;
uint8_t * tempHexPtr;
int dupCount;
size_t dupSize;
currHexPtr = hex1;
prevHexPtr = hex2;
dupCount = 0;
dupSize = 0;
start = (const uint8_t *) inData;
ptr = start;
size = ( inSize > inMaxSize ) ? inMaxSize : inSize;
for( ;; )
{
size_t chunkSize;
uint8_t ascii[ 64 ];
uint8_t * s;
uint8_t c;
size_t i;
// Build a hex string (space every 4 bytes) and pad with space to fill the full 16-byte range.
chunkSize = Min( size, 16 );
s = currHexPtr;
for( i = 0; i < 16; ++i )
{
if( ( i > 0 ) && ( ( i % 4 ) == 0 ) ) *s++ = ' ';
if( i < chunkSize )
{
*s++ = (uint8_t) kHexDigitsLowercase[ ptr[ i ] >> 4 ];
*s++ = (uint8_t) kHexDigitsLowercase[ ptr[ i ] & 0xF ];
}
else
{
*s++ = ' ';
*s++ = ' ';
}
}
*s++ = '\0';
check( ( (size_t)( s - currHexPtr ) ) < sizeof( hex1 ) );
// Build a string with the ASCII version of the data (replaces non-printable characters with '^').
// Pads the string with spaces to fill the full 16 byte range (so it lines up).
s = ascii;
for( i = 0; i < 16; ++i )
{
if( i < chunkSize )
{
c = ptr[ i ];
if( !PrintFIsPrintable( c ) )
{
c = '^';
}
}
else
{
c = ' ';
}
*s++ = c;
}
*s++ = '\0';
check( ( (size_t)( s - ascii ) ) < sizeof( ascii ) );
// Print the data.
if( inSize <= 16 )
{
err = print_indent( inContext, inIndent );
require_action_quiet( err >= 0, exit, total = err );
total += err;
err = PrintFCore( inContext, "%s |%s| (%zu bytes)\n", currHexPtr, ascii, inSize );
require_action_quiet( err >= 0, exit, total = err );
total += err;
}
else if( ptr == start )
{
err = print_indent( inContext, inIndent );
require_action_quiet( err >= 0, exit, total = err );
total += err;
err = PrintFCore( inContext, "+%04X: %s |%s| (%zu bytes)\n", (int)( ptr - start ), currHexPtr, ascii, inSize );
require_action_quiet( err >= 0, exit, total = err );
total += err;
}
else if( ( inFormat->group > 0 ) && ( memcmp( currHexPtr, prevHexPtr, 32 ) == 0 ) )
{
dupCount += 1;
dupSize += chunkSize;
}
else
{
if( dupCount > 0 )
{
err = print_indent( inContext, inIndent );
require_action_quiet( err >= 0, exit, total = err );
total += err;
err = PrintFCore( inContext, "* (%zu more identical bytes, %zu total)\n", dupSize, dupSize + 16 );
require_action_quiet( err >= 0, exit, total = err );
total += err;
dupCount = 0;
dupSize = 0;
}
err = print_indent( inContext, inIndent );
require_action_quiet( err >= 0, exit, total = err );
total += err;
err = PrintFCore( inContext, "+%04X: %s |%s|\n", (int)( ptr - start ), currHexPtr, ascii );
require_action_quiet( err >= 0, exit, total = err );
total += err;
}
tempHexPtr = prevHexPtr;
prevHexPtr = currHexPtr;
currHexPtr = tempHexPtr;
ptr += chunkSize;
size -= chunkSize;
if( size <= 0 ) break;
}
if( dupCount > 0 )
{
err = print_indent( inContext, inIndent );
require_action_quiet( err >= 0, exit, total = err );
total += err;
err = PrintFCore( inContext, "* (%zu more identical bytes, %zu total)\n", dupSize, dupSize + 16 );
require_action_quiet( err >= 0, exit, total = err );
total += err;
}
if( inSize > inMaxSize )
{
err = print_indent( inContext, inIndent );
require_action_quiet( err >= 0, exit, total = err );
total += err;
err = PrintFCore( inContext, "... %zu more bytes ...\n", inSize - inMaxSize );
require_action_quiet( err >= 0, exit, total = err );
total += err;
}
exit:
return( total );
}
//===========================================================================================================================
// PrintFWriteHexOneLine
//===========================================================================================================================
static int PrintFWriteHexOneLine( PrintFContext *inContext, PrintFFormat *inFormat, const uint8_t *inData, size_t inSize )
{
int total = 0;
int err;
size_t i;
size_t j;
uint8_t b;
char hex[ 3 ];
char c;
require_quiet( inSize > 0, exit );
// Print each byte as hex.
if( inFormat->altForm != 2 )
{
for( i = 0; i < inSize; ++i )
{
j = 0;
if( i != 0 ) hex[ j++ ] = ' ';
b = inData[ i ];
hex[ j++ ] = kHexDigitsLowercase[ ( b >> 4 ) & 0x0F ];
hex[ j++ ] = kHexDigitsLowercase[ b & 0x0F ];
err = inContext->callback( hex, j, inContext );
require_action_quiet( err >= 0, exit, total = err );
total += (int) j;
}
}
// Print each byte as ASCII if requested.
if( inFormat->altForm > 0 )
{
if( total > 0 )
{
err = inContext->callback( " |", 2, inContext );
require_action_quiet( err >= 0, exit, total = err );
total += 2;
}
else
{
err = inContext->callback( "|", 1, inContext );
require_action_quiet( err >= 0, exit, total = err );
total += 1;
}
for( i = 0; i < inSize; ++i )
{
c = (char) inData[ i ];
if( ( c < 0x20 ) || ( c >= 0x7F ) ) c = '^';
err = inContext->callback( &c, 1, inContext );
require_action_quiet( err >= 0, exit, total = err );
total += 1;
}
err = inContext->callback( "|", 1, inContext );
require_action_quiet( err >= 0, exit, total = err );
total += 1;
}
exit:
return( total );
}
//===========================================================================================================================
// PrintFWriteHexByteStream
//===========================================================================================================================
static int PrintFWriteHexByteStream( PrintFContext *inContext, Boolean inUppercase, const uint8_t *inData, size_t inSize )
{
const char * const digits = inUppercase ? kHexDigitsUppercase : kHexDigitsLowercase;
int total = 0;
int err;
const uint8_t * src;
const uint8_t * end;
char buf[ 64 ];
char * dst;
char * lim;
size_t len;
src = inData;
end = src + inSize;
dst = buf;
lim = dst + sizeof( buf );
while( src < end )
{
uint8_t b;
if( dst == lim )
{
len = (size_t)( dst - buf );
err = inContext->callback( buf, len, inContext );
require_action_quiet( err >= 0, exit, total = err );
total += (int) len;
dst = buf;
}
b = *src++;
*dst++ = digits[ ( b >> 4 ) & 0x0F ];
*dst++ = digits[ b & 0x0F ];
}
if( dst != buf )
{
len = (size_t)( dst - buf );
err = inContext->callback( buf, len, inContext );
require_action_quiet( err >= 0, exit, total = err );
total += (int) len;
}
exit:
return( total );
}
//===========================================================================================================================
// PrintFWriteMultiLineText
//===========================================================================================================================
static int PrintFWriteMultiLineText( PrintFContext *inContext, PrintFFormat *inFormat, const char *inStr, size_t inLen )
{
int total = 0, err;
const char * line;
const char * end;
const char * eol;
const char * next;
unsigned int i, n;
size_t len;
for( line = inStr, end = line + inLen; line < end; line = next )
{
for( eol = line; ( eol < end ) && ( *eol != '\r' ) && ( *eol != '\n' ); ++eol ) {}
if( eol < end )
{
if( ( eol[ 0 ] == '\r' ) && ( ( ( eol + 1 ) < end ) && ( eol[ 1 ] == '\n' ) ) )
{
next = eol + 2;
}
else
{
next = eol + 1;
}
}
else
{
next = eol;
}
if( ( line < eol ) && ( *line != '\r' ) && ( *line != '\n' ) )
{
n = inFormat->fieldWidth;
for( i = 0; i < n; ++i )
{
err = inContext->callback( " ", 4, inContext );
require_action_quiet( err >= 0, exit, total = err );
total += 4;
}
}
if( line < eol )
{
len = (size_t)( eol - line );
err = inContext->callback( line, len, inContext );
require_action_quiet( err >= 0, exit, total = err );
total += (int) len;
}
if( eol < end )
{
err = inContext->callback( "\n", 1, inContext );
require_action_quiet( err >= 0, exit, total = err );
total += 1;
}
}
exit:
return( total );
}
//===========================================================================================================================
// PrintFWriteNumVersion
//===========================================================================================================================
static int PrintFWriteNumVersion( uint32_t inVersion, char *outStr )
{
char * dst;
char * lim;
uint8_t majorRev;
uint8_t minor;
uint8_t bugFix;
uint8_t stage;
uint8_t revision;
majorRev = (uint8_t)( ( inVersion >> 24 ) & 0xFF );
minor = (uint8_t)( ( inVersion >> 20 ) & 0x0F );
bugFix = (uint8_t)( ( inVersion >> 16 ) & 0x0F );
stage = (uint8_t)( ( inVersion >> 8 ) & 0xFF );
revision = (uint8_t)( inVersion & 0xFF );
// Convert the major, minor, and bugfix numbers. Bugfix only added if it is non-zero (i.e. print 6.2 and not 6.2.0).
dst = outStr;
lim = dst + kPrintFBufSize;
SNPrintF_Add( &dst, lim, "%u", majorRev );
SNPrintF_Add( &dst, lim, ".%u", minor );
if( bugFix != 0 ) SNPrintF_Add( &dst, lim, ".%u", bugFix );
// Convert the version stage and non-release revision number.
switch( stage )
{
case kVersionStageDevelopment: SNPrintF_Add( &dst, lim, "d%u", revision ); break;
case kVersionStageAlpha: SNPrintF_Add( &dst, lim, "a%u", revision ); break;
case kVersionStageBeta: SNPrintF_Add( &dst, lim, "b%u", revision ); break;
case kVersionStageFinal:
// A non-release revision of zero is a special case indicating the software is GM (at the golden master
// stage) and therefore, the non-release revision should not be added to the string.
if( revision != 0 ) SNPrintF_Add( &dst, lim, "f%u", revision );
break;
default:
SNPrintF_Add( &dst, lim, "<< ERROR: invalid NumVersion stage: 0x%02X >>", revision );
break;
}
return( (int)( dst - outStr ) );
}
//===========================================================================================================================
// PrintFWriteObfuscatedPtr
//===========================================================================================================================
static int PrintFWriteObfuscatedPtr( PrintFContext *inContext, const void *inPtr )
{
static dispatch_once_t sOnce = 0;
static uint8_t sKey[ 16 ];
int n;
uint64_t hash;
dispatch_once_f( &sOnce, sKey, _PrintFWriteObfuscatedPtrInit );
hash = inPtr ? SipHash( sKey, &inPtr, sizeof( inPtr ) ) : 0;
n = PrintFCore( inContext, "0x%04X", (uint16_t)( hash & 0xFFFF ) );
return( ( n >= 0 ) ? n : 0 );
}
//===========================================================================================================================
// _PrintFWriteObfuscatedPtrInit
//===========================================================================================================================
static void _PrintFWriteObfuscatedPtrInit( void *inArg )
{
uint8_t * const key = (uint8_t *) inArg;
OSStatus err;
DEBUG_USE_ONLY( err );
err = RandomBytes( key, 16 );
check_noerr( err );
}
//===========================================================================================================================
// PrintFWriteSingleLineText
//===========================================================================================================================
static int PrintFWriteSingleLineText( PrintFContext *inContext, const char *inStr, size_t inLen )
{
int total = 0, err;
const char * src;
const char * end;
const char * ptr;
size_t len;
src = inStr;
end = inStr + inLen;
while( src < end )
{
for( ptr = src; ( src < end ) && ( *src != '\r' ) && ( *src != '\n' ); ++src ) {}
if( ptr < src )
{
len = (size_t)( src - ptr );
err = inContext->callback( ptr, len, inContext );
require_action_quiet( err >= 0, exit, total = err );
total += (int) len;
}
for( ptr = src; ( src < end ) && ( ( *src == '\r' ) || ( *src == '\n' ) ); ++src ) {}
if( ( ptr < src ) && ( src < end ) )
{
len = sizeof_string( " ⏎ " );
err = inContext->callback( " ⏎ ", len, inContext );
require_action_quiet( err >= 0, exit, total = err );
total += (int) len;
}
}
exit:
return( total );
}
//===========================================================================================================================
// PrintFWriteString
//===========================================================================================================================
static int PrintFWriteString( const char *inStr, PrintFFormat *inFormat, char *inBuf, const char **outStrPtr )
{
int i;
const char * s;
PrintFFormat * F;
int c;
s = inStr;
F = inFormat;
if( F->altForm == 0 ) // %s: C-string
{
i = 0;
if( F->havePrecision )
{
int j;
while( ( i < (int) F->precision ) && ( s[ i ] != '\0' ) ) ++i;
// Make sure we don't truncate in the middle of a UTF-8 character.
// If the last character is part of a multi-byte UTF-8 character, back up to the start of it.
// If the actual count of UTF-8 characters matches the encoded UTF-8 count, add it back.
c = 0;
j = 0;
while( ( i > 0 ) && ( ( c = s[ i - 1 ] ) & 0x80 ) ) { ++j; --i; if( ( c & 0xC0 ) != 0x80 ) break; }
if( ( j > 1 ) && ( j <= 6 ) )
{
int test;
int mask;
test = ( 0xFF << ( 8 - j ) ) & 0xFF;
mask = test | ( 1 << ( ( 8 - j ) - 1 ) );
if( ( c & mask ) == test ) i += j;
}
}
else
{
while( s[ i ] != '\0' ) ++i;
}
}
else if( F->altForm == 1 ) // %#s: Pascal-string
{
i = *s++;
}
else if( F->altForm == 2 ) // %##s: DNS label-sequence name
{
const uint8_t * a;
char * dst;
char * lim;
a = (const uint8_t *) s;
dst = inBuf;
lim = dst + kPrintFBufSize;
if( *a == 0 ) *dst++ = '.'; // Special case for root DNS name.
while( *a )
{
if( *a > 63 )
{
SNPrintF_Add( &dst, lim, "<<INVALID DNS LABEL LENGTH %u>>", *a );
break;
}
if( ( dst + *a ) >= &inBuf[ 254 ] )
{
SNPrintF_Add( &dst, lim, "<<DNS NAME TOO LONG>>" );
break;
}
SNPrintF_Add( &dst, lim, "%#s.", a );
a += ( 1 + *a );
}
i = (int)( dst - inBuf );
s = inBuf;
}
else if( F->altForm == 3 ) // %###s: Cleansed function name (i.e. isolate just the [<class>::]<function> part).
{
const char * functionStart;
// This needs to handle function names with the following forms:
//
// main
// main(int, const char **)
// int main(int, const char **)
// MyClass::operator()
// MyClass::operator'()'
// const char * MyClass::MyFunction(const char *) const
// void *MyClass::MyFunction(const char *) const
// +[MyClass MyMethod]
// -[MyClass MyMethod:andParam2:]
functionStart = inStr;
if( ( *functionStart == '+' ) || ( *functionStart == '-' ) ) // Objective-C class or instance method.
{
s = functionStart + strlen( functionStart );
}
else
{
for( s = inStr; ( ( c = *s ) != '\0' ) && ( c != ':' ); ++s )
{
if( c == ' ' ) functionStart = s + 1;
}
if( c == ':' ) c = *( ++s );
if( c == ':' ) ++s;
else
{
// Non-C++ function so re-do the search for a C function name.
functionStart = inStr;
for( s = inStr; ( ( c = *s ) != '\0' ) && ( c != '(' ); ++s )
{
if( c == ' ' ) functionStart = s + 1;
}
}
for( ; ( ( c = *s ) != '\0' ) && ( c != ' ' ) && ( c != '(' ); ++s ) {}
if( ( s[ 0 ] == '(' ) && ( s[ 1 ] == ')' ) && ( s[ 2 ] == '(' ) ) s += 2;
else if( ( s[ 0 ] == '(' ) && ( s[ 1 ] == ')' ) && ( s[ 2 ] == '\'' ) ) s += 3;
if( ( functionStart < s ) && ( *functionStart == '*' ) ) ++functionStart;
}
i = (int)( s - functionStart );
s = functionStart;
}
else
{
i = SNPrintF( inBuf, kPrintFBufSize, "<< ERROR: %%s with too many #'s (%d) >>", F->altForm );
s = inBuf;
}
// Make sure we don't truncate in the middle of a UTF-8 character.
if( F->havePrecision && ( i > (int) F->precision ) )
{
for( i = (int) F->precision; ( i > 0 ) && ( ( s[ i ] & 0xC0 ) == 0x80 ); --i ) {}
}
*outStrPtr = s;
return( i );
}
//===========================================================================================================================
// PrintFWriteText
//===========================================================================================================================
static int PrintFWriteText( PrintFContext *inContext, PrintFFormat *inFormat, const char *inText, size_t inSize )
{
int total = 0;
int err;
int n;
n = (int) inSize;
if( inFormat->prefix != '\0' ) n += 1;
if( inFormat->suffix != '\0' ) n += 1;
// Pad on the left.
if( !inFormat->leftJustify && ( n < (int) inFormat->fieldWidth ) )
{
do
{
err = inContext->callback( " ", 1, inContext );
if( err < 0 ) goto error;
total += 1;
} while( n < (int) --inFormat->fieldWidth );
}
// Write the prefix (if any).
if( inFormat->prefix != '\0' )
{
err = inContext->callback( &inFormat->prefix, 1, inContext );
if( err < 0 ) goto error;
total += 1;
}
// Write the actual text.
err = inContext->callback( inText, inSize, inContext );
if( err < 0 ) goto error;
total += (int) inSize;
// Write the suffix (if any).
if( inFormat->suffix != '\0' )
{
err = inContext->callback( &inFormat->suffix, 1, inContext );
if( err < 0 ) goto error;
total += 1;
}
// Pad on the right.
for( ; n < (int) inFormat->fieldWidth; ++n )
{
err = inContext->callback( " ", 1, inContext );
if( err < 0 ) goto error;
total += 1;
}
return( total );
error:
return( err );
}
//===========================================================================================================================
// PrintFWriteTimeDuration
//
// Converts seconds into a days, hours, minutes, and seconds string. For example: 930232 -> "10d 18h 23m 52s".
//===========================================================================================================================
static int PrintFWriteTimeDuration( uint64_t inSeconds, int inAltForm, char *inBuf )
{
unsigned int years;
unsigned int remain;
unsigned int days;
unsigned int hours;
unsigned int minutes;
unsigned int seconds;
unsigned int x;
char * dst;
years = (unsigned int)( inSeconds / kSecondsPerYear );
remain = (unsigned int)( inSeconds % kSecondsPerYear );
days = remain / kSecondsPerDay;
remain = remain % kSecondsPerDay;
hours = remain / kSecondsPerHour;
remain = remain % kSecondsPerHour;
minutes = remain / kSecondsPerMinute;
seconds = remain % kSecondsPerMinute;
dst = inBuf;
if( years != 0 )
{
append_decimal_string( years, dst );
*dst++ = 'y';
}
if( days != 0 )
{
if( dst != inBuf ) *dst++ = ' ';
append_decimal_string( days, dst );
*dst++ = 'd';
}
x = hours;
if( x != 0 )
{
if( dst != inBuf ) *dst++ = ' ';
if( inAltForm && ( x < 10 ) ) *dst++ = '0';
append_decimal_string( x, dst );
*dst++ = inAltForm ? ':' : 'h';
}
x = minutes;
if( ( x != 0 ) || inAltForm )
{
if( !inAltForm && ( dst != inBuf ) ) *dst++ = ' ';
if( inAltForm && ( x < 10 ) && ( hours != 0 ) ) *dst++ = '0';
append_decimal_string( x, dst );
*dst++ = inAltForm ? ':' : 'm';
}
x = seconds;
if( ( x != 0 ) || ( dst == inBuf ) || inAltForm )
{
if( !inAltForm && ( dst != inBuf ) ) *dst++ = ' ';
if( inAltForm && ( x < 10 ) ) *dst++ = '0';
append_decimal_string( x, dst );
if( !inAltForm ) *dst++ = 's';
}
*dst = '\0';
return( (int)( dst - inBuf ) );
}
//===========================================================================================================================
// PrintFWriteTLV8
//===========================================================================================================================
static int
PrintFWriteTLV8(
PrintFContext * inContext,
PrintFFormat * inFormat,
const char * inDescriptors,
const uint8_t * inPtr,
size_t inLen )
{
int total = 0, n;
const uint8_t * const end = inPtr + inLen;
const uint8_t * src;
const uint8_t * ptr;
const uint8_t * ptr2;
const uint8_t * next;
unsigned int len, len2;
uint8_t type, type2;
unsigned int widestDesc, widestLen;
const char * descPtr;
const char * label;
Boolean isText;
// Determine the widest pieces.
widestDesc = 0;
widestLen = 0;
for( src = inPtr; ( end - src ) >= 2; src = next )
{
type = src[ 0 ];
len = src[ 1 ];
ptr = &src[ 2 ];
next = ptr + len;
if( ( next < src ) || ( next > end ) ) break;
if( len > widestLen ) widestLen = len;
for( descPtr = inDescriptors; ; descPtr += ( len2 + 1 ) )
{
type2 = (uint8_t)( *descPtr++ );
len2 = (unsigned int) strlen( descPtr );
if( len2 == 0 ) break;
if( type2 != type ) continue;
if( len2 > widestDesc ) widestDesc = len2;
}
}
widestLen = ( widestLen < 10 ) ? 1 : ( widestLen < 100 ) ? 2 : 3;
// Print each item.
for( src = inPtr; ( end - src ) >= 2; src = next )
{
type = src[ 0 ];
len = src[ 1 ];
ptr = &src[ 2 ];
next = ptr + len;
if( ( next < src ) || ( next > end ) ) break;
// Search for a label for this type.
label = NULL;
for( descPtr = inDescriptors; ; descPtr += ( len2 + 1 ) )
{
type2 = (uint8_t)( *descPtr++ );
len2 = (unsigned int) strlen( descPtr );
if( len2 == 0 ) break;
if( type2 != type ) continue;
label = descPtr;
break;
}
// Print the item.
for( ptr2 = ptr; ( ptr2 != next ) && PrintFIsPrintable( *ptr2 ); ++ptr2 ) {}
isText = ( ptr2 == next ) ? true : false;
n = PrintFCore( inContext, "%*s0x%02X", inFormat->fieldWidth * 4, "", type );
require_action_quiet( n >= 0, exit, total = n );
total += n;
if( label )
{
n = PrintFCore( inContext, " (%s)", label );
require_action_quiet( n >= 0, exit, total = n );
total += n;
}
len2 = label ? ( widestDesc - ( (unsigned int) strlen( label ) ) ) : ( 3 + widestDesc );
if( len == 0 ) n = PrintFCore( inContext, ", %*s%*u bytes\n", len2, "", widestLen, 0 );
else if( isText ) n = PrintFCore( inContext, ", %*s%*u bytes, \"%.*s\"\n", len2, "", widestLen, len, len, ptr );
else if( len <= 16 ) n = PrintFCore( inContext, ", %*s%*u bytes, %#H\n", len2, "", widestLen, len, ptr, len, len );
else n = PrintFCore( inContext, "\n%*.1H", inFormat->fieldWidth + 1, ptr, len, len );
require_action_quiet( n >= 0, exit, total = n );
total += n;
}
exit:
return( total );
}
//===========================================================================================================================
// PrintFWriteTXTRecord
//===========================================================================================================================
static int PrintFWriteTXTRecord( PrintFContext *inContext, PrintFFormat *inFormat, const void *inPtr, size_t inLen )
{
const unsigned int kIndent = inFormat->fieldWidth * 4;
int total = 0;
int n;
const uint8_t * buf;
const uint8_t * src;
const uint8_t * end;
size_t len;
uint8_t c;
const char * seperator;
buf = (const uint8_t *) inPtr;
src = buf;
end = src + inLen;
// AltForm prints the TXT record on a single line.
if( inFormat->altForm )
{
seperator = "";
for( ; src < end; src += len )
{
len = *src++;
if( ( (size_t)( end - src ) ) < len ) break;
n = PrintFCore( inContext, "%s%.*s", seperator, (int) len, src );
require_action_quiet( n >= 0, exit, total = n );
total += n;
seperator = " | ";
}
}
else
{
// Handle AirPort TXT records that are one big entry with comma-separated name=value pairs.
if( ( inLen >= 6 ) && ( memcmp( &src[ 1 ], "waMA=", 5 ) == 0 ) )
{
uint8_t tempBuf[ 256 ];
uint8_t * tempPtr;
len = *src++;
if( ( src + len ) != end )
{
n = PrintFCore( inContext, "%*s### bad TXT record length byte (%zu, %zu expected)\n",
kIndent, "", len, (size_t)( end - src ) );
require_action_quiet( n >= 0, exit, total = n );
total += n;
goto exit;
}
while( src < end )
{
tempPtr = tempBuf;
while( src < end )
{
c = *src++;
if( c == ',' ) break;
if( c == '\\' )
{
if( src >= end )
{
n = PrintFCore( inContext, "%*s### bad TXT escape: %.*s\n", kIndent, "",
(int)( inLen - 1 ), buf + 1 );
require_action_quiet( n >= 0, exit, total = n );
total += n;
goto exit;
}
c = *src++;
}
*tempPtr++ = c;
}
n = PrintFCore( inContext, "%*s%.*s\n", kIndent, "", (int)( tempPtr - tempBuf ), tempBuf );
require_action_quiet( n >= 0, exit, total = n );
total += n;
}
}
else
{
for( ; src < end; src += len )
{
len = *src++;
if( ( src + len ) > end )
{
n = PrintFCore( inContext, "%*s### TXT record length byte too big (%zu, %zu max)\n",
kIndent, "", len, (size_t)( end - src ) );
require_action_quiet( n >= 0, exit, total = n );
total += n;
goto exit;
}
n = PrintFCore( inContext, "%*s%.*s\n", kIndent, "", (int) len, src );
require_action_quiet( n >= 0, exit, total = n );
total += n;
}
}
if( ( inLen == 0 ) || ( buf[ 0 ] == 0 ) )
{
n = PrintFCore( inContext, "\n" );
require_action_quiet( n >= 0, exit, total = n );
total += n;
}
}
exit:
return( total );
}
//===========================================================================================================================
// PrintFWriteUnicodeString
//===========================================================================================================================
static int PrintFWriteUnicodeString( const uint8_t *inStr, PrintFFormat *inFormat, char *inBuf )
{
int i;
const uint8_t * a;
const uint16_t * u;
PrintFFormat * F;
char * p;
char * q;
int endianIndex;
a = inStr;
F = inFormat;
if( !F->havePrecision || ( F->precision > 0 ) )
{
if( ( a[ 0 ] == 0xFE ) && ( a[ 1 ] == 0xFF ) ) { F->altForm = 1; a += 2; --F->precision; } // Big Endian
else if( ( a[ 0 ] == 0xFF ) && ( a[ 1 ] == 0xFE ) ) { F->altForm = 2; a += 2; --F->precision; } // Little Endian
}
u = (const uint16_t *) a;
p = inBuf;
q = p + kPrintFBufSize;
switch( F->altForm )
{
case 0: // Host Endian
for( i = 0; ( !F->havePrecision || ( i < (int) F->precision ) ) && u[ i ] && ( ( q - p ) > 0 ); ++i )
{
*p++ = PrintFMakePrintable( u[ i ] );
}
break;
case 1: // Big Endian
case 2: // Little Endian
endianIndex = 1 - ( F->altForm - 1 );
for( i = 0; ( !F->havePrecision || ( i < (int) F->precision ) ) && u[ i ] && ( ( q - p ) > 0 ); ++i )
{
*p++ = PrintFMakePrintable( a[ endianIndex ] );
a += 2;
}
break;
default:
i = SNPrintF( inBuf, kPrintFBufSize, "<< ERROR: %%S with too many #'s (%d) >>", F->altForm );
break;
}
return( i );
}
//===========================================================================================================================
// PrintFWriteXMLEscaped
//===========================================================================================================================
static int PrintFWriteXMLEscaped( PrintFContext *inContext, const char *inPtr, size_t inLen )
{
const char * const end = inPtr + ( ( inLen == kSizeCString ) ? strlen( inPtr ) : inLen );
int total = 0;
int n;
char c;
const char * run;
size_t len;
const char * replace;
run = inPtr;
while( inPtr < end )
{
c = *inPtr;
switch( c )
{
case '&': replace = "&"; break;
case '"': replace = """; break;
case '\'': replace = "'"; break; // No ' in HTML 4, but ' works in HTML, XHTML, and XML.
case '<': replace = "<"; break;
case '>': replace = ">"; break;
default: replace = NULL; break;
}
if( replace )
{
len = (size_t)( inPtr - run );
++inPtr;
if( len > 0 )
{
n = inContext->callback( run, len, inContext );
require_action_quiet( n >= 0, exit, total = n );
total += n;
}
run = inPtr;
n = PrintFCore( inContext, "%s", replace );
require_action_quiet( n >= 0, exit, total = n );
total += n;
}
else
{
++inPtr;
}
}
len = (size_t)( inPtr - run );
if( len > 0 )
{
n = inContext->callback( run, len, inContext );
require_action_quiet( n >= 0, exit, total = n );
total += n;
}
exit:
return( total );
}
#if 0
#pragma mark -
#endif
//===========================================================================================================================
// PrintFCallBackFixedString
//===========================================================================================================================
static int PrintFCallBackFixedString( const char *inStr, size_t inSize, PrintFContext *inContext )
{
size_t n;
// If the string is too long, truncate it, but don't truncate in the middle of a UTF-8 character.
n = inContext->reservedSize - inContext->usedSize;
if( inSize > n )
{
while( ( n > 0 ) && ( ( inStr[ n ] & 0xC0 ) == 0x80 ) ) --n;
inSize = n;
}
// Copy the string (excluding any null terminator).
if( inSize > 0 ) memcpy( inContext->str + inContext->usedSize, inStr, inSize );
inContext->usedSize += inSize;
return( (int) inSize );
}
//===========================================================================================================================
// PrintFCallBackAllocatedString
//===========================================================================================================================
static int PrintFCallBackAllocatedString( const char *inStr, size_t inSize, PrintFContext *inContext )
{
int result;
size_t n;
// If there's not enough room in the buffer, resize it. Amortize allocations by rounding the size up.
n = inContext->usedSize + inSize;
if( n > inContext->reservedSize )
{
char * tmp;
if( n < 256 ) n = 256;
else n = ( n + 1023 ) & ~1023U;
#if( TARGET_NO_REALLOC )
tmp = (char *) malloc( n );
require_action( tmp, exit, result = kNoMemoryErr );
memcpy( tmp, inContext->str, inContext->usedSize );
free( inContext->str );
inContext->str = tmp;
inContext->reservedSize = n;
#else
tmp = (char *) realloc( inContext->str, n );
require_action( tmp, exit, result = kNoMemoryErr );
inContext->str = tmp;
inContext->reservedSize = n;
#endif
}
// Copy the string (excluding any null terminator).
memcpy( inContext->str + inContext->usedSize, inStr, inSize );
inContext->usedSize += inSize;
result = (int) inSize;
exit:
return( result );
}
//===========================================================================================================================
// PrintFCallBackUserCallBack
//===========================================================================================================================
static int PrintFCallBackUserCallBack( const char *inStr, size_t inSize, PrintFContext *inContext )
{
return( inContext->userCallBack( inStr, inSize, inContext->userContext ) );
}
#if 0
#pragma mark -
#endif
#if( !defined( PRINTF_UTILS_PRINT_TEST ) )
#if( DEBUG_FPRINTF_ENABLED )
#define PRINTF_UTILS_PRINT_TEST 0
#endif
#endif
#if( !EXCLUDE_UNIT_TESTS )
//===========================================================================================================================
// PrintFUtils_Test
//===========================================================================================================================
static int _PrintFTestExtension1( PrintFContext *ctx, PrintFFormat *inFormat, PrintFVAList *inArgs, void *inUserContext );
static int _PrintFTestExtension2( PrintFContext *ctx, PrintFFormat *inFormat, PrintFVAList *inArgs, void *inUserContext );
static OSStatus _PrintFTestString( const char *inMatch, const char *inFormat, ... );
static OSStatus _PrintFTestVAList( const char *inMatch, const char *inFormat, ... );
#define PFTEST1( MATCH, FORMAT, PARAM ) \
do \
{ \
err = _PrintFTestString( ( MATCH ), ( FORMAT ), ( PARAM ) ); \
require_noerr( err, exit ); \
\
} while( 0 )
#define PFTEST2( MATCH, FORMAT, PARAM1, PARAM2 ) \
do \
{ \
err = _PrintFTestString( ( MATCH ), ( FORMAT ), ( PARAM1 ), ( PARAM2 ) ); \
require_noerr( err, exit ); \
\
} while( 0 )
OSStatus PrintFUtils_Test( void )
{
OSStatus err;
int n;
char buf[ 512 ];
const char * src;
const char * end;
char * dst;
char * lim;
// Field Width and Precision Tests.
PFTEST1( ":hello, world:", ":%s:", "hello, world" );
PFTEST1( ":hello, world:", ":%10s:", "hello, world" );
PFTEST1( ":hello, wor:", ":%.10s:", "hello, world" );
PFTEST1( ":hello, world:", ":%-10s:", "hello, world" );
PFTEST1( ":hello, world:", ":%.15s:", "hello, world" );
PFTEST1( ":hello, world :", ":%-15s:", "hello, world" );
PFTEST1( ": hello, world:", ":%15s:", "hello, world" );
PFTEST1( ": hello, wor:", ":%15.10s:", "hello, world" );
PFTEST1( ":hello, wor :", ":%-15.10s:", "hello, world" );
PFTEST1( ":'hello, world':", ":%'s:", "hello, world" );
PFTEST1( ":\"hello, world\":", ":%''s:", "hello, world" );
PFTEST1( ":'hello, wor':", ":%'.12s:", "hello, world" );
PFTEST1( ": 'hello, world':", ":%'17s:", "hello, world" );
PFTEST1( ":'h':", ":%'.3s:", "hello, world" );
PFTEST1( ":'':", ":%'.2s:", "hello, world" );
PFTEST1( "::", ":%'.1s:", "hello, world" );
// Number Tests.
PFTEST1( "1234", "%d", 1234 );
PFTEST1( "1234", "%#d", 1234 );
PFTEST1( "0", "%'d", 0 );
PFTEST1( "1", "%'d", 1 );
PFTEST1( "12", "%'d", 12 );
PFTEST1( "123", "%'d", 123 );
PFTEST1( "1,234", "%'d", 1234 );
PFTEST1( "12,345", "%'d", 12345 );
PFTEST1( "123,456", "%'d", 123456 );
PFTEST1( "1,234,567", "%'d", 1234567 );
PFTEST1( "-1", "%'d", -1 );
PFTEST1( "-12", "%'d", -12 );
PFTEST1( "-123", "%'d", -123 );
PFTEST1( "-1,234", "%'d", -1234 );
PFTEST1( "-12,345", "%'d", -12345 );
PFTEST1( "-123,456", "%'d", -123456 );
PFTEST1( "-1,234,567", "%'d", -1234567 );
PFTEST1( "1234", "%i", 1234 );
PFTEST1( "1234", "%u", 1234 );
PFTEST1( "2322", "%o", 1234 );
PFTEST1( "02322", "%#o", 1234 );
PFTEST1( "0777", "%#2o", 0777 );
PFTEST1( "12AB", "%X", 0x12AB );
PFTEST1( "12ab", "%x", 0x12AB );
PFTEST1( "0x12ab", "%#x", 0x12AB );
PFTEST1( "0x1", "%#01x", 0x1 );
PFTEST1( "0x01", "%#04x", 0x1 );
PFTEST1( "1001010101011", "%b", 0x12AB );
PFTEST1( " 1234", "%5d", 1234 );
PFTEST1( "1234 ", "%-5d", 1234 );
PFTEST1( "2147483647", "%ld", 2147483647L );
PFTEST1( "4294967295", "%lu", (unsigned long) UINT32_C( 4294967295 ) );
PFTEST1( "9223372036854775807", "%lld", INT64_C( 9223372036854775807 ) );
PFTEST1( "-9223372036854775807", "%lld", INT64_C( -9223372036854775807 ) );
PFTEST1( "18446744073709551615", "%llu", UINT64_C( 18446744073709551615 ) );
PFTEST1( "-46", "%hhd", 1234 );
PFTEST1( "210", "%hhu", 1234 );
PFTEST1( "12345678", "%jX", (intmax_t) 0x12345678 );
PFTEST1( "12345678", "%zX", (size_t) 0x12345678 );
PFTEST1( "305419896", "%zd", (size_t) 0x12345678 );
PFTEST1( "12345678", "%tX", (ptrdiff_t) 0x12345678 );
PFTEST1( "1111011011110110111101101111011", "%lb", (unsigned long) 0x7B7B7B7B );
#if( PRINTF_ENABLE_FLOATING_POINT )
PFTEST1( "123.234000", "%f", 123.234 );
PFTEST1( "123.23", "%.2f", 123.234 );
PFTEST1( " 123.2340000000", "%15.10f", 123.234 );
PFTEST1( "123.2340000000 ", "%-15.10f", 123.234 );
#endif
// Bit Number Tests.
PFTEST1( "12 9 5 4 2", "%##b", 0x1234 );
PFTEST1( "19 22 26 27 29", "%###b", 0x1234 );
PFTEST1( "3 6 10 11 13", "%###hb", 0x1234 );
PFTEST1( "4 1", "%##.8lb", UINT32_C( 0x12 ) );
PFTEST1( "59 62", "%###llb", UINT64_C( 0x12 ) );
PFTEST1( "4 1", "%##.8llb", UINT64_C( 0x12 ) );
PFTEST1( "3 6", "%###.8llb", UINT64_C( 0x12 ) );
PFTEST1( "", "%###.0llb", UINT64_C( 0x12 ) );
PFTEST1( "ERROR: << precision must be 0-64 >>", "%###.128llb", UINT64_C( 0x12 ) );
PFTEST1( "31 0", "%##b", 0x80000001U );
PFTEST1( "0 31", "%###b", 0x80000001U );
PFTEST1( "31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0", "%##b", 0xFFFFFFFFU );
PFTEST1( "0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31", "%###b", 0xFFFFFFFFU );
PFTEST1( "4 1 0 ", "%-##10b", 0x13 );
PFTEST1( " 4 1 0", "%##10b", 0x13 );
// String Tests.
PFTEST1( "test", "%#s", "\04test" );
PFTEST1( "www.apple.com.", "%##s", "\03www\05apple\03com" );
// Address Tests.
PFTEST1( "1.2.3.4", "%.2a", "\x12\x34" );
PFTEST1( "17.205.123.5", "%.4a", "\x11\xCD\x7B\x05" );
PFTEST1( "00:11:22:AA:BB:CC", "%.6a", "\x00\x11\x22\xAA\xBB\xCC" );
PFTEST1( "00:11:22:AA:BB:CC:56:78", "%.8a", "\x00\x11\x22\xAA\xBB\xCC\x56\x78" );
PFTEST1( "102:304:506:708:90a:b0c:d0e:f10", "%.16a", "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10" );
{
mDNSAddrCompat maddr;
memset( &maddr, 0, sizeof( maddr ) );
maddr.type = 4;
maddr.ip.v4[ 0 ] = 127;
maddr.ip.v4[ 1 ] = 0;
maddr.ip.v4[ 2 ] = 0;
maddr.ip.v4[ 3 ] = 1;
PFTEST1( "127.0.0.1", "%#a", &maddr );
memset( &maddr, 0, sizeof( maddr ) );
maddr.type = 6;
maddr.ip.v6[ 0 ] = 0xFE;
maddr.ip.v6[ 1 ] = 0x80;
maddr.ip.v6[ 15 ] = 0x01;
PFTEST1( "fe80::1", "%#a", &maddr );
}
#if( defined( AF_INET ) )
{
struct sockaddr_in sa4;
memset( &sa4, 0, sizeof( sa4 ) );
SIN_LEN_SET( &sa4 );
sa4.sin_family = AF_INET;
sa4.sin_port = hton16( 80 );
sa4.sin_addr.s_addr = hton32( UINT32_C( 0x7f000001 ) );
PFTEST1( "127.0.0.1:80", "%##a", &sa4 );
}
#endif
#if( defined( AF_INET6 ) )
{
struct sockaddr_in6 sa6;
memset( &sa6, 0, sizeof( sa6 ) );
SIN6_LEN_SET( &sa6 );
sa6.sin6_family = AF_INET6;
sa6.sin6_port = hton16( 80 );
sa6.sin6_addr.s6_addr[ 0 ] = 0xFE;
sa6.sin6_addr.s6_addr[ 1 ] = 0x80;
sa6.sin6_addr.s6_addr[ 15 ] = 0x01;
sa6.sin6_scope_id = 2;
#if( TARGET_OS_POSIX )
{
char ifname[ IF_NAMESIZE ];
SNPrintF( buf, sizeof( buf ), "[fe80::1%%%s]:80", if_indextoname( sa6.sin6_scope_id, ifname ) );
PFTEST1( buf, "%##a", &sa6 );
}
#else
PFTEST1( "[fe80::1%2]:80", "%##a", &sa6 );
#endif
memset( &sa6, 0, sizeof( sa6 ) );
SIN6_LEN_SET( &sa6 );
sa6.sin6_family = AF_INET6;
sa6.sin6_port = hton16( 80 );
sa6.sin6_addr.s6_addr[ 10 ] = 0xFF; // ::ffff:<32-bit IPv4 address>
sa6.sin6_addr.s6_addr[ 11 ] = 0xFF;
memcpy( &sa6.sin6_addr.s6_addr[ 12 ], "\xE8\x05\x0F\x49", 4 ); // IPv4 address is in the low 32 bits of the IPv6 address.
PFTEST1( "[::ffff:232.5.15.73]:80", "%##a", &sa6 );
}
#endif
// Unicode Tests.
PFTEST2( "tes", "%.*s", 4, "tes" );
PFTEST2( "test", "%.*s", 4, "test" );
PFTEST2( "test", "%.*s", 4, "testing" );
PFTEST2( "te\xC3\xA9", "%.*s", 4, "te\xC3\xA9" );
PFTEST2( "te\xC3\xA9", "%.*s", 4, "te\xC3\xA9ing" );
PFTEST2( "tes", "%.*s", 4, "tes\xC3\xA9ing" );
PFTEST2( "t\xE3\x82\xBA", "%.*s", 4, "t\xE3\x82\xBA" );
PFTEST2( "t\xE3\x82\xBA", "%.*s", 4, "t\xE3\x82\xBAing" );
PFTEST2( "te", "%.*s", 4, "te\xE3\x82\xBA" );
PFTEST2( "te", "%.*s", 4, "te\xE3\x82\xBAing" );
PFTEST2( "te\xC3\xA9\xE3\x82\xBA", "%.*s", 7, "te\xC3\xA9\xE3\x82\xBAing" );
PFTEST2( "te\xC3\xA9", "%.*s", 6, "te\xC3\xA9\xE3\x82\xBAing" );
PFTEST2( "te\xC3\xA9", "%.*s", 5, "te\xC3\xA9\xE3\x82\xBAing" );
#if( TARGET_RT_BIG_ENDIAN )
PFTEST1( "abcd", "%S", "\x00" "a" "\x00" "b" "\x00" "c" "\x00" "d" "\x00" "\x00" );
#else
PFTEST1( "abcd", "%S", "a" "\x00" "b" "\x00" "c" "\x00" "d" "\x00" "\x00" "\x00" );
#endif
PFTEST1( "abcd", "%S",
"\xFE\xFF" "\x00" "a" "\x00" "b" "\x00" "c" "\x00" "d" "\x00" "\x00" ); // Big Endian BOM
PFTEST1( "abcd", "%S",
"\xFF\xFE" "a" "\x00" "b" "\x00" "c" "\x00" "d" "\x00" "\x00" "\x00" ); // Little Endian BOM
PFTEST1( "abcd", "%#S", "\x00" "a" "\x00" "b" "\x00" "c" "\x00" "d" "\x00" "\x00" ); // Big Endian
PFTEST1( "abcd", "%##S", "a" "\x00" "b" "\x00" "c" "\x00" "d" "\x00" "\x00" "\x00" ); // Little Endian
PFTEST2( "abc", "%.*S",
4, "\xFE\xFF" "\x00" "a" "\x00" "b" "\x00" "c" "\x00" "d" ); // Big Endian BOM
PFTEST2( "abc", "%.*S",
4, "\xFF\xFE" "a" "\x00" "b" "\x00" "c" "\x00" "d" "\x00" ); // Little Endian BOM
#if( TARGET_RT_BIG_ENDIAN )
PFTEST2( "abc", "%.*S", 3, "\x00" "a" "\x00" "b" "\x00" "c" "\x00" "d" );
#else
PFTEST2( "abc", "%.*S", 3, "a" "\x00" "b" "\x00" "c" "\x00" "d" "\x00" );
#endif
PFTEST2( "abc", "%#.*S", 3, "\x00" "a" "\x00" "b" "\x00" "c" "\x00" "d" ); // Big Endian
PFTEST2( "abc", "%##.*S", 3, "a" "\x00" "b" "\x00" "c" "\x00" "d" "\x00" ); // Little Endian
#if( TARGET_OS_WINDOWS )
PFTEST1( "Testing", "%T", TEXT( "Testing" ) );
#endif
// Other Tests.
PFTEST1( "a", "%c", 'a' );
PFTEST1( "'a'", "%'c", 'a' );
PFTEST1( "AbCd", "%C", 0x41624364 /* 'AbCd' */ );
PFTEST1( "'AbCd'", "%'C", 0x41624364 /* 'AbCd' */ );
PFTEST1( "6ba7b810-9dad-11d1-80b4-00c04fd430c8", "%U", "\x10\xb8\xa7\x6b" "\xad\x9d" "\xd1\x11" "\x80\xb4" "\x00\xc0\x4f\xd4\x30\xc8" );
PFTEST1( "10b8a76b-ad9d-d111-80b4-00c04fd430c8", "%#U", "\x10\xb8\xa7\x6b" "\xad\x9d" "\xd1\x11" "\x80\xb4" "\x00\xc0\x4f\xd4\x30\xc8" );
PFTEST2( "Player1 -> Broadcast: <Poll> ", "%{cec}", "\x4F", 1 );
#if( DEBUG || DEBUG_EXPORT_ERROR_STRINGS )
PFTEST1( "noErr", "%m", 0 );
PFTEST1( "kUnknownErr", "%m", kUnknownErr );
PFTEST1( "-6700/0xFFFFE5D4 kUnknownErr", "%#m", kUnknownErr );
#endif
err = _PrintFTestString(
"6b a7 b8 10 9d ad 11 d1 80 b4 00 c0 4f d4 30 c8",
"%H",
"\x6b\xa7\xb8\x10\x9d\xad\x11\xd1\x80\xb4\x00\xc0\x4f\xd4\x30\xc8", 16, 16 );
require_noerr( err, exit );
err = _PrintFTestString(
"6b a7 b8 10 9d ad 11 d1 80 b4 00 c0 4f d4 30 c8 "
"6b a7 b8 10 9d ad 11 d1 80 b4 00 c0 4f d4 30 c8",
"%H",
"\x6b\xa7\xb8\x10\x9d\xad\x11\xd1\x80\xb4\x00\xc0\x4f\xd4\x30\xc8"
"\x6b\xa7\xb8\x10\x9d\xad\x11\xd1\x80\xb4\x00\xc0\x4f\xd4\x30\xc8",
32, 32 );
require_noerr( err, exit );
err = _PrintFTestString( "6b a7", "%H", "\x6b\xa7", 2, 2 );
require_noerr( err, exit );
err = _PrintFTestString( "0123456789abcdef", "%.3H", "\x01\x23\x45\x67\x89\xab\xcd\xef", 8, 8 );
require_noerr( err, exit );
err = _PrintFTestString( "0123456789ABCDEF", "%.4H", "\x01\x23\x45\x67\x89\xAB\xCD\xEF", 8, 8 );
require_noerr( err, exit );
#if( DEBUG_CF_OBJECTS_ENABLED )
{
CFNumberRef num;
int64_t s64;
PFTEST1( ":hello, world:", ":%@:", CFSTR( "hello, world" ) );
PFTEST1( ":hello, wor :", ":%-15.10@:", CFSTR( "hello, world" ) );
PFTEST1( ": hello, world:", ":%15@:", CFSTR( "hello, world" ) );
s64 = INT64_C( 9223372036854775807 );
num = CFNumberCreate( NULL, kCFNumberSInt64Type, &s64 );
require_action( num, exit, err = kNoMemoryErr );
err = _PrintFTestString( "9223372036854775807", "%@", num );
CFRelease( num );
require_noerr( err, exit );
}
#endif
PFTEST1( "1.2.3b4", "%v", (uint32_t) 0x01236004 );
PFTEST1( "%5", "%%%d", 5 );
err = _PrintFTestString( "Test 123 hello, world", "Test %d %s%n", 123, "hello, world", &n );
require_noerr( err, exit );
require_action( n == 21, exit, err = kResponseErr );
err = _PrintFTestVAList( "begin 123 test 456 end", "%d test %s%n", 123, "456", &n );
require_noerr( err, exit );
require_action( n == 12, exit, err = kResponseErr );
PFTEST1( "0s", "%{dur}", 0 );
PFTEST1( "10d 18h 23m 52s", "%{dur}", 930232 );
PFTEST1( "a", "%c", 'a' );
err = _PrintFTestString(
"Line 1"
, "%{text}",
"Line 1"
, kSizeCString );
require_noerr( err, exit );
err = _PrintFTestString(
"Line 1\n"
"Line 2\n"
"Line 3"
, "%{text}",
"Line 1\n"
"Line 2\n"
"Line 3"
, kSizeCString );
require_noerr( err, exit );
err = _PrintFTestString(
"Line 1\n"
"Line 2\n"
"Line 3\n"
"\n"
"\n"
"\n"
"Line 7\n"
, "%{text}",
"Line 1\r"
"Line 2\r\n"
"Line 3\n"
"\n"
"\r"
"\r\n"
"Line 7\n"
, kSizeCString );
require_noerr( err, exit );
err = _PrintFTestString(
" Line 1\n"
" Line 2\n"
" Line 3\n"
"\n"
"\n"
"\n"
" Line 7\n"
, "%1{text}",
"Line 1\r"
"Line 2\r\n"
"Line 3\n"
"\n"
"\r"
"\r\n"
"Line 7\n"
, kSizeCString );
require_noerr( err, exit );
err = _PrintFTestString( ":abc123:", ":%?s%?d%?d%?s:", true, "abc", true, 123, false, 456, false, "xyz" );
require_noerr( err, exit );
// %{fill}
PFTEST2( "", "%{fill}", '*', 0 );
PFTEST2( "*", "%{fill}", '*', 1 );
PFTEST2( "*******", "%{fill}", '*', 7 );
PFTEST2( "\t\t\t", "%{fill}", '\t', 3 );
memset( buf, 'z', 400 );
buf[ 400 ] = '\0';
PFTEST2( buf, "%{fill}", 'z', 400 );
// %{flags}
PFTEST2( "< >", "%{flags}", 0,
"\x02" "FLAG2\0"
"\x08" "FLAG8\0"
"\x00" );
PFTEST2( "< FLAG2 FLAG8 >", "%{flags}", 0x1F4,
"\x02" "FLAG2\0"
"\x08" "FLAG8\0"
"\x00" );
PFTEST2( "0xFF < FLAG0 FLAG1 FLAG2 FLAG3 FLAG4 FLAG5 FLAG6 FLAG7 >", "%#{flags}", 0xFF,
"\x00" "FLAG0\0"
"\x01" "FLAG1\0"
"\x02" "FLAG2\0"
"\x03" "FLAG3\0"
"\x04" "FLAG4\0"
"\x05" "FLAG5\0"
"\x06" "FLAG6\0"
"\x07" "FLAG7\0"
"\x00" );
PFTEST2( "0x800000000022 < FLAG1 FLAG5 FLAG47 >", "%#ll{flags}", UINT64_C( 0x800000000022 ),
"\x00" "FLAG0\0"
"\x01" "FLAG1\0"
"\x05" "FLAG5\0"
"\x2F" "FLAG47\0"
"\x30" "FLAG48\0"
"\x00" );
// %{ptr}
n = SNPrintF( buf, sizeof( buf ), "%{ptr}", buf );
require_action( n == 6, exit, err = kSizeErr );
require_action( buf[ 0 ] == '0', exit, err = kMismatchErr );
require_action( buf[ 1 ] == 'x', exit, err = kMismatchErr );
n = SNPrintF( buf, sizeof( buf ), "%{ptr}", NULL );
require_action( n == 6, exit, err = kSizeErr );
require_action( strcmp( buf, "0x0000" ) == 0, exit, err = kMismatchErr );
// %#{txt}
n = SNPrintF( buf, sizeof( buf ), "%#{txt}", NULL, (size_t) 0 );
require_action( n == 0, exit, err = kSizeErr );
require_action( strcmp( buf, "" ) == 0, exit, err = kMismatchErr );
n = SNPrintF( buf, sizeof( buf ), "%#{txt}", "\x03" "a=b", (size_t) 4 );
require_action( n == 3, exit, err = kSizeErr );
require_action( strcmp( buf, "a=b" ) == 0, exit, err = kMismatchErr );
n = SNPrintF( buf, sizeof( buf ), "%#{txt}", "\x06" "a=1234" "\x05" "abc=x", (size_t) 13 );
require_action( n == 14, exit, err = kSizeErr );
require_action( strcmp( buf, "a=1234 | abc=x" ) == 0, exit, err = kMismatchErr );
// %{xml}
PFTEST2( "", "%{xml}", "", 0 );
PFTEST2( "test", "%{xml}", "test", 4 );
PFTEST2( "<test>", "%{xml}", "<test>", kSizeCString );
PFTEST2( "&"'<>", "%{xml}", "&\"'<>", kSizeCString );
PFTEST2( " & " ' < > ", "%{xml}", " & \" ' < > ", kSizeCString );
PFTEST2( "<test", "%{xml}", "<test", kSizeCString );
PFTEST2( "test>", "%{xml}", "test>", kSizeCString );
PFTEST2( "Test of a "string" of text", "%{xml}", "Test of a \"string\" of text", kSizeCString );
// Extension tests.
PFTEST1( "< <<UNKNOWN PRINTF EXTENSION 'test1'>> >", "< %{test1} >", 123 );
err = PrintFRegisterExtension( "test1", _PrintFTestExtension1, NULL );
require_noerr( err, exit );
PFTEST2( "< Alt=0, a=123, b='xyz' >", "< %{test1} >", 123, "xyz" );
PrintFDeregisterExtension( "test1" );
PFTEST1( "< <<UNKNOWN PRINTF EXTENSION 'test1'>> >", "< %{test1} >", 123 );
err = PrintFRegisterExtension( "test1", _PrintFTestExtension1, NULL );
require_noerr( err, exit );
err = PrintFRegisterExtension( "test2", _PrintFTestExtension2, NULL );
require_noerr( err, exit );
PFTEST2( "< Alt=1, a=456, b='ABC' >", "< %#{test1} >", 456, "ABC" );
PFTEST1( "< NoArgsExtension >", "< %{test2} >", 123 );
PrintFDeregisterExtension( "test1" );
PFTEST1( "< <<UNKNOWN PRINTF EXTENSION 'test1'>> >", "< %{test1} >", 123 );
PFTEST1( "< NoArgsExtension >", "< %{test2} >", 123 );
PrintFDeregisterExtension( "test2" );
PFTEST1( "< <<UNKNOWN PRINTF EXTENSION 'test1'>> >", "< %{test1} >", 123 );
PFTEST1( "< <<UNKNOWN PRINTF EXTENSION 'test2'>> >", "< %{test2} >", 123 );
err = PrintFRegisterExtension( "test1", _PrintFTestExtension1, NULL );
require_noerr( err, exit );
err = PrintFRegisterExtension( "test2", _PrintFTestExtension2, NULL );
require_noerr( err, exit );
PFTEST2( "< Alt=1, a=456, b='ABC' >", "< %#{test1} >", 456, "ABC" );
PFTEST1( "< NoArgsExtension >", "< %{test2} >", 123 );
PrintFDeregisterExtension( "test2" );
PFTEST2( "< Alt=1, a=456, b='ABC' >", "< %#{test1} >", 456, "ABC" );
PFTEST1( "< <<UNKNOWN PRINTF EXTENSION 'test2'>> >", "< %{test2} >", 123 );
PrintFDeregisterExtension( "test1" );
PFTEST1( "< <<UNKNOWN PRINTF EXTENSION 'test1'>> >", "< %{test1} >", 123 );
PFTEST1( "< <<UNKNOWN PRINTF EXTENSION 'test2'>> >", "< %{test2} >", 123 );
// Bounds Tests.
memset( buf, 'Z', sizeof( buf ) );
n = SNPrintF( buf, 0, "%s", "test" );
require_action( n == 4, exit, err = kResponseErr );
src = buf;
end = buf + sizeof( buf );
while( ( src < end ) && ( *src == 'Z' ) ) ++src;
require_action( src == end, exit, err = kImmutableErr );
memset( buf, 'Z', sizeof( buf ) );
n = SNPrintF( buf, 3, "%s", "test" );
require_action( n == 4, exit, err = kResponseErr );
require_action( buf[ 2 ] == '\0', exit, err = kResponseErr );
require_action( strcmp( buf, "te" ) == 0, exit, err = kResponseErr );
src = buf + 3;
end = buf + sizeof( buf );
while( ( src < end ) && ( *src == 'Z' ) ) ++src;
require_action( src == end, exit, err = kImmutableErr );
memset( buf, 'Z', sizeof( buf ) );
n = SNPrintF( buf, 4, "%s", "te\xC3\xA9" );
require_action( n == 4, exit, err = kResponseErr );
require_action( buf[ 2 ] == '\0', exit, err = kResponseErr );
require_action( strcmp( buf, "te" ) == 0, exit, err = kResponseErr );
src = buf + 3;
end = buf + sizeof( buf );
while( ( src < end ) && ( *src == 'Z' ) ) ++src;
require_action( src == end, exit, err = kImmutableErr );
// SNPrintF_Add
dst = buf;
lim = dst + 10;
err = SNPrintF_Add( &dst, lim, "12345" );
require_noerr( err, exit );
require_action( strcmp( buf, "12345" ) == 0, exit, err = -1 );
err = SNPrintF_Add( &dst, lim, "67890" );
require_action( err != kNoErr, exit, err = -1 );
require_action( strcmp( buf, "123456789" ) == 0, exit, err = -1 );
err = SNPrintF_Add( &dst, lim, "ABCDE" );
require_action( err != kNoErr, exit, err = -1 );
require_action( strcmp( buf, "123456789" ) == 0, exit, err = -1 );
dst = buf;
lim = dst + 10;
err = SNPrintF_Add( &dst, lim, "12345" );
require_noerr( err, exit );
require_action( strcmp( buf, "12345" ) == 0, exit, err = -1 );
err = SNPrintF_Add( &dst, lim, "6789" );
require_noerr( err, exit );
require_action( strcmp( buf, "123456789" ) == 0, exit, err = -1 );
err = SNPrintF_Add( &dst, lim, "ABCDE" );
require_action( err != kNoErr, exit, err = -1 );
require_action( strcmp( buf, "123456789" ) == 0, exit, err = -1 );
memcpy( buf, "abc", 4 );
dst = buf;
lim = dst;
err = SNPrintF_Add( &dst, lim, "12345" );
require_action( err != kNoErr, exit, err = -1 );
require_action( strcmp( lim, "abc" ) == 0, exit, err = -1 );
#if( COMPILER_OBJC )
@autoreleasepool
{
require_action( [NSPrintF( "Test %d", 123 ) isEqual:@"Test 123"], exit, err = -1 );
require_action( [NSPrintF( "abc" ) isEqual:@"abc"], exit, err = -1 );
require_action( [NSPrintF( "%m", kNoErr ) isEqual:@"noErr"], exit, err = -1 );
}
#endif
err = kNoErr;
exit:
PrintFDeregisterExtension( "test1" );
PrintFDeregisterExtension( "test2" );
printf( "PrintFUtils: %s\n", !err ? "PASSED" : "FAILED" );
return( err );
}
//===========================================================================================================================
// _PrintFTestExtension1
//===========================================================================================================================
static int _PrintFTestExtension1( PrintFContext *ctx, PrintFFormat *inFormat, PrintFVAList *inArgs, void *inUserContext )
{
int a;
const char * b;
(void) inUserContext;
a = va_arg( inArgs->args, int );
b = va_arg( inArgs->args, const char * );
return( PrintFCore( ctx, "Alt=%d, a=%d, b='%s'", inFormat->altForm, a, b ) );
}
//===========================================================================================================================
// _PrintFTestExtension2
//===========================================================================================================================
static int _PrintFTestExtension2( PrintFContext *ctx, PrintFFormat *inFormat, PrintFVAList *inArgs, void *inUserContext )
{
(void) inFormat;
(void) inArgs;
(void) inUserContext;
return( PrintFCore( ctx, "NoArgsExtension" ) );
}
//===========================================================================================================================
// _PrintFTestString
//===========================================================================================================================
static OSStatus _PrintFTestString( const char *inMatch, const char *inFormat, ... )
{
OSStatus err;
size_t size;
int n;
va_list args;
char buf[ 512 ];
const char * src;
const char * end;
memset( buf, 'Z', sizeof( buf ) );
va_start( args, inFormat );
n = VSNPrintF( buf, sizeof( buf ), inFormat, args );
va_end( args );
#if( PRINTF_UTILS_PRINT_TEST )
printf( "\"%.*s\"\n", (int) sizeof( buf ), buf );
#endif
size = strlen( inMatch );
require_action_quiet( n == (int) size, exit, err = kSizeErr );
require_action_quiet( buf[ n ] == '\0', exit, err = kOverrunErr );
require_action_quiet( strcmp( buf, inMatch ) == 0, exit, err = kMismatchErr );
src = &buf[ n + 1 ];
end = buf + sizeof( buf );
while( ( src < end ) && ( *src == 'Z' ) ) ++src;
require_action_quiet( src == end, exit, err = kImmutableErr );
err = kNoErr;
exit:
if( err ) printf( "### Bad PrintF output:\n'%s'\nExpected:\n'%s'", buf, inMatch );
return( err );
}
//===========================================================================================================================
// _PrintFTestVAList
//===========================================================================================================================
static OSStatus _PrintFTestVAList( const char *inMatch, const char *inFormat, ... )
{
OSStatus err;
va_list args;
va_start( args, inFormat );
err = _PrintFTestString( inMatch, "begin %V end", inFormat, &args );
va_end( args );
return( err );
}
#endif // !EXCLUDE_UNIT_TESTS
| 30.601966 | 138 | 0.520966 | [
"object"
] |
7c47524540e4221bc0a38aa0471732180f6bebdb | 6,542 | h | C | aws-cpp-sdk-rekognition/include/aws/rekognition/model/ProtectiveEquipmentPerson.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-rekognition/include/aws/rekognition/model/ProtectiveEquipmentPerson.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-rekognition/include/aws/rekognition/model/ProtectiveEquipmentPerson.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/rekognition/Rekognition_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/rekognition/model/BoundingBox.h>
#include <aws/rekognition/model/ProtectiveEquipmentBodyPart.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace Rekognition
{
namespace Model
{
/**
* <p>A person detected by a call to <a>DetectProtectiveEquipment</a>. The API
* returns all persons detected in the input image in an array of
* <code>ProtectiveEquipmentPerson</code> objects.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/rekognition-2016-06-27/ProtectiveEquipmentPerson">AWS
* API Reference</a></p>
*/
class AWS_REKOGNITION_API ProtectiveEquipmentPerson
{
public:
ProtectiveEquipmentPerson();
ProtectiveEquipmentPerson(Aws::Utils::Json::JsonView jsonValue);
ProtectiveEquipmentPerson& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>An array of body parts detected on a person's body (including body parts
* without PPE). </p>
*/
inline const Aws::Vector<ProtectiveEquipmentBodyPart>& GetBodyParts() const{ return m_bodyParts; }
/**
* <p>An array of body parts detected on a person's body (including body parts
* without PPE). </p>
*/
inline bool BodyPartsHasBeenSet() const { return m_bodyPartsHasBeenSet; }
/**
* <p>An array of body parts detected on a person's body (including body parts
* without PPE). </p>
*/
inline void SetBodyParts(const Aws::Vector<ProtectiveEquipmentBodyPart>& value) { m_bodyPartsHasBeenSet = true; m_bodyParts = value; }
/**
* <p>An array of body parts detected on a person's body (including body parts
* without PPE). </p>
*/
inline void SetBodyParts(Aws::Vector<ProtectiveEquipmentBodyPart>&& value) { m_bodyPartsHasBeenSet = true; m_bodyParts = std::move(value); }
/**
* <p>An array of body parts detected on a person's body (including body parts
* without PPE). </p>
*/
inline ProtectiveEquipmentPerson& WithBodyParts(const Aws::Vector<ProtectiveEquipmentBodyPart>& value) { SetBodyParts(value); return *this;}
/**
* <p>An array of body parts detected on a person's body (including body parts
* without PPE). </p>
*/
inline ProtectiveEquipmentPerson& WithBodyParts(Aws::Vector<ProtectiveEquipmentBodyPart>&& value) { SetBodyParts(std::move(value)); return *this;}
/**
* <p>An array of body parts detected on a person's body (including body parts
* without PPE). </p>
*/
inline ProtectiveEquipmentPerson& AddBodyParts(const ProtectiveEquipmentBodyPart& value) { m_bodyPartsHasBeenSet = true; m_bodyParts.push_back(value); return *this; }
/**
* <p>An array of body parts detected on a person's body (including body parts
* without PPE). </p>
*/
inline ProtectiveEquipmentPerson& AddBodyParts(ProtectiveEquipmentBodyPart&& value) { m_bodyPartsHasBeenSet = true; m_bodyParts.push_back(std::move(value)); return *this; }
/**
* <p>A bounding box around the detected person.</p>
*/
inline const BoundingBox& GetBoundingBox() const{ return m_boundingBox; }
/**
* <p>A bounding box around the detected person.</p>
*/
inline bool BoundingBoxHasBeenSet() const { return m_boundingBoxHasBeenSet; }
/**
* <p>A bounding box around the detected person.</p>
*/
inline void SetBoundingBox(const BoundingBox& value) { m_boundingBoxHasBeenSet = true; m_boundingBox = value; }
/**
* <p>A bounding box around the detected person.</p>
*/
inline void SetBoundingBox(BoundingBox&& value) { m_boundingBoxHasBeenSet = true; m_boundingBox = std::move(value); }
/**
* <p>A bounding box around the detected person.</p>
*/
inline ProtectiveEquipmentPerson& WithBoundingBox(const BoundingBox& value) { SetBoundingBox(value); return *this;}
/**
* <p>A bounding box around the detected person.</p>
*/
inline ProtectiveEquipmentPerson& WithBoundingBox(BoundingBox&& value) { SetBoundingBox(std::move(value)); return *this;}
/**
* <p>The confidence that Amazon Rekognition has that the bounding box contains a
* person.</p>
*/
inline double GetConfidence() const{ return m_confidence; }
/**
* <p>The confidence that Amazon Rekognition has that the bounding box contains a
* person.</p>
*/
inline bool ConfidenceHasBeenSet() const { return m_confidenceHasBeenSet; }
/**
* <p>The confidence that Amazon Rekognition has that the bounding box contains a
* person.</p>
*/
inline void SetConfidence(double value) { m_confidenceHasBeenSet = true; m_confidence = value; }
/**
* <p>The confidence that Amazon Rekognition has that the bounding box contains a
* person.</p>
*/
inline ProtectiveEquipmentPerson& WithConfidence(double value) { SetConfidence(value); return *this;}
/**
* <p>The identifier for the detected person. The identifier is only unique for a
* single call to <code>DetectProtectiveEquipment</code>.</p>
*/
inline int GetId() const{ return m_id; }
/**
* <p>The identifier for the detected person. The identifier is only unique for a
* single call to <code>DetectProtectiveEquipment</code>.</p>
*/
inline bool IdHasBeenSet() const { return m_idHasBeenSet; }
/**
* <p>The identifier for the detected person. The identifier is only unique for a
* single call to <code>DetectProtectiveEquipment</code>.</p>
*/
inline void SetId(int value) { m_idHasBeenSet = true; m_id = value; }
/**
* <p>The identifier for the detected person. The identifier is only unique for a
* single call to <code>DetectProtectiveEquipment</code>.</p>
*/
inline ProtectiveEquipmentPerson& WithId(int value) { SetId(value); return *this;}
private:
Aws::Vector<ProtectiveEquipmentBodyPart> m_bodyParts;
bool m_bodyPartsHasBeenSet;
BoundingBox m_boundingBox;
bool m_boundingBoxHasBeenSet;
double m_confidence;
bool m_confidenceHasBeenSet;
int m_id;
bool m_idHasBeenSet;
};
} // namespace Model
} // namespace Rekognition
} // namespace Aws
| 34.251309 | 176 | 0.685723 | [
"vector",
"model"
] |
7c54daaa79b5c9c0e1576c412863042cbdeb9a0e | 2,885 | h | C | src/SynchronizationInstrumentor/FunctionFileReader.h | mozafari/vprofiler | 23e44f04ba7476d35080bd3bc3a03c8e941e762a | [
"Apache-2.0"
] | 107 | 2016-03-11T04:45:42.000Z | 2022-03-06T05:06:38.000Z | src/SynchronizationInstrumentor/FunctionFileReader.h | mozafari/vprofiler | 23e44f04ba7476d35080bd3bc3a03c8e941e762a | [
"Apache-2.0"
] | 14 | 2016-03-02T21:30:54.000Z | 2019-12-22T18:56:17.000Z | src/SynchronizationInstrumentor/FunctionFileReader.h | mozafari/vprofiler | 23e44f04ba7476d35080bd3bc3a03c8e941e762a | [
"Apache-2.0"
] | 12 | 2017-05-31T02:05:21.000Z | 2021-11-27T13:59:57.000Z | #ifndef FUNCTIONFILEREADER_H
#define FUNCTIONFILEREADER_H
// VProf libs
#include "Utils.h"
// STL libs
#include <memory>
#include <unordered_map>
#include <string>
#include <vector>
#include <set>
#include <fstream>
#include <stdexcept>
#include <algorithm>
enum Operation { MUTEX_LOCK, MUTEX_UNLOCK, // Mutexes
CV_WAIT, CV_BROADCAST, CV_SIGNAL, // CVs
QUEUE_ENQUEUE, QUEUE_DEQUEUE, // Queues
MESSAGE_SEND, MESSAGE_RECEIVE, // Messaging
MKNOD, OPEN, CLOSE, READ, WRITE, PIPE, // IPC FIFO/pipe
MSGGET, MSGSND, MSGRCV }; // IPC message queue
struct LogInformation {
unsigned int functionID;
Operation op;
};
class FunctionFileReader {
public:
FunctionFileReader(const std::string _userFilename):
userFilename(_userFilename),
funcMap(std::make_shared<std::unordered_map<std::string, std::string>>()),
opMap(std::make_shared<std::unordered_map<std::string, std::string>>()),
unqualifiedNames(std::make_shared<std::vector<std::string>>()),
qualifiedNames(std::make_shared<std::vector<std::string>>()),
operationStrings({ "MUTEX_LOCK", "MUTEX_UNLOCK", "CV_WAIT",
"CV_BROADCAST", "CV_SIGNAL", "QUEUE_ENQUEUE",
"QUEUE_DEQUEUE", "MESSAGE_SEND", "MESSAGE_RECEIVE",
"MKNOD", "CLOSE", "OPEN", "READ", "WRITE", "PIPE",
"MSGGET", "MSGSND", "MSGRCV" }),
beenParsed(false) {}
// Parse the file
void Parse();
// Returns the function map generated by parse.
// Parse must be called prior to this.
std::shared_ptr<std::unordered_map<std::string, std::string>> GetFunctionMap();
// Returns a map of qualified function name to log info struct
std::shared_ptr<std::unordered_map<std::string, std::string>> GetOperationMap();
// Returns a vector of all the qualified function names.
// Parse must be called prior to this.
std::shared_ptr<std::vector<std::string>> GetQualifiedFunctionNames();
// Returns a vector of all the unqualified function names.
// Parse must be called prior to this.
std::shared_ptr<std::vector<std::string>> GetUnqualifiedFunctionNames();
private:
const std::string userFilename;
std::shared_ptr<std::unordered_map<std::string, std::string>> funcMap;
std::shared_ptr<std::unordered_map<std::string, std::string>> opMap;
std::shared_ptr<std::vector<std::string>> unqualifiedNames;
std::shared_ptr<std::vector<std::string>> qualifiedNames;
std::set<std::string> operationStrings;
bool beenParsed;
void Parse(const std::string &filename);
};
#endif
| 37.467532 | 88 | 0.613518 | [
"vector"
] |
7c5fa0b45bf0e65ace9d8f99641aef1b20c637c8 | 3,449 | h | C | source/frame.h | ramenhut/final-stage-path-tracer-2-0 | 77c3a706f6521d88245b95b6310344b202be0e37 | [
"BSD-2-Clause"
] | 5 | 2019-07-26T06:24:16.000Z | 2019-11-10T09:41:20.000Z | source/frame.h | ramenhut/final-stage-path-tracer-2-0 | 77c3a706f6521d88245b95b6310344b202be0e37 | [
"BSD-2-Clause"
] | null | null | null | source/frame.h | ramenhut/final-stage-path-tracer-2-0 | 77c3a706f6521d88245b95b6310344b202be0e37 | [
"BSD-2-Clause"
] | 2 | 2019-09-18T13:01:45.000Z | 2021-10-17T00:04:04.000Z | /*
//
// Copyright (c) 1998-2019 Joe Bertolami. All Right Reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, CLUDG, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, DIRECT, CIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (CLUDG, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSESS TERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER CONTRACT, STRICT
// LIABILITY, OR TORT (CLUDG NEGLIGENCE OR OTHERWISE) ARISG ANY WAY OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Additional Information:
//
// For more information, visit http://www.bertolami.com.
//
*/
#ifndef __FRAME_H__
#define __FRAME_H__
#include "math/base.h"
#include "math/vector3.h"
namespace base {
typedef struct TraceResult {
vector3 color;
vector3 normal;
float32 depth;
uint64 material_id;
uint64 ray_count;
TraceResult() : depth(0.0f), material_id(0), ray_count(0) {}
} TraceResult;
class DisplayFrame {
public:
DisplayFrame(uint32 width, uint32 height);
~DisplayFrame();
// Clears internal buffers to black (0), and resets pixel counts.
// Call this when beginning a new frame.
void Reset();
// Writes pixel into the render buffer, increments count, and writes the
// output pixel.
void WritePixel(const vector3& pixel, uint32 x, uint32 y);
// Incorporates a trace result into a final pixel value.
void WritePixel(const TraceResult& result, uint32 x, uint32 y);
// Returns a pointer to the current output buffer.
uint8* GetDisplayBuffer() { return display_buffer_; }
// Returns the width of the frame.
uint32 GetWidth() { return width_; }
// Returns the height of the frame.
uint32 GetHeight() { return height_; }
// Returns width / height.
float32 GetAspectRatio() { return (float32) width_ / height_; }
// Sets the current frame count.
void SetFrameCount(uint32 count) { frame_count_ = count; }
private:
uint32 frame_count_;
// Width of the frame, in pixels.
uint32 width_;
// Height of the frame, in pixels.
uint32 height_;
// Intermediary floating point frame buffer. May include HDR values.
vector3* render_target_;
// Intermediary filtered frame buffer.
vector3* filtered_render_target_;
// Final frame buffer used for display.
uint8* display_buffer_;
// Running count of samples for each pixel.
uint32* count_buffer_;
// Per-pixel normals for the scene.
vector3* normal_buffer_;
// Per-pixel depth values for the scene.
float32* depth_buffer_;
// Per-pixel material ids for the scene.
uint64* material_id_buffer_;
};
} // namespace base
#endif // __FRAME_H__ | 35.927083 | 80 | 0.729777 | [
"render"
] |
7c616f8405b5d04f2fa4a4c8d1b055f57d590b15 | 213,709 | c | C | src/codelib/resources/reslib/src/resmgr.c | Terebinth/freefalcon-central | c28d807183ab447ef6a801068aa3769527d55deb | [
"BSD-2-Clause"
] | 117 | 2015-01-13T14:48:49.000Z | 2022-03-16T01:38:19.000Z | src/codelib/resources/reslib/src/resmgr.c | darongE/freefalcon-central | c28d807183ab447ef6a801068aa3769527d55deb | [
"BSD-2-Clause"
] | 4 | 2015-05-01T13:09:53.000Z | 2017-07-22T09:11:06.000Z | src/codelib/resources/reslib/src/resmgr.c | darongE/freefalcon-central | c28d807183ab447ef6a801068aa3769527d55deb | [
"BSD-2-Clause"
] | 78 | 2015-01-13T09:27:47.000Z | 2022-03-18T14:39:09.000Z | /* ----------------------------------------------------------------------
Resource Manager
Version 2.05 Released 03/26/97
Written by Kevin Ray (x301) (c) 1996 Spectrum Holobyte
----------------------------------------------------------------------
The resource manager's main function is to provide a single entry
point for file i/o from within an application. Besides this
obvious requirement, this implementation also provides these
added functional blocks:
1) file extraction from archive (zip) files.
2) virtual file system that allows easy patching of data.
3) caching beyond the minimal i/o buffers bitand mscdex.
4) asynchronous read/writes.
5) event logging (for general debugging as well as to
provide a table from which to sort the contents of
a CD to minimize seeks).
6) Significant debugging options.
For the most part, all of the exported functions are syntactically
similiar to the low-level i/o functions (io.h). Obvious exceptions
to this rule are the functions for reading the contents of a
directory. Since the standard dos functions _findfirst, _findnext,
_findclose have always been cumbersome and 'unnatural', this
implementation uses the metaphor used by the UNIX opendir
command (Roger Fujii's suggestion). For more information, look
at the comment above the ResOpenDirectory function.
There are several compiler options that can be selected to build
various flavors of the Resource Manager. Debugging, obviously,
can be included or excluded. Within the general debugging
category, Event Logging, Parameter Checking and use of a debug
window can all be included or excluded. Each of these latter
options requires that the RES_DEBUG_VERSION be defined and
non-zero (just use 'YES' in the header file).
Since the bafoons at Microsoft have deemed multithreading to be
such an awesome feature (like they invented it - it's not like
there aren't multithreaded operating systems on even lowly 8-bit
microcontrollers) this feature can be disabled. Obviously this
may seem somewhat rediculous considering that asynch i/o is the
main feature you want threads for, but MS Visual C++ shows some
terribly worrisome behaviors with threads. For instance, the
compiler doesn't recognize _beginthread() even with <process.h>
included unless you have the link option /MT selected. Why does
the compiler care? And there is no kill() so callbacks being
instantiated from a thread are problematic since the callbacks
context is always that of the thread. Therefore, if you want
to hide this functionality from the others using ResMgr, you
can turn it off.
In summary, here are the different buid options:
debugging on or off
multithreading on or off
standalone version capability
flat or hierarchical database (explained below)
event logging
parameter checking
To use this library, you need to do just a few things. Here is
a synopsis of the functions you'll need to call and the order
in which to call them:
1) ResInit initialize the resource manager
2) ResCreatePath give the resource manager somewhere to
look for files
3) ResAttach (optional) open an archive file
4) ResOpenFile,
ResReadFile, perform file i/o
ResCloseFile
5) ResExit shut-down the resource manager
History:
03/18/96 KBR Created/Thieved (unzip/inflate from Fujii via gcc).
04/01/96 KBR Integrated unzip/inflate under virtual filesystem.
TBD: CD statistic caching (head movements, warning tracks, etc).
---------------------------------------------------------------------- */
#include <cISO646>
#include "lists.h" /* list manipulation functions (+list.cpp) */
#include "resmgr.h" /* exported prototypes bitand type definitions */
//#include "memmgr.h"
#include "omni.h"
#include <stdio.h> /* low-level file i/o (+io.h) */
#include <string.h>
#include <memory.h>
#include <sys/stat.h> /* _S_IWRITE */
#include <stdarg.h>
#include <assert.h>
#if USE_WINDOWS
# include <io.h>
# include <direct.h>
# include <process.h> /* _beginthread() MUST SET C++ OPTIONS UNDER
MSVC SETTINGS */
# include <windows.h> /* all this for MessageBox (may move to debug.cpp)*/
#endif /* USE_WINDOWS */
#include "unzip.h"
#ifdef USE_SH_POOLS
#undef MemFree
#undef MemFreePtr
#undef MemMalloc
#include "Smartheap/Include/smrtheap.h"
MEM_POOL gResmgrMemPool = NULL;
#endif
#define SHOULD_I_CALL(idx,retval) if( RES_CALLBACK[(idx)] )\
retval = ( *(RES_CALLBACK[(idx)]));
#define SHOULD_I_CALL_WITH(idx,param,retval) if( RES_CALLBACK[(idx)] )\
retval = ((*(RES_CALLBACK[(idx)]))(param));
#if( RES_STREAMING_IO )
RES_EXPORT FILE * __cdecl _getstream(void);
RES_EXPORT FILE * __cdecl _openfile(const char *, const char *, int, FILE *);
RES_EXPORT void __cdecl _getbuf(FILE *);
RES_EXPORT int __cdecl _flush(FILE *);
RES_EXPORT long __cdecl ftell(FILE *);
RES_EXPORT long __cdecl _ftell_lk(FILE *);
extern void __cdecl _getbuf(FILE *);
extern int __cdecl _flush(FILE * str);
#define EINVAL 22
#define _IOYOURBUF 0x0100
#define _INTERNAL_BUFSIZ 4096
#define _IOARCHIVE 0x00010000
#define _IOLOOSE 0x00020000
#define _SMALL_BUFSIZ 512 /* from stdio.h */
#define _INTERNAL_BUFSIZ 4096 /* from stdio.h */
#define _IOSETVBUF 0x0400 /* from file2.h */
#define _SH_DENYNO 0x40 /* from share.h */
#define anybuf(s) ((s)->_flag bitand (_IOMYBUF|_IONBF|_IOYOURBUF))
#define inuse(s) ((s)->_flag bitand (_IOREAD|_IOWRT|_IORW))
#define SHOULD_I_CALL(idx,retval) if( RES_CALLBACK[(idx)] )\
retval = ( *(RES_CALLBACK[(idx)]));
#define SHOULD_I_CALL_WITH(idx,param,retval) if( RES_CALLBACK[(idx)] )\
retval = ((*(RES_CALLBACK[(idx)]))(param));
#endif /* RES_STREAMING_IO */
#define RES_INIT_DIRECTORY_SIZE 8 /* initial size for buffer used in ResCountDirectory */
/* realloc'ed as needed */
/* ----------------------------------------------------------------------
FLAT MODEL VS. HIERARCHICAL MODEL
----------------------------------------------------------------------
There are two different implementation models that can be chosen from.
The first model is one in which all files are peers of one another.
Regardless of where the file resides, the flat model treats all files
as if they were to be found in a single directory. If there happens
to be two files with the same name, but in two different directories,
the file which resides in the directory which was LAST processed is the
file that is entered into the database (in effect, it overrides the
existence of the previous file).
The second implementation model is hierarchical. In this model
directory paths are used to differentiate between identically named
files. This is the only model which supports wildcarding within a
directory (\objects\*.3ds). I'm not sure how usefull this model is, but
considering what a pain it was to implement, I hope it somehow is. Since
one of the most important uses of the Resource Manager is to allow
projects to be 'patched' by simply copying newer data to a higher
priority directory, I exposed an 'override' function so that this
functionality is still present in the hierarchical model. In essence, if
there is a file c:\game\foo.dat and another file c:\object\foo.dat, if
I override with a file called c:\game\patches\foo.dat I have replaced both
\game\foo.dat AND \object\foo.dat with the file found in c:\game\patches --
obviously this requires that more attention be paid to reducing these
complexities and avoiding possible pitfalls.
Flat model: Single hash table
All filenames are peers
Last file entered takes precedence
'Override' is automatic
Hierarchical model: Hash table for each directory
Supports multiple instances of a like-named file
'Override' files manually by calling override
In the flat model, files within a compressed archive are globbed right
along within the same table as all other files. The hierarchical model
will interpret any directory information within the archive file if it
exists, if not all files will go into their own hash table (as if all the
files within the archive were in the same directory).
The flat model is the default.
---------------------------------------------------------------------- */
/* ----------------------------------------------------------------------
U T I L I T Y M A C R O S
---------------------------------------------------------------------- */
#ifndef MAX
# define MAX(a,b) ((a) > (b) ? (a) : (b))
#endif
#ifndef MIN
# define MIN(a,b) ((a) < (b) ? (a) : (b))
#endif
#define RES_STRING_SET( dst, src, ptr ); { strcpy( ptr, src ); \
dst = ptr; \
ptr += strlen(src)+1; }
#define NOTHING -1
#define FLAG_TEST(a,b) ( a bitand b )
#define FLAG_SET(a,b) ( a or_eq b )
#define FLAG_UNSET(a,b) ( a xor_eq compl b )
#define HI_WORD(a) ((a)>>16)
#define LO_WORD(a) ((a)&0x0ffff)
#define SET_HIWORD(a,b) { a or_eq ((b)<<16); }
#define SET_LOWORD(a,b) { a or_eq (b)&0x0ffff; }
#define WRITTEN_TO_FLAG -1
#ifdef _MT
extern void __cdecl _unlock_file(FILE *);
extern void __cdecl _lock_file(FILE *);
extern void __cdecl _lock_fhandle(int);
extern void __cdecl _unlock_fhandle(int);
# define LOCK_STREAM(a) { _lock_file(a); LOG( "+ %d\n", __LINE__ ); }
# define UNLOCK_STREAM(a) { _unlock_file(a); LOG( "- %d\n", __LINE__ ); }
#else
# define LOCK_STREAM(a)
# define UNLOCK_STREAM(a)
#endif
enum /* compression methods */
{
METHOD_STORED = 0, /* just stored in archive (no compression) */
METHOD_DEFLATED, /* pkzip style 'deflation' */
METHOD_LOOSE /* loose file on harddrive */
};
#define EMPTY(a) ((a) == NOTHING)
/* ----------------------------------------------------------------------
T Y P E D E F I N I T I O N S
----------------------------------------------------------------------- */
typedef struct ASYNCH_DATA /* created when spawning a read/write thread */
{
int file; /* handle of file performing i/o on */
void * buffer; /* ptr to buffer used to read to/write from */
size_t size; /* bytes to read -or- bytes to write */
PFV callback; /* callback to issue upon completion */
} ASYNCH_DATA;
/* ----------------------------------------------------------------------
D E B U G S P E C I F I C I T E M S
---------------------------------------------------------------------- */
#if( RES_DEBUG_VERSION )
# include "errno.h"
/* ---- DEBUG FUNCTIONS ---- */
void
dbg_analyze_hash(HASH_TABLE * hsh),
dbg_print(HASH_ENTRY * entry),
dbg_dir(HASH_TABLE * hsh),
dbg_device(DEVICE_ENTRY * dev);
STRING RES_ERR_OR_MSGS[] =
{
"Not enough memory", /* Debug - Verbose Error Messages */
"Incorrect parameter",
"Path not found",
"File sharing (network error)",
"There is no matching cd number",
"File already closed",
"File not found",
"Can't attrib directory",
"Can't attrib file",
"Directory already exists",
"Not a directory",
"Could not delete",
"Could not change directory",
"Must create search path",
"Could not spawn thread",
"Could not open file",
"Problem reading file",
"Problem writing file",
"System path has not been created yet",
"Cannot interpret file/path",
"Unknown archive",
"Too many open files",
"Illegal file handle",
"Cannot delete file",
"Cannot open archive file",
"Corrupt archive file",
"Unknown error",
"Directory already in search path",
"Destination directory not known (must add first)",
"Cannot write to an archive",
"Unsupported compression type",
"Too many directories"
};
int
RES_ERR_COUNT = sizeof(RES_ERR_OR_MSGS) / sizeof(RES_ERR_OR_MSGS[0]);
void
_say_error(int error, const char * msg, int line, const char * filename);
# define SAY_ERROR(a,b) _say_error((a),(b), __LINE__, __FILE__ )
int RES_DEBUG_FLAG = TRUE; /* run-time toggle for debugging */
int RES_DEBUG_LOGGING = FALSE; /* are we currently logging events? */
int RES_DEBUG_OPEN_LOG = FALSE; /* is a log file open? */
int RES_DEBUG_FILE = -1; /* file handle for logging events */
#if( RES_DEBUG_LOG )
# define IF_LOG(a) a
# define LOG ResDbgPrintf
#else
# define IF_LOG(a)
# define LOG
#endif
# define IF_DEBUG(a) a
#else /* RES_DEBUG_VERSION ? */
# define IF_DEBUG(a)
# define IF_LOG(a)
# define LOG
# define SAY_ERROR(a,b) {RES_DEBUG_ERRNO=(a);}
#endif
#if( RES_DEBUG_VERSION == 0 )
# if( RES_DEBUG_PARAMS )
# error RES_DEBUG_VERSION must be TRUE to use RES_DEBUG_PARAMS
# endif
#endif
#define CREATE_LOCK(a) CreateMutex( NULL, FALSE, a );
#define REQUEST_LOCK(a) WaitForSingleObject(a, INFINITE);
#define RELEASE_LOCK(a) ReleaseMutex(a);
#define DESTROY_LOCK(a) CloseHandle(a);
/* ----------------------------------------------------------------------
S T A T I C D A T A
---------------------------------------------------------------------- */
#if (RES_MULTITHREAD)
static HANDLE GLOCK = 0;
#endif
HASH_TABLE /* For a flat model, this is the only hash table, */
* GLOBAL_HASH_TABLE = NULL; /* for a hierarchical model, this is the hashed */
/* version of a root directory */
FILE_ENTRY
* FILE_HANDLES = NULL; /* Slots for open file handles */
PFI
RES_CALLBACK[ NUMBER_OF_CALLBACKS ];
PRIVATE
LIST
* ARCHIVE_LIST = NULL;
PRIVATE
LIST
* OPEN_DIR_LIST = NULL;
char
* RES_PATH[ RES_DIR_LAST ],
* GLOBAL_SEARCH_PATH[ MAX_DIRECTORIES ];
char
GLOBAL_INIT_PATH[ _MAX_PATH ],
GLOBAL_CURRENT_PATH[ _MAX_PATH ];
int
RESMGR_INIT = FALSE;
LIST
* GLOBAL_PATH_LIST = NULL;
DEVICE_ENTRY
* RES_DEVICES = NULL;
int
GLOBAL_INIT_DRIVE;
int
GLOBAL_CURRENT_DRIVE;
int
GLOBAL_CURRENT_CD;
int
GLOBAL_VOLUME_MASK = 0; /* which drive volumes are available */
int
GLOBAL_SEARCH_INDEX = 0;
int
GLOBAL_CD_DEVICE;
int
RES_DEBUG_ERRNO; /* the equivalent of an 'errno' */
static char resmgr_version[] = "[Version] ResMgr version 2.0";
static HWND RES_GLOBAL_HWND;
/* ----------------------------------------------------------------------
L O C A L P R O T O T Y P E S
---------------------------------------------------------------------- */
/* ---- ASYNCH I/O ---- */
void
asynch_write(void * thread_data), /* thread function to handle asynch writes */
asynch_read(void * thread_data); /* thread function to handle asynch reads */
/* ---- HASH FUNCTIONS ---- */
int
hash(const char * string, int size); /* hash function */
int
hash_resize(HASH_TABLE * hsh), /* dynamically resize a hash table */
hash_delete(HASH_ENTRY * entry, HASH_TABLE * hsh); /* delete an entry from a hash table */
void
hash_destroy(HASH_TABLE * hsh), /* destroy a hash table */
// hash_purge( HASH_TABLE * hsh, char * archive, char * volume, char * directory, char * name ); /* purge hash entries */
hash_purge(HASH_TABLE * hsh, const char * archive, const char * volume, const int * directory, const char * name); /* purge hash entries */
HASH_TABLE
* hash_create(int size, char * name); /* create a new hash table */
HASH_ENTRY
* hash_find(const char * name, HASH_TABLE * hsh), /* find an entry within a hash table */
* hash_add(struct _finddata_t * data, HASH_TABLE * hsh), /* add an entry to a hash table */
* hash_find_table(const char * name, HASH_TABLE ** table); /* find an entry within many tables */
char
* hash_strcpy(HASH_TABLE * hsh, char * string); /* strcpy that uses the hash table string pool */
/* ---- MISCELLANEOUS ---- */
int
get_handle(void); /* return an available file handle */
void
split_path(const char * path, char * filename, char * dirpath), /* cut a path string in two */
shut_down(void); /* release allocations bitand reset Resource Mgr. */
char
* res_fullpath(char * abs_buffer, const char * rel_buffer, int maxlen);
void
res_detach_ex(ARCHIVE * arc); /* allows func ptr to be passed to LIST_DESTROY */
void
sort_path(void); /* forces cd-based paths to the bottom of the
search path */
int
get_dir_index(char * path);
/* From unzip.cpp */
extern
ARCHIVE
* archive_create(const char * attach_point, const char * filename, HASH_TABLE * table, int replace_flag);
extern
void
archive_delete(ARCHIVE * arc);
extern
int
process_local_file_hdr(local_file_hdr * lrec, char * buffer);
/* From inflate.cpp */
extern
int
inflate(COMPRESSED_FILE * cmp);
extern
int
inflate_free(void);
/* From MSVC CRT */
extern __cdecl _freebuf(FILE *);
extern __cdecl _fseek_lk(FILE *, long, int);
extern __cdecl _lseek_lk(int, long, int);
extern __cdecl _read_lk(int, char *, int);
/* ----------------------------------------------------------------------
----------------------------------------------------------------------
R E S O U R C E M A N A G E R * P U B L I C F U N C T I O N S
----------------------------------------------------------------------
---------------------------------------------------------------------- */
/* =======================================================
FUNCTION: ResInit
PURPOSE: Initialize the resource manager.
PARAMETERS: Parent window pointer
RETURNS: TRUE (pass) / FALSE (fail)
======================================================= */
RES_EXPORT int ResInit(HWND hwnd)
{
DEVICE_ENTRY * dev;
unsigned long length,
file;
int drive,
index;
char root[] = "C:\\"; /* root dir mask used to query devices */
char string[_MAX_PATH]; /* dummy string to fill out parameter list */
#if USE_SH_POOLS
if (gResmgrMemPool == NULL)
{
gResmgrMemPool = MemPoolInit(0);
}
#endif
/* if the user is calling ResInit to re-initialize the resource manager
(since this is allowable), we need to free up any previous allocations. */
if ( not RESMGR_INIT)
{
memset(GLOBAL_SEARCH_PATH, 0, sizeof(GLOBAL_SEARCH_PATH));
memset(RES_PATH, 0, sizeof(char*) * RES_DIR_LAST); /* reset system paths */
GLOBAL_SEARCH_INDEX = 0;
}
shut_down();
RES_GLOBAL_HWND = hwnd;
#ifdef USE_SH_POOLS
FILE_HANDLES = (FILE_ENTRY *)MemAllocPtr(gResmgrMemPool, sizeof(FILE_ENTRY) * MAX_FILE_HANDLES, 0);
#else
FILE_HANDLES = (FILE_ENTRY *)MemMalloc(sizeof(FILE_ENTRY) * MAX_FILE_HANDLES, "File handles");
#endif
if ( not FILE_HANDLES)
{
SAY_ERROR(RES_ERR_NO_MEMORY, "ResInit");
return(FALSE);
}
memset(FILE_HANDLES, 0, sizeof(FILE_ENTRY) * MAX_FILE_HANDLES);
for (index = 0; index < MAX_FILE_HANDLES; index++)
FILE_HANDLES[ index ].os_handle = -1;
/* Save current drive. */
GLOBAL_INIT_DRIVE = _getdrive();
_getdcwd(GLOBAL_INIT_DRIVE, GLOBAL_INIT_PATH, _MAX_PATH);
RES_PATH[ RES_DIR_CURR ] = MemStrDup(GLOBAL_INIT_PATH);
/* -------------------------------------------------------------
Minimal Hardware Query
-------------------------------------------------------------
We determine all devices in the host machine and store the
volume name and volume serial number of the media that is
current mounted on that device. It there is ever a read
failure, or ResCheckMedia is explicitly called, we use
this information to determine if the end-user has swapped
the media without our knowledge.
Since it's not unimagineable that a user that is attached
to a LAN has all his drive letters mapped to network drives,
or, that under Win95 his CD letter is towards the high end
of the alphabet because of network drives, it is recommended
that you use 26 as the value for MAX_DEVICES. It's not
very much memory to give up, and you may be glad you did.
------------------------------------------------------------- */
GLOBAL_VOLUME_MASK = 0;
#if 0
for (drive = 1; drive <= MAX_DEVICES; drive++)
{
/* If we can switch to the drive, it exists. - not if there is a seriously
damaged floppy in the drive, it is possible to crash VxD HFLOP just by
switching to the device. Of course, for this case, anytime the user
double clicks on the floppy icon from the desktop will also cause this
crash. Caveat Emptor. */
if ( not _chdrive(drive))
{
GLOBAL_VOLUME_MASK or_eq (1 << drive);
}
}
#endif
GLOBAL_VOLUME_MASK = GetLogicalDrives();
GLOBAL_VOLUME_MASK <<= 1; /* 1 is drive A in ResMgr, GetLogicalDrives returns A equals 0 */
#ifdef USE_SH_POOLS
RES_DEVICES = (DEVICE_ENTRY *)MemAllocPtr(gResmgrMemPool, MAX_DEVICES * sizeof(DEVICE_ENTRY), 0);
#else
RES_DEVICES = (DEVICE_ENTRY *)MemMalloc(MAX_DEVICES * sizeof(DEVICE_ENTRY), "Devices");
#endif
if ( not RES_DEVICES)
{
SAY_ERROR(RES_ERR_NO_MEMORY, "ResInit");
return(FALSE);
}
GLOBAL_CD_DEVICE = -1;
for (drive = 1; drive <= MAX_DEVICES; drive++)
{
dev = &RES_DEVICES[drive - 1];
if (GLOBAL_VOLUME_MASK bitand (1 << drive))
{
root[0] = (char)('A' + (drive - 1));
/* According to Microsoft, most of the parameters to GetVolumeInformation are optional, however
this is not the case. It is possible to completely destroy the file system on a floppy
diskette by calling this seemingly innocuous function without all of the parameters */
dev -> type = (char)(GetDriveType(root));
dev -> letter = root[0];
if ((dev -> type == DRIVE_FIXED) or
(dev -> type == DRIVE_CDROM) or
(dev -> type == DRIVE_RAMDISK))
{
GetVolumeInformation(root, dev -> name, 24, &dev -> serial, &length, &file, string, _MAX_PATH);
}
else
{
strcpy(dev -> name, "unknown");
dev -> serial = 0L;
}
/* Initialize default entries into the system path tables */
if ((dev -> type == DRIVE_CDROM) and not RES_PATH[ RES_DIR_CD ])
{
GLOBAL_CD_DEVICE = drive - 1; /* NEED A BETTER WAY */
RES_PATH[ RES_DIR_CD ] = MemStrDup(root);
}
if ((drive == 3) and (dev -> type == DRIVE_FIXED))
RES_PATH[ RES_DIR_HD ] = MemStrDup(root);
}
else
{
dev -> type = -1;
dev -> letter = ASCII_DOT;
strcpy(dev -> name, "unknown");
dev -> serial = 0L;
}
}
GetTempPath(_MAX_PATH, string);
RES_PATH[ RES_DIR_TEMP ] = MemStrDup(string);
#if (RES_MULTITHREAD)
if ( not GLOCK) GLOCK = CREATE_LOCK("multithread");
#endif
IF_LOG(LOG("Resource Manager Initialized.\n"));
RESMGR_INIT = TRUE; /* reinitialize the statics */
return(TRUE);
}
/* =======================================================
FUNCTION: ResExit
PURPOSE: Shut down the resource manager.
PARAMETERS: None.
RETURNS: None.
======================================================= */
RES_EXPORT void ResExit(void)
{
IF_LOG(LOG("Resource Manager Exiting.\n"));
#if (RES_MULTITHREAD)
if (GLOCK) DESTROY_LOCK(GLOCK);
GLOCK = 0;
#endif
shut_down();
/* Restore original drive.*/
_chdrive(GLOBAL_INIT_DRIVE);
_chdir(GLOBAL_INIT_PATH);
#if( RES_DEBUG_VERSION )
if (RES_DEBUG_LOGGING)
ResDbgLogClose();
# if( USE_MEMMGR )
MemSanity();
# endif /* USE_MEMMGR */
#endif /*RES_DEBUG_VERSION */
#if USE_SH_POOLS
if (gResmgrMemPool not_eq NULL)
{
MemPoolFree(gResmgrMemPool);
gResmgrMemPool = NULL;
}
#endif
}
/* =======================================================
FUNCTION: ResMountCD
PURPOSE: Mount a cd. If there is already a mounted
disc, call the user callback and allow
the user to resynch to the current cd.
PARAMETERS: Parent window pointer
RETURNS: TRUE (pass) / FALSE (fail)
======================================================= */
RES_EXPORT int ResMountCD(int cd_number, int device)
{
int resynch = FALSE;
int retval = 1;
IF_LOG(LOG("mounted cd %d\n", cd_number));
#if( RES_DEBUG_PARAMS ) /* parameter checking only with debug version */
if (cd_number < 1 or cd_number > MAX_CD)
SHOULD_I_CALL_WITH(CALLBACK_UNKNOWN_CD, RES_ERR_ILLEGAL_CD, retval);
if ( not retval)
return(FALSE);
#endif
GLOBAL_CD_DEVICE = device;
if (GLOBAL_CURRENT_CD not_eq cd_number) /* we need this flag later */
resynch = TRUE;
/* has the user installed a handler for swap cd? */
SHOULD_I_CALL_WITH(CALLBACK_SWAP_CD, cd_number, retval);
if ( not retval)
return(FALSE);
GLOBAL_CURRENT_CD = cd_number;
/* has the user installed a handler for resynch to the new cd? */
SHOULD_I_CALL_WITH(CALLBACK_RESYNCH_CD, cd_number, retval);
if ( not retval)
return(FALSE);
/* haven't failed so far... */
return(TRUE);
}
/* =======================================================
FUNCTION: ResDismountCD
PURPOSE: Dismount the currently mounted CD.
PARAMETERS: None.
RETURNS: TRUE (pass) / FALSE (fail)
======================================================= */
RES_EXPORT int ResDismountCD(void)
{
ARCHIVE * archive;
LIST * list;
int hit;
int dir; /* GFG change from char to int */
if (GLOBAL_CD_DEVICE == -1)
return(FALSE);
if (ARCHIVE_LIST)
{
do
{
hit = 0;
for (list = ARCHIVE_LIST; list; list = list -> next)
{
archive = (ARCHIVE *)list -> node;
if (archive -> volume == (char)GLOBAL_CD_DEVICE)
{
REQUEST_LOCK(archive -> lock);
dir = archive -> directory;
ResDetach(archive -> os_handle);
ResPurge(NULL, NULL, &dir, NULL);
hit = 1;
RELEASE_LOCK(archive -> lock);
break;
}
}
}
while (hit);
}
ResPurge(NULL, (char *)&GLOBAL_CD_DEVICE, NULL, NULL);
return(TRUE);
}
/* =======================================================
FUNCTION: ResCheckMedia
PURPOSE: Determine if the end-user has swapped
the media for the specified device.
PARAMETERS: 0=A, 1=B, 2=C (drive ordinal).
RETURNS: 0 - yes they changed the media
1 - no they didn't change media
-1 - error reading device (probably in
process of changing media.
======================================================= */
RES_EXPORT int ResCheckMedia(int device)
{
int drive;
int retval = 1;
char root[] = "C:\\";
char name[26],
dummy[6]; /* possible bug in GetVolumeInformation */
unsigned long serial,
long1, /* possible bug in GetVolumeInformation */
long2; /* possible bug in GetVolumeInformation */
DEVICE_ENTRY * dev;
#if( RES_DEBUG_PARAMS )
if (device < 0 or device > MAX_DEVICES)
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "ResCheckMedia (use ordinals)");
return(-1);
}
#endif /* RES_DEBUG_PARAMS */
drive = _getdrive();
if (_chdrive(device + 1))
return(-1);
_chdrive(drive);
dev = &RES_DEVICES[ device ];
root[0] = (char)(device + 'A');
if (GetVolumeInformation(root, name, 22, &serial, &long1, &long2, dummy, 5))
{
if (strcmp(name, dev -> name) or (serial not_eq dev -> serial))
{
strcpy(dev -> name, name);
dev -> serial = serial;
IF_DEBUG(LOG("Media has changed on volume %s\n", root));
SHOULD_I_CALL_WITH(CALLBACK_SWAP_CD, GLOBAL_CURRENT_CD, retval);
return(0);
}
return(1);
}
IF_DEBUG(LOG("Could not read media on volume %s\n", root));
return(-1);
}
/* =======================================================
FUNCTION: ResAttach
PURPOSE: Open an archive file (zip).
PARAMETERS: Directory to graft archive into, name of
an archive file, replace flag. If
attact_point is NULL, the archive is
grafted on to the current working
directory. If replace_flag is TRUE, any
files contained within the archive that
collide with files on the attach_point
are replaced (the matching files in the
archive file replace those at the
destination attach point) otherwise
the reverse is true (the files within
the archive take precedence).
RETURNS: Handle if sucessful, otherwise -1.
======================================================= */
RES_EXPORT int ResAttach(const char * attach_point_arg, const char * filename, int replace_flag)
{
ARCHIVE * archive;
HASH_TABLE * table = NULL;
char path[_MAX_PATH];
char attach_point_backup[_MAX_PATH];
char * attach_point;
int len, i;
struct _finddata_t info;
#if( not RES_USE_FLAT_MODEL )
HASH_ENTRY * entry;
#endif
// _getcwd(old_cwd,MAX_PATH);
if (attach_point_arg)
{
strcpy(attach_point_backup, attach_point_arg);
attach_point = attach_point_backup;
}
else
{
attach_point = NULL;
}
IF_LOG(LOG("attach: %s %s\n", attach_point, filename));
#if( RES_DEBUG_PARAMS )
if ( not filename or (strlen(filename) > _MAX_FNAME))
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "ResAttach");
return(-1);
}
#endif
if ( not GLOBAL_HASH_TABLE)
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "ResAttach");
return(-1);
}
if ( not attach_point)
attach_point = GLOBAL_CURRENT_PATH;
#if( RES_COERCE_FILENAMES )
len = strlen(attach_point);
if (attach_point[len - 1] not_eq ASCII_BACKSLASH)
{
attach_point[len++] = ASCII_BACKSLASH;
attach_point[len] = 0x00;
}
res_fullpath(path, attach_point, _MAX_PATH);
attach_point = path;
#endif /* RES_COERCE_FILENAMES */
info.size = 0;
#if( not RES_USE_FLAT_MODEL )
entry = hash_find(attach_point, GLOBAL_HASH_TABLE);
/* I used to force you to use a directory already in
the resource manager for the attach point. Roger
Fujii asked for anything to be used (allowing you
to create artificial directories). If you want
the original functionality, define RES_ALLOW_ALIAS
to false. */
#if( not RES_ALLOW_ALIAS )
if ( not entry)
{
SAY_ERROR(RES_ERR_PATH_NOT_FOUND, attach_point);
return(-1);
}
#else
/* The attach point does not have to be either a directory -or-
an 'added' directory (a directory that has been incorporated
into the Resource Manager via ResAddPath or ResCreatePath */
if ( not entry)
{
#if( RES_DEBUG_VERSION )
if (GLOBAL_SEARCH_INDEX >= (MAX_DIRECTORIES - 1))
{
assert( not "Exceeded MAX_DIRECTORIES as defined in omni.h");
// SAY_ERROR( RES_ERR_TOO_MANY_DIRECTORIES, "ResAddPath" );
return(FALSE);
}
#endif
table = hash_create(ARCHIVE_TABLE_SIZE, attach_point);
strcpy(info.name, attach_point); /* insert a dummy entry into the global hash table */
info.attrib = _A_SUBDIR bitor (unsigned int)FORCE_BIT;
info.time_create = 0;
info.time_access = 0;
info.size = 0;
entry = hash_add(&info, GLOBAL_HASH_TABLE);
if ( not entry)
{
SAY_ERROR(RES_ERR_UNKNOWN, "ResAttach");
return(-1);
}
entry -> archive = -1; /* the actual directory existence should not be considered
as part of the archive. All of the contents found within
the directory are. This allows a hard disk based file to
override a zip archive */
entry -> volume = (char)(toupper(attach_point[0]) - 'A');
entry -> directory = GLOBAL_SEARCH_INDEX;
GLOBAL_SEARCH_PATH[ GLOBAL_SEARCH_INDEX++ ] = MemStrDup(attach_point);
GLOBAL_PATH_LIST = LIST_APPEND(GLOBAL_PATH_LIST, table);
strcpy(GLOBAL_CURRENT_PATH, attach_point);
entry -> dir = table;
}
#endif /* RES_ALLOW_ALIAS */
archive = archive_create(attach_point, filename, (HASH_TABLE *)entry -> dir, replace_flag);
#else /* RES_FLAT_MODEL */
archive = archive_create(attach_point, filename, GLOBAL_HASH_TABLE, replace_flag);
#endif /* RES_FLAT_MODEL */
if ( not archive)
{
SAY_ERROR(RES_ERR_CANT_OPEN_ARCHIVE, filename);
return(-1);
}
for (i = 0; i < (GLOBAL_SEARCH_INDEX - 1); i++)
{
if ( not stricmp(GLOBAL_SEARCH_PATH[i], attach_point))
{
// archive -> directory = (char)i; /* GFG */
archive -> directory = (char)(i); /* GFG */
break;
}
}
if (i == GLOBAL_SEARCH_INDEX)
DebugBreak();
ARCHIVE_LIST = LIST_APPEND(ARCHIVE_LIST, archive);
return(archive -> os_handle);
}
/* =======================================================
FUNCTION: ResDevice
PURPOSE: Returns information about a given drive.
PARAMETERS: Id of device to query.
RETURNS: TRUE (pass) / FALSE (fail).
======================================================= */
RES_EXPORT int ResDevice(int device_id, DEVICE_ENTRY * dev)
{
#if( RES_DEBUG_PARAMS )
if (device_id < 0 or device_id > MAX_DEVICES or not dev)
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "ResDevice");
return(FALSE);
}
#endif /* RES_DEBUG_PARAMS */
memcpy(dev, (void *)&RES_DEVICES[device_id], sizeof(DEVICE_ENTRY));
return(TRUE);
}
/* =======================================================
FUNCTION: ResDetach
PURPOSE: Closes an open archive file (zip).
PARAMETERS: Handle of an opened archive file.
RETURNS: None.
======================================================= */
RES_EXPORT void ResDetach(int handle)
{
ARCHIVE * archive = NULL;
LIST * list = NULL;
#if( RES_DEBUG_PARAMS )
if ( not ARCHIVE_LIST)
{
//SAY_ERROR( RES_ERR_UNKNOWN_ARCHIVE, "ResDetach" );
return;
}
#endif /* RES_DEBUG_PARAMS */
/* using the handle, search the list for the structure */
for (list = ARCHIVE_LIST; list; list = list -> next)
{
archive = (ARCHIVE *)list -> node;
if (archive -> os_handle == handle)
break;
}
if ( not list) /* couldn't find it, may already have been closed - or handle is incorrect */
{
SAY_ERROR(RES_ERR_UNKNOWN_ARCHIVE, "ResDetach");
return;
}
IF_LOG(LOG("detach: %s\n", archive -> name));
REQUEST_LOCK(archive -> lock);
ResPurge((char *)&archive -> os_handle, NULL, NULL, NULL);
/* remove the archive from out list */
ARCHIVE_LIST = LIST_REMOVE(ARCHIVE_LIST, archive);
/* The inflation code builds a table of constant values for decompressing
files compressed with pkzip's FIXED compression mode. The tables are
dynamically created (if they don't already exist) when you decompress
data via that method. Therefore, we don't want to free it up until
all the zips are detached - then we might as well to reclaim memory */
if ( not ARCHIVE_LIST)
inflate_free();
/* close the actual archive file */
_close(archive -> os_handle);
RELEASE_LOCK(archive -> lock);
DESTROY_LOCK(archive -> lock);
#ifdef USE_SH_POOLS
MemFreePtr(archive);
#else
MemFree(archive);
#endif
}
/* =======================================================
FUNCTION: ResOpenFile
PURPOSE: Open a file via the Resource Manager.
PARAMETERS: Filename, mode to open with.
Wildcards are not supported.
RETURNS: File int if sucessful, otherwise -1.
======================================================= */
RES_EXPORT int ResOpenFile(const char * name, int mode)
{
HASH_TABLE * table = NULL;
HASH_ENTRY * entry = NULL;
FILE_ENTRY * file = NULL;
LIST * list = NULL;
ARCHIVE * archive = NULL;
char dirpath[_MAX_PATH];
char filename[_MAX_PATH];
int retval = 1;
int handle;
int dir_index;
struct _finddata_t data; /* used to dummy-up a hash entry */
char tmp[LREC_SIZE];
local_file_hdr lrec;
IF_LOG(LOG("open (%s):\n", name));
#if( RES_DEBUG_PARAMS )
if ( not name)
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "ResOpenFile");
return(-1);
}
#endif
#if (RES_MULTITHREAD)
REQUEST_LOCK(GLOCK);
#endif
/* get the next available file handle */
handle = get_handle();
if (handle == -1) /* none left */
{
SAY_ERROR(RES_ERR_TOO_MANY_FILES, "ResOpenFile");
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK); /* GFG */
#endif
return(-1);
}
file = &FILE_HANDLES[ handle ];
/* ----------------------------------------------------
Find the hash entry for the given filename. If we
are building a hierarchical model, we need to search
all of the tables in the order of our search path
(hash_find_table), otherwise, we just need to search
our main hash table (hash_find).
If filename coercion is being used, the filename
string is scanned for the occurence of a backslash.
If there is one, the code forces a fullpath name
conversion on this string in-case it is a relative
pathname (eg; ..\windows\foo.c).
---------------------------------------------------- */
#if( not RES_USE_FLAT_MODEL )
entry = hash_find_table(name, &table);
#else /* flat model */
entry = hash_find(name, GLOBAL_HASH_TABLE);
#endif
if ( not entry) /* NOT FOUND */
{
/* if the user is trying to create a file on the harddrive,
this is ok. */
if ( not (mode bitand _O_CREAT))
{
SAY_ERROR(RES_ERR_FILE_NOT_FOUND, name);
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK); /* GFG */
#endif
return(-1);
}
else
{
/* CREATING A FILE */
/* In this case, we need to make sure that the directory is already 'added'
to the resource manager if we are using hierarchical model. If we are
using the flat model, we just need to create a dummy hash_entry for the
file. The file size member of the hash entry structure will be set
in ResFileClose. */
IF_LOG(LOG("creating file: %s\n", name));
#if( not RES_USE_FLAT_MODEL )
if (strchr(name, ASCII_BACKSLASH))
{
split_path(name, filename, dirpath);
entry = hash_find(dirpath, GLOBAL_HASH_TABLE);
}
else /* current directory */
{
strcpy(filename, name);
strcpy(dirpath, GLOBAL_CURRENT_PATH);
entry = hash_find(GLOBAL_CURRENT_PATH, GLOBAL_HASH_TABLE);
}
if ( not entry or not entry -> dir) /* directory is not already added */
{
SAY_ERROR(RES_ERR_UNKNOWN_WRITE_TO, name);
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK); /* GFG */
#endif
return(-1);
}
else
{
table = (HASH_TABLE *)entry -> dir;
}
#else /* flat model */
if (strchr(name, ASCII_BACKSLASH))
split_path(name, filename, dirpath);
else /* current directory */
strcpy(filename, name);
table = GLOBAL_HASH_TABLE;
#endif /* not RES_USE_FLAT_MODEL */
strcpy(data.name, filename);
data.attrib = (unsigned int)FORCE_BIT;
data.time_create = 0;
data.time_access = 0;
data.size = 0;
entry = hash_add(&data, table);
if ( not entry)
{
SAY_ERROR(RES_ERR_UNKNOWN, "ResOpen - create");
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK); /* GFG */
#endif
return(-1);
}
for (dir_index = 0; dir_index <= GLOBAL_SEARCH_INDEX; dir_index++)
{
if ( not stricmp(dirpath, GLOBAL_SEARCH_PATH[ dir_index ]))
{
entry -> directory = dir_index;
entry -> volume = (char)(toupper(dirpath[0]) - 'A');
break;
}
}
if (dir_index > GLOBAL_SEARCH_INDEX)
{
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK); /* GFG */
#endif
return(-1);
}
entry -> archive = -1;
}
}
/* Make sure the user isn't trying to write to an archive file.
Someday this may be possible, but not for a while. */
if (entry -> archive not_eq -1)
{
int check;
check = (_O_CREAT bitor _O_APPEND bitor _O_RDWR bitor _O_WRONLY);
check and_eq mode;
if (check) /* don't known why had to do it broken out like this - ask MSVC */
{
SAY_ERROR(RES_ERR_CANT_WRITE_ARCHIVE, name);
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK); /* GFG */
#endif
return(-1);
}
}
/* Initialize some common data */
file -> current_pos = 0;
file -> current_filbuf_pos = 0;
/* Is this a loose file (not in an archive?) */
if (entry -> archive == -1)
{
/* may seem redundant but there are too many pathological cases otherwise */
if (mode bitand _O_CREAT)
res_fullpath(filename, name, _MAX_PATH); /* regardless of coercion state */
else
sprintf(filename, "%s%s", GLOBAL_SEARCH_PATH[ entry -> directory ], entry -> name);
/* there is actually a third parameter to open() (MSVC just doesn't admit it)
octal 666 ensures that stack-crap won't accidently create this file as
read-only. Thank to Roger Fujii for this fix */
file -> os_handle = _open(filename, mode, 0x1b6 /* choked on O666 and O666L */);
if (file -> os_handle == -1)
{
if (errno == EACCES)
{
SAY_ERROR(RES_ERR_FILE_SHARING, filename);
}
else
{
SAY_ERROR(RES_ERR_FILE_NOT_FOUND, filename);
}
ResCheckMedia(entry -> volume);
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK); /* GFG */
#endif
return(-1);
}
file -> seek_start = 0;
file -> size = entry -> size;
file -> csize = 0;
file -> attrib = entry -> attrib;
file -> mode = mode;
file -> location = -1;
file -> zip = NULL;
file -> filename = MemStrDup(filename);
file -> device = entry -> volume;
SHOULD_I_CALL_WITH(CALLBACK_OPEN_FILE, handle, retval);
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK); /* GFG */
#endif
return(handle);
}
else /* in an archive */
{
/* using the handle, search the list for the structure */
for (list = ARCHIVE_LIST; list; list = list -> next)
{
archive = (ARCHIVE *)list -> node;
if (archive -> os_handle == entry -> archive)
break;
}
if ( not list)
{
SAY_ERROR(RES_ERR_UNKNOWN, " "); /* archive handle in hash entry is incorrect (or archive detached) */
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK); /* GFG */
#endif
return(-1);
}
sprintf(filename, "%s%s", GLOBAL_SEARCH_PATH[ entry -> directory ], entry -> name);
lseek(archive -> os_handle, entry -> file_position + SIGNATURE_SIZE, SEEK_SET);
_read(archive -> os_handle, tmp, LREC_SIZE);
process_local_file_hdr(&lrec, tmp); /* return PK-type error code */
file -> seek_start = lseek(archive -> os_handle, lrec.filename_length + lrec.extra_field_length, SEEK_CUR);
switch (entry -> method)
{
case STORED:
{
file -> os_handle = archive -> os_handle;
//file -> seek_start = entry -> file_position;
file -> csize = 0;
file -> size = entry -> size;
file -> filename = MemStrDup(filename);
file -> mode = mode;
file -> device = entry -> volume;
file -> zip = NULL; /* only used if we need to deflate */
SHOULD_I_CALL_WITH(CALLBACK_OPEN_FILE, handle, retval);
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK); /* GFG */
#endif
return(handle);
break;
}
case DEFLATED:
{
COMPRESSED_FILE * zip;
#ifdef USE_SH_POOLS
zip = (COMPRESSED_FILE *)MemAllocPtr(gResmgrMemPool, sizeof(COMPRESSED_FILE) + (entry -> size), 0);
#else
zip = (COMPRESSED_FILE *)MemMalloc(sizeof(COMPRESSED_FILE) + (entry -> size), "Inflate");
#endif
if ( not zip)
{
SAY_ERROR(RES_ERR_NO_MEMORY, "Inflate");
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK); /* GFG */
#endif
return(-1);
}
file -> os_handle = archive -> os_handle;
//file -> seek_start = entry -> file_position;
file -> csize = entry -> csize;
file -> size = entry -> size;
file -> filename = MemStrDup(filename);
file -> mode = mode;
file -> device = entry -> volume;
#ifdef USE_SH_POOLS
zip -> slide = (uch *)MemAllocPtr(gResmgrMemPool, UNZIP_SLIDE_SIZE + INPUTBUFSIZE, 0); /* glob temporary allocations */
#else
zip -> slide = (uch *)MemMalloc(UNZIP_SLIDE_SIZE + INPUTBUFSIZE, "deflate"); /* glob temporary allocations */
#endif
zip -> in_buffer = (uch *)zip -> slide + UNZIP_SLIDE_SIZE;
zip -> in_ptr = (uch *)zip -> in_buffer;
zip -> in_count = 0;
zip -> in_size = file -> csize > INPUTBUFSIZE ? INPUTBUFSIZE : file -> csize;
zip -> csize = file -> csize;
zip -> out_buffer = (char *)zip + sizeof(COMPRESSED_FILE);
zip -> out_count = 0;
zip -> archive = archive;
file -> zip = zip; /* Future use: I may add incremental deflation */
inflate(zip);
#ifdef USE_SH_POOLS
MemFreePtr(zip -> slide); /* Free temporary allocations */
#else
MemFree(zip -> slide); /* Free temporary allocations */
#endif
SHOULD_I_CALL_WITH(CALLBACK_OPEN_FILE, handle, retval);
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK); /* GFG */
#endif
return(handle);
break;
}
default:
SAY_ERROR(RES_ERR_UNSUPPORTED_COMPRESSION, entry -> name);
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK); /* GFG */
#endif
return(-1);
break;
}
}
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK); /* GFG */
#endif
return(-1);
}
/* =======================================================
FUNCTION: ResSizeFile
PURPOSE: Determine the size of a file
PARAMETERS: File handle.
RETURNS: Size of the file in bytes.
======================================================= */
RES_EXPORT int ResSizeFile(int file)
{
#if( RES_DEBUG_PARAMS )
if (file < 0 or file >= MAX_FILE_HANDLES)
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "ResSizeFile");
return(-1);
}
if (FILE_HANDLES[ file ].os_handle == -1)
{
SAY_ERROR(RES_ERR_ILLEGAL_FILE_HANDLE, "ResSizeFile");
return(-1);
}
#endif /* RES_DEBUG_PARAMS */
return(FILE_HANDLES[ file ].size);
}
/* =======================================================
FUNCTION: ResReadFile
PURPOSE: Read from a file via the Resource Manager.
PARAMETERS: File int, ptr to a buffer to place
data, number of bytes to read.
RETURNS: Number of bytes actually read, -1 in case
of an error.
======================================================= */
RES_EXPORT int ResReadFile(int handle, void * buffer, size_t count)
{
FILE_ENTRY * file;
int len;
int retval = 1;
#if( RES_DEBUG_PARAMS )
if ( not buffer or handle < 0 or handle > MAX_FILE_HANDLES)
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "ResReadFile");
return(-1);
}
#endif /* RES_DEBUG_PARAMS */
#if (RES_MULTITHREAD)
REQUEST_LOCK(GLOCK); /* GFG */
#endif
file = &FILE_HANDLES[ handle ];
if (file -> os_handle == -1)
{
SAY_ERROR(RES_ERR_ILLEGAL_FILE_HANDLE, "ResReadFile");
return(-1);
}
IF_LOG(LOG("read (%s): (%d bytes)\n", file -> filename, count));
SHOULD_I_CALL_WITH(CALLBACK_READ_FILE, handle, retval);
if (file -> current_pos >= file -> size)
{
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK); /* GFG */
#endif
return(0); /* GFG NOV 18 was return (-1) */
}
if ( not file -> zip)
{
/* The only way to insure that the heads will be in the right place is
to reseek on every read (since multiple threads may be reading this
file). This is actually not as expensive as it seems. First of all,
if the heads are in the same position, or the cache contains the byte
stream from that offset, no seek will be done. If that isn't so, a
seek was going to happen anyway when the OS tries to do the read. */
lseek(file -> os_handle, (file -> seek_start + file -> current_pos), SEEK_SET);
len = _read(file -> os_handle, buffer, count);
if (len < 0) /* error, see if media has changed */
ResCheckMedia(file -> device);
else
file -> current_pos += len;
IF_LOG(LOG("read (%s): %d\n", file -> filename, len));
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK); /* GFG */
#endif
return(len);
}
else
{
if (count > (file -> size - file -> current_pos))
count = file -> size - file -> current_pos;
memcpy(buffer, file -> zip -> out_buffer + file -> current_pos, count);
file -> current_pos += count;
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK); /* GFG */
#endif
return(count);
}
return(0);
}
/* =======================================================
FUNCTION: ResLoadFile
PURPOSE: Load an entire file into memory. This is
really a convenience function that
encorporates these components:
ResOpenFile
malloc
ResReadFile
ResCloseFile
PARAMETERS: Filename, optional ptr to store number
of bytes actually read, optional ptr to
buffer you want file read to.
RETURNS: Ptr to buffer holding file or NULL (on error).
======================================================= */
RES_EXPORT char * ResLoadFile(const char * filename, char * buffer, size_t * size)
{
int file;
int check;
int s;
char * alloc_buffer;
IF_LOG(LOG("load (%s):\n", filename));
#if( RES_DEBUG_PARAMS )
if ( not filename)
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "ResLoadFile");
return(NULL);
}
#endif /* RES_DEBUG_PARAMS */
file = ResOpenFile(filename, _O_RDONLY bitor _O_BINARY);
if (EMPTY(file))
return(NULL); /* message will already have been printed if using the debug version */
s = ResSizeFile(file);
if ( not buffer)
{
#ifdef USE_SH_POOLS
alloc_buffer = (char *)MemAllocPtr(gResmgrMemPool, s, 0);
#else
alloc_buffer = (char *)MemMalloc(s, filename);
#endif
if ( not alloc_buffer)
{
SAY_ERROR(RES_ERR_NO_MEMORY, filename);
ResCloseFile(file);
if (size)
*size = 0;
return(NULL);
}
}
else
alloc_buffer = buffer;
check = ResReadFile(file, alloc_buffer, s);
ResCloseFile(file);
if (check < 0) /* error reading file */
{
#ifdef USE_SH_POOLS
MemFreePtr(alloc_buffer);
#else
MemFree(alloc_buffer);
#endif
alloc_buffer = NULL;
}
if (size)
*size = check;
return(alloc_buffer);
}
/* =======================================================
FUNCTION: ResUnloadFile
PURPOSE: Unloads a file that was allocated via
ResLoadFile. This function is here for
two purposes, 1) provide a balance to
the API for ResLoadFile, and 2) to provide
a placeholder should ResLoadFile be expanded
to allow some sort of caching.
PARAMETERS: Memory pointer that was returned from
ResLoadFile.
RETURNS: None.
======================================================= */
RES_EXPORT void ResUnloadFile(char * buffer)
{
#if( RES_DEBUG_PARAMS )
if ( not buffer)
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "ResUnloadFile");
return;
}
#endif /* RES_DEBUG_PARAMS */
#ifdef USE_SH_POOLS
MemFreePtr(buffer);
#else
MemFree(buffer);
#endif
}
/* =======================================================
FUNCTION: ResCloseFile
PURPOSE: Close a previously opened file.
PARAMETERS: File int.
RETURNS: TRUE (pass) / FALSE (fail)
======================================================= */
RES_EXPORT int ResCloseFile(int file)
{
HASH_ENTRY * entry;
char filename[_MAX_PATH],
dirpath[_MAX_PATH];
long size;
int retval = 1;
#if( RES_DEBUG_PARAMS )
if (file < 0 or file >= MAX_FILE_HANDLES)
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "ResCloseFile");
return(FALSE);
}
if (FILE_HANDLES[ file ].os_handle == -1)
{
SAY_ERROR(RES_ERR_ILLEGAL_FILE_HANDLE, "ResCloseFile");
return(FALSE);
}
#endif /* RES_DEBUG_PARAMS */
#if (RES_MULTITHREAD)
REQUEST_LOCK(GLOCK);
#endif
IF_LOG(LOG("close (%s):\n", FILE_HANDLES[ file ].filename));
SHOULD_I_CALL_WITH(CALLBACK_CLOSE_FILE, file, retval);
if ( not FILE_HANDLES[file].zip)
{
/* if the file has been written to, recheck the size */
if (FILE_HANDLES[file].csize == (unsigned int)WRITTEN_TO_FLAG)
{
/* flush to disk */
_commit(FILE_HANDLES[file].os_handle);
/* go to the end of the file */
size = lseek(FILE_HANDLES[file].os_handle, 0, SEEK_END);
split_path(FILE_HANDLES[file].filename, filename, dirpath);
#if( not RES_USE_FLAT_MODEL )
entry = hash_find(dirpath, GLOBAL_HASH_TABLE);
if (entry)
{
entry = hash_find(filename, (HASH_TABLE *)entry -> dir);
if (entry)
entry -> size = size;
else
{
SAY_ERROR(RES_ERR_UNKNOWN, "set size");
}
}
else
{
SAY_ERROR(RES_ERR_UNKNOWN, "set size");
}
#else /* flat model */
entry = hash_find(filename, GLOBAL_HASH_TABLE);
if (entry)
entry -> size = size;
else
{
SAY_ERROR(RES_ERR_UNKNOWN, "set size");
}
#endif /* not RES_USE_FLAT_MODEL */
}
if ( not FILE_HANDLES[ file ].seek_start) /* don't close an archive */
_close(FILE_HANDLES[ file ].os_handle);
#ifdef USE_SH_POOLS
MemFreePtr(FILE_HANDLES[ file ].filename);
#else
MemFree(FILE_HANDLES[ file ].filename);
#endif
FILE_HANDLES[ file ].filename = NULL;
FILE_HANDLES[ file ].os_handle = -1;
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(TRUE);
}
else
{
#ifdef USE_SH_POOLS
MemFreePtr(FILE_HANDLES[file].zip);
MemFreePtr(FILE_HANDLES[file].filename);
#else
MemFree(FILE_HANDLES[file].zip);
MemFree(FILE_HANDLES[file].filename);
#endif
FILE_HANDLES[ file ].zip = NULL;
FILE_HANDLES[ file ].filename = NULL;
FILE_HANDLES[ file ].os_handle = -1;
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(TRUE);
}
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(FALSE);
}
/* =======================================================
FUNCTION: ResWriteFile
PURPOSE: Write to a file via the Resource Manager.
PARAMETERS: File int, ptr to a buffer to get
data from, number of bytes to write.
RETURNS: Number of bytes actually written.
======================================================= */
RES_EXPORT size_t ResWriteFile(int handle, const void * buffer, size_t count)
{
FILE_ENTRY * file;
int check;
int retval = 1;
#if( RES_DEBUG_PARAMS )
if (handle < 0 or handle >= MAX_FILE_HANDLES or not buffer)
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "ResWriteFile");
return(0);
}
#endif /* RES_DEBUG_PARAMS */
#if (RES_MULTITHREAD)
REQUEST_LOCK(GLOCK);
#endif
file = &FILE_HANDLES[ handle ];
if (file -> os_handle == -1)
{
SAY_ERROR(RES_ERR_ILLEGAL_FILE_HANDLE, "ResWriteFile");
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(0);
}
if ( not (file -> mode bitand (_O_CREAT bitor _O_APPEND bitor _O_RDWR bitor _O_WRONLY)))
{
SAY_ERROR(RES_ERR_PROBLEM_WRITING, file -> filename);
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(0);
}
SHOULD_I_CALL_WITH(CALLBACK_WRITE_FILE, handle, retval);
/* Set a bit so we know to reestablish the file size on ResCloseFile() */
/* Use the csize field since we no this is not used for files we can write to */
file -> csize = (unsigned int)WRITTEN_TO_FLAG;
IF_LOG(LOG("write (%s): (%d bytes)\n", file -> filename, count));
check = _write(file -> os_handle, buffer, count);
if (check < 0)
ResCheckMedia(file -> device);
else
file -> current_pos += count;
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(check);
}
/* =======================================================
FUNCTION: ResDeleteFile
PURPOSE: Remove a file from the r/w medium.
PARAMETERS: Filename.
RETURNS: TRUE (pass) / FALSE (fail)
======================================================= */
RES_EXPORT int ResDeleteFile(const char * name)
{
HASH_ENTRY * entry;
HASH_TABLE * table;
int check;
#if( RES_DEBUG_PARAMS )
if ( not name)
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "ResDeleteFile");
return(FALSE);
}
#endif
#if (RES_MULTITHREAD)
REQUEST_LOCK(GLOCK);
#endif
IF_LOG(LOG("delete: %s\n", name));
#if( not RES_USE_FLAT_MODEL )
/* find both the entry bitand the table it resides in */
entry = hash_find_table(name, &table);
#else
entry = hash_find(name, GLOBAL_HASH_TABLE);
table = GLOBAL_HASH_TABLE;
#endif
if ( not entry)
{
SAY_ERROR(RES_ERR_FILE_NOT_FOUND, name);
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(FALSE);
}
if (entry -> file_position == -1)
{
chmod(entry -> name, _S_IWRITE);
check = remove(entry -> name);
if (check == -1)
{
SAY_ERROR(RES_ERR_CANT_DELETE_FILE, name);
}
/* don't return yet, remove file from hash
table even if delete at os level fails */
}
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(hash_delete(entry, table));
}
/* =======================================================
FUNCTION: ResModifyFile
PURPOSE: Modify the attributes of a file stored on
r/w medium.
PARAMETERS: Filename.
RETURNS: TRUE (pass) / FALSE (fail)
======================================================= */
RES_EXPORT int ResModifyFile(const char * name, int flags)
{
HASH_ENTRY * entry; /* ptr to entry in hash table */
int check; /* test return val from system calls */
#if( RES_DEBUG_PARAMS )
if ( not name)
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "ResModifyFile");
return(FALSE);
}
#endif
#if (RES_MULTITHREAD)
REQUEST_LOCK(GLOCK);
#endif
IF_LOG(LOG("modify: %s %d\n", name, flags));
#if( not RES_USE_FLAT_MODEL )
entry = hash_find_table(name, NULL);
#else
entry = hash_find(name, GLOBAL_HASH_TABLE);
#endif
if ( not entry)
{
SAY_ERROR(RES_ERR_FILE_NOT_FOUND, name);
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(FALSE);
}
if (entry -> file_position == -1) /* is the file on the harddrive */
{
check = chmod(entry -> name, flags);
if (check == -1)
{
SAY_ERROR(RES_ERR_CANT_ATTRIB_FILE, name);
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(FALSE);
}
entry -> attrib = flags bitor FORCE_BIT;
}
else
{
SAY_ERROR(RES_ERR_CANT_ATTRIB_FILE, name);
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(FALSE);
}
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(TRUE);
}
/* =======================================================
FUNCTION: ResMakeDirectory
PURPOSE: Create a directory.
PARAMETERS: Filename.
RETURNS: TRUE (pass) / FALSE (fail)
======================================================= */
RES_EXPORT int ResMakeDirectory(char * pathname)
{
int check;
#if( RES_DEBUG_PARAMS )
if ( not pathname)
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "ResMakeDirectory");
return(FALSE);
}
#endif
check = _mkdir(pathname);
IF_LOG(LOG("mkdir: %s\n", pathname));
if (check == -1)
{
#if( RES_DEBUG_PARAMS )
if (errno == EACCES)
{
SAY_ERROR(RES_ERR_DIRECTORY_EXISTS, pathname);
}
else if (errno == ENOENT)
{
SAY_ERROR(RES_ERR_PATH_NOT_FOUND, pathname);
}
#endif /* RES_DEBUG_PARAMS */
return(FALSE);
}
ResAddPath(pathname, FALSE);
return(TRUE);
}
/* =======================================================
FUNCTION: ResDeleteDirectory
PURPOSE: Remove a directory tree.
PARAMETERS: Filename.
RETURNS: TRUE (pass) / FALSE (fail)
=======================================================
03/17/97 [GAB] - wrote.
======================================================= */
RES_EXPORT int ResDeleteDirectory(char * pathname, int forced)
{
int handle,
check,
status;
char full_path[ MAX_PATH ],
old_cwd[ MAX_PATH ];
struct _finddata_t fileinfo;
status = 0;
handle = _findfirst(pathname, &fileinfo);
if (handle == -1)
return(FALSE); /* couldn't find directory */
IF_LOG(LOG("deltree: %s\n", pathname));
if ( not (fileinfo.attrib bitand _A_SUBDIR))
{
SAY_ERROR(RES_ERR_IS_NOT_DIRECTORY, pathname);
return(FALSE);
}
_findclose(handle);
_getcwd(old_cwd, MAX_PATH);
_chdir(pathname);
sprintf(full_path, "%s\\*.*", pathname);
handle = _findfirst(full_path, &fileinfo);
while (status not_eq -1)
{
if ( not stricmp(fileinfo.name, ".") or not stricmp(fileinfo.name, ".."))
{
status = _findnext(handle, &fileinfo);
continue;
}
if (fileinfo.attrib bitand _A_SUBDIR)
{
char recurse_path[MAX_PATH];
sprintf(recurse_path, "%s\\%s", pathname, fileinfo.name);
ResDeleteDirectory(recurse_path, TRUE);
status = _findnext(handle, &fileinfo);
continue;
}
check = remove(fileinfo.name);
if (check == -1)
{
if (forced)
{
chmod(fileinfo.name, _S_IWRITE);
check = remove(fileinfo.name);
}
if (check == -1)
{
SAY_ERROR(RES_ERR_COULD_NOT_DELETE, fileinfo.name);
break;
}
}
status = _findnext(handle, &fileinfo);
}
_findclose(handle);
_chdir(old_cwd);
_rmdir(pathname);
if (handle == -1)
{
SAY_ERROR(RES_ERR_COULD_NOT_DELETE, pathname);
return(FALSE);
}
return(TRUE);
}
/* =======================================================
FUNCTION: ResOpenDirectory
PURPOSE: Read the contents of a specified directory
(based on the unix opendir).
The idea is that the order of operations is
1) open dir, 2) read dir, 3) close dir.
_findfirst, _findnext and _findclose sort
of do this but are uglier and more
cumbersome.
The ResOpenDirectory implementation is:
ResOpen creates a table of filenames for
the entire directory. ResRead returns
each filename in succession. ResClose
frees the allocation from ResOpen. If
you use the debug version of the Resource
Manager, ResExit will report any open
directories that have not been freed.
ResOpen will fail if the directory does
not exist or if there is not enough
memory to allocate space for the whole
directory.
This function is only useful with the
hierarchical model.
PARAMETERS: Directory name.
RETURNS: Ptr to a RES_DIR struct or NULL (on error).
======================================================= */
RES_EXPORT RES_DIR * ResOpenDirectory(char * pathname)
{
// int count = 0;
#if( not RES_USE_FLAT_MODEL )
HASH_TABLE * hsh;
HASH_ENTRY * entry;
RES_DIR * dir;
size_t size;
char dirpath[_MAX_PATH];
int index, i;
#if( RES_DEBUG_PARAMS )
if ( not GLOBAL_SEARCH_INDEX)
return(NULL);
#endif
IF_LOG(LOG("opendir: %s\n", pathname));
res_fullpath(dirpath, pathname, _MAX_PATH);
entry = hash_find(dirpath, GLOBAL_HASH_TABLE);
if (entry and entry -> dir)
{
hsh = (HASH_TABLE *)entry -> dir;
size = sizeof(RES_DIR);
size += sizeof(char *) * (hsh -> num_entries);
size += MAX_FILENAME * (hsh -> num_entries + 12);
#ifdef USE_SH_POOLS
dir = (RES_DIR *)MemAllocPtr(gResmgrMemPool, size, 0);
#else
dir = (RES_DIR *)MemMalloc(size, "RES_DIR");
#endif
dir -> filenames = (char**)((char*)dir + sizeof(RES_DIR));
dir -> string_pool = (char*)dir + sizeof(RES_DIR) + (sizeof(char *) * (hsh -> num_entries));
if ( not dir -> filenames or not dir -> string_pool)
{
SAY_ERROR(RES_ERR_NO_MEMORY, "ResOpenDirectory");
return(NULL);
}
dir -> string_ptr = dir -> string_pool;
RES_STRING_SET(dir -> name, entry -> name, dir -> string_ptr);
index = 0;
for (i = 0; i < hsh->table_size; i++)
{
entry = &hsh -> table[i];
if (entry -> next)
{
while (entry)
{
RES_STRING_SET(dir -> filenames[ index++ ], entry -> name, dir -> string_ptr);
entry = entry -> next;
}
}
else
{
if (entry -> attrib)
{
RES_STRING_SET(dir -> filenames[ index++ ], entry -> name, dir -> string_ptr);
}
}
}
dir -> num_entries = index;
dir -> current = 0;
#if( RES_DEBUG_VERSION )
OPEN_DIR_LIST = LIST_APPEND(OPEN_DIR_LIST, dir);
#endif /* RES_DEBUG_VERSION */
return(dir);
}
#endif /* not RES_USE_FLAT_MODEL */
return(NULL); /* only usefull in the hierarchical version */
}
/* =======================================================
FUNCTION: ResReadDirectory
PURPOSE: Returns filenames sequentially.
PARAMETERS: RES_DIR structure.
RETURNS: Ptr to filename string or NULL (on error).
======================================================= */
RES_EXPORT char * ResReadDirectory(RES_DIR * dir)
{
#if( RES_DEBUG_PARAMS )
if ( not dir)
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "ResReadDirectory");
return(NULL);
}
#endif /* RES_DEBUG_PARAMS */
IF_LOG(LOG("readdir: %s\n", dir -> name));
if (dir -> current >= dir -> num_entries)
return(NULL);
return((char *)(dir -> filenames[ dir -> current++ ]));
}
/* =======================================================
FUNCTION: ResCloseDirectory
PURPOSE: Frees the allocations of ResOpenDirectory.
PARAMETERS: RES_DIR structure.
RETURNS: None.
======================================================= */
RES_EXPORT void ResCloseDirectory(RES_DIR * dir)
{
#if( RES_DEBUG_PARAMS )
if ( not dir)
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "ResCloseDirectory");
return;
}
#endif /* RES_DEBUG_PARAMS */
IF_LOG(LOG("closedir: %s\n", dir -> name));
#ifdef USE_SH_POOLS
MemFreePtr(dir);
#else
MemFree(dir);
#endif
#if( RES_DEBUG_VERSION )
OPEN_DIR_LIST = LIST_REMOVE(OPEN_DIR_LIST, dir);
#endif
}
/* =======================================================
FUNCTION: ResExistFile
PURPOSE: Determine if a file exists.
PARAMETERS: Filename.
RETURNS: TRUE (yes) / FALSE (no).
======================================================= */
RES_EXPORT int ResExistFile(char * name)
{
HASH_ENTRY * entry;
#if( RES_DEBUG_PARAMS )
if ( not name)
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "ResExistFile");
return(FALSE);
}
#endif
#if (RES_MULTITHREAD)
REQUEST_LOCK(GLOCK);
#endif
IF_LOG(LOG("exist file: %s\n", name));
#if( not RES_USE_FLAT_MODEL )
entry = hash_find_table(name, NULL);
#else /* flat model */
entry = hash_find(name, GLOBAL_HASH_TABLE);
#endif
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
if (entry)
return(TRUE);
return(FALSE);
}
/* =======================================================
FUNCTION: ResExistDirectory
PURPOSE: Determine if a directory already exists.
PARAMETERS: Directory name.
RETURNS: TRUE (yes) / FALSE (no).
======================================================= */
RES_EXPORT int ResExistDirectory(char * pathname)
{
char path[_MAX_PATH];
int len;
#if( RES_DEBUG_PARAMS )
if ( not pathname)
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "ResExistDirectory");
return(FALSE);
}
#endif
res_fullpath(path, pathname, _MAX_PATH);
#if( RES_COERCE_FILENAMES )
len = strlen(path);
if (path[len - 1] not_eq ASCII_BACKSLASH)
{
path[len++] = ASCII_BACKSLASH;
path[len] = 0x00;
}
#endif /* RES_COERCE_FILENAMES */
IF_LOG(LOG("exist dir: %s\n", pathname));
return((int)hash_find(path, GLOBAL_HASH_TABLE));
}
/* =======================================================
FUNCTION: ResTellFile
PURPOSE: Returns the current offset within a file
at which point i/o is set to occur.
PARAMETERS: File handle.
RETURNS: Size in bytes from the beginning of file.
-1 indicates an error.
======================================================= */
RES_EXPORT long ResTellFile(int handle)
{
#if( RES_DEBUG_PARAMS )
if (handle < 0 or handle >= MAX_FILE_HANDLES)
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "ResTellFile");
return(-1);
}
#endif
#if (RES_MULTITHREAD)
REQUEST_LOCK(GLOCK);
#endif
if (FILE_HANDLES[ handle ].os_handle == -1)
{
SAY_ERROR(RES_ERR_ILLEGAL_FILE_HANDLE, "ResTellFile");
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(-1);
}
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(FILE_HANDLES[ handle ].current_pos);
}
/* =======================================================
FUNCTION: ResSeekFile
PURPOSE: Moves the file pointer within an open
file a number of bytes from an origin
(either the current location, end of file,
or beginning of file).
PARAMETERS: File int, offset in bytes, origin.
Origin can be one of:
SEEK_CUR - current location
SEEK_SET - beginning of file
SEEK_END - end of file
RETURNS: New position in file or -1 for error.
======================================================= */
RES_EXPORT int ResSeekFile(int handle, size_t offset, int origin)
{
#if( RES_DEBUG_PARAMS )
if (handle < 0 or handle >= MAX_FILE_HANDLES)
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "ResSeekFile");
return(-1);
}
if ((origin not_eq SEEK_CUR) and (origin not_eq SEEK_SET) and (origin not_eq SEEK_END))
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "ResSeekFile");
return(-1);
}
#endif /* RES_DEBUG_PARAMS */
#if (RES_MULTITHREAD)
REQUEST_LOCK(GLOCK);
#endif
IF_LOG(LOG("seek: %s\n", FILE_HANDLES[handle].filename));
if (FILE_HANDLES[ handle ].os_handle == -1)
{
SAY_ERROR(RES_ERR_ILLEGAL_FILE_HANDLE, "ResReadFile");
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(-1);
}
/* If we are writing, do seek anyway */
if (FILE_HANDLES[ handle ].mode bitand (O_WRONLY bitor O_RDWR))
{
FILE_HANDLES[ handle ].current_pos = lseek(FILE_HANDLES[ handle ].os_handle, offset, origin);
}
else
{
/* cache the seek until we perform the read */
switch (origin)
{
case SEEK_SET: /* 0 */
FILE_HANDLES[ handle ].current_pos = offset;
break;
case SEEK_CUR: /* 1 */
FILE_HANDLES[ handle ].current_pos += offset;
break;
case SEEK_END: /* 2 */
FILE_HANDLES[ handle ].current_pos = FILE_HANDLES[ handle ].size + offset;
break;
}
}
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(FILE_HANDLES[ handle ].current_pos);
}
/* =======================================================
FUNCTION: ResSetDirectory
PURPOSE: Sets the current working directory
Only useful is using the hierarchical
model.
PARAMETERS: Directory name.
RETURNS: TRUE (pass) / FALSE (fail).
======================================================= */
RES_EXPORT int ResSetDirectory(const char * pathname)
{
HASH_ENTRY * entry;
#if( RES_COERCE_FILENAMES )
char full[_MAX_PATH];
int len;
#endif
#if( RES_DEBUG_PARAMS )
if ( not pathname or not (*pathname))
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "ResSetDirectory");
return(FALSE);
}
if ( not GLOBAL_PATH_LIST)
{
SAY_ERROR(RES_ERR_MUST_CREATE_PATH, "ResSetDirectory");
return(FALSE);
}
#endif
#if( RES_COERCE_FILENAMES )
res_fullpath(full, pathname, (_MAX_PATH - 2));
len = strlen(full);
if (full[len - 1] not_eq ASCII_BACKSLASH)
{
full[len++] = ASCII_BACKSLASH;
full[len++] = '\0';
}
pathname = full;
#endif /* RES_COERCE_FILENAMES */
entry = hash_find(pathname, GLOBAL_HASH_TABLE);
if ( not entry or not entry -> dir)
{
SAY_ERROR(RES_ERR_PATH_NOT_FOUND, pathname);
return(FALSE);
}
sort_path(); /* sort path BEFORE forcing one of the entries
to the top. Since we subjigate all of the
paths that are based on the CD, this allows
the caller to force a CD path to be on top
of the search path. All of the other CD
paths, however, are still at the bottom. */
#if( not RES_USE_FLAT_MODEL )
/* Force to the head of the list */
GLOBAL_PATH_LIST = LIST_REMOVE(GLOBAL_PATH_LIST, entry -> dir);
GLOBAL_PATH_LIST = LIST_APPEND(GLOBAL_PATH_LIST, entry -> dir);
#endif /* RES_USE_FLAT_MODEL */
strcpy(GLOBAL_CURRENT_PATH, pathname);
/* If we allow alias attach points ('fake' directories to
attach archive's onto) we should disable the error
reporting. */
#if 0 // GFG May 05/98
#if( not RES_ALLOW_ALIAS )
if (_chdir(pathname))
{
SAY_ERROR(errno, "ResSetDirectory");
}
#else
_chdir(pathname);
#endif
#endif
GLOBAL_CURRENT_DRIVE = pathname[0];
IF_LOG(LOG("set dir: %s\n", pathname));
return(TRUE);
}
/* =======================================================
FUNCTION: ResGetDirectory
PURPOSE: Returns the current working directory
PARAMETERS: Buffer to copy the current working
directory name in to.
RETURNS: Number of characters written.
======================================================= */
RES_EXPORT int ResGetDirectory(char * buffer)
{
char * check;
#if( RES_DEBUG_PARAMS )
if ( not buffer)
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "ResGetDirectory");
return(0);
}
if ( not GLOBAL_PATH_LIST)
{
SAY_ERROR(RES_ERR_MUST_CREATE_PATH, "ResSetDirectory");
return(0);
}
#endif
#if( not RES_USE_FLAT_MODEL )
check = strcpy(buffer, ((HASH_TABLE *)(GLOBAL_PATH_LIST -> node)) -> name);
#else
check = strcpy(buffer, GLOBAL_CURRENT_PATH);
#endif /* not RES_USE_FLAT_MODEL */
IF_LOG(LOG("get dir: %s\n", buffer));
if (check)
return(strlen(buffer));
return(0); /* nothing was copied into buffer */
}
/* =======================================================
FUNCTION: ResGetPath
PURPOSE: Returns the nth entry in the search path.
PARAMETERS: Index, buffer to copy directory name in to.
RETURNS: Number of characters written to buffer.
======================================================= */
RES_EXPORT int ResGetPath(int idx, char * buffer)
{
LIST * list;
char * check = NULL;
#if( RES_DEBUG_PARAMS )
if ( not buffer or idx < 0)
{
return(0);
}
#endif /* RES_DEBUG_PARAMS */
list = LIST_NTH(GLOBAL_PATH_LIST, idx);
if (list)
check = strcpy(buffer, ((HASH_TABLE *)(list -> node)) -> name);
else
*buffer = 0x00;
return(check ? strlen(buffer) : 0);
}
/* =======================================================
FUNCTION: ResGetArchive
PURPOSE: Returns the archive name for the given
handle.
PARAMETERS: Archive handle, buffer to copy directory
name in to.
RETURNS: Number of characters written to buffer.
======================================================= */
RES_EXPORT int ResGetArchive(int handle, char * buffer)
{
ARCHIVE * archive = NULL;
LIST * list = NULL;
#if( RES_DEBUG_PARAMS )
if ( not ARCHIVE_LIST)
{
*buffer = 0x00;
return(0);
}
#endif /* RES_DEBUG_PARAMS */
/* using the handle, search the list for the structure */
for (list = ARCHIVE_LIST; list; list = list -> next)
{
archive = (ARCHIVE *)list -> node;
if (archive -> os_handle == handle)
break;
}
if ( not list) /* couldn't find it, may already have been closed - or handle is incorrect */
{
*buffer = 0x00;
return(0);
}
strcpy(buffer, archive -> name);
return(strlen(buffer));
}
/* =======================================================
FUNCTION: ResWhereIs
PURPOSE: Find the location of a specified file.
PARAMETERS: Filename, optional ptr to buffer for
storage of directory path.
RETURNS: Bit pattern made up of:
RES_HD 0x00010000
RES_CD 0x00020000
RES_NET 0x00040000
RES_ARCHIVE 0x00080000
RES_FLOPPY 0x00100000
-and-
CD number stored in low word
First cd is 1. 0 indicates
cd is unknown or not
applicable.
or -1 indicating an error.
======================================================= */
RES_EXPORT int ResWhereIs(char * filename, char * path)
{
HASH_ENTRY * entry;
int retval = 0,
type;
#if( RES_DEBUG_PARAMS )
if ( not filename)
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "ResGetDirectory");
return(-1);
}
#endif
#if (RES_MULTITHREAD)
REQUEST_LOCK(GLOCK);
#endif
#if( not RES_USE_FLAT_MODEL )
entry = hash_find_table(filename, NULL);
#else /* flat model */
// entry = hash_find( file, GLOBAL_HASH_TABLE ); /* GFG 31/01/98 */
entry = hash_find(filename, GLOBAL_HASH_TABLE);
#endif /* not RES_USE_FLAT_MODEL */
if ( not entry)
{
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(-1);
}
if (entry -> archive not_eq -1)
retval or_eq RES_ARCHIVE;
type = RES_DEVICES[ entry -> volume ].type;
if (type == DRIVE_CDROM)
{
retval or_eq RES_CD;
retval or_eq RES_DEVICES[ entry -> volume ].id;
}
if (type == DRIVE_REMOTE)
retval or_eq RES_NET;
if (type == DRIVE_FIXED)
retval or_eq RES_HD;
if (type == DRIVE_REMOVABLE)
retval or_eq RES_FLOPPY;
if (path)
strcpy(path, GLOBAL_SEARCH_PATH[ entry -> directory ]);
IF_LOG(LOG("where is: %s\n", filename));
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(retval);
}
/* =======================================================
FUNCTION: ResWhichCD
PURPOSE: Find out which cd is currently mounted.
PARAMETERS: None.
RETURNS: CD Number.
1 is the first cd
CD_MAX is the last cd
-1 is no cd is currently mounted
======================================================= */
RES_EXPORT int ResWhichCD(void)
{
IF_LOG(LOG("which cd: %d\n", GLOBAL_CURRENT_CD));
return(GLOBAL_CURRENT_CD);
}
/* =======================================================
FUNCTION: ResWriteTOC
PURPOSE: Writes the Unified Table of Contents
file. This file is the global table of
contents of all files contained on cd-roms
for a given project.
PARAMETERS: Filename to write file to.
RETURNS: TRUE (pass) / FALSE (fail).
======================================================= */
RES_EXPORT int ResWriteTOC(char * filename)
{
filename;
IF_LOG(LOG("write t.o.c.: %s\n", filename));
return(FALSE);
}
/* =======================================================
FUNCTION: ResStatusFile
PURPOSE: Query statistics about an opened file.
PARAMETERS: File handle, buffer to copy statistics.
RETURNS: TRUE (pass) / FALSE (fail).
======================================================= */
RES_EXPORT int ResStatusFile(const char * filename, RES_STAT * stat_buffer)
{
HASH_ENTRY * entry;
LIST * list;
int hit;
char * src;
#if( RES_DEBUG_PARAMS )
if ( not filename or not stat_buffer)
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "ResStatusFile");
return(FALSE);
}
#endif /* RES_DEBUG_PARAMS */
if ( not GLOBAL_SEARCH_INDEX)
{
SAY_ERROR(RES_ERR_MUST_CREATE_PATH, "ResStatusFile");
return(FALSE);
}
#if (RES_MULTITHREAD)
REQUEST_LOCK(GLOCK);
#endif
entry = hash_find_table(filename, NULL);
if ( not entry)
{
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(FALSE);
}
stat_buffer -> size = entry -> size;
stat_buffer -> csize = entry -> csize;
stat_buffer -> volume = entry -> volume;
stat_buffer -> attributes = entry -> attrib;
stat_buffer -> archive = entry -> archive;
stat_buffer -> directory = -1;
src = GLOBAL_SEARCH_PATH[ entry -> directory ];
hit = 0;
for (list = GLOBAL_PATH_LIST; list; list = list -> next)
{
if ( not (strcmp(src, ((HASH_TABLE *)(list -> node)) -> name)))
{
stat_buffer -> directory = hit;
break;
}
hit++;
}
IF_LOG(LOG("stat: %s\n", filename));
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(TRUE);
}
/* =======================================================
FUNCTION: ResSetCallback
PURPOSE: Set one of the user-defined callback ptrs.
PARAMETERS: Which callback, pointer to a function
that returns a integer value (PFI).
RETURNS: Any previously set callback, or NULL
(on error).
======================================================= */
RES_EXPORT PFI ResSetCallback(int which, PFI func)
{
PFI old_ptr;
#if( RES_DEBUG_PARAMS )
if ((which < 0) or (which >= NUMBER_OF_CALLBACKS))
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "ResSetCallback");
return(NULL);
}
#endif /* RES_DEBUG_PARAMS */
old_ptr = RES_CALLBACK[ which ];
RES_CALLBACK[ which ] = func;
IF_LOG(LOG("set callback: %d\n", which));
return(old_ptr);
}
/* =======================================================
FUNCTION: ResGetCallback
PURPOSE: Query for a specified user defined
callback.
PARAMETERS: Which callback.
RETURNS: Any previously set callback ptr, or
NULL (on error).
======================================================= */
RES_EXPORT PFI ResGetCallback(int which)
{
#if( RES_DEBUG_PARAMS )
if ((which < 0) or (which >= NUMBER_OF_CALLBACKS))
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "ResGetCallback");
return(NULL);
}
#endif /* RES_DEBUG_PARAMS */
IF_LOG(LOG("get callback: %d\n", which));
return(RES_CALLBACK[ which ]);
}
/* =======================================================
FUNCTION: ResCreatePath
PURPOSE: Initialize a search path for the resource
manager. The resource manager maintains
a separate hash table for each directory's
contents.
PARAMS: Ptr to pathname to parse.
RETURNS: TRUE (pass) / FALSE (fail)
A return value of false indicates that the
filename was not interprettable.
======================================================= */
RES_EXPORT int ResCreatePath(char * path, int recurse)
{
LIST * list;
#if( RES_DEBUG_VERSON )
if ( not path)
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "ResCreatePath");
return(FALSE);
}
#endif /* RES_DEBUG_VERSON */
#if (RES_MULTITHREAD)
REQUEST_LOCK(GLOCK);
#endif
IF_LOG(LOG("create path: %s\n", path));
if (GLOBAL_HASH_TABLE)
hash_destroy(GLOBAL_HASH_TABLE);
if (GLOBAL_PATH_LIST)
{
for (list = GLOBAL_PATH_LIST; list; list = list -> next)
{
#if( RES_USE_FLAT_MODEL )
#ifdef USE_SH_POOLS
MemFreePtr(list -> node);
#else
MemFree(list -> node);
#endif
#else
hash_destroy((HASH_TABLE *)list -> node);
#endif /* RES_USE_FLAT_MODEL */
}
LIST_DESTROY(GLOBAL_PATH_LIST, NULL);
}
GLOBAL_PATH_LIST = NULL;
GLOBAL_HASH_TABLE = hash_create(HASH_TABLE_SIZE, "Global");
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
if ( not GLOBAL_HASH_TABLE)
return(FALSE);
return(ResAddPath(path, recurse));
}
/* =======================================================
FUNCTION: ResAddPath
PURPOSE: Add a search path to the resource manager.
This process includes hashing all of the
directory names found in the indicated
directory and either a) adding them to
the global hash directory if using the
flat model -or- b) adding them to a hash
table created specifically for this
directory.
PARAMS: Ptr to pathname to parse.
RETURNS: TRUE (pass) / FALSE (fail)
A return value of false indicates that
the filename was not interprettable.
======================================================= */
RES_EXPORT int ResAddPath(char * path, int recurse)
{
struct _finddata_t data;
int length = 0,
count = 0,
done = 0,
refresh = FALSE,
full_yet = FALSE,
retval = TRUE,
filenum = 0, filecount = 0;
long directory = 0;
char tmp_path[ _MAX_PATH ] = {0};
char buffer[ _MAX_PATH ] = {0};
HASH_TABLE * local_table = NULL;
HASH_ENTRY * entry = NULL;
char vol_was = 0;
int dir_was = 0;
struct _finddata_t *file_data = NULL;
int currentDrive;
char currentPath[ _MAX_PATH];
/* Save original drive/path.*/
currentDrive = _getdrive();
_getdcwd(currentDrive, currentPath, _MAX_PATH);
#ifdef RES_NO_REPEATED_ADDPATHS
if (get_dir_index(path) not_eq -1)
{
return TRUE;
}
#endif
IF_LOG(LOG("adding path: %s\n", path));
#if( RES_DEBUG_PARAMS )
if ( not path)
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "ResAddPath");
return(FALSE);
}
if ( not GLOBAL_HASH_TABLE)
{
printf("You must first call ResCreatePath()\n");
return(FALSE);
}
#endif /* RES_DEBUG_VERSON */
#if( RES_DEBUG_VERSION )
if (GLOBAL_SEARCH_INDEX >= (MAX_DIRECTORIES - 1))
{
assert( not "Exceeded MAX_DIRECTORIES as defined in omni.h");
// SAY_ERROR( RES_ERR_TOO_MANY_DIRECTORIES, "ResAddPath" );
return(FALSE);
}
#endif
/* The hash index must be determined from hashing the full pathname */
res_fullpath(tmp_path, path, (_MAX_PATH - 2)); /* non-portable */
#if( not RES_USE_FLAT_MODEL )
entry = hash_find(tmp_path, GLOBAL_HASH_TABLE);
if (entry)
refresh = TRUE;
#endif
/* we need a trailing backslash */
length = strlen(tmp_path);
if (tmp_path[ length - 1 ] not_eq ASCII_BACKSLASH)
{
tmp_path[ length++ ] = ASCII_BACKSLASH;
tmp_path[ length ] = '\0';
}
/* the size of the hash table for this directory will be defined by
the macro HASH_OPTIMAL_RATIO times the number of files in the
directory (a small price to pay) */
filecount = count = ResCountDirectory(tmp_path, &file_data);
if (count == -1)
{
#ifdef USE_SH_POOLS
if (file_data) MemFreePtr(file_data);
#else
if (file_data) MemFree(file_data);
#endif
return FALSE;
}
count = (int)((float)count * (float)(HASH_OPTIMAL_RATIO));
count = MAX(count, 10); /* minimum of 10 entries set aside for a directory */
strcpy(buffer, tmp_path);
length = strlen(tmp_path); /* append wildcard to the filename (*.*) */
tmp_path[ length++ ] = ASCII_ASTERISK;
tmp_path[ length++ ] = ASCII_PERIOD;
tmp_path[ length++ ] = ASCII_ASTERISK;
tmp_path[ length ] = '\0';
#if( not RES_USE_FLAT_MODEL )
/* for the hierarchical model, we create a new hash table for the directory to
be added. Then we insert a hashed entry into the GLOBAL_HASH_TABLE which
points to this new table. */
#if 1
memcpy(&data, file_data, sizeof(struct _finddata_t));
#else
directory = _findfirst(tmp_path, &data); /* make sure it exists */
if (directory == -1)
{
SAY_ERROR(RES_ERR_PATH_NOT_FOUND, tmp_path);
return(FALSE);
}
_findclose(directory);
#endif
if ( not entry or not entry -> dir)
local_table = hash_create(count, buffer); /* create a new table */
else if (entry)
local_table = entry -> dir;
if ( not local_table)
return(FALSE);
strcpy(data.name, buffer); /* insert a dummy entry into the global hash table */
data.attrib = _A_SUBDIR bitor (unsigned int)FORCE_BIT;
data.time_create = 0;
data.time_access = 0;
data.size = 0;
if ( not entry)
entry = hash_add(&data, GLOBAL_HASH_TABLE);
if ( not entry)
return(FALSE);
if ( not entry -> dir)
entry -> dir = local_table;
if ( not refresh)
{
entry -> offset = 0;
entry -> csize = 0;
entry -> method = 0;
entry -> archive = -1;
entry -> file_position = -1;
entry -> volume = (char)(toupper(tmp_path[0]) - 'A');
entry -> directory = GLOBAL_SEARCH_INDEX;
GLOBAL_PATH_LIST = LIST_APPEND(GLOBAL_PATH_LIST, local_table);
}
#else
local_table = GLOBAL_HASH_TABLE; /* flat mode - all entries go into the root */
#endif /* not RES_USE_FLAT_MODEL */
/* enter the files into the local hash table, keeping count of the total
number of entries. */
done = 0;
vol_was = (char)(toupper(tmp_path[0]) - 'A');
if ( not refresh)
{
dir_was = GLOBAL_SEARCH_INDEX;
GLOBAL_SEARCH_PATH[ GLOBAL_SEARCH_INDEX++ ] = MemStrDup(buffer);
strcpy(GLOBAL_CURRENT_PATH, buffer);
}
else
dir_was = get_dir_index(path);
// if( _chdir( buffer )) // GFG MAY 05 / 98
// SAY_ERROR( errno, "ResAddPath" );
#if 1
memcpy(&data, file_data, sizeof(struct _finddata_t));
directory = 1;
filenum = 0;
#else
directory = _findfirst(tmp_path, &data);
#endif
if (directory not_eq -1)
{
/* integral volume id bitand path index */
while ( not done)
{
/* don't add directories to the hash table,
ResTreeAdd is used to recurse directories */
if ( not (data.attrib bitand _A_SUBDIR))
{
/* Reject empty files before calling hash_add. This
allows file creation to still be able to use hash_add. */
#if( RES_REJECT_EMPTY_FILES )
if (data.size == 0)
{
IF_LOG(LOG("empty file rejected: %s\n", data.name));
#if 1
if (filenum < filecount - 1)
{
filenum++;
memcpy(&data, file_data + filenum, sizeof(struct _finddata_t));
}
else
done = filenum;
#else
done = _findnext(directory, &data);
#endif
continue;
}
#endif /* not RES_ALLOW_EMPTY_FILES */
if (refresh)
{
if (hash_find(data.name, local_table))
{
#if 1
if (filenum < filecount - 1)
{
filenum++;
memcpy(&data, file_data + filenum, sizeof(struct _finddata_t));
}
else
done = filenum;
#else
done = _findnext(directory, &data);
#endif
continue;
}
entry = hash_find(data.name, local_table);
if ( not entry)
entry = hash_add(&data, local_table);
if (entry)
{
entry -> size = data.size;
entry -> attrib = data.attrib bitor FORCE_BIT;
}
}
else
{
entry = hash_add(&data, local_table);
}
if (entry) /* empty files may be rejected from hash_add */
{
IF_LOG(LOG("add: %s\n", entry -> name));
entry -> offset = 0;
entry -> csize = 0;
entry -> method = 0;
entry -> volume = vol_was;
entry -> directory = dir_was;
entry -> archive = -1;
entry -> file_position = -1;
}
}
else /* if we want to add an entire directory tree, recurse is TRUE */
{
if (recurse and not full_yet)
{
if (strcmp(data.name, ".") and strcmp(data.name, ".."))
{
int idx, ln;
ln = strlen(tmp_path);
for (idx = ln - 1; idx, tmp_path[idx] not_eq ASCII_BACKSLASH; idx--) ;
strncpy(buffer, tmp_path, idx);
sprintf(&buffer[idx], "\\%s\\", data.name);
if ( not ResAddPath(buffer, TRUE)) /* Recursively call this function. */
{
full_yet = TRUE; /* We want to continue adding this directory, and THEN */
retval = FALSE; /* trickle up a return flag. */
}
}
}
}
#if 1
if (filenum < filecount - 1)
{
filenum++;
memcpy(&data, file_data + filenum, sizeof(struct _finddata_t));
}
else
done = filenum;
#else
done = _findnext(directory, &data);
#endif
}
#if 0
_findclose(directory); /* done */
#endif
}
sort_path();
if (file_data)
{
#ifdef USE_SH_POOLS
MemFreePtr(file_data);
#else
MemFree(file_data);
#endif
file_data = NULL;
}
/* Restore original drive.*/ // GFG MAY 05 /98
_chdrive(currentDrive);
_chdir(currentPath);
return(retval);
}
/* =======================================================
FUNCTION: ResBuildPathname
PURPOSE: Builds a complex pathname. Whether the
input is a relative path, missing the
trailing slash, or needs to be built off
of a system directory, the output is
always a full pathname.
PARAMS: Optional enum representing a special
system path.
RES_DIR_INSTALL - path program was installed.
RES_DIR_WINDOWS - windows directory.
RES_DIR_CURR - current path.
RES_DIR_CD - path to the cd-rom
RES_DIR_HD - path to the boot hd
RES_DIR_TEMP - system temp directory
RES_DIR_SAVE - save game directory
RES_DIR_NONE - none
RETURNS: Number of characters written to path_out.
======================================================= */
RES_EXPORT int ResBuildPathname(int index, char * path_in, char * path_out)
{
char tmp[ _MAX_PATH ] = {0};
int len = 0;
char * ptr = NULL;
#if( RES_DEBUG_PARAMS )
if ((index < RES_DIR_NONE) or
(index >= RES_DIR_LAST) or
( not path_out))
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "ResBuildPathname");
return(-1);
}
if ((index not_eq RES_DIR_NONE) and (RES_PATH[ index ] == NULL))
{
SAY_ERROR(RES_ERR_NO_SYSTEM_PATH, "ResBuildPathname");
*path_out = '\0';
return(-1);
}
#endif /* RES_DEBUG_PARAMS */
/* path_in is optional, but, of course without it you get the same
effect as strcpy( path_out, RES_PATH[ index ]) */
if (path_in)
{
if (index not_eq RES_DIR_NONE) /* since all these end with a slash */
while (*path_in == ASCII_BACKSLASH) /* trim leading backslashes */
path_in++;
strcpy(tmp, path_in);
ptr = tmp;
while (*ptr)
{
if (*ptr == ASCII_FORESLASH) /* substitute backslash for forward slashes */
*ptr = ASCII_BACKSLASH;
*ptr = (char)(toupper(*ptr)); /* force to upper case */
ptr++;
}
/* trailing backslash */
len = strlen(tmp);
if (len and (tmp[len - 1] not_eq ASCII_BACKSLASH))
{
tmp[len++] = ASCII_BACKSLASH;
tmp[len] = '\0';
}
}
else
{
tmp[0] = '\0';
tmp[1] = '\0';
}
/* if there is a system path index */
if (index not_eq RES_DIR_NONE)
sprintf(path_out, "%s%s", RES_PATH[ index ], tmp);
else
strcpy(path_out, tmp);
return(len);
}
/* =======================================================
FUNCTION: ResCountDirectory
PURPOSE: Count the number of files within a
directory.
PARAMS: Ptr to a pathname.
RETURNS: Number of files found within given
directory.
======================================================= */
RES_EXPORT int ResCountDirectory(char * path , struct _finddata_t **file_data)
{
// HASH_ENTRY * entry=NULL;
char fullpath[ _MAX_PATH ];
// struct _finddata_t data;
struct _finddata_t *data;
int dir,
len,
count = -1,
data_count = 0,
ret;
IF_LOG(LOG("count: %s\n", path));
#if( RES_DEBUG_PARAMS )
if ( not path)
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "ResCountDirectory");
return(-1);
}
#endif /* RES_DEBUG_PARAMS */
/* we need to make sure we have an absolute (full) path */
res_fullpath(fullpath, path, (_MAX_PATH - 3));
#if( not RES_USE_FLAT_MODEL )
#if 0
entry = hash_find(fullpath, GLOBAL_HASH_TABLE);
if (entry and entry -> dir)
return(((HASH_TABLE *)entry -> dir) -> num_entries);
#endif
#endif /* RES_USE_FLAT_MODEL */
/* add a wildcard to the end of the path */
len = strlen(fullpath);
fullpath[ len++ ] = ASCII_ASTERISK;
fullpath[ len++ ] = ASCII_PERIOD;
fullpath[ len++ ] = ASCII_ASTERISK;
fullpath[ len ] = '\0';
data_count = RES_INIT_DIRECTORY_SIZE;
#ifdef USE_SH_POOLS
*file_data = data = MemAllocPtr(gResmgrMemPool, data_count * sizeof(struct _finddata_t), 0);
#else
*file_data = data = MemMalloc(data_count * sizeof(struct _finddata_t), "ResCountDirectory");
#endif
if ( not data)
{
SAY_ERROR(RES_ERR_NO_MEMORY, "ResCountDirectory");
return (-1);
}
/* try to open the directory */
// dir = _findfirst( fullpath, &data );
dir = _findfirst(fullpath, data);
if (dir not_eq -1)
{
count = 1;
do
{
if (count >= data_count)
{
data_count += RES_INIT_DIRECTORY_SIZE;
#ifdef USE_SH_POOLS
*file_data = MemReAllocPtr(*file_data, data_count * sizeof(struct _finddata_t), 0);
#else
*file_data = MemRealloc(*file_data, data_count * sizeof(struct _finddata_t));
#endif
data = *file_data + (count - 1);
}
data++;
ret = _findnext(dir, data);
if ( not ret)
{
count++;
}
}
while ( not ret);
_findclose(dir);
}
else
{
IF_LOG(LOG("Could not open directory %s\n", fullpath));
}
return(count);
}
/* =======================================================
FUNCTION: ResAssignPath
PURPOSE: What C++ was invented for. ResAssignPath
allows a public method to initialize
private data.
PARAMS: Enumerated value that represents one of
the slots open for system paths, ptr to
a pathname to assign to that slot.
RETURNS: None.
======================================================= */
RES_EXPORT void ResAssignPath(int index, char * path)
{
char * ptr;
int len;
#if( RES_DEBUG_PARAMS )
if ((index <= RES_DIR_NONE) or
(index >= RES_DIR_LAST) or
( not path))
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "ResAssignPath");
return;
}
#endif /* RES_DEBUG_PARAMS */
if (RES_PATH[ index ])
#ifdef USE_SH_POOLS
MemFreePtr(RES_PATH[ index ]);
#else
MemFree(RES_PATH[ index ]);
#endif
#ifdef USE_SH_POOLS
ptr = (char *)MemAllocPtr(gResmgrMemPool, _MAX_PATH, 0);
#else
ptr = (char *)MemMalloc(_MAX_PATH, path);
#endif
if ( not ptr)
{
SAY_ERROR(RES_ERR_NO_MEMORY, "Assign path");
return;
}
/* All of the pathnames within the RES_PATH array should end with
a backslash, therefore, we want to trim any leading backslashes
from the path here. */
while (*path == ASCII_BACKSLASH)
path++;
strcpy(ptr, path);
len = strlen(ptr);
if (len and (ptr[ len - 1 ] not_eq ASCII_BACKSLASH))
{
ptr[len++] = ASCII_BACKSLASH;
ptr[len] = '\0';
}
RES_PATH[ index ] = ptr;
IF_LOG(LOG("assign: %s [%d]\n", ptr, index));
}
/* =======================================================
FUNCTION: ResAsynchRead
PURPOSE: Perform an asynchronous read.
PARAMETERS: File int, buffer to read data in to,
function ptr for callback on completion.
RETURNS: TRUE (pass) / FALSE (fail).
True means the reader thread was
spawned to int the task - not that
the read was actually completed.
Confirmation that the read was actually
performed is intd by the callback.
IMPORTANT NOTE: Remember that the callback
is executed by the reader thread. Since
this thread is necessarily a low priority
thread - AND - that the callback will
exist within the context of this thread
(it will be the reader threads instruction
pointer - not the main instruction
pointer that executes the callback), you
should take care that the callback function
is short, simple and finite
======================================================= */
RES_EXPORT int ResAsynchRead(int file, void * buffer, PFV callback)
{
ASYNCH_DATA * data;
int thread_id;
#if( RES_DEBUG_PARAMS )
if ( not buffer or (file < 0) or (file > MAX_FILE_HANDLES))
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "ResAsynchRead");
return(FALSE);
}
#endif
IF_LOG(LOG("asynch read %s\n", FILE_HANDLES[file].filename));
#ifdef USE_SH_POOLS
data = (ASYNCH_DATA *)MemAllocPtr(gResmgrMemPool, sizeof(ASYNCH_DATA), 0);
#else
data = (ASYNCH_DATA *)MemMalloc(sizeof(ASYNCH_DATA), "Asynch data");
#endif
if ( not data)
{
SAY_ERROR(RES_ERR_NO_MEMORY, NULL);
return(FALSE);
}
data -> file = file;
data -> buffer = buffer;
data -> callback = callback;
thread_id = _beginthread(asynch_read, 128 /*stack size*/, (void *)(data));
if (thread_id == -1)
{
SAY_ERROR(RES_ERR_COULDNT_SPAWN_THREAD, NULL);
return(FALSE);
}
return(TRUE);
}
/* =======================================================
FUNCTION: ResAsynchWrite
PURPOSE: Perform an asynchronous write.
PARAMETERS: File int, buffer to read data from,
function ptr for callback on completion.
RETURNS: TRUE (pass) / FALSE (fail).
True means the reader thread was
spawned to int the task - not that
the write was actually completed.
Confirmation that the write was actually
performed is intd by the callback.
IMPORTANT NOTE: Remember that the callback
is executed by the writer thread. Since
this thread is necessarily a low priority
thread - AND - that the callback will
exist within the context of this thread
(it will be the writer threads instruction
pointer - not the main instruction
pointer that executes the callback), you
should take care that the callback function
is short, simple and finite
======================================================= */
RES_EXPORT int ResAsynchWrite(int file, void * buffer, PFV callback)
{
ASYNCH_DATA * data;
int thread_id;
#if( RES_DEBUG_PARAMS )
if ( not buffer or (file < 0) or (file > MAX_FILE_HANDLES))
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "ResAsynchWrite");
return(FALSE);
}
#endif
IF_LOG(LOG("asynch write %s\n", FILE_HANDLES[file].filename));
#ifdef USE_SH_POOLS
data = (ASYNCH_DATA *)MemAllocPtr(gResmgrMemPool, sizeof(ASYNCH_DATA), 0);
#else
data = (ASYNCH_DATA *)MemMalloc(sizeof(ASYNCH_DATA), "Asynch data");
#endif
if ( not data)
{
SAY_ERROR(RES_ERR_NO_MEMORY, NULL);
return(FALSE);
}
data -> file = file;
data -> buffer = buffer;
data -> callback = callback;
thread_id = _beginthread(asynch_write, 128 /*stack size*/, (void *)(data));
//SetThreadPriority( thread_id, THREAD_PRIORITY_LOWEST );
//#error PROTOTYPE THIS
if (thread_id == -1)
{
SAY_ERROR(RES_ERR_COULDNT_SPAWN_THREAD, NULL);
return(FALSE);
}
IF_DEBUG(LOG("Write thread (%d) spawned.", thread_id));
return(TRUE);
}
/* =======================================================
FUNCTION: ResExtractFile
PURPOSE: Convenience function for extacting
members of an archive.
PARAMETERS: Ptr to destination filename, ptr to
source filename.
RETURNS: Number of bytes written, or -1 in
case of an error.
======================================================= */
RES_EXPORT int ResExtractFile(const char * dst, const char * src)
{
char * buffer;
int handle;
unsigned int size;
const char * fdst = dst; /* expanded pathnames */
const char * fsrc = src;
#if( RES_COERCE_FILENAMES )
char fulldst[_MAX_PATH],
fullsrc[_MAX_PATH];
#endif /*RES_COERCE_FILENAMES */
#if( RES_DEBUG_PARAMS )
if ( not dst or not src)
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "ResExtract");
return(-1);
}
#endif /* RES_DEBUG_PARAMS */
#if( RES_COERCE_FILENAMES )
if (strchr(dst, ASCII_BACKSLASH))
{
res_fullpath(fulldst, dst, _MAX_PATH);
fdst = fulldst;
}
if (strchr(src, ASCII_BACKSLASH))
{
res_fullpath(fullsrc, src, _MAX_PATH);
fsrc = fullsrc;
}
#endif /* RES_COERCE_FILENAMES */
buffer = ResLoadFile(fsrc, NULL, &size);
if (buffer)
{
handle = ResOpenFile(fdst, _O_CREAT bitor _O_WRONLY bitor _O_BINARY);
if (handle not_eq -1)
{
size = ResWriteFile(handle, buffer, size);
ResCloseFile(handle);
}
ResUnloadFile(buffer);
}
else
return(-1);
return(size);
}
/* =======================================================
FUNCTION: ResPurge
PURPOSE: Purge entries from the Resource Manager
based on identical archive handle,
volume id, and/or directory path.
PARAMETERS: Ptr to archive handle, volume id,
directory handle. Pass NULL for any
unused parameter.
RETURNS: None.
======================================================= */
//RES_EXPORT void ResPurge( char * archive, char * volume, char * directory, char * filename )
RES_EXPORT void ResPurge(const char * archive, const char * volume, const int * directory, const char * filename)
{
LIST * list;
if ( not archive and not volume and not directory and not filename)
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "ResPurge");
return;
}
if ( not GLOBAL_PATH_LIST)
return;
for (list = GLOBAL_PATH_LIST; list; list = list -> next)
hash_purge((HASH_TABLE*)list -> node, archive, volume, directory, filename);
}
#if( RES_STREAMING_IO )
/* -----------------------------------------------------------------------------------------------
STREAM I/O Functions
All of the functions listed here should work.
Basically, if you want to perform streaming i/o, use ResFOpen the same way you would
use fopen. The returned value is a lightweight pointer to a _iob struct (FILE *).
From this point on, you can use this file pointer as if it were truly returned from
fopen. When you're ready to close the file, use ResFClose.
example:
{
FILE * file;
char name[255],
buffer[1024];
int date,
time;
file = ResFOpen( "test.txt", "r" );
if( not file )
return;
fscanf( file, "%s", &name );
fscanf( file, "%d", &date );
fscanf( file, "%d", &time );
printf( "name: %s date: %d time: %d\n", name, date, time );
fseek( file, 1024, SEEK_CUR );
while( (t = fread( buffer, 1, 64, file )) == 64 )
printf( "%s\n", buffer );
ResFClose( file );
}
Regardless of whether this file is located on a hard-drive, cd-rom drive, or floppy --
or whether the file is stored within a zip file -- or whether the file is compressed
within a zip file -- all the stdio streaming functions should work seamlessly using the
same FILE pointer.
-----------------------------------------------------------------------------------------------
These stream i/o functions are TOTALLY SUPPORTED
clearerr Clear error indicator for stream
fclose Close stream
feof Test for end of file on stream
ferror Test for error on stream
fflush Flush stream to buffer or storage device
fgetc Read character from stream (function versions of getc and getwc)
fgets Read string from stream
fopen Open stream
fprintf Write formatted data to stream
fputc Write a character to a stream (function versions of putc and putwc)
fputs Write string to stream
fread Read unformatted data from stream
fscanf Read formatted data from stream
fwrite Write unformatted data items to stream
_getw Read binary int from stream
puts Write line to stream
_putw Write binary int to stream
vfprintf Write formatted data to stream
These stream i/o functions are NOT SUPPORTED
_fdopen Associate stream with handle to open file
_flushall Flush all streams to buffer or storage device
These stream i/o functions are PARTIALLY SUPPORTED
These three functions act slightly differently from their normal
stdio behavior. The file may be flushed, and ungetc will be
cleared on archive files. All other behaviors are the same.
fseek Move file position to given location
fsetpos Set position indicator of stream
rewind Move file position to beginning of stream
This returns you a ResMgr handle if the file is found within
an archive, and an OS handle if the file is found loose on
hard-drive, cd, or floppy.
_fileno Get file handle associated with stream
These functions do not work on archive based files (but do on loose files):
ftell Get current file position
fgetpos Get position indicator of stream
This function is not guaranteed to work on archive files (but sometimes will):
ungetc Push character back onto stream
ungetc may work most of the time for all types of files, but
is not guarenteed to work on an archive file if:
ungetc is called on the first character (_cnt == _size),
ungetc is called twice in a row,
ungetc returned character is EOF.
-------------------------------------------------------------------------------------------- */
/* the flags field within an _iob struct (internal version of FILE struct)
is masked with the bit-fields found within stdio.h. The highest value
bit-field is 0x0200, and embarrassingly, I've munged my bit-fields into
this same member, starting at 0x00010000 */
#define _IOARCHIVE 0x00010000
#define _IOLOOSE 0x00020000
/* =======================================================
FUNCTION: ResSetBuf
PURPOSE: Controls stream buffer location and size.
Synonimous with setvbuf().
PARAMETERS: FILE ptr, ptr to an allocated buffer, mode
used for file buffering, size of buffer.
RETURNS: None.
NOT CURRENTLY SUPPORTED
======================================================= */
#if 0
RES_EXPORT void ResSetbuf(FILE * file, void * buffer, int mode, size_t size)
{
}
#endif
/* =======================================================
FUNCTION: fopen / ResFOpen
PURPOSE: Open a file for streaming i/o
PARAMETERS: Filename,
RETURNS: None.
======================================================= */
RES_EXPORT FILE * RES_FOPEN(const char * name, const char * mode)
{
FILE * stream;
int write_flag = FALSE;
HASH_ENTRY * entry;
HASH_TABLE * table = NULL;
char filename[_MAX_PATH],
dirpath[_MAX_PATH];
int retval = 1; /* to test return value of callbacks */
int dir_index;
struct _finddata_t data;
char tmp[LREC_SIZE];
local_file_hdr lrec;
#if( RES_DEBUG_PARAMS )
if ( not name or not mode)
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "ResFOpen");
return(FALSE);
}
#endif /* RES_DEBUG_PARAMS */
#if (RES_MULTITHREAD)
REQUEST_LOCK(GLOCK);
#endif
/* if the mode string contains either a 'w' or a '+' we
need to return an error if the file being operated on
is an archive file (eventually, this may be otherwise) */
if (strchr(mode, 'w') or strchr(mode, 'a'))
write_flag = TRUE;
/* find the file */
#if( not RES_USE_FLAT_MODEL )
entry = hash_find_table(name, &table); /* look through tables in search path order */
#else
entry = hash_find(name, GLOBAL_HASH_TABLE); /* look in the root hash table (flat model) */
#endif
if ( not entry and table and not write_flag)
{
SAY_ERROR(RES_ERR_FILE_NOT_FOUND, name);
SHOULD_I_CALL_WITH(CALLBACK_OPEN_FILE, -1, retval);
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(NULL);
}
/* -------------------------------------
Creating a file for writing
------------------------------------- */
if ( not entry and write_flag) /* FILE NOT FOUND */
{
/* if the user is trying to create a file on the harddrive,
this is ok (entry not found), but if they are not even
openning the file for any writing, we can return with
an error now. */
#if( not RES_USE_FLAT_MODEL )
/* see if the destination directory exists */
if (strchr(name, ASCII_BACKSLASH))
{
split_path((char *)name, filename, dirpath);
entry = hash_find(dirpath, GLOBAL_HASH_TABLE);
}
else /* current directory */
{
strcpy(filename, name);
strcpy(dirpath, GLOBAL_CURRENT_PATH);
entry = hash_find(GLOBAL_CURRENT_PATH, GLOBAL_HASH_TABLE);
}
/* if the directory does not exist, this is an error. Otherwise,
we get the ptr to the hash table for the destination directory */
if ( not entry or not entry -> dir) /* directory not found in resmgr */
{
SAY_ERROR(RES_ERR_UNKNOWN_WRITE_TO, name);
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(NULL);
}
else
{
table = (HASH_TABLE *)entry -> dir;
}
#else /* flat model */
/* if this is flat-mode, just look in the root hash table for
existance of the file, and set the table ptr to be the global
hash table (the sole hash table in this case). */
if (strchr(name, ASCII_BACKSLASH))
split_path(name, filename, dirpath);
else
strcpy(filename, name);
table = GLOBAL_HASH_TABLE;
#endif /* not RES_USE_FLAT_MODEL */
/* We use a dummy _finddata_t struct to stuff an entry for
this file into the hash table */
strcpy(data.name, filename);
data.attrib = (unsigned int)FORCE_BIT;
data.time_create = 0;
data.time_access = 0;
data.size = 0;
entry = hash_add(&data, table);
if ( not entry)
{
SAY_ERROR(RES_ERR_UNKNOWN, "ResFOpen - create");
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(NULL);
}
/* Look through the array of directory names comparing these to
our destination directory. The index value of the match is
set in our hash entry for later use. If no match is found
( this should never occur ), there is a big problem in the
hash tables */
for (dir_index = 0; dir_index <= GLOBAL_SEARCH_INDEX; dir_index++)
{
if ( not stricmp(dirpath, GLOBAL_SEARCH_PATH[ dir_index ]))
{
entry -> directory = dir_index;
entry -> volume = (char)(toupper(dirpath[0]) - 'A');
break;
}
}
/* oops. big problem. */
if (dir_index > GLOBAL_SEARCH_INDEX)
{
SAY_ERROR(RES_ERR_UNKNOWN, "ResFOpen - create");
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(NULL);
}
}
/* Make sure the user isn't trying to write to an archive file.
Someday this may be possible, but not for a while. */
if (entry and (entry -> archive not_eq -1) and write_flag)
{
SAY_ERROR(RES_ERR_CANT_WRITE_ARCHIVE, "ResFOpen");
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(NULL);
}
/* we want to use the same allocation scheme that the
visual c++ run-time uses because a) it isn't that
bad, b) it assures the highest integration with the
stream i/o functions, and c) it may keep fclose(file)
from thrashing your system. */
stream = _getstream(); /* taken from open.c */
if ( not stream)
{
SAY_ERROR(RES_ERR_TOO_MANY_FILES, "ResFOpen");
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(NULL);
}
/* these initialization values may change */
stream -> _ptr = NULL;
stream -> _cnt = 0;
stream -> _base = NULL;
stream -> _flag = _IOREAD; /* *MUST* have this for inuse to think it's full */
stream -> _file = 0;
stream -> _charbuf = 0;
stream -> _bufsiz = 0;
stream -> _tmpfname = NULL;
if ( not entry or (entry -> archive == -1))
{
/* ----- Loose file ----- */
/* If the file is loose (not in an archive) we will want
_filbuf to work as normal - therefore the file handle
should be the OS handle of the open file. If the file
is in an archive, the handle is our file handle which
we use to access the archive and read the file. */
if ( not entry) /* assume it's a 'create' acceptable mode */
res_fullpath(filename, name, _MAX_PATH); /* regardless of coercion state */
else
sprintf(filename, "%s%s", GLOBAL_SEARCH_PATH[ entry -> directory ], entry -> name);
/* call the same low-level open file that fopen uses */
if ( not _openfile(filename, mode, _SH_DENYNO, stream))
{
if (errno == EACCES)
{
SAY_ERROR(RES_ERR_FILE_SHARING, filename);
}
else
{
SAY_ERROR(RES_ERR_PROBLEM_READING, filename);
}
/* Don't forget to free the stream handle, duh */
stream -> _flag = 0;
stream -> _ptr = NULL;
stream -> _cnt = 0;
UNLOCK_STREAM(stream);
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(NULL);
}
SHOULD_I_CALL_WITH(CALLBACK_OPEN_FILE, -1, retval);
/* tag the structure as our own flavor (specifically 'loose') */
stream -> _flag or_eq _IOLOOSE;
UNLOCK_STREAM(stream);
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(stream);
}
else
{
/* ----- Archive File ----- */
/* This is the case that we're doing all the work for.
If the file being read is a member of an archive, we
treat it as if we were using ResOpenFile at this
point. Later, during the _filbuf() function, we'll
use this data to simulate the stream i/o filling
routine. */
/* We need one of our special file descriptors */
int handle = 0;
FILE_ENTRY * file = NULL;
LIST * list = NULL;
ARCHIVE * archive = NULL;
handle = get_handle();
if (handle == -1) /* none left */
{
SAY_ERROR(RES_ERR_TOO_MANY_FILES, "ResOpenFile");
UNLOCK_STREAM(stream);
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(NULL);
}
file = &FILE_HANDLES[ handle ];
/* Find the archive file from which this file is found */
for (list = ARCHIVE_LIST; list; list = list -> next)
{
archive = (ARCHIVE *)list -> node;
if (archive -> os_handle == entry -> archive)
break;
}
/* oops. big problem. */
if ( not list)
{
SAY_ERROR(RES_ERR_UNKNOWN, "ResFOpen"); /* archive handle in hash entry is incorrect (or archive detached) */
UNLOCK_STREAM(stream);
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(NULL);
}
/* Use our own file descriptor here. This is where we do two cheats, one
obvious, one subtle. We stuff our own descriptor into the file member
of the stream structure so we can use our own access methods within our
modified _filbuf routine. However, we also use a sleazy little VC++
uniqueness by setting a flag that this is a _IOSTRG (stream is really
a string). This ensures that if the user accidently passes the FILE
ptr to fclose, nothing nasty will occur. It also ensures that should
the run-time library decide to go south, the clean-up code won't
exaserbate the problem, possibly allowing you to debug the original
problem. */
stream -> _file = handle;
/* Tag the structure as our own flavor (specifically 'archive'), as well
as use a vc++ uniqueness. */
stream -> _flag or_eq (_IOARCHIVE bitor _IOSTRG bitor _IOREAD);
/* ---------------------------------------------------------------------------
UGGGH
Microsoft morons didn't implement any of their stdio streaming functions
like everyone else in the fucking world, so this is a sordid fix. The
problem is that fread will bypass _filbuf if the requested read size is
larger than the buffer. Now, this alone is not a bad optimization, but
it would have been a hell of lot easier if they had done it like everyone
else and just put a function ptr for read/write within the iobuf struct.
--------------------------------------------------------------------------- */
stream -> _bufsiz = 0xffffffff;
/* --------------------------------------------------------------------------- */
UNLOCK_STREAM(stream);
REQUEST_LOCK(archive -> lock);
sprintf(filename, "%s%s", GLOBAL_SEARCH_PATH[ entry -> directory ], entry -> name);
lseek(archive -> os_handle, entry -> file_position + SIGNATURE_SIZE, SEEK_SET);
_read(archive -> os_handle, tmp, LREC_SIZE);
process_local_file_hdr(&lrec, tmp); /* return PK-type error code */
file -> seek_start = lseek(archive -> os_handle, lrec.filename_length + lrec.extra_field_length, SEEK_CUR);
/* Initialize some common data */
file -> current_pos = 0;
file -> current_filbuf_pos = 0;
switch (entry -> method)
{
case STORED:
{
file -> os_handle = archive -> os_handle;
//file -> seek_start = entry -> file_position;
file -> csize = 0;
file -> size = entry -> size;
file -> filename = MemStrDup(filename);
file -> mode = _O_RDONLY bitor _O_BINARY;
file -> device = entry -> volume;
file -> zip = NULL; /* only used if we need to deflate */
SHOULD_I_CALL_WITH(CALLBACK_OPEN_FILE, handle, retval);
RELEASE_LOCK(archive -> lock);
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(stream);
break;
}
case DEFLATED:
{
COMPRESSED_FILE * zip;
#ifdef USE_SH_POOLS
zip = (COMPRESSED_FILE *)MemAllocPtr(gResmgrMemPool, sizeof(COMPRESSED_FILE) + (entry -> size), 0);
#else
zip = (COMPRESSED_FILE *)MemMalloc(sizeof(COMPRESSED_FILE) + (entry -> size), "Inflate");
#endif
if ( not zip)
{
SAY_ERROR(RES_ERR_NO_MEMORY, "Inflate");
RELEASE_LOCK(archive -> lock);
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(NULL);
}
file -> os_handle = archive -> os_handle;
//file -> seek_start = entry -> file_position;
file -> csize = entry -> csize;
file -> size = entry -> size;
file -> filename = MemStrDup(filename);
file -> mode = _O_RDONLY bitor _O_BINARY;
file -> device = entry -> volume;
#ifdef USE_SH_POOLS
zip -> slide = (uch *)MemAllocPtr(gResmgrMemPool, UNZIP_SLIDE_SIZE + INPUTBUFSIZE, 0); /* glob temporary allocations */
#else
zip -> slide = (uch *)MemMalloc(UNZIP_SLIDE_SIZE + INPUTBUFSIZE, "deflate"); /* glob temporary allocations */
#endif
zip -> in_buffer = (uch *)zip -> slide + UNZIP_SLIDE_SIZE;
zip -> in_ptr = (uch *)zip -> in_buffer;
zip -> in_count = 0;
zip -> in_size = file -> csize > INPUTBUFSIZE ? INPUTBUFSIZE : file -> csize;
zip -> csize = file -> csize;
zip -> out_buffer = (char *)zip + sizeof(COMPRESSED_FILE);
zip -> out_count = 0;
zip -> archive = archive;
file -> zip = zip; /* Future use: I may add incremental deflation */
//lseek( file -> os_handle, file -> seek_start, SEEK_SET );
inflate(zip);
#ifdef USE_SH_POOLS
MemFreePtr(zip -> slide); /* Free temporary allocations */
#else
MemFree(zip -> slide); /* Free temporary allocations */
#endif
SHOULD_I_CALL_WITH(CALLBACK_OPEN_FILE, handle, retval);
RELEASE_LOCK(archive -> lock);
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(stream);
break;
}
default:
SAY_ERROR(RES_ERR_UNSUPPORTED_COMPRESSION, entry -> name);
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(NULL);
break;
}
RELEASE_LOCK(archive -> lock);
}
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(NULL);
}
/* =======================================================
FUNCTION: fclose / ResFClose
PURPOSE: Closes a file that has previously been
opened using ResFOpen().
PARAMETERS: File ptr.
RETURNS: None.
======================================================= */
int __cdecl RES_FCLOSE(FILE * file)
{
int handle,
result;
#if( RES_DEBUG_PARAMS )
/* check to see if it's one of our two flavors of FILE ptrs */
if ( not file or not (file -> _flag, (_IOARCHIVE bitor _IOLOOSE)))
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "ResFClose");
return(EOF); /* error */
}
#endif
#if (RES_MULTITHREAD)
REQUEST_LOCK(GLOCK);
#endif
if (FLAG_TEST(file -> _flag, _IOARCHIVE))
{
handle = file -> _file;
if (FILE_HANDLES[ handle ].zip)
#ifdef USE_SH_POOLS
MemFreePtr(FILE_HANDLES[ handle ].zip);
#else
MemFree(FILE_HANDLES[ handle ].zip);
#endif
#ifdef USE_SH_POOLS
MemFreePtr(FILE_HANDLES[ handle ].filename);
#else
MemFree(FILE_HANDLES[ handle ].filename);
#endif
FILE_HANDLES[ handle ].zip = NULL;
FILE_HANDLES[ handle ].filename = NULL;
FILE_HANDLES[ handle ].os_handle = -1;
/* since microsoft doesn't use have symmetry with it's _getstream()
function (eg; _freestream()), we just set the _flag field to 0
and assume that's all there is to do (seems like this is true
after looking at close.c and fclose.c */
/* Actually, not quite. If the streaming io functions are used then
a call to _freebuf is needed. Looking closely at fclose.c and
_freebuf.c it seems safe to do all the time. LRKUDGE
*/
LOCK_STREAM(file);
_freebuf(file);
file -> _flag = 0;
file -> _ptr = NULL;
file -> _cnt = 0;
UNLOCK_STREAM(file);
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(0);
}
else
{
FLAG_UNSET(file -> _flag, _IOLOOSE); /* we want to unset our unique flags before */
FLAG_UNSET(file -> _flag, _IOSTRG); /* calling any CRT functions. */
/* this is basically all that fclose does */
LOCK_STREAM(file);
result = _flush(file);
_freebuf(file);
if (_close(_fileno(file)) < 0)
result = EOF;
UNLOCK_STREAM(file);
file -> _flag = 0; /* now we clear all flags */
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(result);
}
}
#define bigbuf(s) ((s)->_flag bitand (_IOMYBUF|_IOYOURBUF))
#define _osfile(i) ( _pioinfo(i)->osfile
#define FCRLF 0x04 /* CR-LF across read buffer (in text mode) */
#define _IOCTRLZ 0x2000
#define FTEXT 0x80 /* file handle is in text mode */
/* =======================================================
FUNCTION: ftell / ResFTell
PURPOSE: Replaces the stdio ftell function to be
able to correctly handle streaming i/o
from within the Resource Manager.
NOTE: THIS IS WRAPPED BECAUSE...
The Microsoft source for ftell is
surprisingly long and ugly and I'm
way to lazy to want to implement all
the special case crap they have.
However, for the sake of consistency
with the API for streaming functions,
and because I think this will work
for 99.9999% of our projects, I did
the skinny solution.
And, having acknowledged that there
may be several pathalogic cases where
this version will fail, (eg; files
opened with fopen instead of ResFOpen,
in text-mode, without buffering) I'll
let you choose which version to use.
If ftell doesn't work for you as it is
here (first of all, call me because
I'll be amazed), define
RES_REPLACE_FTELL to be FALSE and call
ResFTell. This will always work.
PARAMETERS: File ptr.
RETURNS: File position, or -1 in case of error.
NOTE: Based on the vc++ run-time source file
ftell.c
======================================================= */
long __cdecl RES_FTELL(FILE * stream)
{
unsigned int offset;
long filepos;
register char * p;
char * max;
int fd;
unsigned int rdcnt;
int handle,
count;
#if( RES_DEBUG_PARAMS )
if ( not stream)
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "ftell");
return(-1);
}
#endif /* RES_DEBUG_PARAMS */
#if (RES_MULTITHREAD)
REQUEST_LOCK(GLOCK);
#endif
/* --------- File within a compressed archive --------- */
LOCK_STREAM(stream);
if ((stream -> _flag) bitand _IOARCHIVE)
{
handle = stream -> _file;
/* GFG_NOV06 count = (int)( stream -> _ptr - stream -> _base ); *//* should be safe (key word: SHOULD) */
if (handle < 0 or handle > MAX_FILE_HANDLES or (FILE_HANDLES[ handle ].os_handle == -1 and not (stream -> _flag bitand _IOLOOSE)))
{
SAY_ERROR(RES_ERR_ILLEGAL_FILE_HANDLE, "ftell");
UNLOCK_STREAM(stream);
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(-1);
}
/*** GFG_NOV06
if( stream -> _flag bitand _IOARCHIVE )
count = FILE_HANDLES[ handle ].current_pos - stream -> _cnt;
else
count += FILE_HANDLES[ handle ].current_pos;
***/
count = FILE_HANDLES[ handle ].current_pos;;
UNLOCK_STREAM(stream);
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(count);
}
/* ------------------- Loose file ------------------- */
/* Init stream pointer and file descriptor */
fd = _fileno(stream);
if (stream->_cnt < 0)
stream->_cnt = 0;
UNLOCK_STREAM(stream);
if ((filepos = _lseek(fd, 0L, SEEK_CUR)) < 0L)
{
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(-1L);
}
if ( not bigbuf(stream)) /* _IONBF or no buffering designated */
{
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(filepos - stream->_cnt);
}
LOCK_STREAM(stream);
offset = stream->_ptr - stream->_base;
if (stream->_flag bitand (_IOWRT bitor _IOREAD))
{
if (stream -> _flag bitand _O_TEXT)
for (p = stream->_base; p < stream->_ptr; p++)
if (*p == '\n') /* adjust for '\r' */
offset++;
}
else if ( not (stream->_flag bitand _IORW))
{
errno = EINVAL;
UNLOCK_STREAM(stream);
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(-1L);
}
if (filepos == 0L)
{
UNLOCK_STREAM(stream);
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return((long)offset);
}
if (stream->_flag bitand _IOREAD) /* go to preceding sector */
{
if (stream->_cnt == 0) /* filepos holds correct location */
{
UNLOCK_STREAM(stream);
offset = 0;
}
else
{
/* Subtract out the number of unread bytes left in the
buffer. [We can't simply use _iob[]._bufsiz because
the last read may have hit EOF and, thus, the buffer
was not completely filled.] */
rdcnt = stream->_cnt + (stream->_ptr - stream->_base);
/* If text mode, adjust for the cr/lf substitution. If
binary mode, we're outta here. */
if (stream -> _flag bitand _O_TEXT)
{
/* (1) If we're not at eof, simply copy _bufsiz
onto rdcnt to get the # of untranslated
chars read. (2) If we're at eof, we must
look through the buffer expanding the '\n'
chars one at a time. */
/* [NOTE: Performance issue -- it is faster to
do the two _lseek() calls than to blindly go
through and expand the '\n' chars regardless
of whether we're at eof or not.] */
UNLOCK_STREAM(stream);
if (_lseek(fd, 0L, 2) == filepos)
{
LOCK_STREAM(stream);
max = stream->_base + rdcnt;
for (p = stream->_base; p < max; p++)
if (*p == '\n') /* adjust for '\r' */
rdcnt++;
/* If last byte was ^Z, the lowio read
didn't tell us about it. Check flag
and bump count, if necessary. */
if (stream->_flag bitand _IOCTRLZ)
++rdcnt;
UNLOCK_STREAM(stream);
}
else
{
_lseek(fd, filepos, 0);
/* We want to set rdcnt to the number
of bytes originally read into the
stream buffer (before crlf->lf
translation). In most cases, this
will just be _bufsiz. However, the
buffer size may have been changed,
due to fseek optimization, at the
END of the last _filbuf call. */
LOCK_STREAM(stream);
if ((rdcnt <= _SMALL_BUFSIZ) and
(stream->_flag bitand _IOMYBUF) and
not (stream->_flag bitand _IOSETVBUF))
{
/* The translated contents of
the buffer is small and we
are not at eof. The buffer
size must have been set to
_SMALL_BUFSIZ during the
last _filbuf call. */
rdcnt = _SMALL_BUFSIZ;
}
else
rdcnt = stream->_bufsiz;
/* If first byte in untranslated buffer
was a '\n', assume it was preceeded
by a '\r' which was discarded by the
previous read operation and count
the '\n'. */
if (*stream->_base == '\n')
++rdcnt;
UNLOCK_STREAM(stream);
}
} /* end if FTEXT */
else
UNLOCK_STREAM(stream);
filepos -= (long)rdcnt;
} /* end else stream->_cnt not_eq 0 */
}
else
UNLOCK_STREAM(stream);
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(filepos + (long)offset);
}
/* ==================================================================================
R E P L A C E M E N T F R E A D
================================================================================== */
/* define the normal version */
size_t __cdecl RES_FREAD(void *buffer, size_t size, size_t num, FILE *stream)
{
char *data; /* point to where should be read next */
unsigned total; /* total bytes to read */
unsigned count; /* num bytes left to read */
unsigned bufsize; /* size of stream buffer */
unsigned nbytes; /* how much to read now */
unsigned nread; /* how much we did read */
int c; /* a temp char */
/* initialize local vars */
data = buffer;
if ((count = total = size * num) == 0)
return 0;
#if (RES_MULTITHREAD)
REQUEST_LOCK(GLOCK);
#endif
LOCK_STREAM(stream);
if (anybuf(stream)) /* already has buffer, use its size */
bufsize = stream->_bufsiz;
else
#if defined (_M_M68K) or defined (_M_MPPC)
bufsize = BUFSIZ; /* assume will get BUFSIZ buffer */
#else /* defined (_M_M68K) or defined (_M_MPPC) */
bufsize = _INTERNAL_BUFSIZ; /* assume will get _INTERNAL_BUFSIZ buffer */
#endif /* defined (_M_M68K) or defined (_M_MPPC) */
/* here is the main loop -- we go through here until we're done */
while (count not_eq 0)
{
/* if the buffer exists and has characters, copy them to user
buffer */
if (anybuf(stream) and stream->_cnt not_eq 0)
{
/* how much do we want? */
nbytes = (count < (unsigned)stream->_cnt) ? count : stream->_cnt;
memcpy(data, stream->_ptr, nbytes);
/* update stream and amt of data read */
count -= nbytes;
stream->_cnt -= nbytes;
stream->_ptr += nbytes;
data += nbytes;
/* GFG_NOV06 */
if (stream -> _flag bitand _IOARCHIVE)
FILE_HANDLES[ stream -> _file ].current_pos += nbytes;
} // |<---------- MODIFIED ----------->|
else if ((count >= bufsize) and not (stream -> _flag bitand _IOARCHIVE))
{
// |<---------- MODIFIED ----------->|
/* If we have more than bufsize chars to read, get data
by calling read with an integral number of bufsiz
blocks. Note that if the stream is text mode, read
will return less chars than we ordered. */
/* calc chars to read -- (count/bufsize) * bufsize */
nbytes = (bufsize ? (count - count % bufsize) :
count);
UNLOCK_STREAM(stream);
nread = _read(_fileno(stream), data, nbytes);
LOCK_STREAM(stream);
if (nread == 0)
{
/* end of file -- out of here */
stream->_flag or_eq _IOEOF;
UNLOCK_STREAM(stream);
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return (total - count) / size;
}
else if (nread == (unsigned) - 1)
{
/* error -- out of here */
stream->_flag or_eq _IOERR;
UNLOCK_STREAM(stream);
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return (total - count) / size;
}
/* update count and data to reflect read */
count -= nread;
data += nread;
}
else
{
/* less than bufsize chars to read, so call _filbuf to
fill buffer */
if ((c = _filbuf(stream)) == EOF)
{
/* error or eof, stream flags set by _filbuf */
UNLOCK_STREAM(stream);
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return (total - count) / size;
}
/* _filbuf returned a char -- store it */
*data++ = (char) c;
--count;
/* GFG_NOV06 */
if (stream -> _flag bitand _IOARCHIVE)
FILE_HANDLES[ stream -> _file ].current_pos++;
/* update buffer size */
bufsize = stream->_bufsiz;
}
}
UNLOCK_STREAM(stream);
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
/* we finished successfully, so just return num */
return num;
}
/* ==================================================================================
R E P L A C E M E N T F S E E K
================================================================================== */
/* =======================================================
FUNCTION: fseek
PURPOSE: Replaces the stdio fseek function to be
able to correctly handle streaming i/o.
PARAMETERS: File ptr, offset, enumerated token
defining the starting location.
RETURNS: 0 if succeccful, or -1 in case of error.
NOTE: Based on the vc++ run-time source file
fseek.c
======================================================= */
int __cdecl RES_FSEEK(FILE * stream, long offset, int whence)
{
unsigned int pos;
#if( RES_DEBUG_PARAMS )
if ( not stream)
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "fseek");
return(-1);
}
#endif /* RES_DEBUG_PARAMS */
#if (RES_MULTITHREAD)
REQUEST_LOCK(GLOCK);
#endif
LOCK_STREAM(stream);
if (stream -> _flag bitand _IOARCHIVE)
{
pos = FILE_HANDLES[ stream -> _file ].current_pos;
switch (whence)
{
case SEEK_SET: /* 0 */
pos = offset;
break;
case SEEK_CUR: /* 1 */
pos += offset;
break;
case SEEK_END: /* 2 */
pos = FILE_HANDLES[ stream -> _file ].size + offset;
break;
}
stream -> _cnt = 0; /* force next read to replenish buffers */
stream -> _ptr = stream -> _base;
UNLOCK_STREAM(stream);
if (pos > FILE_HANDLES[ stream -> _file ].size)
{
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(-1);
}
FILE_HANDLES[ stream -> _file ].current_pos = pos;
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(0);
}
else
{
if ( not inuse(stream) or
((whence not_eq SEEK_SET) and
(whence not_eq SEEK_CUR) and
(whence not_eq SEEK_END)))
{
errno = EINVAL;
UNLOCK_STREAM(stream);
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(-1);
}
/* Clear EOF flag */
stream -> _flag and_eq compl _IOEOF;
/* If seeking relative to current location, then convert to
a seek relative to beginning of file. This accounts for
buffering, etc. by letting fseek() tell us where we are. */
if (whence == SEEK_CUR)
{
offset += ftell(stream);
whence = SEEK_SET;
}
/* Flush buffer as necessary */
_flush(stream);
/* If file opened for read/write, clear flags since we don't know
what the user is going to do next. If the file was opened for
read access only, decrease _bufsiz so that the next _filbuf
won't cost quite so much */
if (stream->_flag bitand _IORW)
stream->_flag and_eq compl (_IOWRT bitor _IOREAD);
else
{
if ((stream->_flag bitand _IOREAD) and
(stream->_flag bitand _IOMYBUF) and
not (stream->_flag bitand _IOSETVBUF))
{
stream->_bufsiz = _SMALL_BUFSIZ;
}
}
/* Seek to the desired locale and return. */
#ifdef _MT
pos = _lseek(stream -> _file, offset, whence);
#else
pos = _lseek_lk(stream -> _file, offset, whence);
#endif
stream -> _ptr = stream -> _base;
// There is no file handle assosciated with a streaming 'loose'
// file. Therefore... the following fix was actually scribling
// memory.
// if( pos not_eq -1 )
// FILE_HANDLES[ stream -> _file ].current_pos = pos; [KBR SEPT 10 96]
if (pos == -1)
{
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(-1);
}
if ((stream -> _flag bitand _IOARCHIVE) and (pos not_eq -1))
FILE_HANDLES[ stream -> _file ].current_pos = pos;
}
UNLOCK_STREAM(stream);
#if (RES_MULTITHREAD)
RELEASE_LOCK(GLOCK);
#endif
return(0);
}
#endif /* RES_STREAMING_IO */
/* ==================================================================================
R E P L A C E M E N T _ F I L B U F
================================================================================== */
/* =======================================================
FUNCTION: _filbuf
PURPOSE: Low-level read routine used by stdio
streaming functions. _flsbuf is the
low-level write routine, but since write
is not allowed on a compressed archive,
we don't need to replace this function.
PARAMETERS: File ptr.
RETURNS: None.
NOTE: Originally I was using the _fillbuf
routine that is included with the
Free Software Foundation's gcc
distribution. Then I grabbed Microsoft's
version (on the MSDEV cd with the library
source code). This version is a
unique (bastard) version of the two.
======================================================= */
int __cdecl _filbuf(FILE * stream)
{
int retval = FALSE; /* used for the callback */
int handle = 0;
FILE_ENTRY * file = NULL; /* my file descriptor */
int compressed_flag = TRUE;
#if( RES_DEBUG_PARAMS )
if ( not stream)
{
SAY_ERROR(RES_ERR_INCORRECT_PARAMETER, "_filbuf");
return(EOF);
}
// if( not (stream -> _flag bitand ( _IOARCHIVE bitor _IOLOOSE )) ) {
// /* You can actually remove this error trap if you want fopen
// as well as ResFOpen */
// SAY_ERROR( RES_ERR_UNKNOWN, "Stream not created with ResFOpen" );
// stream -> _flag or_eq _IOREAD;
// return( EOF );
// }
#endif
//LRKLUDGE
// If its a string return
if ( not inuse(stream) or
((stream->_flag bitand _IOSTRG) and
not (stream->_flag bitand (_IOLOOSE bitor _IOARCHIVE))))
return(EOF);
/* if stream is opened as WRITE ONLY, set error and return */
if (stream -> _flag bitand _IOWRT)
{
stream -> _flag or_eq _IOERR;
return(EOF);
}
/* force flag */
stream -> _flag or_eq _IOREAD;
/* Get a buffer, if necessary. (taken from _filbuf.c) */
if ( not (stream -> _base))
_getbuf(stream);
else
stream -> _ptr = stream -> _base;
/* if the callback routine does the fill it should return TRUE,
designating that this routine can exit immediately */
SHOULD_I_CALL_WITH(CALLBACK_FILL_STREAM, stream, retval);
if (retval)
return(0xff bitand retval);
/* READ OR DECOMPRESS ? */
/* if a file is loose on the hard-drive, we will want to replenish
the buffer by simply reading the file directly. If a file is
'stored' (not compressed) within an archive file, we replenish
the buffer by seeking within the archive, and then doing a
simple read. Finally, if the file is compressed within an
archive, we assume we already have a decomressed buffer from
which to copy bytes. */
if ( not (stream -> _flag bitand _IOARCHIVE))
{
compressed_flag = FALSE;
handle = stream -> _file;
}
else
{
file = &FILE_HANDLES[ stream -> _file ];
/* if( file -> current_pos >= file -> size ) was GFG */
if (file -> current_filbuf_pos >= file -> size)
{
return(EOF);
}
if (file -> os_handle == -1)
{
SAY_ERROR(RES_ERR_ILLEGAL_FILE_HANDLE, "_filbuf internal error");
stream -> _flag or_eq _IOERR;
return(EOF);
}
if ( not file -> zip) /* file is just stored */
{
compressed_flag = FALSE;
handle = file -> os_handle;
#ifdef _MT
/*_lseek_lk( handle, (file -> seek_start + file -> current_pos), SEEK_SET );*/
#else
lseek(handle, (file -> seek_start + file -> current_pos), SEEK_SET);
#endif
}
else /* end of file check ? */
{
int count;
count = stream -> _bufsiz;
if (count > (int)(file -> size - file -> current_filbuf_pos)) /* was current_pos */
{
memset(stream -> _base, 0, stream -> _bufsiz);
count = file -> size - file -> current_filbuf_pos; /* was current_pos */
}
memcpy(stream -> _base, file -> zip -> out_buffer + file -> current_filbuf_pos, count); /* was current_pos */
file -> current_filbuf_pos += count; /* GFG_NOV06 */
stream -> _cnt = count;
}
}
if ( not compressed_flag)
{
stream -> _cnt = _read(handle, stream -> _base, stream -> _bufsiz);
if (file) /* stored in an archive */
{
if (stream -> _cnt < 0) /* error reading */
{
stream -> _flag or_eq _IOERR;
if (stream -> _flag bitand (_IOARCHIVE bitor _IOLOOSE)) /* make sure this is an fopen() file */
ResCheckMedia(file -> device); /* if not, has media changed? */
return(EOF);
}
/**** GFG_NOV06
else
file -> current_pos += stream -> _cnt;
***/
}
if ((stream -> _cnt == 0) or (stream -> _cnt == -1))
{
stream -> _flag or_eq stream -> _cnt ? _IOERR : _IOEOF;
stream -> _cnt = 0;
return(EOF);
}
// Don't think I need this, but... _osfile_safe(i) expands to (_pioinfo_safe(i)->osfile)
// if( not (stream -> _flag bitand ( _IOWRT bitor _IORW )) and ((_osfile_safe(_fileno(stream)) bitand (FTEXT|FEOFLAG)) == (FTEXT|FEOFLAG)))
// stream -> _flag or_eq _IOCTRLZ;
/* Check for small _bufsiz (_SMALL_BUFSIZ). If it is small and
if it is our buffer, then this must be the first _filbuf after
an fseek on a read-access-only stream. Restore _bufsiz to its
larger value (_INTERNAL_BUFSIZ) so that the next _filbuf call,
if one is made, will fill the whole buffer. */
if ((stream -> _bufsiz == _SMALL_BUFSIZ) and
(stream -> _flag bitand _IOMYBUF) and
not (stream -> _flag bitand _IOSETVBUF))
{
stream -> _bufsiz = _INTERNAL_BUFSIZ;
}
}
stream -> _cnt--;
return(0xff bitand *stream -> _ptr++);
}
#if( RES_DEBUG_VERSION )
/* =======================================================
FUNCTION: ResDbg
PURPOSE: Toggle the state of debugging at runtime.
PARAMETERS: Boolean state TRUE (on) / FALSE (off).
RETURNS: None.
======================================================= */
RES_EXPORT void ResDbg(int on)
{
RES_DEBUG_FLAG = on;
}
/* =======================================================
FUNCTION: ResDbgLogOpen
PURPOSE: Open a file for event logging.
PARAMETERS: Filename to write data to.
RETURNS: TRUE (pass) / FALSE (fail).
======================================================= */
RES_EXPORT int ResDbgLogOpen(char * filename)
{
if (RES_DEBUG_LOGGING)
ResDbgLogClose();
/* there is actually a third parameter to open() (MSVC just doesn't admit it)
octal 666 ensures that stack-crap won't accidently create this file as
read-only. Thank to Roger Fujii for this fix */
RES_DEBUG_FILE = _open(filename, _O_RDWR bitor _O_CREAT bitor _O_TEXT, 0x1b6 /* Choked on O666L and O666 */);
if (RES_DEBUG_FILE == -1)
{
SAY_ERROR(RES_ERR_COULDNT_OPEN_FILE, filename);
RES_DEBUG_OPEN_LOG = FALSE;
RES_DEBUG_LOGGING = FALSE;
return(FALSE);
}
RES_DEBUG_OPEN_LOG = TRUE;
RES_DEBUG_LOGGING = TRUE;
IF_DEBUG(LOG("Log file opened.\n\n"));
return(TRUE);
}
/* =======================================================
FUNCTION: ResDbgLogClose
PURPOSE: Closes a previously opened log file.
PARAMETERS: None.
RETURNS: None.
======================================================= */
RES_EXPORT void ResDbgLogClose(void)
{
if (RES_DEBUG_OPEN_LOG)
_close(RES_DEBUG_FILE);
RES_DEBUG_OPEN_LOG = FALSE;
RES_DEBUG_LOGGING = FALSE;
}
/* =======================================================
FUNCTION: ResDbgPrintf
PURPOSE: Handle stdio output.
PARAMETERS: Same as printf().
RETURNS: None.
======================================================= */
RES_EXPORT void ResDbgPrintf(char * msg, ...)
{
va_list data; /* c sucks */
char buffer[255];
int length;
va_start(data, msg); /* init variable args */
length = vsprintf(buffer, msg, data);
if (RES_DEBUG_OPEN_LOG and RES_DEBUG_LOGGING)
_write(RES_DEBUG_FILE, buffer, length);
#ifdef RES_DEBUG_STDIO
RES_DEBUG_STDIO(buffer, length); /* external func for dumping text msg's to the console */
#endif /*RES_DEBUG_STDIO */
va_end(data); /* reset variable args */
}
/* =======================================================
FUNCTION: ResDbgLogPause
PURPOSE: Sets the state of event logging ( a log
file obviously must already be opened).
PARAMETERS: None.
RETURNS: TRUE (pass) / FALSE (fail).
======================================================= */
RES_EXPORT void ResDbgLogPause(int on)
{
RES_DEBUG_LOGGING = on;
}
/* =======================================================
FUNCTION: ResDbgLogDump
PURPOSE: Dump statistics to the log file.
PARAMETERS: None.
RETURNS: None.
======================================================= */
RES_EXPORT void ResDbgDump(void)
{
HASH_TABLE * table;
DEVICE_ENTRY * dev;
LIST * list;
int i;
if (RES_DEBUG_LOGGING and RES_DEBUG_OPEN_LOG)
{
IF_LOG(LOG("\n\n-------------\n"));
IF_LOG(LOG("Statistics...\n"));
IF_LOG(LOG("-------------\n"));
for (list = GLOBAL_PATH_LIST; list; list = list -> next)
{
table = (HASH_TABLE *)list -> node;
dbg_analyze_hash(table);
dbg_dir(table);
}
dev = RES_DEVICES;
for (i = 0; i < MAX_DEVICES; i++)
if (dev -> serial)
dbg_device(dev++);
}
else
IF_LOG(LOG("Either no open log file, or event logging paused.\n"));
}
#endif /* RES_DEBUG_VERSION */
/* -----------------------------------------------------------------------
-----------------------------------------------------------------------
R E S O U R C E M A N A G E R * P R I V A T E F U N C T I O N S
-----------------------------------------------------------------------
----------------------------------------------------------------------- */
/* =======================================================
FUNCTION: asynch_write (local only) THREAD FUNCTION
PURPOSE: Asynchronously write to a file.
PARAMETERS: Thread data (ASYNCH_DATA struct).
RETURNS: None. (callback on completion)
======================================================= */
void
asynch_write(void * thread_data)
{
int check;
ASYNCH_DATA * data;
data = (ASYNCH_DATA *)thread_data;
check = _write(data->file, data->buffer, data->size);
if (data->callback)
(*(data->callback))(data->file);
#ifdef USE_SH_POOLS
MemFreePtr(data);
#else
MemFree(data);
#endif
IF_LOG(LOG("Write thread exited."));
}
/* =======================================================
FUNCTION: asynch_read (local only) THREAD FUNCTION
PURPOSE: Asynchronously write to a file.
PARAMETERS: Thread data (ASYNCH_DATA struct).
RETURNS: None. (callback on completion)
======================================================= */
void
asynch_read(void * thread_data)
{
ASYNCH_DATA * data;
data = (ASYNCH_DATA *)thread_data;
_read(data->file, data->buffer, data->size);
if (data->callback)
(*(data->callback))(data->file);
#ifdef USE_SH_POOLS
MemFreePtr(data);
#else
MemFree(data);
#endif
IF_LOG(LOG("Read thread exited."));
}
/* =======================================================
FUNCTION: shut_down
PURPOSE: Shut down the resource manager. Since
the user is allowed to re-ResInit the
manager, this function is called by both
ResInit and ResExit.
PARAMETERS: None.
RETURNS: None.
======================================================= */
void shut_down(void)
{
LIST * list;
int index;
/* Reset system paths. The paths were stored with strdup, so we
free them here. */
for (index = 0; index < RES_DIR_LAST; index++)
if (RES_PATH[ index ])
#ifdef USE_SH_POOLS
MemFreePtr(RES_PATH[ index ]);
#else
MemFree(RES_PATH[ index ]);
#endif
if (GLOBAL_SEARCH_INDEX)
for (index = 0; index < GLOBAL_SEARCH_INDEX; index++)
#ifdef USE_SH_POOLS
MemFreePtr(GLOBAL_SEARCH_PATH[ index ]);
#else
MemFree(GLOBAL_SEARCH_PATH[ index ]);
#endif
memset(GLOBAL_SEARCH_PATH, 0, sizeof(GLOBAL_SEARCH_PATH));
GLOBAL_SEARCH_INDEX = 0;
memset(RES_PATH, 0, sizeof(char*) * RES_DIR_LAST); /* reset system paths */
/* If there are any files that are still open (regardless of whether the
media has been ejected by the user or not) allocations will still
exist. Close any of them here. */
if (FILE_HANDLES) /* close any open file handles, clear for heck of it */
{
for (index = 0; index < MAX_FILE_HANDLES; index++)
if (FILE_HANDLES[ index ].os_handle not_eq -1)
ResCloseFile(index);
#ifdef USE_SH_POOLS
MemFreePtr(FILE_HANDLES);
#else
MemFree(FILE_HANDLES);
#endif
FILE_HANDLES = NULL;
}
/* If there are any archive files that haven't been closed, do
so now. */
if (ARCHIVE_LIST)
{
for (list = ARCHIVE_LIST; list; list = list -> next)
res_detach_ex((ARCHIVE *)list -> node);
LIST_DESTROY(ARCHIVE_LIST, NULL);
//UGGH --> Why won't this compile? LIST_DESTROY( ARCHIVE_LIST, res_detach_ex );
ARCHIVE_LIST = NULL;
inflate_free();
}
#if( RES_DEBUG_VERSION )
/* If you've called any ResOpenDirectory()'s without calling the
destructor ResCloseDirectory, the debug version takes care of
it for you. Do this using the Release version and you'll
leak. */
if (OPEN_DIR_LIST)
{
RES_DIR * dir;
for (list = OPEN_DIR_LIST; list; list = list -> next)
{
dir = (RES_DIR *)list -> node;
ResCloseDirectory(dir);
IF_LOG(LOG("directory leak prevented: %s\n", dir -> name));
}
LIST_DESTROY(OPEN_DIR_LIST, NULL);
OPEN_DIR_LIST = NULL;
}
#endif /* RES_DEBUG_VERSION */
if (RES_DEVICES)
#ifdef USE_SH_POOLS
MemFreePtr(RES_DEVICES);
#else
MemFree(RES_DEVICES);
#endif
RES_DEVICES = NULL;
if (GLOBAL_PATH_LIST)
{
for (list = GLOBAL_PATH_LIST; list; list = list -> next)
hash_destroy((HASH_TABLE *)list -> node);
LIST_DESTROY(GLOBAL_PATH_LIST, NULL);
GLOBAL_PATH_LIST = NULL;
}
if (GLOBAL_HASH_TABLE)
{
hash_destroy(GLOBAL_HASH_TABLE);
GLOBAL_HASH_TABLE = NULL;
}
}
/* =======================================================
FUNCTION: get_dir_index
PURPOSE: Returns the path index given a path name.
PARAMETERS: Pathname.
RETURNS: Index or -1 if not found.
======================================================= */
int get_dir_index(char * path)
{
int dir_index;
for (dir_index = 0; dir_index < GLOBAL_SEARCH_INDEX; dir_index++)
{
if ( not stricmp(path, GLOBAL_SEARCH_PATH[ dir_index ]))
return(dir_index);
}
return(-1);
}
/* =======================================================
FUNCTION: sort_path
PURPOSE: Force cd based paths to be at the end of
the search path.
PARAMETERS: None.
RETURNS: None.
NOTE: Given a path similar to: (c-hard drive, f-cd)
c:\game\
f:\game\objects\
c:\
f:\game\data
f:\
c:\game\sound\
New path would be
c:\game\
c:\
c:\game\sound\
f:\game\objects\
f:\game\data
f:\
None of the members are sub-sorted.
======================================================= */
void sort_path(void)
{
char cd_id;
HASH_TABLE * ht;
LIST * hd_list = NULL,
* cd_list = NULL;
LIST * list;
cd_id = (char)(GLOBAL_CD_DEVICE + 'A');
/* ugly - look at the first character in the pathname to
determine which volume is referenced. If this volume
is the CD-drive, subjigate this to the cd list. The
new search path is hard-drive list + cd list. */
for (list = GLOBAL_PATH_LIST; list; list = list -> next)
{
ht = (HASH_TABLE *)list -> node;
if (cd_id == toupper(ht -> name[0]))
cd_list = LIST_APPEND_END(cd_list, ht);
else
hd_list = LIST_APPEND_END(hd_list, ht);
}
LIST_DESTROY(GLOBAL_PATH_LIST, NULL);
GLOBAL_PATH_LIST = LIST_CATENATE(hd_list, cd_list);
}
/* =======================================================
FUNCTION: res_detach_ex
PURPOSE: Closes an open archive file (zip).
PARAMETERS: Ptr to an archive.
RETURNS: None.
======================================================= */
void res_detach_ex(ARCHIVE * archive)
{
HASH_ENTRY * entry;
int i;
#if( not RES_USE_FLAT_MODEL )
HASH_TABLE * table;
for (i = 0; i < archive -> num_entries; i++)
{
entry = hash_find_table(&archive -> name[i], &table);
if ( not entry)
{
SAY_ERROR(RES_ERR_FILE_NOT_FOUND, &archive -> name[i]);
continue;
}
if (((ARCHIVE*)entry -> archive) -> os_handle == archive -> os_handle) /* make sure the entry wasn't overridden */
hash_delete(entry, table);
}
#else
for (i = 0; i < archive -> num_entries; i++)
{
entry = hash_find(&archive -> name[i], GLOBAL_HASH_TABLE);
if ( not entry)
{
SAY_ERROR(RES_ERR_FILE_NOT_FOUND, &archive -> name[i]);
continue;
}
if (((ARCHIVE *)entry -> archive) -> os_handle == archive -> os_handle) /* make sure the entry wasn't overridden */
hash_delete(entry, GLOBAL_HASH_TABLE);
}
#endif /* not USE_FLAT_MODEL */
_close(archive -> os_handle);
DESTROY_LOCK(archive -> lock);
#ifdef USE_SH_POOLS
MemFreePtr(archive);
#else
MemFree(archive);
#endif
}
/* =======================================================
FUNCTION: hash
PURPOSE: Hashing function. This was taken from
Sedgewicks' Algorithms in C.
PARAMS: ASCII string to hash.
RETURNS: Hashed value (guarenteed to be less than
the size of the hash table).
======================================================= */
int hash(const char * string, int size)
{
int i;
#if( USE_SEDGEWICK )
for (i = 0; *string not_eq '\0'; string++)
i = (HASH_CONST * i + (toupper(*string))) % size;
# error DO NOT USE SEDGEWICK - RH
#endif
#if( USE_AFU )
int res = 0;
int pos = 1;
while (*string)
{
res += toupper(*string) * pos;
pos++;
string++;
}
i = (res bitand 0xffffff) % size;
#endif
return(i);
}
#if( USE_AFU and USE_SEDGEWICK )
# error You cannot use both hashing algorithms
#endif /* USE_BOTH? */
/* =======================================================
FUNCTION: hash_create
PURPOSE: Create a hash table. The hash table used
to be allocated with the wrapper, and the
table ptr set to be base + sizeof(wrapper),
but this made RESIZE difficult.
PARAMS: Size of hash table to create.
RETURNS: Ptr to a hash structure.
======================================================= */
HASH_TABLE * hash_create(int size, char * name)
{
HASH_TABLE * hsh;
char * string_space;
int sizeb;
#ifdef USE_SH_POOLS
hsh = (HASH_TABLE *)MemAllocPtr(gResmgrMemPool, sizeof(HASH_TABLE), 0);
#else
hsh = (HASH_TABLE *)MemMalloc(sizeof(HASH_TABLE), "Hash wrapper");
#endif
if ( not hsh)
{
SAY_ERROR(RES_ERR_NO_MEMORY, "hash_create");
return(NULL);
}
#ifdef USE_SH_POOLS
hsh -> table = (HASH_ENTRY *)MemAllocPtr(gResmgrMemPool, size * sizeof(HASH_ENTRY), 0);
#else
hsh -> table = (HASH_ENTRY *)MemMalloc(size * sizeof(HASH_ENTRY), name);
#endif
if ( not hsh -> table)
{
SAY_ERROR(RES_ERR_NO_MEMORY, "hash_create");
return(NULL);
}
memset(hsh -> table, 0, size * sizeof(HASH_ENTRY));
sizeb = size * MAX_FILENAME;
#ifdef USE_SH_POOLS
string_space = (char *)MemAllocPtr(gResmgrMemPool, sizeb, 0);
#else
string_space = (char *)MemMalloc(sizeb, "Strings");
#endif
if ( not string_space)
{
SAY_ERROR(RES_ERR_NO_MEMORY, "hash_create");
return(NULL);
}
hsh -> table_size = size;
hsh -> num_entries = 0;
hsh -> ptr_in = string_space;
size = (int)(STRING_SAFETY_SIZE * (float)sizeb); /* safety buffer on string pool */
hsh -> ptr_end = string_space + size;
hsh -> str_list = NULL;
hsh -> str_list = LIST_APPEND(hsh->str_list, string_space);
hsh -> name = hash_strcpy(hsh, name);
return(hsh);
}
/* =======================================================
FUNCTION: hash_destroy
PURPOSE: Destroy an entire hash table.
PARAMS: Ptr to a hash table structure.
RETURNS: None.
======================================================= */
void hash_destroy(HASH_TABLE * hsh)
{
int index;
HASH_ENTRY * entry,
* prev,
* curr;
for (index = 0; index < hsh -> table_size; index++)
{
entry = &hsh -> table[index];
entry -> attrib = 0;
if ( not entry -> next)
continue;
prev = entry -> next;
curr = prev -> next;
while (curr)
{
#ifdef USE_SH_POOLS
MemFreePtr(prev);
#else
MemFree(prev);
#endif
prev = curr;
curr = curr -> next;
}
#ifdef USE_SH_POOLS
MemFreePtr(prev);
#else
MemFree(prev);
#endif
}
#if( RES_DEBUG_VERSION )
hsh -> num_entries = 0;
hsh -> table_size = 0;
#endif
#ifdef USE_SH_POOLS
LIST_DESTROY(hsh->str_list, free);
#else
LIST_DESTROY(hsh->str_list, MemFreePtr);
#endif
#ifdef USE_SH_POOLS
MemFreePtr(hsh -> table);
MemFreePtr(hsh);
#else
MemFree(hsh -> table);
MemFree(hsh);
#endif
}
char * hash_strcpy(HASH_TABLE * hsh, char * string)
{
char * string_space;
char * ptr_out;
int size;
ptr_out = hsh -> ptr_in;
strcpy(hsh -> ptr_in, string);
hsh -> ptr_in += strlen(string);
*hsh -> ptr_in = '\0'; /*safety*/
hsh -> ptr_in++;
if (hsh -> ptr_in > hsh -> ptr_end)
{
size = HASH_TABLE_SIZE * MAX_FILENAME;
#ifdef USE_SH_POOLS
string_space = (char *)MemAllocPtr(gResmgrMemPool, size, 0);
#else
string_space = (char *)MemMalloc(size, "Strings");
#endif
hsh -> str_list = LIST_APPEND(hsh -> str_list, string_space);
hsh -> ptr_in = string_space;
size = (int)((float)STRING_SAFETY_SIZE * (float)size);
hsh -> ptr_end = string_space + size;
}
return(ptr_out);
}
/* =======================================================
FUNCTION: hash_add
PURPOSE: Add an entry into a hash table.
PARAMS: Ptr to a file data structure, ptr to a
hash table wrapper struct.
RETURNS: Ptr to the hash entry.
======================================================= */
HASH_ENTRY * hash_add(struct _finddata_t * data, HASH_TABLE * hsh)
{
int hash_val;
HASH_ENTRY * entry = NULL;
/* If we need to do a resize, we want to do it when there
are no HASH_ENTRY pointers being used. Currently, the
HASH_TABLE is NOT being checked for a lock before
a resize is performed. This is not safe. */
/* Resize before searching (and returning) a HASH_ENTRY ptr */
if (hsh -> num_entries)
{
/* efficiency ratio of the hash table (entries/num slots) */
float ratio = ((float)hsh -> table_size / (float)hsh -> num_entries);
if (ratio < HASH_MINIMAL_RATIO)
hash_resize(hsh); /* WARNING: THIS IS STILL NOT THREAD SAFE */
}
hash_val = hash(data -> name, hsh -> table_size);
if (hsh -> table[ hash_val ].attrib) /* an entry already exists here */
{
#if( RES_USE_FLAT_MODEL )
entry = hash_find(data -> name, hsh);
if (entry) /* override automatically if this is the flat model */
{
IF_LOG(LOG("Override %s\n", data -> name));
entry -> name = hash_strcpy(hsh, data -> name);
entry -> offset = 0;
entry -> size = data -> size;
entry -> attrib = data -> attrib bitor FORCE_BIT; /* FORCE_BIT ensures the field will be non-zero */
/* entry -> next stays the same */
/* hsh -> num_entries stays the same */
return(entry);
}
#endif /* RES_USE_FLAT_MODEL */
entry = &hsh -> table[ hash_val ];
while (entry -> next) /* go to the end of the list */
entry = entry -> next;
#ifdef USE_SH_POOLS
entry -> next = (HASH_ENTRY *)MemAllocPtr(gResmgrMemPool, sizeof(HASH_ENTRY), 0);
#else
entry -> next = (HASH_ENTRY *)MemMalloc(sizeof(HASH_ENTRY), "Hash entry");
#endif
if ( not entry -> next) /* malloc failed */
{
SAY_ERROR(RES_ERR_NO_MEMORY, "hash_add");
return(NULL);
}
memset(entry ->next, 0, sizeof(HASH_ENTRY)); // OW BC
entry = entry -> next;
}
else
{
entry = &hsh -> table[ hash_val ];
}
entry -> name = hash_strcpy(hsh, data -> name);
entry -> offset = 0;
entry -> size = data -> size;
entry -> attrib = data -> attrib bitor FORCE_BIT; /* FORCE_BIT ensures the field will be non-zero */
entry -> next = NULL;
entry -> archive = -1; // Changed on AUG30th [KBR]
#if( not RES_USE_FLAT_MODEL )
entry -> dir = NULL;
#endif /* not RES_USE_FLAT_MODEL */
hsh -> num_entries++;
return(entry);
}
/* =======================================================
FUNCTION: hash_copy
PURPOSE: Save some typing.
PARAMS: Ptr to a source HASH_ENTRY, ptr to
a destination HASH_ENTRY.
RETURNS: True / False. False implies error.
======================================================= */
void hash_copy(HASH_ENTRY * dst, HASH_ENTRY * src)
{
if (dst -> attrib)
{
while (dst -> next) /* go to the end of the list */
dst = dst -> next;
#ifdef USE_SH_POOLS
dst -> next = (HASH_ENTRY *)MemAllocPtr(gResmgrMemPool, sizeof(HASH_ENTRY), 0);
#else
dst -> next = (HASH_ENTRY *)MemMalloc(sizeof(HASH_ENTRY), "Hash entry");
#endif
if (dst->next) memset(dst->next, 0, sizeof(HASH_ENTRY)); // OW BC
dst = dst -> next;
}
dst -> name = src -> name;
dst -> offset = src -> offset;
dst -> size = src -> size;
dst -> csize = src -> csize;
dst -> method = src -> method;
dst -> volume = src -> volume;
dst -> directory = src -> directory;
dst -> file_position = src -> file_position;
dst -> archive = src -> archive;
dst -> attrib = src -> attrib;
dst -> dir = src -> dir;
dst -> next = NULL;
}
/* =======================================================
FUNCTION: hash_resize
PURPOSE: Resize a hash table. This is
unfortunately, not a trivial task. All
entries in the original table must be
rehashed into the new table since
altering the size dramatically alters
the hash algorithm.
PARAMS: Ptr to a hash table wrapper struct.
RETURNS: True / False. False implies error.
======================================================= */
int hash_resize(HASH_TABLE * hsh)
{
int size;
int i, val;
HASH_ENTRY * entry;
HASH_ENTRY * src,
* dst,
* prev;
IF_LOG(LOG("resizing hash table %s\n", hsh -> name));
/* calc the size of the new hash table */
size = (int)((float)hsh -> num_entries * HASH_OPTIMAL_RATIO);
/* create the new hash entries */
#ifdef USE_SH_POOLS
entry = (HASH_ENTRY *)MemAllocPtr(gResmgrMemPool, size * sizeof(HASH_ENTRY), 0);
#else
entry = (HASH_ENTRY *)MemMalloc(size * sizeof(HASH_ENTRY), "Hash resized");
#endif
if ( not entry)
{
SAY_ERROR(RES_ERR_NO_MEMORY, "hash_resize");
return(FALSE);
}
memset(entry, 0, size * sizeof(HASH_ENTRY));
/* we have to rehash ALL of the entries in the old table into the new table */
for (i = 0; i < hsh -> table_size; i++)
{
src = &hsh -> table[i];
if (src -> attrib)
{
val = hash(src -> name, size);
dst = &entry[ val ];
hash_copy(dst, src);
}
if (src -> next)
{
for (src = src -> next; src; src = src -> next)
{
val = hash(src -> name, size);
dst = &entry[ val ];
hash_copy(dst, src);
}
}
}
for (i = 0; i < hsh -> table_size; i++)
{
src = &hsh -> table[i];
src -> attrib = 0;
if ( not src -> next)
continue;
prev = src -> next;
dst = prev -> next;
while (dst)
{
prev -> next = NULL;
#ifdef USE_SH_POOLS
MemFreePtr(prev);
#else
MemFree(prev);
#endif
prev = dst;
dst = dst -> next;
}
#ifdef USE_SH_POOLS
MemFreePtr(prev);
#else
MemFree(prev);
#endif
src -> next = NULL;
}
#ifdef USE_SH_POOLS
MemFreePtr(hsh->table);
#else
MemFree(hsh->table);
#endif
hsh -> table_size = size;
hsh -> table = entry;
return(TRUE);
}
/* =======================================================
FUNCTION: hash_find
PURPOSE: Find an entry within a hash table.
PARAMS: Ptr to a filename to find, ptr to a hash
table wrapper struct.
RETURNS: Ptr to the found entry or NULL (if not found).
======================================================= */
HASH_ENTRY * hash_find(const char * name, HASH_TABLE * hsh)
{
int hash_val;
HASH_ENTRY * entry;
if ( not GLOBAL_HASH_TABLE)
return(NULL);
hash_val = hash(name, hsh -> table_size); /* calc the hash value for the given string */
if ( not hsh -> table[ hash_val ].attrib) /* no hash entry found */
return(NULL);
if (hsh -> table[ hash_val ].next == NULL)
if ( not stricmp(hsh -> table[ hash_val ].name, name))
return(&hsh -> table[ hash_val ]); /* just one entry found in the hash position */
/* found imperfect hash entry */
for (entry = &hsh -> table[ hash_val ]; entry; entry = entry -> next)
if ( not stricmp(entry -> name, name))
return(entry); /* assumes only one occurrence of a given name */
return(NULL); /* not found */
}
/* =======================================================
FUNCTION: hash_delete
PURPOSE: Removes an entry from a hash table.
PARAMS: Ptr to a file data structure, ptr to a
hash table wrapper.
RETURNS: None.
======================================================= */
int hash_delete(HASH_ENTRY * hash_entry, HASH_TABLE * hsh)
{
int i;
HASH_ENTRY * entry,
* prev;
if (hash_entry -> dir)
hash_destroy((HASH_TABLE *)hash_entry -> dir);
for (i = 0; i < hsh -> table_size; i++)
{
entry = &hsh -> table[i];
if (entry == hash_entry)
{
if (hash_entry -> next) /* pop the chain of hash collisions */
{
entry = hash_entry -> next;
memcpy(hash_entry, entry, sizeof(HASH_ENTRY));
#ifdef USE_SH_POOLS
MemFreePtr(entry);
#else
MemFree(entry);
#endif
hsh -> num_entries--;
}
else
{
entry -> attrib = 0; /* no chain to pop. just flag this entry as being empty */
hsh -> num_entries--;
}
return(TRUE);
}
if (entry -> next) /* look for hash entry on a chain */
{
prev = entry;
entry = entry -> next;
while (entry)
{
if (entry == hash_entry)
{
prev -> next = entry -> next; /* cut from chain */
#ifdef USE_SH_POOLS
MemFreePtr(entry);
#else
MemFree(entry);
#endif
hsh -> num_entries--;
return(TRUE);
}
prev = entry;
entry = entry -> next;
}
}
}
return(FALSE);
}
/* =======================================================
FUNCTION: hash_purge
PURPOSE: Purge entries from a single hash table
based on identical archive handle, volume
id, and/or directory handle.
PARAMETERS: Ptr to archive handle, volume id,
directory handle and filename.
Pass NULL for any unused parameter.
RETURNS: None.
======================================================= */
//void hash_purge( HASH_TABLE * hsh, char * archive, char * volume, char * directory, char * filename )
void hash_purge(HASH_TABLE * hsh, const char * archive, const char * volume, const int * directory, const char * filename)
{
int index;
HASH_ENTRY * entry,
* prev,
* curr;
if (archive)
{
IF_LOG(LOG("purging entries from archive %d\n", *archive));
}
if (volume)
{
IF_LOG(LOG("purging entries from volume %d\n", *volume));
}
if (directory)
{
IF_LOG(LOG("purging entries from directory %d\n", *directory));
}
if (filename)
{
IF_LOG(LOG("purging entries named %s\n", filename));
}
for (index = 0; index < hsh -> table_size; index++)
{
entry = &hsh -> table[ index ];
if ( not entry -> attrib)
continue; /* empty hash entry */
if (entry -> next)
{
prev = entry;
curr = entry -> next;
while (curr)
{
if ((volume and (curr -> volume == *volume)) or
(archive and (curr -> archive == *archive)) or
(directory and (curr -> directory == *directory)) or
(filename and not strcmp(entry -> name, filename)))
{
if (curr -> dir)
hash_destroy((HASH_TABLE*)prev -> dir);
prev -> next = curr -> next;
#ifdef USE_SH_POOLS
MemFreePtr(curr);
#else
MemFree(curr);
#endif
}
else
prev = curr;
curr = prev -> next;
}
}
if ((volume and (entry -> volume == *volume)) or
(archive and (entry -> archive == *archive)) or
(directory and (entry -> directory == *directory)) or
(filename and not strcmp(entry -> name, filename)))
{
if (entry -> dir)
{
hash_destroy((HASH_TABLE *)entry -> dir);
entry -> dir = NULL;
}
if (entry -> next)
{
prev = entry -> next;
memcpy(entry, prev, sizeof(HASH_ENTRY));
if (prev -> dir)
hash_destroy((HASH_TABLE *)prev -> dir); // navio: (408)328-0630
entry -> next = prev -> next;
#ifdef USE_SH_POOLS
MemFreePtr(prev);
#else
MemFree(prev);
#endif
}
else
{
entry -> attrib = 0;
if (entry -> dir)
{
hash_destroy((HASH_TABLE *) entry -> dir);
entry -> dir = NULL;
}
}
}
}
}
/* =======================================================
FUNCTION: hash_find_table (local only)
PURPOSE: Find a file wherever it exist.
PARAMETERS: Filename with or without path, ptr to
a hash table ptr. The last parameter
can be NULL if this information is not
needed.
RETURNS: Ptr to an entry from the hash table, or
NULL if file not found or error
encountered.
======================================================= */
HASH_ENTRY * hash_find_table(const char * name, HASH_TABLE ** table)
{
int path_used = FALSE,
wild_path = FALSE;
HASH_TABLE * ht = NULL;
int wild_len = 0,
len = 0,
i;
char fullpath[ _MAX_PATH ] = {0},
filename[ _MAX_FNAME ] = {0};
HASH_ENTRY * entry = NULL;
#if( not RES_USE_FLAT_MODEL )
LIST * list = NULL;
#endif /* not RES_USE_FLAT_MODEL */
if ( not GLOBAL_HASH_TABLE)
return(NULL);
#if( RES_WILDCARD_PATHS )
/* wildcard directory */
/* wild carding a directory means that you can specify a neo-absolute path. Where
an absolute path is really a shortcut to typing a path relative to your current
working directory, wildcarding a path allows you to specify a branch from a directory
tree, and that you want to look for files in a file in all directories that have
the same branch. For instance,
given this:
*\objects\foo.dat
all of these would be found:
c:\game\install\objects\foo.dat
f:\objects\foo.dat
<archive>\data\objects\foo.dat
Obviously this is primarily to find files that can be found on multiple volumes,
rather than multiple locations on one volume. The other way of doing this would
have been to simply leave the volume identifier out of the hash lookup function.
This however, would have made it impossible to explicitly specify a volume to
differentiate between two files. */
/* It may not be a good idea to implement this here (at a point so low in the code).
I haven't made up my mind yet whether this should be done at a higher level
(like the way unix expands argv[] wildcards) or whether it should be so
cancerously ingrained here. For now, here it goes. */
if (name[0] == ASCII_ASTERISK)
{
/* strip the filename out of 'name' and then stuff what path information we
do have into fullpath. 'wild_len' is the number of characters that we will
compare of each of the directory entries in our search path with the path
we have here. */
wild_path = TRUE;
path_used = TRUE;
name++;
strcpy(fullpath, name);
wild_len = strlen(name);
for (wild_len; (name[wild_len] not_eq ASCII_BACKSLASH) and wild_len; wild_len--) ;
if (wild_len)
{
strcpy(filename, &name[ wild_len + 1 ]);
fullpath[wild_len + 1] = 0x00;
}
else
return(NULL); /* improper use of wildcard directory */
}
#endif /* RES_WILDCARD_PATHS */
/* check to see if a directory name is specified */
if ( not wild_path and (strchr(name, ASCII_BACKSLASH) or (name[0] == ASCII_DOT)))
{
/* utterly non-portable */
/* create a full path name from what could be a partial path */
if (res_fullpath(fullpath, name, _MAX_PATH) == NULL)
{
SAY_ERROR(RES_ERR_CANT_INTERPRET, name);
return(NULL);
}
/* split the full path name into components */
len = strlen(fullpath);
for (i = len; i >= 0; i--)
{
if (fullpath[i] == ASCII_BACKSLASH)
{
strcpy(filename, &fullpath[i + 1]);
fullpath[i + 1] = 0x00;
break;
}
}
#if( RES_USE_FLAT_MODEL )
if (filename[0] == 0x00)
{
SAY_ERROR(RES_ERR_CANT_INTERPRET, name);
if (table)
*table = NULL;
return(NULL);
}
#endif /* RES_USE_FLAT_MODEL */
path_used = TRUE;
}
#if( not RES_USE_FLAT_MODEL ) /* HIERARCHICAL MODEL */
if (path_used)
{
#if( RES_WILDCARD_PATHS )
if (wild_path)
{
for (list = GLOBAL_PATH_LIST; list; list = list -> next)
{
ht = (HASH_TABLE *)list -> node;
len = strlen(ht -> name);
if (wild_len > len)
continue;
if ( not strnicmp(&ht -> name[ len - wild_len - 1 ], fullpath, wild_len))
{
entry = hash_find(filename, ht);
if (table)
*table = ht;
if (entry)
return(entry);
}
}
if (table)
*table = NULL;
return(NULL);
}
else
{
#endif /* RES_WILDCARD_PATHS */
entry = hash_find(fullpath, GLOBAL_HASH_TABLE);
if (entry)
{
if (entry -> dir)
{
if (table)
*table = (HASH_TABLE *)entry -> dir;
return(hash_find(filename, (HASH_TABLE *)entry -> dir));
}
}
else
{
if (table)
*table = NULL;
return(NULL);
}
}
}
else /* path_used == FALSE */
{
/* look in order */
for (list = GLOBAL_PATH_LIST; list; list = list -> next)
{
entry = hash_find(name, (HASH_TABLE *)list -> node);
if (entry)
{
if (table)
*table = (HASH_TABLE *)list -> node;
return(entry);
}
}
if (table)
*table = NULL;
return(NULL);
}
#else /* not RES_USE_FLAT_MODEL */
if (path_used)
entry = hash_find(filename, GLOBAL_HASH_TABLE);
else
entry = hash_find(name, GLOBAL_HASH_TABLE);
if ( not entry)
{
if (table)
*table = NULL;
}
else if (table)
*table = GLOBAL_HASH_TABLE;
return(entry);
#endif
if (table)
*table = NULL;
return(NULL);
}
/* =======================================================
FUNCTION: get_handle
PURPOSE: Returns the next available file handle.
PARAMS: None.
RETURNS: File handle or -1 on an error.
======================================================= */
int get_handle(void)
{
int i;
for (i = 0; i < MAX_FILE_HANDLES; i++)
if (FILE_HANDLES[i].os_handle == -1)
return(i);
return(-1);
}
/* =======================================================
FUNCTION: split_handle
PURPOSE: Returns the filename and the path for
a given full file desription.
PARAMS: Full filename (path bitand filename), ptr to
a buffer for filename, ptr to a buffer
for path.
RETURNS: None.
NOTES: Ex: c:\object\ships\klingon.dat yeilds
filename = klingon.dat
path = c:\object\ships\
======================================================= */
void split_path(const char * in_name, char * out_filename, char * out_dirpath)
{
char fullpath[ _MAX_PATH ];
int len,
i;
if (res_fullpath(fullpath, in_name, _MAX_PATH) == NULL)
{
if (out_filename) *out_filename = '\0';
if (out_dirpath) *out_dirpath = '\0';
return;
}
len = strlen(fullpath);
for (i = len; i >= 0; i--)
{
if ((fullpath[i] == ASCII_BACKSLASH) or
(fullpath[i] == ASCII_COLON))
{
if (out_filename) strcpy(out_filename, &fullpath[i + 1]);
fullpath[i + 1] = 0x00;
if (out_dirpath) strcpy(out_dirpath, fullpath);
return;
}
}
if (out_filename) strcpy(out_filename, fullpath);
if (out_dirpath) *out_dirpath = '\0';
}
/* =======================================================
FUNCTION: say_error (local only bitand debug only)
PURPOSE: Display dialog box with error message.
PARAMETERS: Error number, optional string.
RETURNS: None.
======================================================= */
#if( RES_DEBUG_VERSION )
void _say_error(int error, const char * msg, int line, const char * filename)
{
int err_code;
char buffer[ 255 ];
char title[] = "Resource Manager Error";
char blank[] = "???";
int retval = 1;
IF_LOG(LOG("ERROR (line: %d file: %s):\n", line, filename));
if ( not msg)
msg = blank;
RES_DEBUG_ERRNO = error; /* set the equiv. of an errno */
err_code = error;
switch (error)
{
/* from erno.h */
case EACCES:
sprintf(buffer, "Tried to open read-only file (%s) for writing.", msg);
break;
case EEXIST:
sprintf(buffer, "Create flag specified, but filename (%s) already exists.", msg);
break;
case ENOENT:
sprintf(buffer, "File or path not found. (%s).", msg);
break;
default: /* an error that is specific to this file */
if ((error > RES_ERR_FIRST_ERROR) and (error < RES_ERR_LAST_ERROR))
{
/* error values run from -5000 up, so error will always be negative,
and so will (RES_ERR_OR_FIRST+1). We want to normalize this to
0,1,2,3... */
error = error + (-RES_ERR_FIRST_ERROR - 1);
sprintf(buffer, "%s (%s)\n\n\nFile: %s\nLine: %d", RES_ERR_OR_MSGS[ error ], msg, filename, line);
}
else
{
sprintf(buffer, "Unknown error encountered with file. (%s)\n\n\nFile: %s\nLine: %d\n", msg, filename, line);
}
}
IF_LOG(LOG("---> %s\n", buffer));
SHOULD_I_CALL_WITH(CALLBACK_ERROR, err_code, retval);
// MessageBox( NULL, buffer, title, MB_OK bitor MB_ICONEXCLAMATION );
if ( not retval)
MessageBox(RES_GLOBAL_HWND, buffer, title, MB_OK bitor MB_ICONEXCLAMATION);
}
/* =======================================================
FUNCTION: dbg_print
PURPOSE: Print a familiar looking file description.
PARAMS: Ptr to a file data structure.
RETURNS: None.
======================================================= */
void dbg_print(HASH_ENTRY * data)
{
int attrib;
attrib = data -> attrib;
printf("%-17s", data -> name);
printf("size: %5d ", data -> size);
printf("csize: %5d ", data -> csize);
printf("method: %1d ", data -> method);
if (attrib bitand _A_RDONLY) printf("R");
else printf(" ");
if (attrib bitand _A_HIDDEN) printf("H");
else printf(" ");
if (attrib bitand _A_SYSTEM) printf("S");
else printf(" ");
if (attrib bitand _A_ARCH) printf("A");
else printf(" ");
if (attrib bitand _A_SUBDIR) printf("\t\t<DIR>");
else printf("\t\t ");
printf("\n");
}
/* =======================================================
FUNCTION: dbg_device
PURPOSE: Print a device description.
PARAMS: Ptr to a device structure.
RETURNS: None.
======================================================= */
void dbg_device(DEVICE_ENTRY * dev)
{
IF_LOG(LOG("Drive letter: %c\n", dev -> letter));
IF_LOG(LOG("Volume name: %s\n", dev -> name));
IF_LOG(LOG("Serial num: %x-%x\n", HI_WORD(dev->serial), LO_WORD(dev -> serial)));
IF_LOG(LOG("Type: [%d] ", dev -> type));
switch (dev -> type)
{
case 1:
IF_LOG(LOG("The root directory does not exist.\n"));
break;
case DRIVE_REMOVABLE:
IF_LOG(LOG("The drive can be removed from the drive.\n"));
break;
case DRIVE_FIXED:
IF_LOG(LOG("The disk cannot be removed from the drive.\n"));
break;
case DRIVE_REMOTE:
IF_LOG(LOG("The drive is a remote (network) drive.\n"));
break;
case DRIVE_CDROM:
IF_LOG(LOG("The drive is a CD-ROM drive.\n"));
break;
case DRIVE_RAMDISK:
IF_LOG(LOG("The drive is a RAM disk.\n"));
break;
case 0:
default:
IF_LOG(LOG("The drive type cannot be determined.\n"));
}
IF_LOG(LOG("----------------\n"));
}
/* =======================================================
FUNCTION: dbg_analyze_hash
PURPOSE: Print statistics regarding hash
performance bitand contents
PARAMS: Ptr to a hash table wrapper structure.
RETURNS: None.
======================================================= */
void dbg_analyze_hash(HASH_TABLE * hsh)
{
int i,
len,
max_len,
hits = 0;
HASH_ENTRY * entry;
IF_LOG(LOG("Table name............. %s\n", hsh -> name));
IF_LOG(LOG("Hash size.............. %d\n", hsh -> table_size));
IF_LOG(LOG("Num entries............ %d\n", hsh -> num_entries));
IF_LOG(LOG("Ratio.................. %-3.0f%%\n", ((float)hsh -> table_size / (float)hsh -> num_entries) * 100.0));
max_len = 0;
for (i = 0; i < hsh->table_size; i++)
{
if (hsh -> table[i].next)
{
hits++;
entry = &hsh -> table[i];
len = 0;
while (entry)
{
entry = entry -> next;
len++;
}
if (len > max_len)
max_len = len;
}
}
IF_LOG(LOG("Hash collisions........ %d\n", hits));
IF_LOG(LOG("Hash peformance........ %-3.0f%%\n", (1.0 - ((float)hits / (float)hsh->num_entries)) * 100.0));
IF_LOG(LOG("Maximum chain length... %d\n", max_len));
}
/* =======================================================
FUNCTION: dbg_dir
PURPOSE: Print the contents of a directory
PARAMS: Ptr to a hash table wrapper structure.
RETURNS: None.
======================================================= */
void dbg_dir(HASH_TABLE * hsh)
{
int i,
count,
hits = 0;
HASH_ENTRY * entry;
count = 0;
IF_LOG(LOG("\n\n"));
for (i = 0; i < hsh->table_size; i++)
{
if (hsh -> table[i].next)
{
hits++;
entry = &hsh -> table[i];
while (entry)
{
IF_LOG(LOG("%-14s ", entry -> name));
count++;
if ( not (count % 4)) IF_LOG(LOG("\n"));
entry = entry -> next;
}
}
else if (hsh -> table[i].attrib)
{
IF_LOG(LOG("%-14s ", hsh -> table[i].name));
count++;
if ( not (count % 4)) IF_LOG(LOG("\n"));
}
}
IF_LOG(LOG("\n\n"));
}
#endif /* RES_DEBUG_VERSION */
/* -----------------------------------------------------------------------
Unfortunately there was a pathologic problem using the VC++ runtime
function _fullpath(). If you attach an archive to a virtual attach
point, and then try to open the file using a relative pathname, and
have RES_COERCE_FILENAMES true, you would always get File Not Found.
This fixes the problem, however I am worried about two things:
1) its late.
2) this change affects a lot of functions
Therefore, if things appear flaky define RES_USE_FULLPATH to be
false, and go back to the old way.
NOTE: If you continue using res_fullpath, be advised that current
working directories of OTHER VOLUMES will not be maintained
(eg F:readme.txt will parse to the literal string, not
F:\some_dir\readme.txt). This will not be fixed (I doubt it will
affect anyone anyway).
PS: Five days later and all is well with this function. good sign.
------------------------------------------------------------------------ */
/* =======================================================
FUNCTION: res_fullpath
PURPOSE: Convert relative path names into
absolute path names.
PARAMS: Ptr to a buffer to store the absolute
pathname, ptr to a relative pathname,
maximum length of absolute pathname
(parameter is unused, but I include it
to maintain consistency with _fullpath().
RETURNS: Ptr to abs_buffer or NULL on error.
NOTE: All of these forms are supported:
..\file.ext
\file.ext
..\dir\dir\file.ext
\dir\file.ext
file.ext
c:\dir\file.ext
======================================================= */
char * res_fullpath(char * abs_buffer, const char * rel_buffer, int maxlen)
{
#if( RES_USE_FULLPATH )
char * colon;
char * rel;
char drive[4];
char tmp_buffer[ _MAX_PATH ];
char current_path[ _MAX_PATH ];
int chop = 0,
len,
i;
maxlen;
if ( not GLOBAL_PATH_LIST)
strcpy(current_path, "c:\\");
else
strcpy(current_path, ((HASH_TABLE *)(GLOBAL_PATH_LIST -> node)) -> name);
rel = (char *)rel_buffer;
colon = strchr(rel, ASCII_COLON);
if (colon)
{
if (rel_buffer[1] not_eq ASCII_COLON)
{
*abs_buffer = 0x00;
return(NULL);
}
if ( not strstr(rel_buffer, ".."))
return(strcpy(abs_buffer, rel_buffer));
strncpy(drive, rel_buffer, 2);
drive[2] = ASCII_BACKSLASH;
drive[3] = 0x00;
rel += 2;
}
else
{
strncpy(drive, current_path, 2);
drive[2] = ASCII_BACKSLASH;
drive[3] = 0x00;
if (rel_buffer[0] == ASCII_BACKSLASH)
{
sprintf(abs_buffer, "%s%s", drive, &rel_buffer[1]);
return(abs_buffer);
}
}
if (*rel == ASCII_BACKSLASH)
{
sprintf(abs_buffer, "%s%s", drive, rel);
return(abs_buffer);
}
while ( not memcmp(rel, "..", 3))
{
chop++;
rel += 2;
if (*rel == ASCII_BACKSLASH)
*rel++;
}
len = strlen(current_path) - 2;
for (i = len; i and chop; i--)
if (current_path[i] == ASCII_BACKSLASH)
chop--;
if ( not i)
i = 1;
strncpy(tmp_buffer, current_path, i + 2);
strcpy(&tmp_buffer[i + 2], rel);
return(strcpy(abs_buffer, tmp_buffer));
#else
return(_fullpath(abs_path, rel_path, maxlen));
#endif
} | 25.938706 | 155 | 0.524475 | [
"object",
"model"
] |
7c6d2ddef161f0bcb86aa7875e3c8711aafb5962 | 918 | h | C | src/BabylonImGui/include/babylon/inspector/components/actiontabs/pane_component.h | sacceus/BabylonCpp | 94669cf7cbe3214ec6e905cbf249fa0c9daf6222 | [
"Apache-2.0"
] | 277 | 2017-05-18T08:27:10.000Z | 2022-03-26T01:31:37.000Z | src/BabylonImGui/include/babylon/inspector/components/actiontabs/pane_component.h | sacceus/BabylonCpp | 94669cf7cbe3214ec6e905cbf249fa0c9daf6222 | [
"Apache-2.0"
] | 77 | 2017-09-03T15:35:02.000Z | 2022-03-28T18:47:20.000Z | src/BabylonImGui/include/babylon/inspector/components/actiontabs/pane_component.h | sacceus/BabylonCpp | 94669cf7cbe3214ec6e905cbf249fa0c9daf6222 | [
"Apache-2.0"
] | 37 | 2017-03-30T03:36:24.000Z | 2022-01-28T08:28:36.000Z | #ifndef BABYLON_INSPECTOR_COMPONENTS_ACTION_TABS_PANE_COMPONENT_H
#define BABYLON_INSPECTOR_COMPONENTS_ACTION_TABS_PANE_COMPONENT_H
#include <optional>
#include <string>
#include <babylon/babylon_api.h>
#include <babylon/inspector/entity.h>
namespace BABYLON {
struct EntityInfo;
class Scene;
struct BABYLON_SHARED_EXPORT IPaneComponentProps {
std::string title;
std::string icon;
Scene* scene = nullptr;
std::optional<EntityInfo> selectedEntity = std::nullopt;
}; // end of struct IPaneComponentProps
class BABYLON_SHARED_EXPORT PaneComponent {
public:
PaneComponent(const IPaneComponentProps& props);
virtual ~PaneComponent(); // = default
virtual void render() = 0;
protected:
const IPaneComponentProps& props;
}; // end of class PaneComponent
} // end of namespace BABYLON
#endif // end of
// BABYLON_INSPECTOR_COMPONENTS_ACTION_TABS_PANE_COMPONENT_H
| 23.538462 | 67 | 0.760349 | [
"render"
] |
7c75190e0047bd58ffcc73212faadaa902a42125 | 883 | h | C | src/hotkey/hotkey.h | darksworm/hksel | eb998343d01cc37a72e9ec9104cc3d0731f764a9 | [
"MIT"
] | 1 | 2021-08-12T15:44:43.000Z | 2021-08-12T15:44:43.000Z | src/hotkey/hotkey.h | darksworm/hksel | eb998343d01cc37a72e9ec9104cc3d0731f764a9 | [
"MIT"
] | null | null | null | src/hotkey/hotkey.h | darksworm/hksel | eb998343d01cc37a72e9ec9104cc3d0731f764a9 | [
"MIT"
] | null | null | null | #pragma once
#include <utility>
#include <vector>
#include <iostream>
#include <unordered_set>
class Hotkey {
private:
const std::unordered_set<std::string> rawKeyNames;
const std::vector<std::string> tags;
const std::string name;
const std::string description;
public:
const std::unordered_set<std::string> *getKeyCodes() {
return &rawKeyNames;
}
const std::vector<std::string> *getTags() {
return &tags;
}
const std::string getDescription() {
return description;
}
const std::string getName() {
return name;
}
Hotkey(std::unordered_set<std::string> raw_key_names, std::vector<std::string> tags, std::string description,
std::string name)
: rawKeyNames(raw_key_names), tags(std::move(tags)), description(std::move(description)), name(
std::move(name)) {}
}; | 25.228571 | 113 | 0.637599 | [
"vector"
] |
7c7b3fd80a6f1df2a495c3f4fd8ad1c78eae5794 | 1,790 | h | C | cpp/openScenarioLib/src/common/ILocator.h | RA-Consulting-GmbH/openscenario.api.test | 4b8aa781fc51862cac382b312855d520ea61aaa7 | [
"Apache-2.0"
] | 27 | 2020-08-13T11:39:24.000Z | 2022-02-13T06:21:16.000Z | cpp/openScenarioLib/src/common/ILocator.h | RA-Consulting-GmbH/openscenario.api.test | 4b8aa781fc51862cac382b312855d520ea61aaa7 | [
"Apache-2.0"
] | 62 | 2020-08-12T14:53:29.000Z | 2022-02-21T14:39:23.000Z | cpp/openScenarioLib/src/common/ILocator.h | ahege/openscenario.api.test | 94cc39a6caad0418c71aadc6567fa200ded0ac65 | [
"Apache-2.0"
] | 4 | 2021-07-08T03:04:14.000Z | 2022-01-11T11:16:43.000Z | /*
* Copyright 2020 RA Consulting
*
* RA Consulting GmbH licenses this file 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 <string>
#include "Textmarker.h"
#include "MemLeakDetection.h"
namespace NET_ASAM_OPENSCENARIO
{
/**
* A locator for objects in a text file.
*
*/
class ILocator
{
public:
virtual ~ILocator() = default;
/**
* Locates the start of an object in a text file
* @return the start marker
*/
virtual Textmarker GetStartMarker() = 0;
/**
* Locates the end of an object in a text file
* @return the end marker
*/
virtual Textmarker GetEndMarker() = 0;
/**
* Locates the start of an property that belongs to an object in a text file
* @param propertyKey the property (attribute) in xml
* @return the start marker
*/
virtual Textmarker GetStartMarkerOfProperty(const std::string& propertyKey) = 0;
/**
* Locates the end of an property that belongs to an object in a text file
* @param propertyKey the property (attribute) in xml
* @return the end marker
*/
virtual Textmarker GetEndMarkerOfProperty(const std::string &propertyKey) = 0;
};
}
| 28.870968 | 89 | 0.652514 | [
"object"
] |
7c7f5bb26636cd81d197e6c017bbe44d52506906 | 5,599 | h | C | include/lmqtt_server.h | slimem/lmqtt_cpp | d0e2b032d17ac7cc19c1d0e32773a4b6f8c9171b | [
"MIT"
] | null | null | null | include/lmqtt_server.h | slimem/lmqtt_cpp | d0e2b032d17ac7cc19c1d0e32773a4b6f8c9171b | [
"MIT"
] | null | null | null | include/lmqtt_server.h | slimem/lmqtt_cpp | d0e2b032d17ac7cc19c1d0e32773a4b6f8c9171b | [
"MIT"
] | null | null | null | #pragma once
#include "lmqtt_common.h"
#include "lmqtt_tsqueue.h"
#include "lmqtt_connection.h"
#include "lmqtt_timer.h"
namespace lmqtt {
class lmqtt_server {
public:
lmqtt_server(
uint16_t port
) :
_acceptor(
_context,
asio::ip::tcp::endpoint(asio::ip::tcp::v4(), port)
),
_port(port) {
// will not use the timer for now
/*_timer = std::make_shared<lmqtt_timer>(5000, [this] {
std::cout << "Calling function" << std::endl;
_timer->reset(_timer->get_time()/2);
_timer->count--;
if (_timer->count == 2) {
std::cout << "Trying to pause thread" << std::endl;
_timer->stop();
std::this_thread::sleep_for(2s);
std::cout << "Trying to resume thread" << std::endl;
_timer->reset(5000);
_timer->count = 5;
_timer->resume();
}
}
);*/
}
virtual ~lmqtt_server() {
stop();
}
[[nodiscard]] bool start() {
try {
wait_for_clients();
_thContext = std::thread([this]() {_context.run(); });
_cleanupThread = std::thread([this]() {deleter_job(); });
} catch (std::exception& e) {
std::cerr << "[SERVER] Could Not Start Server. Reason:\n" << e.what() << "\n";
stop();
return false;
}
std::cout << "[SERVER] Successfully Started LMQTT Server\n";
std::cout << "[SERVER] Listening on port " << _port << "\n";
return true;
}
void stop() {
// attempt to stop the asio context, then join its thread
_context.stop();
// maybe the context will be busy, so we have to wait
// for it to finish using std::thread.join()
if (_thContext.joinable()) {
_thContext.join();
}
std::cout << "[SERVER] Successfully Stopped LMQTT Server.\n";
_exitCleanupThread = true;
if (_cleanupThread.joinable()) {
_cleanupThread.join();
}
std::cout << "[SERVER] Successfully Stopped connections cleaner\n";
}
protected:
// async method: wait for connection
// It's here where all the magic happens
void wait_for_clients() {
_acceptor.async_accept(
[this](std::error_code ec, asio::ip::tcp::socket socket) {
if (!ec) {
// if the connection attempt is successful
std::cout << "[SERVER] New Connection: " << socket.remote_endpoint() << "\n";
// create a new connection object for this specific client
// since we used a smart pointer, the new connection will be destroyed
// when it falls out of scope, in case the connection was not accepted
std::shared_ptr<connection> newConnection =
std::make_shared<connection>(
_context,
std::move(socket),
_activeSessions,
_deletionQueue
);
if (on_client_connection(newConnection)) {
// if the connection was accepted, we push it to our connections container.
// if the connection was not accepted, the new connection will be destroyed
// since we are using a smart pointer
//newConnection->connect_to_client();
_activeSessions.push_back(std::move(newConnection));
_activeSessions.back()->connect_to_client(100);
std::cout << "[" << _activeSessions.back()->get_remote_endpoint() << "] Connection Accepted, waiting for identification..\n";
} else {
std::cout << "[SERVER] Connection to " << newConnection->get_remote_endpoint() << " Denied. Reason: Reached maximum number of allowed connections\n";
_deletionQueue.push_back(newConnection);
}
} else {
// error occurred during acceptance
std::cout << "[SERVER] New Connection Error: " << ec.message() << "\n";
}
wait_for_clients();
}
);
}
public:
// can be used to change how many messages can be processed at a time
void update(size_t maxMessages = -1) {
_messages.wait();
}
void deleter_job() {
while (!_exitCleanupThread) {
_deletionQueue.wait();
//_messages.wait();
if (!_deletionQueue.empty()) {
std::chrono::system_clock::time_point timeStart = std::chrono::system_clock::now();
//std::cout << "Detected deletion queue not empty\n";
auto connection = _deletionQueue.pop_front();
connection->shutdown();
_activeSessions.find_and_erase(connection);
std::chrono::system_clock::time_point timeEnd = std::chrono::system_clock::now();
std::cout << "[SERVER] (thread " << std::this_thread::get_id() << ") deleting connection " << connection.get() << std::endl;
//std::cout << "Deletion from queue took " << std::chrono::duration_cast<std::chrono::microseconds>(timeEnd - timeStart).count() << " us\n";
}
}
}
protected:
bool on_client_connection(std::shared_ptr<connection> connection) {
if (_activeSessions.size() > 1) {
return false;
}
return true;
}
void client_timeout_handler(std::error_code ec) {
if (!ec) {
std::cout << "This timer for client has expired\n";
}
}
protected:
// container for active connections
ts_queue<std::shared_ptr<connection>> _activeSessions;
// container for connections scheduled for deletion
ts_queue<std::shared_ptr<connection>> _deletionQueue;
// container for messages to be treated
ts_queue<std::pair<std::weak_ptr<connection>, std::string_view>> _messages;
// thread for cleanup
std::thread _cleanupThread;
std::atomic<bool> _exitCleanupThread;
// timeout
std::shared_ptr<lmqtt_timer> _timer;
// for the server to actually run with asio
asio::io_context _context;
std::thread _thContext;
// since we dont need sockets, we need acceptors
asio::ip::tcp::acceptor _acceptor;
// Server will identify client by this ID, and use them for reporting.
// also, it will help with some data charting later
uint32_t _idCounter = 0;
uint16_t _port = 0;
};
} // namespace lmqtt
| 27.581281 | 155 | 0.660832 | [
"object"
] |
7c9833bacecade5b4cbb389c7961f6941bb0f6c5 | 3,742 | c | C | src/MPIFunctions/MPIGatherArraynD.c | LLNL/mhysa | e97d841191718cfa6d81b38d904340e2c753df85 | [
"MIT"
] | 12 | 2020-03-16T16:50:03.000Z | 2022-03-20T10:09:10.000Z | src/MPIFunctions/MPIGatherArraynD.c | zhangzhg0508/mhysa | e97d841191718cfa6d81b38d904340e2c753df85 | [
"MIT"
] | null | null | null | src/MPIFunctions/MPIGatherArraynD.c | zhangzhg0508/mhysa | e97d841191718cfa6d81b38d904340e2c753df85 | [
"MIT"
] | 4 | 2020-03-16T16:50:04.000Z | 2021-06-04T05:36:45.000Z | /*! @file MPIGatherArraynD.c
@brief Gather an n-dimensional array in to a global array
@author Debojyoti Ghosh
*/
#include <stdio.h>
#include <stdlib.h>
#include <basic.h>
#include <arrayfunctions.h>
#include <mpivars.h>
/*!
Gathers the contents of an n-dimensional array, partitioned amongst the MPI ranks, in to a global
array on rank 0. See documentation of MPIExchangeBoundariesnD() for how the n-dimensional array is
stored in the memory as a single-index array.
Notes:
+ The global array must have no ghost points.
+ The global array must be allocated only on rank 0. On other ranks, it must be NULL.
*/
int MPIGatherArraynD(
int ndims, /*!< Number of spatial dimensions */
void *m, /*!< MPI object of type #MPIVariables */
double *xg, /*!< Global array (preallocated) without ghost points */
double *x, /*!< Local array */
int *dim_global, /*!< Integer array with elements as global size along each spatial dimension */
int *dim_local, /*!< Integer array with elements as local size along each spatial dimension */
int ghosts, /*!< Number of ghost points */
int nvars /*!< Number of variables (vector components) */
)
{
MPIVariables *mpi = (MPIVariables*) m;
int d, size;
_DECLARE_IERR_;
int is[ndims], ie[ndims], index[ndims], bounds[ndims];
/* xg should be non-null only on root */
if (mpi->rank && xg) {
fprintf(stderr,"Error in MPIGatherArraynD(): global array exists on non-root processors (rank %d).\n",
mpi->rank);
return(1);
}
if ((!mpi->rank) && (!xg)) {
fprintf(stderr,"Error in MPIGatherArraynD(): global array is not allocated on root processor.\n");
return(1);
}
/* calculate total size of local domain (w/o ghosts) */
size = 1;
for (d = 0; d < ndims; d++) size *= dim_local[d];
/* create and copy data to send to root process */
double *buffer = (double*) calloc (size*nvars, sizeof(double));
IERR ArrayCopynD(ndims,x,buffer,dim_local,ghosts,0,index,nvars); CHECKERR(ierr);
if (!mpi->rank) {
int proc;
for (proc = 0; proc < mpi->nproc; proc++) {
int d,done,size;
/* Find out the domain limits for each process */
IERR MPILocalDomainLimits(ndims,proc,mpi,dim_global,is,ie); CHECKERR(ierr);
size = 1;
for (d=0; d<ndims; d++) {
size *= (ie[d]-is[d]);
bounds[d] = ie[d] - is[d];
}
if (proc) {
#ifndef serial
MPI_Status status;
double *recvbuf = (double*) calloc (size*nvars, sizeof(double));
MPI_Recv(recvbuf,size*nvars,MPI_DOUBLE,proc,1902,mpi->world,&status);
int done = 0; _ArraySetValue_(index,ndims,0);
while (!done) {
int p1; _ArrayIndex1D_(ndims,bounds,index,0,p1);
int p2; _ArrayIndex1DWO_(ndims,dim_global,index,is,0,p2);
_ArrayCopy1D_((recvbuf+nvars*p1),(xg+nvars*p2),nvars);
_ArrayIncrementIndex_(ndims,bounds,index,done);
}
free(recvbuf);
#endif
} else {
done = 0; _ArraySetValue_(index,ndims,0);
while (!done) {
int p1; _ArrayIndex1D_(ndims,bounds,index,0,p1);
int p2; _ArrayIndex1DWO_(ndims,dim_global,index,is,0,p2);
_ArrayCopy1D_((buffer+nvars*p1),(xg+nvars*p2),nvars);
_ArrayIncrementIndex_(ndims,bounds,index,done);
}
}
}
} else {
#ifndef serial
/* Meanwhile, on other processes */
MPI_Send(buffer,size*nvars,MPI_DOUBLE,0,1902,mpi->world);
#endif
}
free(buffer);
return(0);
}
| 36.330097 | 123 | 0.595136 | [
"object",
"vector"
] |
7c9afdb6d321001ef03fbd3dc6f0e79e9de37f61 | 15,003 | h | C | cusp/system/detail/generic/blas.h | Raman-sh/cusplibrary | 99dcde05991ef59cbc4546aeced6eb3bd49c90c9 | [
"Apache-2.0"
] | 270 | 2015-01-12T19:40:50.000Z | 2022-03-28T00:58:21.000Z | cusp/system/detail/generic/blas.h | njh19/cusplibrary | 4f72f152804dee592fec86719049af2b5469295a | [
"Apache-2.0"
] | 41 | 2015-01-08T18:07:42.000Z | 2022-02-27T02:37:38.000Z | cusp/system/detail/generic/blas.h | njh19/cusplibrary | 4f72f152804dee592fec86719049af2b5469295a | [
"Apache-2.0"
] | 106 | 2015-02-27T19:30:58.000Z | 2022-03-29T13:55:53.000Z | /*
* Copyright 2008-2014 NVIDIA 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.
*/
#pragma once
#include <cusp/array1d.h>
#include <cusp/complex.h>
#include <cusp/exception.h>
#include <cusp/functional.h>
#include <thrust/copy.h>
#include <thrust/fill.h>
#include <thrust/functional.h>
#include <thrust/transform.h>
#include <thrust/transform_reduce.h>
#include <thrust/inner_product.h>
#include <thrust/iterator/transform_iterator.h>
#include <cmath>
namespace cusp
{
namespace system
{
namespace detail
{
namespace generic
{
namespace blas
{
template <typename T>
struct SCAL
{
T alpha;
SCAL(T _alpha)
: alpha(_alpha) {}
template <typename T2>
__host__ __device__
void operator()(T2& x)
{
x = T(alpha) * x;
}
};
template <typename T>
struct AXPY
{
T alpha;
AXPY(T _alpha)
: alpha(_alpha) {}
template <typename Tuple>
__host__ __device__
void operator()(Tuple t)
{
thrust::get<1>(t) = alpha * thrust::get<0>(t) +
thrust::get<1>(t);
}
};
template <typename T1, typename T2>
struct AXPBY
{
T1 alpha;
T2 beta;
AXPBY(T1 _alpha, T2 _beta)
: alpha(_alpha), beta(_beta) {}
template <typename Tuple>
__host__ __device__
void operator()(Tuple t)
{
thrust::get<2>(t) = alpha * thrust::get<0>(t) +
beta * thrust::get<1>(t);
}
};
template <typename T1,typename T2,typename T3>
struct AXPBYPCZ
{
T1 alpha;
T2 beta;
T3 gamma;
AXPBYPCZ(T1 _alpha, T2 _beta, T3 _gamma)
: alpha(_alpha), beta(_beta), gamma(_gamma) {}
template <typename Tuple>
__host__ __device__
void operator()(Tuple t)
{
thrust::get<3>(t) = alpha * thrust::get<0>(t) +
beta * thrust::get<1>(t) +
gamma * thrust::get<2>(t);
}
};
template <typename T>
struct XMY : public thrust::binary_function<T,T,T>
{
__host__ __device__
T operator()(const T& x, const T& y)
{
return x * y;
}
};
template<typename T>
struct AMAX : public thrust::binary_function<T,T,bool>
{
__host__ __device__
bool operator()(const T& lhs, const T& rhs)
{
return cusp::abs(lhs) < cusp::abs(rhs);
}
};
template <typename DerivedPolicy,
typename Array>
int amax(thrust::execution_policy<DerivedPolicy>& exec,
const Array& x)
{
typedef typename Array::value_type ValueType;
#if THRUST_VERSION >= 100800
typedef typename Array::const_iterator Iterator;
typedef cusp::abs_functor<ValueType> UnaryOp;
typedef thrust::transform_iterator<UnaryOp, Iterator> TransformIterator;
TransformIterator iter(x.begin(), UnaryOp());
int index = thrust::max_element(exec, iter, iter + x.size()) - iter;
#else
int index = thrust::max_element(exec, x.begin(), x.end(), AMAX<ValueType>()) - x.begin();
#endif
return index;
}
template <typename DerivedPolicy,
typename Array>
typename cusp::norm_type<typename Array::value_type>::type
asum(thrust::execution_policy<DerivedPolicy>& exec,
const Array& x)
{
typedef typename Array::value_type ValueType;
typedef typename cusp::norm_type<ValueType>::type NormType;
cusp::abs_functor<ValueType> unary_op;
thrust::plus<NormType> binary_op;
NormType init = 0;
return thrust::transform_reduce(exec, x.begin(), x.end(), unary_op, init, binary_op);
}
template <typename DerivedPolicy,
typename Array1,
typename Array2,
typename ScalarType>
void axpy(thrust::execution_policy<DerivedPolicy>& exec,
const Array1& x,
Array2& y,
const ScalarType alpha)
{
typedef typename Array1::value_type ValueType;
cusp::assert_same_dimensions(x, y);
size_t N = x.size();
thrust::for_each(exec,
thrust::make_zip_iterator(thrust::make_tuple(x.begin(), y.begin())),
thrust::make_zip_iterator(thrust::make_tuple(x.begin(), y.begin())) + N,
AXPY<ValueType>(alpha));
}
template <typename DerivedPolicy,
typename Array1,
typename Array2,
typename Array3,
typename ScalarType1,
typename ScalarType2>
void axpby(thrust::execution_policy<DerivedPolicy> &exec,
const Array1& x,
const Array2& y,
Array3& z,
const ScalarType1 alpha,
const ScalarType2 beta)
{
typedef typename Array1::value_type ValueType;
cusp::assert_same_dimensions(x, y, z);
size_t N = x.size();
thrust::for_each(exec,
thrust::make_zip_iterator(thrust::make_tuple(x.begin(), y.begin(), z.begin())),
thrust::make_zip_iterator(thrust::make_tuple(x.begin(), y.begin(), z.begin())) + N,
AXPBY<ValueType,ValueType>(alpha, beta));
}
template <typename DerivedPolicy,
typename Array1,
typename Array2,
typename Array3,
typename Array4,
typename ScalarType1,
typename ScalarType2,
typename ScalarType3>
void axpbypcz(thrust::execution_policy<DerivedPolicy> &exec,
const Array1& x,
const Array2& y,
const Array3& z,
Array4& output,
const ScalarType1 alpha,
const ScalarType2 beta,
const ScalarType3 gamma)
{
typedef typename Array1::value_type ValueType;
cusp::assert_same_dimensions(x, y, z, output);
size_t N = x.size();
thrust::for_each(exec,
thrust::make_zip_iterator(thrust::make_tuple(x.begin(), y.begin(), z.begin(), output.begin())),
thrust::make_zip_iterator(thrust::make_tuple(x.begin(), y.begin(), z.begin(), output.begin())) + N,
AXPBYPCZ<ValueType,ValueType,ValueType>(alpha, beta, gamma));
}
template <typename DerivedPolicy,
typename Array1,
typename Array2,
typename Array3>
void xmy(thrust::execution_policy<DerivedPolicy> &exec,
const Array1& x,
const Array2& y,
Array3& z)
{
typedef typename Array3::value_type ValueType;
cusp::assert_same_dimensions(x, y, z);
thrust::transform(exec, x.begin(), x.end(), y.begin(), z.begin(), XMY<ValueType>());
}
template <typename DerivedPolicy,
typename Array1,
typename Array2>
void copy(thrust::execution_policy<DerivedPolicy>& exec,
const Array1& x,
Array2& y)
{
cusp::assert_same_dimensions(x, y);
thrust::copy(exec, x.begin(), x.end(), y.begin());
}
// TODO properly harmonize heterogenous types
template <typename DerivedPolicy,
typename Array1,
typename Array2>
typename Array1::value_type
dot(thrust::execution_policy<DerivedPolicy>& exec,
const Array1& x,
const Array2& y)
{
typedef typename Array1::value_type OutputType;
cusp::assert_same_dimensions(x, y);
return thrust::inner_product(exec, x.begin(), x.end(), y.begin(), OutputType(0));
}
// TODO properly harmonize heterogenous types
template <typename DerivedPolicy,
typename Array1,
typename Array2>
typename Array1::value_type
dotc(thrust::execution_policy<DerivedPolicy>& exec,
const Array1& x,
const Array2& y)
{
typedef typename Array1::value_type OutputType;
cusp::assert_same_dimensions(x, y);
return thrust::inner_product(exec,
thrust::make_transform_iterator(x.begin(), cusp::conj_functor<OutputType>()),
thrust::make_transform_iterator(x.end(), cusp::conj_functor<OutputType>()),
y.begin(),
OutputType(0));
}
template <typename DerivedPolicy,
typename Array,
typename ScalarType>
void fill(thrust::execution_policy<DerivedPolicy>& exec,
Array& x,
const ScalarType alpha)
{
thrust::fill(exec, x.begin(), x.end(), alpha);
}
template <typename DerivedPolicy,
typename Array>
typename cusp::norm_type<typename Array::value_type>::type
nrm2(thrust::execution_policy<DerivedPolicy>& exec,
const Array& x)
{
typedef typename Array::value_type ValueType;
typedef typename cusp::norm_type<ValueType>::type NormType;
cusp::abs_squared_functor<ValueType> unary_op;
thrust::plus<NormType> binary_op;
NormType init = 0;
return std::sqrt(thrust::transform_reduce(exec, x.begin(), x.end(), unary_op, init, binary_op));
}
template <typename DerivedPolicy,
typename Array,
typename ScalarType>
void scal(thrust::execution_policy<DerivedPolicy>& exec,
Array& x,
const ScalarType alpha)
{
thrust::for_each(exec, x.begin(), x.end(), SCAL<ScalarType>(alpha));
}
template<typename DerivedPolicy,
typename Array2d,
typename Array1d1,
typename Array1d2,
typename ScalarType1,
typename ScalarType2>
void gemv(thrust::execution_policy<DerivedPolicy>& exec,
const Array2d& A,
const Array1d1& x,
Array1d2& y,
const ScalarType1 alpha,
const ScalarType2 beta)
{
throw cusp::not_implemented_exception("CUSP GEMV not implemented");
}
template <typename DerivedPolicy,
typename Array1d1,
typename Array1d2,
typename Array2d1,
typename ScalarType>
void ger(thrust::execution_policy<DerivedPolicy> &exec,
const Array1d1& x,
const Array1d2& y,
Array2d1& A,
const ScalarType alpha)
{
throw cusp::not_implemented_exception("CUSP GER not implemented");
}
template <typename DerivedPolicy,
typename Array2d1,
typename Array1d1,
typename Array1d2,
typename ScalarType1,
typename ScalarType2>
void symv(thrust::execution_policy<DerivedPolicy> &exec,
const Array2d1& A,
const Array1d1& x,
Array1d2& y,
const ScalarType1 alpha,
const ScalarType2 beta)
{
throw cusp::not_implemented_exception("CUSP SYMV not implemented");
}
template <typename DerivedPolicy,
typename Array1d,
typename Array2d,
typename ScalarType>
void syr(thrust::execution_policy<DerivedPolicy> &exec,
const Array1d& x,
Array2d& A,
const ScalarType alpha)
{
throw cusp::not_implemented_exception("CUSP SYR not implemented");
}
template <typename DerivedPolicy,
typename Array2d,
typename Array1d>
void trmv(thrust::execution_policy<DerivedPolicy> &exec,
const Array2d& A,
Array1d& x)
{
throw cusp::not_implemented_exception("CUSP TRMV not implemented");
}
template <typename DerivedPolicy,
typename Array2d,
typename Array1d>
void trsv(thrust::execution_policy<DerivedPolicy> &exec,
const Array2d& A,
Array1d& x)
{
throw cusp::not_implemented_exception("CUSP TRSV not implemented");
}
template<typename DerivedPolicy,
typename Array2d1,
typename Array2d2,
typename Array2d3,
typename ScalarType1,
typename ScalarType2>
void gemm(thrust::execution_policy<DerivedPolicy>& exec,
const Array2d1& A,
const Array2d2& B,
Array2d3& C,
const ScalarType1 alpha,
const ScalarType2 beta)
{
throw cusp::not_implemented_exception("CUSP GEMM not implemented");
}
template<typename DerivedPolicy,
typename Array2d1,
typename Array2d2,
typename Array2d3,
typename ScalarType1,
typename ScalarType2>
void symm(thrust::execution_policy<DerivedPolicy>& exec,
const Array2d1& A,
const Array2d2& B,
Array2d3& C,
const ScalarType1 alpha,
const ScalarType2 beta)
{
throw cusp::not_implemented_exception("CUSP SYMM not implemented");
}
template <typename DerivedPolicy,
typename Array2d1,
typename Array2d2,
typename ScalarType1,
typename ScalarType2>
void syrk(thrust::execution_policy<DerivedPolicy> &exec,
const Array2d1& A,
Array2d2& B,
const ScalarType1 alpha,
const ScalarType2 beta)
{
throw cusp::not_implemented_exception("CUSP SYRK not implemented");
}
template<typename DerivedPolicy,
typename Array2d1,
typename Array2d2,
typename Array2d3,
typename ScalarType1,
typename ScalarType2>
void syr2k(thrust::execution_policy<DerivedPolicy>& exec,
const Array2d1& A,
const Array2d2& B,
Array2d3& C,
const ScalarType1 alpha,
const ScalarType2 beta)
{
throw cusp::not_implemented_exception("CUSP SYR2K not implemented");
}
template<typename DerivedPolicy,
typename Array2d1,
typename Array2d2,
typename ScalarType>
void trmm(thrust::execution_policy<DerivedPolicy>& exec,
const Array2d1& A,
Array2d2& B,
const ScalarType alpha)
{
throw cusp::not_implemented_exception("CUSP TRMM not implemented");
}
template<typename DerivedPolicy,
typename Array2d1,
typename Array2d2,
typename ScalarType>
void trsm(thrust::execution_policy<DerivedPolicy>& exec,
const Array2d1& A,
Array2d2& B,
const ScalarType alpha)
{
throw cusp::not_implemented_exception("CUSP TRSM not implemented");
}
template <typename DerivedPolicy,
typename Array>
typename cusp::norm_type<typename Array::value_type>::type
nrm1(thrust::execution_policy<DerivedPolicy>& exec,
const Array& x)
{
return cusp::blas::asum(exec, x);
}
template <typename DerivedPolicy,
typename Array>
typename cusp::norm_type<typename Array::value_type>::type
nrmmax(thrust::execution_policy<DerivedPolicy>& exec,
const Array& x)
{
typedef typename Array::value_type ValueType;
int index = cusp::blas::amax(exec, x);
ValueType val = *(x.begin() + index);
return cusp::abs(val);
}
} // end namespace blas
} // end namespace generic
} // end namespace detail
} // end namespace system
} // end namespace cusp
| 27.52844 | 120 | 0.631074 | [
"transform"
] |
7c9bc51bdff395567bd09ca0c743bbad60b20f97 | 3,496 | h | C | Sources/Elastos/Frameworks/Droid/Base/Core/inc/elastos/droid/internal/http/HttpDateTime.h | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/Frameworks/Droid/Base/Core/inc/elastos/droid/internal/http/HttpDateTime.h | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/Frameworks/Droid/Base/Core/inc/elastos/droid/internal/http/HttpDateTime.h | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos 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.
//=========================================================================
#ifndef __ELASTOS_DROID_INTERNAL_HTTP_HTTPDATETIME_H__
#define __ELASTOS_DROID_INTERNAL_HTTP_HTTPDATETIME_H__
#include "elastos/droid/ext/frameworkext.h"
#include <elastos/core/Object.h>
using Elastos::Utility::Regex::IPattern;
namespace Elastos {
namespace Droid {
namespace Internal {
namespace Http {
/**
* Helper for parsing an HTTP date.
*/
class HttpDateTime
{
private:
class TimeOfDay : public Object
{
public:
TimeOfDay(
/* [in] */ Int32 h,
/* [in] */ Int32 m,
/* [in] */ Int32 s);
public:
Int32 mHour;
Int32 mMinute;
Int32 mSecond;
};
public:
static CARAPI Parse(
/* [in] */ const String& timeString,
/* [out] */ Int64* time);
private:
static CARAPI_(Int32) GetDate(
/* [in] */ const String& dateString);
/*
* jan = 9 + 0 + 13 = 22
* feb = 5 + 4 + 1 = 10
* mar = 12 + 0 + 17 = 29
* apr = 0 + 15 + 17 = 32
* may = 12 + 0 + 24 = 36
* jun = 9 + 20 + 13 = 42
* jul = 9 + 20 + 11 = 40
* aug = 0 + 20 + 6 = 26
* sep = 18 + 4 + 15 = 37
* oct = 14 + 2 + 19 = 35
* nov = 13 + 14 + 21 = 48
* dec = 3 + 4 + 2 = 9
*/
static CARAPI GetMonth(
/* [in] */ const String& monthString,
/* [out] */ Int32* month);
static CARAPI_(Int32) GetYear(
/* [in] */ const String& yearString);
static CARAPI_(AutoPtr<TimeOfDay>) GetTime(
/* [in] */ const String& timeString);
private:
HttpDateTime();
private:
/*
* Regular expression for parsing HTTP-date.
*
* Wdy, DD Mon YYYY HH:MM:SS GMT
* RFC 822, updated by RFC 1123
*
* Weekday, DD-Mon-YY HH:MM:SS GMT
* RFC 850, obsoleted by RFC 1036
*
* Wdy Mon DD HH:MM:SS YYYY
* ANSI C's asctime() format
*
* with following variations
*
* Wdy, DD-Mon-YYYY HH:MM:SS GMT
* Wdy, (SP)D Mon YYYY HH:MM:SS GMT
* Wdy,DD Mon YYYY HH:MM:SS GMT
* Wdy, DD-Mon-YY HH:MM:SS GMT
* Wdy, DD Mon YYYY HH:MM:SS -HHMM
* Wdy, DD Mon YYYY HH:MM:SS
* Wdy Mon (SP)D HH:MM:SS YYYY
* Wdy Mon DD HH:MM:SS YYYY GMT
*
* HH can be H if the first digit is zero.
*
* Mon can be the full name of the month.
*/
static const String HTTP_DATE_RFC_REGEXP;
static const String HTTP_DATE_ANSIC_REGEXP;
/**
* The compiled version of the HTTP-date regular expressions.
*/
static const AutoPtr<IPattern> HTTP_DATE_RFC_PATTERN;
static const AutoPtr<IPattern> HTTP_DATE_ANSIC_PATTERN;
};
} // namespace Http
} // namespace Internal
} // namespace Droid
} // namespace Elastos
#endif // __ELASTOS_DROID_INTERNAL_HTTP_HTTPDATETIME_H__
| 26.687023 | 75 | 0.578661 | [
"object"
] |
7ca0cd812e03e8e14f0a5f61a94c2c2471200ba0 | 1,766 | h | C | libcloud/stats.h | transpixel/tpqz | 2d8400b1be03292d0c5ab74710b87e798ae6c52c | [
"MIT"
] | 1 | 2017-06-01T00:21:16.000Z | 2017-06-01T00:21:16.000Z | libcloud/stats.h | transpixel/tpqz | 2d8400b1be03292d0c5ab74710b87e798ae6c52c | [
"MIT"
] | 3 | 2017-06-01T00:26:16.000Z | 2020-05-09T21:06:27.000Z | libcloud/stats.h | transpixel/tpqz | 2d8400b1be03292d0c5ab74710b87e798ae6c52c | [
"MIT"
] | null | null | null | //
//
// MIT License
//
// Copyright (c) 2017 Stellacore Corporation.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject
// to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
// KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
// AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//
#ifndef cloud_stats_INCL_
#define cloud_stats_INCL_
/*! \file
\brief Declarations for cloud::stats
*/
#include "libdat/Volume.h"
#include "libcloud/FixedPoint.h"
#include <vector>
namespace cloud
{
/*! \brief Functions that represent statistics for point clouds.
\par Example
\dontinclude testcloud/ustats.cpp
\skip ExampleStart
\until ExampleEnd
*/
namespace stats
{
//! Rectangular volume (exactly) containing all points
dat::Volume<double>
boundingVolumeOf
( std::vector<FixedPoint> const & fpnts
);
}
}
// Inline definitions
#include "libcloud/stats.inl"
#endif // cloud_stats_INCL_
| 24.873239 | 72 | 0.749717 | [
"vector"
] |
7ca529d4cc804a23cbb092941fba1299703a9cd5 | 486 | h | C | Source/Storm-Packager/include/PackagerManager.h | SunlayGGX/Storm | 83a34c14cc7d936347b6b8193a64cd13ccbf00a8 | [
"MIT"
] | 3 | 2021-11-27T04:56:12.000Z | 2022-02-14T04:02:10.000Z | Source/Storm-Packager/include/PackagerManager.h | SunlayGGX/Storm | 83a34c14cc7d936347b6b8193a64cd13ccbf00a8 | [
"MIT"
] | null | null | null | Source/Storm-Packager/include/PackagerManager.h | SunlayGGX/Storm | 83a34c14cc7d936347b6b8193a64cd13ccbf00a8 | [
"MIT"
] | null | null | null | #pragma once
#include "Singleton.h"
namespace StormPackager
{
class ITaskLogic;
class PackagerManager final : private Storm::Singleton<StormPackager::PackagerManager>
{
STORM_DECLARE_SINGLETON(PackagerManager);
private:
using PackagerContainer = std::vector<std::unique_ptr<StormPackager::ITaskLogic>>;
private:
void initialize_Implementation();
void cleanUp_Implementation();
public:
bool run();
private:
PackagerContainer _taskList;
bool _prepared;
};
}
| 16.758621 | 87 | 0.763374 | [
"vector"
] |
7ca56bb759160afec2809462ee78bddf20dad56d | 4,269 | h | C | src/include/utils/rel.h | emotionbug/incubator-age-pg | 676e3c735dec32ba0448fdd0faf9ace37c1fa792 | [
"BSD-4-Clause-UC"
] | null | null | null | src/include/utils/rel.h | emotionbug/incubator-age-pg | 676e3c735dec32ba0448fdd0faf9ace37c1fa792 | [
"BSD-4-Clause-UC"
] | null | null | null | src/include/utils/rel.h | emotionbug/incubator-age-pg | 676e3c735dec32ba0448fdd0faf9ace37c1fa792 | [
"BSD-4-Clause-UC"
] | null | null | null | /*-------------------------------------------------------------------------
*
* rel.h--
* POSTGRES relation descriptor definitions.
*
*
* Copyright (c) 1994, Regents of the University of California
*
* $Id: rel.h,v 1.7 1996/11/04 11:51:24 scrappy Exp $
*
*-------------------------------------------------------------------------
*/
#ifndef REL_H
#define REL_H
#include <catalog/pg_am.h>
#include <catalog/pg_class.h>
#include <access/strat.h>
#include <access/tupdesc.h>
#include <rewrite/prs2lock.h>
#include <storage/fd.h>
typedef struct RelationData {
File rd_fd; /* open file descriptor */
int rd_nblocks; /* number of blocks in rel */
uint16 rd_refcnt; /* reference count */
bool rd_islocal; /* uses the local buffer mgr */
bool rd_isnailed; /* rel is nailed in cache */
bool rd_istemp; /* rel is a temp rel */
bool rd_tmpunlinked; /* temp rel already unlinked */
Form_pg_am rd_am; /* AM tuple */
Form_pg_class rd_rel; /* RELATION tuple */
Oid rd_id; /* relations's object id */
Pointer lockInfo; /* ptr. to misc. info. */
TupleDesc rd_att; /* tuple desciptor */
RuleLock *rd_rules; /* rewrite rules */
IndexStrategy rd_istrat;
RegProcedure* rd_support;
} RelationData;
typedef RelationData *Relation;
/* ----------------
* RelationPtr is used in the executor to support index scans
* where we have to keep track of several index relations in an
* array. -cim 9/10/89
* ----------------
*/
typedef Relation *RelationPtr;
#define InvalidRelation ((Relation)NULL)
typedef char ArchiveMode;
/*
* RelationIsValid --
* True iff relation descriptor is valid.
*/
#define RelationIsValid(relation) PointerIsValid(relation)
/*
* RelationGetSystemPort --
* Returns system port of a relation.
*
* Note:
* Assumes relation descriptor is valid.
*/
#define RelationGetSystemPort(relation) ((relation)->rd_fd)
/*
* RelationGetLockInfo --
* Returns the lock information structure in the reldesc
*
*/
#define RelationGetLockInfo(relation) ((relation)->lockInfo)
/*
* RelationHasReferenceCountZero --
* True iff relation reference count is zero.
*
* Note:
* Assumes relation descriptor is valid.
*/
#define RelationHasReferenceCountZero(relation) \
((bool)((relation)->rd_refcnt == 0))
/*
* RelationSetReferenceCount --
* Sets relation reference count.
*/
#define RelationSetReferenceCount(relation,count) ((relation)->rd_refcnt = count)
/*
* RelationIncrementReferenceCount --
* Increments relation reference count.
*/
#define RelationIncrementReferenceCount(relation) ((relation)->rd_refcnt += 1);
/*
* RelationDecrementReferenceCount --
* Decrements relation reference count.
*/
#define RelationDecrementReferenceCount(relation) ((relation)->rd_refcnt -= 1)
/*
* RelationGetAccessMethodTupleForm --
* Returns access method attribute values for a relation.
*
* Note:
* Assumes relation descriptor is valid.
*/
#define RelationGetAccessMethodTupleForm(relation) ((relation)->rd_am)
/*
* RelationGetRelationTupleForm --
* Returns relation attribute values for a relation.
*
* Note:
* Assumes relation descriptor is valid.
*/
#define RelationGetRelationTupleForm(relation) ((relation)->rd_rel)
/*
* RelationGetRelationId --
*
* returns the object id of the relation
*
*/
#define RelationGetRelationId(relation) ((relation)->rd_id)
/*
* RelationGetFile --
*
* Returns the open File decscriptor
*/
#define RelationGetFile(relation) ((relation)->rd_fd)
/*
* RelationGetRelationName --
*
* Returns a Relation Name
*/
#define RelationGetRelationName(relation) (&(relation)->rd_rel->relname)
/*
* RelationGetRelationName --
*
* Returns a the number of attributes.
*/
#define RelationGetNumberOfAttributes(relation) ((relation)->rd_rel->relnatts)
/*
* RelationGetTupleDescriptor --
* Returns tuple descriptor for a relation.
*
* Note:
* Assumes relation descriptor is valid.
*/
#define RelationGetTupleDescriptor(relation) ((relation)->rd_att)
extern IndexStrategy RelationGetIndexStrategy(Relation relation);
extern void RelationSetIndexSupport(Relation relation, IndexStrategy strategy,
RegProcedure *support);
#endif /* REL_H */
| 25.410714 | 81 | 0.674631 | [
"object"
] |
7cab31e8a2ab4668e42dabab28863d9cc374f747 | 4,523 | h | C | android/android_42/base/libs/hwui/font/Font.h | yakuizhao/intel-vaapi-driver | b2bb0383352694941826543a171b557efac2219b | [
"MIT"
] | null | null | null | android/android_42/base/libs/hwui/font/Font.h | yakuizhao/intel-vaapi-driver | b2bb0383352694941826543a171b557efac2219b | [
"MIT"
] | null | null | null | android/android_42/base/libs/hwui/font/Font.h | yakuizhao/intel-vaapi-driver | b2bb0383352694941826543a171b557efac2219b | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2012 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.
*/
#ifndef ANDROID_HWUI_FONT_H
#define ANDROID_HWUI_FONT_H
#include <utils/KeyedVector.h>
#include <SkScalerContext.h>
#include <SkPaint.h>
#include <SkPathMeasure.h>
#include "CachedGlyphInfo.h"
#include "../Rect.h"
namespace android {
namespace uirenderer {
///////////////////////////////////////////////////////////////////////////////
// Font
///////////////////////////////////////////////////////////////////////////////
class FontRenderer;
/**
* Represents a font, defined by a Skia font id and a font size. A font is used
* to generate glyphs and cache them in the FontState.
*/
class Font {
public:
enum Style {
kFakeBold = 1
};
~Font();
/**
* Renders the specified string of text.
* If bitmap is specified, it will be used as the render target
*/
void render(SkPaint* paint, const char *text, uint32_t start, uint32_t len,
int numGlyphs, int x, int y, uint8_t *bitmap = NULL,
uint32_t bitmapW = 0, uint32_t bitmapH = 0);
void render(SkPaint* paint, const char *text, uint32_t start, uint32_t len,
int numGlyphs, int x, int y, const float* positions);
void render(SkPaint* paint, const char *text, uint32_t start, uint32_t len,
int numGlyphs, SkPath* path, float hOffset, float vOffset);
/**
* Creates a new font associated with the specified font state.
*/
static Font* create(FontRenderer* state, uint32_t fontId, float fontSize,
int flags, uint32_t italicStyle, uint32_t scaleX, SkPaint::Style style,
uint32_t strokeWidth);
private:
friend class FontRenderer;
typedef void (Font::*RenderGlyph)(CachedGlyphInfo*, int, int, uint8_t*,
uint32_t, uint32_t, Rect*, const float*);
enum RenderMode {
FRAMEBUFFER,
BITMAP,
MEASURE,
};
void precache(SkPaint* paint, const char* text, int numGlyphs);
void render(SkPaint* paint, const char *text, uint32_t start, uint32_t len,
int numGlyphs, int x, int y, RenderMode mode, uint8_t *bitmap,
uint32_t bitmapW, uint32_t bitmapH, Rect *bounds, const float* positions);
void measure(SkPaint* paint, const char* text, uint32_t start, uint32_t len,
int numGlyphs, Rect *bounds, const float* positions);
Font(FontRenderer* state, uint32_t fontId, float fontSize, int flags, uint32_t italicStyle,
uint32_t scaleX, SkPaint::Style style, uint32_t strokeWidth);
// Cache of glyphs
DefaultKeyedVector<glyph_t, CachedGlyphInfo*> mCachedGlyphs;
void invalidateTextureCache(CacheTexture* cacheTexture = NULL);
CachedGlyphInfo* cacheGlyph(SkPaint* paint, glyph_t glyph, bool precaching);
void updateGlyphCache(SkPaint* paint, const SkGlyph& skiaGlyph, CachedGlyphInfo* glyph,
bool precaching);
void measureCachedGlyph(CachedGlyphInfo* glyph, int x, int y,
uint8_t *bitmap, uint32_t bitmapW, uint32_t bitmapH,
Rect* bounds, const float* pos);
void drawCachedGlyph(CachedGlyphInfo* glyph, int x, int y,
uint8_t *bitmap, uint32_t bitmapW, uint32_t bitmapH,
Rect* bounds, const float* pos);
void drawCachedGlyphBitmap(CachedGlyphInfo* glyph, int x, int y,
uint8_t *bitmap, uint32_t bitmapW, uint32_t bitmapH,
Rect* bounds, const float* pos);
void drawCachedGlyph(CachedGlyphInfo* glyph, float x, float hOffset, float vOffset,
SkPathMeasure& measure, SkPoint* position, SkVector* tangent);
CachedGlyphInfo* getCachedGlyph(SkPaint* paint, glyph_t textUnit, bool precaching = false);
FontRenderer* mState;
uint32_t mFontId;
float mFontSize;
int mFlags;
uint32_t mItalicStyle;
uint32_t mScaleX;
SkPaint::Style mStyle;
uint32_t mStrokeWidth;
};
}; // namespace uirenderer
}; // namespace android
#endif // ANDROID_HWUI_FONT_H
| 34.526718 | 95 | 0.665045 | [
"render"
] |
7cb1b901fe5dab36d6bc42011eaf4a084679f775 | 6,440 | h | C | src/analyze.h | chenlijun99/FuzzGen | 0f6ad947b3d573407b573cc54833263e03a6af73 | [
"Apache-2.0"
] | 233 | 2019-11-01T19:05:17.000Z | 2022-03-19T07:00:11.000Z | src/analyze.h | chenlijun99/FuzzGen | 0f6ad947b3d573407b573cc54833263e03a6af73 | [
"Apache-2.0"
] | 21 | 2020-03-21T16:26:55.000Z | 2022-03-07T11:14:27.000Z | src/analyze.h | chenlijun99/FuzzGen | 0f6ad947b3d573407b573cc54833263e03a6af73 | [
"Apache-2.0"
] | 54 | 2020-05-28T00:12:38.000Z | 2022-03-19T07:00:13.000Z | // ------------------------------------------------------------------------------------------------
/*
* Copyright (C) 2018 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.
*
*
* ___ ___ ___ ___ ___ ___ ___
* /\__\ /\ \ /\__\ /\__\ /\__\ /\__\ /\ \
* /:/ _/_ \:\ \ /::| | /::| | /:/ _/_ /:/ _/_ \:\ \
* /:/ /\__\ \:\ \ /:/:| | /:/:| | /:/ /\ \ /:/ /\__\ \:\ \
* /:/ /:/ / ___ \:\ \ /:/|:| |__ /:/|:| |__ /:/ /::\ \ /:/ /:/ _/_ _____\:\ \
* /:/_/:/ / /\ \ \:\__\ /:/ |:| /\__\ /:/ |:| /\__\ /:/__\/\:\__\ /:/_/:/ /\__\ /::::::::\__\
* \:\/:/ / \:\ \ /:/ / \/__|:|/:/ / \/__|:|/:/ / \:\ \ /:/ / \:\/:/ /:/ / \:\~~\~~\/__/
* \::/__/ \:\ /:/ / |:/:/ / |:/:/ / \:\ /:/ / \::/_/:/ / \:\ \
* \:\ \ \:\/:/ / |::/ / |::/ / \:\/:/ / \:\/:/ / \:\ \
* \:\__\ \::/ / |:/ / |:/ / \::/ / \::/ / \:\__\
* \/__/ \/__/ |/__/ |/__/ \/__/ \/__/ \/__/
*
* FuzzGen - Automatic Fuzzer Generation
*
*
*
* analyze.h
*
* Header file for analyze.cpp.
*
*/
// ------------------------------------------------------------------------------------------------
#ifndef LIBRARY_ANALYZE_H
#define LIBRARY_ANALYZE_H
#include "common.h" // local includes
#include "interwork.h"
#include "llvm/Pass.h" // llvm includes
#include "llvm/IR/Module.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/CallSite.h"
#include "llvm/Analysis/CallGraph.h"
#include "llvm/Analysis/Passes.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/Support/SourceMgr.h"
#include <typeinfo> // c++ includes
#include <cstring>
#include <set>
#include <map>
using namespace llvm;
using namespace std;
/* analyzer status */
enum AnalyzerStatus {
STATUS_FAILURE = 0x00,
STATUS_SUCCESS = 0x01
};
/* analyzer status */
enum ModuleType {
MODULE_ANY = 0x00,
MODULE_LIBRARY = 0x01,
MODULE_EXTERNAL = 0x02
};
class AnalyzerNGRecursive; // forward declaration
// ------------------------------------------------------------------------------------------------
// * ModulesNG module *
//
// The next generation class for holding and processing all analyzed modules.
//
class ModulesNG {
public:
struct ModuleObject { // module object
string name; // module name
Module *module; // actuall llvm module
int type; // module type
};
/* class constructor */
ModulesNG();
/* class destructor */
~ModulesNG();
/* associate a module name with a type */
void assocType(string, int);
/* add a module to the list */
bool add(string, Module *);
/* get the library module (when there are multiple external ones) */
Module *getLibModule();
/* clear all modules */
void clear();
// private:
vector<ModuleObject *> modules; // the actual modules
map<string, int> modType; // module type
};
// ------------------------------------------------------------------------------------------------
// * AnalyzerNG module *
//
// The next generation analyzer that analyze multiple IR modules at once
//
class AnalyzerNG {
public:
ModulesNG modules; // analyzed modules (next generation)
/* class constructor */
AnalyzerNG(Context *);
/* class destructor */
~AnalyzerNG();
/* add an IR file to analyze */
void addIR(string, int);
/* add an LLVM Pass to run on the analyzed files */
void addPass(Pass *);
/* run the Pass on all IR files */
int run();
/* quickly run a Pass on a single IR file */
int quickRun(string, Pass *);
/* clear analyzer's state */
void clear();
private:
Context *ctx; // execution context
deque<string> filenames; // IR file names
Pass *pass; // Pass object
/* the actual function that runs the Pass on some IR files */
static int runIntrl(string, Pass *, Context *);
/* AnalyzerNGRecursive is a friend class so it can access runIntrl() */
friend class AnalyzerNGRecursive;
};
// ------------------------------------------------------------------------------------------------
// * AnalyzerNGRecursive module *
//
// The recursive version of the next generation analyzer that assists the whole process.
//
class AnalyzerNGRecursive : public ModulePass {
public:
static char ID; // Pass ID
/* function to invoke on each module */
bool runOnModule(Module &) override;
/* override these functions from ModulePass */
virtual void getAnalysisUsage(AnalysisUsage &) const override;
virtual StringRef getPassName() const override { return "analyzer-ng"; }
/* class constructor */
AnalyzerNGRecursive(deque<string> &, ModulesNG &, Pass *, Context *);
/* class destructor */
~AnalyzerNGRecursive();
private:
Context *ctx; // execution context
Pass *pass; // Pass object
deque<string> &filenames; // IR file names
ModulesNG &modules; // analyzed module objects
};
// ------------------------------------------------------------------------------------------------
#endif
| 31.568627 | 99 | 0.45854 | [
"object",
"vector"
] |
7cb8cdbbc0c1a1d5d00d0da6dc5abcc5bab4bf48 | 2,453 | h | C | benchmarks/fmm-2d/exafmm.h | CHART-Team/xitao | 497a7eec3651df19dd8df02126f3b28ab1f20cbf | [
"BSD-3-Clause"
] | 2 | 2020-12-03T13:16:37.000Z | 2020-12-15T11:35:11.000Z | benchmarks/fmm-2d/exafmm.h | CHART-Team/xitao | 497a7eec3651df19dd8df02126f3b28ab1f20cbf | [
"BSD-3-Clause"
] | null | null | null | benchmarks/fmm-2d/exafmm.h | CHART-Team/xitao | 497a7eec3651df19dd8df02126f3b28ab1f20cbf | [
"BSD-3-Clause"
] | null | null | null | #ifndef exafmm_h
#define exafmm_h
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <vector>
namespace exafmm {
//! Basic type definitions
typedef double real_t; //!< Floating point type is single precision
typedef std::complex<real_t> complex_t; //!< Complex type
//! Structure of bodies
struct Body {
real_t X[2]; //!< Position
real_t q; //!< Charge
real_t p; //!< Potential
real_t F[2]; //!< Force
};
typedef std::vector<Body> Bodies; //!< Vector of bodies
//! Structure of cells
struct Cell {
int NCHILD; //!< Number of child cells
int NBODY; //!< Number of descendant bodies
size_t INDEX; //!< Index of cell in the vector of cells
Cell * CHILD; //!< Pointer of first child cell
Body * BODY; //!< Pointer of first body
real_t X[2]; //!< Cell center
real_t R; //!< Cell radius
std::vector<Cell*> listM2L; //!< M2L interaction list
std::vector<Cell*> listP2P; //!< P2P interaction list
std::vector<complex_t> M; //!< Multipole expansion coefficients
std::vector<complex_t> L; //!< Local expansion coefficients
};
typedef std::vector<Cell> Cells; //!< Vector of cells
//! Global variables
int P; //!< Order of expansions
int ncrit; //!< Number of bodies per leaf cell
real_t theta; //!< Multipole acceptance criterion
real_t dX[2]; //!< Distance vector
#pragma omp threadprivate(dX) //!< Make global variables private
}
#endif
| 52.191489 | 108 | 0.387281 | [
"vector"
] |
2d9f805e964bc5eaf8f51f3a4e9faf50c318ef2c | 7,358 | h | C | CoreImage/CIFilter+Essentials.h | Tricertops/Essentials | 4f7ed910cd470158315137b724704be53cf1772e | [
"MIT"
] | 17 | 2016-02-13T12:20:42.000Z | 2021-04-26T22:54:41.000Z | CoreImage/CIFilter+Essentials.h | Tricertops/Essentials | 4f7ed910cd470158315137b724704be53cf1772e | [
"MIT"
] | null | null | null | CoreImage/CIFilter+Essentials.h | Tricertops/Essentials | 4f7ed910cd470158315137b724704be53cf1772e | [
"MIT"
] | 1 | 2018-11-16T06:08:22.000Z | 2018-11-16T06:08:22.000Z | //
// CIFilter+Essentials.h
// Essentials
//
// Created by Martin Kiss on 6.9.14.
// Copyright (c) 2014 iAdverti. All rights reserved.
//
#import "Foundation+Essentials.h"
#import "CoreImage+Essentials.h"
typedef CGFloat CIScalar;
typedef CGFloat CIDistance;
typedef CGFloat CIAngle;
@interface CIFilter (Essentials)
#pragma mark - Properties
/// Forwards to value for key "inputImage".
@property CIImage *inputImage;
#pragma mark - Combining
/// Sets input image of the argument to output image of the receiver.
- (void)connectToFilter:(CIFilter *)filter;
/// Connects input images with output images. Returns last filter of the input array.
+ (CIFilter *)chainFilters:(NSArray<CIFilter *> *)filters;
#pragma mark - Factory
/// Convenience constructors for many filters listed in Core Image Filter Reference.
#pragma mark Category: Geometry
/// Applies a crop to an image. (CICrop)
+ (instancetype)crop:(CGRect)extent;
/// Applies an affine transform to an image. (CIAffineTransform)
+ (instancetype)transform:(CGAffineTransform)transform;
/// Applies a scale to an image. (CIAffineTransform)
+ (instancetype)scale:(CGSize)scales;
/// Applies a rotation to an image. (CIAffineTransform)
+ (instancetype)rotate:(CIAngle)radians;
/// Applies a translation to an image. (CIAffineTransform)
+ (instancetype)move:(CGPoint)offset;
/// Rotates the source image. The image is scaled and cropped so it fits the extent of the input image. (CIStraightenFilter)
+ (instancetype)straighten:(CIAngle)radians;
#pragma mark Category: Blur
/// Spreads source pixels by an amount specified by a Gaussian distribution. (CIGaussianBlur)
+ (instancetype)blurWithRadius:(CIDistance)radius;
/// Blurs an image to simulate the effect of using a camera that moves a specified angle. (CIMotionBlur)
+ (instancetype)motionBlurWithRadius:(CIDistance)radius angle:(CIAngle)radians;
/// Simulates the effect of zooming the camera while capturing the image. (CIZoomBlur)
+ (instancetype)zoomBlurWithAmount:(CIDistance)amount center:(CIVector *)center;
#pragma mark Category: Color Adjustments
/// Modifies color values to keep them within a specified range. (CIColorClamp)
+ (instancetype)clampColorsFrom:(CIVector *)minRGBA to:(CIVector *)maxRGBA;
/// Modifies red component values to keep them within a specified range. (CIColorClamp)
+ (instancetype)clampRedFrom:(CIScalar)min to:(CIScalar)max;
/// Modifies green component values to keep them within a specified range. (CIColorClamp)
+ (instancetype)clampGreenFrom:(CIScalar)min to:(CIScalar)max;
/// Modifies blue component values to keep them within a specified range. (CIColorClamp)
+ (instancetype)clampBlueFrom:(CIScalar)min to:(CIScalar)max;
/// Modifies alpha component values to keep them within a specified range. (CIColorClamp)
+ (instancetype)clampAlphaFrom:(CIScalar)min to:(CIScalar)max;
/// Adjusts saturation, brightness, and contrast values. Parameter details below. (CIColorControls)
+ (instancetype)adjustSaturation:(CIScalar)s brightness:(CIScalar)b contrast:(CIScalar)c;
/// Adjusts saturation only. Pass 0.0 for grayscale, 1.0 for original or >1 for to increase saturation. (CIColorControls)
+ (instancetype)adjustSaturation:(CIScalar)saturation;
/// Adjusts brightness only. Parameter is added to add color components. (CIColorControls)
+ (instancetype)adjustBrightness:(CIScalar)brightness;
/// Adjusts contrast only. Pass 1.0 for original. (CIColorControls)
+ (instancetype)adjustContrast:(CIScalar)contrast;
/// Multiplies source color values and adds a bias factor to each color component.
+ (instancetype)transformRed:(CIVector *)rRGBA green:(CIVector *)gRGBA blue:(CIVector *)bRGBA alpha:(CIVector *)aRGBA bias:(CIVector *)biasRGBA;
/// Multiplies source color values and adds a bias factor to red color component.
+ (instancetype)transformRed:(CIVector *)RGBA bias:(CIScalar)bias;
/// Multiplies source color values and adds a bias factor to green color component.
+ (instancetype)transformGreen:(CIVector *)RGBA bias:(CIScalar)bias;
/// Multiplies source color values and adds a bias factor to blue color component.
+ (instancetype)transformBlue:(CIVector *)RGBA bias:(CIScalar)bias;
/// Multiplies source color values and adds a bias factor to alpha color component.
+ (instancetype)transformAlpha:(CIVector *)RGBA bias:(CIScalar)bias;
/// Adjusts the exposure setting for an image similar to the way you control exposure for a camera when you change the F-stop. (CIExposureAdjust)
+ (instancetype)adjustExposure:(CIScalar)EV;
/// Adjusts midtone brightness. (CIGammaAdjust)
+ (instancetype)adjustGamma:(CIScalar)power;
/// Changes the overall hue, or tint, of the source pixels. (CIHueAdjust)
+ (instancetype)adjustHue:(CIAngle)angle;
/// Adjusts the saturation of an image while keeping pleasing skin tones. (CIVibrance)
+ (instancetype)adjustVibrance:(CIScalar)amount;
/// Adjusts the reference white point for an image and maps all colors in the source using the new reference. (CIWhitePointAdjust)
+ (instancetype)adjustWhitePoint:(CIColor *)color;
#pragma mark Category: Color Effects
/// Inverts the colors in an image. (CIColorInvert)
+ (instancetype)invertColors;
/// Desaturates colors in the image (CIColorControls with “saturation” 0.0)
+ (instancetype)grayscaleColors;
/// Remaps colors so they fall within shades of a single color. (CIColorMonochrome)
+ (instancetype)monochromeColor:(CIColor *)color intensity:(CIScalar)intensity;
/// Remaps red, green, and blue color components to the number of brightness values you specify for each color component. (CIColorPosterize)
+ (instancetype)posterizeWithLevels:(CIScalar)levels;
/// Maps luminance to a color ramp of two colors. (CIFalseColor)
+ (instancetype)falseColor:(CIColor *)color0 toColor:(CIColor *)color1;
/// Converts a grayscale image to a white image that is masked by alpha, the black values become completely transparent.
+ (instancetype)maskToAlpha;
/// Maps the colors of an image to various shades of brown. (CISepiaTone)
+ (instancetype)sepiaWithIntensity:(CIScalar)intensity;
/// Reduces the brightness of an image at the periphery. (CIVignette)
+ (instancetype)vignetteWithRadius:(CIDistance)radius intensity:(CIScalar)intensity;
#pragma mark Category: Photo Effects
/// These 8 filters are used in iOS 7 Camera app and they apply a preconfigured set of effects.
/// Imitate vintage photography film with exaggerated color. (CIPhotoEffectChrome)
+ (instancetype)photoEffectChrome;
/// Imitate vintage photography film with diminished color. (CIPhotoEffectFade)
+ (instancetype)photoEffectFade;
/// Imitate vintage photography film with distorted colors. (CIPhotoEffectInstant)
+ (instancetype)photoEffectInstant;
/// Imitate black-and-white photography film with low contrast. (CIPhotoEffectMono)
+ (instancetype)photoEffectMono;
/// Imitate black-and-white photography film with exaggerated contrast. (CIPhotoEffectNoir)
+ (instancetype)photoEffectNoir;
/// Imitate vintage photography film with emphasized cool colors. (CIPhotoEffectProcess)
+ (instancetype)photoEffectProcess;
/// Imitate black-and-white photography film without significantly altering contrast. (CIPhotoEffectTonal)
+ (instancetype)photoEffectTonal;
/// Imitate vintage photography film with emphasized warm colors. (CIPhotoEffectTransfer)
+ (instancetype)photoEffectTransfer;
@end
| 40.428571 | 145 | 0.779967 | [
"geometry",
"transform"
] |
2dad67bcd65815d0de896c8363356e4f3d544163 | 1,090 | h | C | BSOPM_new/BSOPM_new/BSOPM.h | xnd-r/BlackScholesOptionPricingModel | 23f86028afe809a6d2db427df3ed2addb0811b00 | [
"MIT"
] | 1 | 2021-06-21T12:56:27.000Z | 2021-06-21T12:56:27.000Z | BSOPM_new/BSOPM_new/BSOPM.h | xnd-r/BlackScholesOptionPricingModel | 23f86028afe809a6d2db427df3ed2addb0811b00 | [
"MIT"
] | null | null | null | BSOPM_new/BSOPM_new/BSOPM.h | xnd-r/BlackScholesOptionPricingModel | 23f86028afe809a6d2db427df3ed2addb0811b00 | [
"MIT"
] | 1 | 2020-07-07T12:06:23.000Z | 2020-07-07T12:06:23.000Z | // (c) 2019 Alexander Romanov
#ifndef ____BLACK_SHOLES_OPTION_PRICING_MODELING____
#define ____BLACK_SHOLES_OPTION_PRICING_MODELING____
#include <omp.h>
#include "mkl.h"
#include <math.h>
#include <time.h>
#include <string>
#include <algorithm>
#include <vector>
//#include <stdio.h>
#include <assert.h>
#include <iostream>
#if defined(_WIN64) || defined(_WIN32)
#define _CRT_SECURE_NO_WARNINGS // using unsafe functions
#pragma warning(disable : 4068) // fopen warning disable
//#pragma warning(disable : 4005) // fopen warning disable
#pragma warning(disable : 4005) // fopen warning disable
#pragma warning(disable : 4996) // REDEFINITION WARNING DISABLED!
#endif
class BSOPM {
public:
BSOPM() {};
~BSOPM() {};
/*protected*/
VSLStreamStatePtr initGen(unsigned int seed, int indexGen/*, int dim = 1*/);
void wienerProcess(VSLStreamStatePtr stream, int nsteps, float time, float *dw);
void wAndZProcesses(VSLStreamStatePtr stream, int nsteps, float time, float *buffer);
std::string getTimestamp(std::string fileName);
};
#endif // !____BLACK_SHOLES_OPTION_PRICING_MODELING____
| 30.277778 | 86 | 0.758716 | [
"vector"
] |
2dbc604d10eec8d00aafe674bfa094987e3da137 | 13,885 | h | C | modules/sofa/component/typedef/InteractionForceField_float.h | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | modules/sofa/component/typedef/InteractionForceField_float.h | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | modules/sofa/component/typedef/InteractionForceField_float.h | sofa-framework/issofa | 94855f488465bc3ed41223cbde987581dfca5389 | [
"OML"
] | null | null | null | /******************************************************************************
* SOFA, Simulation Open-Framework Architecture, development version *
* (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH *
* *
* This program 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 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 Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
// File automatically generated by "generateTypedef"
#ifndef SOFA_TYPEDEF_InteractionForceField_float_H
#define SOFA_TYPEDEF_InteractionForceField_float_H
//Default files containing the declaration of the vector type
#include <sofa/defaulttype/VecTypes.h>
#include <sofa/defaulttype/RigidTypes.h>
#include <sofa/defaulttype/Mat.h>
#include <SofaGeneralObjectInteraction/BoxStiffSpringForceField.h>
#include <SofaGeneralDeformable/FrameSpringForceField.h>
#include <SofaMiscForceField/GearSpringForceField.h>
#include <SofaGeneralObjectInteraction/InteractionEllipsoidForceField.h>
#include <SofaRigid/JointSpringForceField.h>
#include <SofaMiscForceField/LineBendingSprings.h>
#include <SofaDeformable/MeshSpringForceField.h>
#include <SofaObjectInteraction/PenalityContactForceField.h>
#include <SofaGeneralDeformable/QuadBendingSprings.h>
#include <SofaGeneralDeformable/RegularGridSpringForceField.h>
#include <SofaGeneralObjectInteraction/RepulsiveSpringForceField.h>
#include <SofaDeformable/SpringForceField.h>
#include <SofaDeformable/StiffSpringForceField.h>
#include <SofaGeneralDeformable/TriangleBendingSprings.h>
#include <SofaGeneralDeformable/VectorSpringForceField.h>
//---------------------------------------------------------------------------------------------
//Typedef for BoxStiffSpringForceField
typedef sofa::component::interactionforcefield::BoxStiffSpringForceField<sofa::defaulttype::StdVectorTypes<sofa::defaulttype::Vec<1, float>, sofa::defaulttype::Vec<1, float>, float> > BoxStiffSpringForceField1f;
typedef sofa::component::interactionforcefield::BoxStiffSpringForceField<sofa::defaulttype::StdVectorTypes<sofa::defaulttype::Vec<2, float>, sofa::defaulttype::Vec<2, float>, float> > BoxStiffSpringForceField2f;
typedef sofa::component::interactionforcefield::BoxStiffSpringForceField<sofa::defaulttype::StdVectorTypes<sofa::defaulttype::Vec<3, float>, sofa::defaulttype::Vec<3, float>, float> > BoxStiffSpringForceField3f;
typedef sofa::component::interactionforcefield::BoxStiffSpringForceField<sofa::defaulttype::StdVectorTypes<sofa::defaulttype::Vec<6, float>, sofa::defaulttype::Vec<6, float>, float> > BoxStiffSpringForceField6f;
//---------------------------------------------------------------------------------------------
//Typedef for FrameSpringForceField
typedef sofa::component::interactionforcefield::FrameSpringForceField<sofa::defaulttype::StdRigidTypes<3, float> > FrameSpringForceFieldRigid3f;
//---------------------------------------------------------------------------------------------
//Typedef for GearSpringForceField
typedef sofa::component::interactionforcefield::GearSpringForceField<sofa::defaulttype::StdRigidTypes<3, float> > GearSpringForceFieldRigid3f;
//---------------------------------------------------------------------------------------------
//Typedef for InteractionEllipsoidForceField
typedef sofa::component::interactionforcefield::InteractionEllipsoidForceField<sofa::defaulttype::StdVectorTypes<sofa::defaulttype::Vec<3, float>, sofa::defaulttype::Vec<3, float>, float>, sofa::defaulttype::StdRigidTypes<3, float> > InteractionEllipsoidForceField3f_Rigid3f;
//---------------------------------------------------------------------------------------------
//Typedef for JointSpringForceField
typedef sofa::component::interactionforcefield::JointSpringForceField<sofa::defaulttype::StdRigidTypes<3, float> > JointSpringForceFieldRigid3f;
//---------------------------------------------------------------------------------------------
//Typedef for LineBendingSprings
typedef sofa::component::interactionforcefield::LineBendingSprings<sofa::defaulttype::StdVectorTypes<sofa::defaulttype::Vec<2, float>, sofa::defaulttype::Vec<2, float>, float> > LineBendingSprings2f;
typedef sofa::component::interactionforcefield::LineBendingSprings<sofa::defaulttype::StdVectorTypes<sofa::defaulttype::Vec<3, float>, sofa::defaulttype::Vec<3, float>, float> > LineBendingSprings3f;
//---------------------------------------------------------------------------------------------
//Typedef for MeshSpringForceField
typedef sofa::component::interactionforcefield::MeshSpringForceField<sofa::defaulttype::StdVectorTypes<sofa::defaulttype::Vec<1, float>, sofa::defaulttype::Vec<1, float>, float> > MeshSpringForceField1f;
typedef sofa::component::interactionforcefield::MeshSpringForceField<sofa::defaulttype::StdVectorTypes<sofa::defaulttype::Vec<2, float>, sofa::defaulttype::Vec<2, float>, float> > MeshSpringForceField2f;
typedef sofa::component::interactionforcefield::MeshSpringForceField<sofa::defaulttype::StdVectorTypes<sofa::defaulttype::Vec<3, float>, sofa::defaulttype::Vec<3, float>, float> > MeshSpringForceField3f;
//---------------------------------------------------------------------------------------------
//Typedef for PenalityContactForceField
typedef sofa::component::interactionforcefield::PenalityContactForceField<sofa::defaulttype::StdVectorTypes<sofa::defaulttype::Vec<3, float>, sofa::defaulttype::Vec<3, float>, float> > PenalityContactForceField3f;
//---------------------------------------------------------------------------------------------
//Typedef for QuadBendingSprings
typedef sofa::component::interactionforcefield::QuadBendingSprings<sofa::defaulttype::StdVectorTypes<sofa::defaulttype::Vec<2, float>, sofa::defaulttype::Vec<2, float>, float> > QuadBendingSprings2f;
typedef sofa::component::interactionforcefield::QuadBendingSprings<sofa::defaulttype::StdVectorTypes<sofa::defaulttype::Vec<3, float>, sofa::defaulttype::Vec<3, float>, float> > QuadBendingSprings3f;
//---------------------------------------------------------------------------------------------
//Typedef for RegularGridSpringForceField
typedef sofa::component::interactionforcefield::RegularGridSpringForceField<sofa::defaulttype::StdVectorTypes<sofa::defaulttype::Vec<1, float>, sofa::defaulttype::Vec<1, float>, float> > RegularGridSpringForceField1f;
typedef sofa::component::interactionforcefield::RegularGridSpringForceField<sofa::defaulttype::StdVectorTypes<sofa::defaulttype::Vec<2, float>, sofa::defaulttype::Vec<2, float>, float> > RegularGridSpringForceField2f;
typedef sofa::component::interactionforcefield::RegularGridSpringForceField<sofa::defaulttype::StdVectorTypes<sofa::defaulttype::Vec<3, float>, sofa::defaulttype::Vec<3, float>, float> > RegularGridSpringForceField3f;
typedef sofa::component::interactionforcefield::RegularGridSpringForceField<sofa::defaulttype::StdVectorTypes<sofa::defaulttype::Vec<6, float>, sofa::defaulttype::Vec<6, float>, float> > RegularGridSpringForceField6f;
//---------------------------------------------------------------------------------------------
//Typedef for RepulsiveSpringForceField
typedef sofa::component::interactionforcefield::RepulsiveSpringForceField<sofa::defaulttype::StdVectorTypes<sofa::defaulttype::Vec<1, float>, sofa::defaulttype::Vec<1, float>, float> > RepulsiveSpringForceField1f;
typedef sofa::component::interactionforcefield::RepulsiveSpringForceField<sofa::defaulttype::StdVectorTypes<sofa::defaulttype::Vec<2, float>, sofa::defaulttype::Vec<2, float>, float> > RepulsiveSpringForceField2f;
typedef sofa::component::interactionforcefield::RepulsiveSpringForceField<sofa::defaulttype::StdVectorTypes<sofa::defaulttype::Vec<3, float>, sofa::defaulttype::Vec<3, float>, float> > RepulsiveSpringForceField3f;
//---------------------------------------------------------------------------------------------
//Typedef for SpringForceField
typedef sofa::component::interactionforcefield::SpringForceField<sofa::defaulttype::StdVectorTypes<sofa::defaulttype::Vec<1, float>, sofa::defaulttype::Vec<1, float>, float> > SpringForceField1f;
typedef sofa::component::interactionforcefield::SpringForceField<sofa::defaulttype::StdVectorTypes<sofa::defaulttype::Vec<2, float>, sofa::defaulttype::Vec<2, float>, float> > SpringForceField2f;
typedef sofa::component::interactionforcefield::SpringForceField<sofa::defaulttype::StdVectorTypes<sofa::defaulttype::Vec<3, float>, sofa::defaulttype::Vec<3, float>, float> > SpringForceField3f;
typedef sofa::component::interactionforcefield::SpringForceField<sofa::defaulttype::StdVectorTypes<sofa::defaulttype::Vec<6, float>, sofa::defaulttype::Vec<6, float>, float> > SpringForceField6f;
//---------------------------------------------------------------------------------------------
//Typedef for StiffSpringForceField
typedef sofa::component::interactionforcefield::StiffSpringForceField<sofa::defaulttype::StdVectorTypes<sofa::defaulttype::Vec<1, float>, sofa::defaulttype::Vec<1, float>, float> > StiffSpringForceField1f;
typedef sofa::component::interactionforcefield::StiffSpringForceField<sofa::defaulttype::StdVectorTypes<sofa::defaulttype::Vec<2, float>, sofa::defaulttype::Vec<2, float>, float> > StiffSpringForceField2f;
typedef sofa::component::interactionforcefield::StiffSpringForceField<sofa::defaulttype::StdVectorTypes<sofa::defaulttype::Vec<3, float>, sofa::defaulttype::Vec<3, float>, float> > StiffSpringForceField3f;
typedef sofa::component::interactionforcefield::StiffSpringForceField<sofa::defaulttype::StdVectorTypes<sofa::defaulttype::Vec<6, float>, sofa::defaulttype::Vec<6, float>, float> > StiffSpringForceField6f;
//---------------------------------------------------------------------------------------------
//Typedef for TriangleBendingSprings
typedef sofa::component::interactionforcefield::TriangleBendingSprings<sofa::defaulttype::StdVectorTypes<sofa::defaulttype::Vec<2, float>, sofa::defaulttype::Vec<2, float>, float> > TriangleBendingSprings2f;
typedef sofa::component::interactionforcefield::TriangleBendingSprings<sofa::defaulttype::StdVectorTypes<sofa::defaulttype::Vec<3, float>, sofa::defaulttype::Vec<3, float>, float> > TriangleBendingSprings3f;
//---------------------------------------------------------------------------------------------
//Typedef for VectorSpringForceField
typedef sofa::component::interactionforcefield::VectorSpringForceField<sofa::defaulttype::StdVectorTypes<sofa::defaulttype::Vec<3, float>, sofa::defaulttype::Vec<3, float>, float> > VectorSpringForceField3f;
#ifdef SOFA_FLOAT
typedef BoxStiffSpringForceField1f BoxStiffSpringForceField1;
typedef BoxStiffSpringForceField2f BoxStiffSpringForceField2;
typedef BoxStiffSpringForceField3f BoxStiffSpringForceField3;
typedef BoxStiffSpringForceField6f BoxStiffSpringForceField6;
typedef FrameSpringForceFieldRigid3f FrameSpringForceFieldRigid3;
typedef GearSpringForceFieldRigid3f GearSpringForceFieldRigid3;
typedef InteractionEllipsoidForceField3f_Rigid3f InteractionEllipsoidForceField3_Rigid3;
typedef JointSpringForceFieldRigid3f JointSpringForceFieldRigid3;
typedef LineBendingSprings2f LineBendingSprings2;
typedef LineBendingSprings3f LineBendingSprings3;
typedef MeshSpringForceField1f MeshSpringForceField1;
typedef MeshSpringForceField2f MeshSpringForceField2;
typedef MeshSpringForceField3f MeshSpringForceField3;
typedef PenalityContactForceField3f PenalityContactForceField3;
typedef QuadBendingSprings2f QuadBendingSprings2;
typedef QuadBendingSprings3f QuadBendingSprings3;
typedef RegularGridSpringForceField1f RegularGridSpringForceField1;
typedef RegularGridSpringForceField2f RegularGridSpringForceField2;
typedef RegularGridSpringForceField3f RegularGridSpringForceField3;
typedef RegularGridSpringForceField6f RegularGridSpringForceField6;
typedef RepulsiveSpringForceField1f RepulsiveSpringForceField1;
typedef RepulsiveSpringForceField2f RepulsiveSpringForceField2;
typedef RepulsiveSpringForceField3f RepulsiveSpringForceField3;
typedef SpringForceField1f SpringForceField1;
typedef SpringForceField2f SpringForceField2;
typedef SpringForceField3f SpringForceField3;
typedef SpringForceField6f SpringForceField6;
typedef StiffSpringForceField1f StiffSpringForceField1;
typedef StiffSpringForceField2f StiffSpringForceField2;
typedef StiffSpringForceField3f StiffSpringForceField3;
typedef StiffSpringForceField6f StiffSpringForceField6;
typedef TriangleBendingSprings2f TriangleBendingSprings2;
typedef TriangleBendingSprings3f TriangleBendingSprings3;
typedef VectorSpringForceField3f VectorSpringForceField3;
#endif
#endif
| 67.402913 | 275 | 0.700972 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.