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
8828efc1587444d0ce6c98007e7d2a1be7ee4613
750
h
C
src/memory.h
QcO-dev/dragon
25de2e6e69e9631dd741771518b16f7e9b16bbff
[ "MIT" ]
4
2021-08-30T12:51:20.000Z
2021-11-24T23:11:13.000Z
src/memory.h
QcO-dev/dragon
25de2e6e69e9631dd741771518b16f7e9b16bbff
[ "MIT" ]
2
2021-11-24T21:14:52.000Z
2021-11-24T21:25:25.000Z
src/memory.h
QcO-dev/dragon
25de2e6e69e9631dd741771518b16f7e9b16bbff
[ "MIT" ]
null
null
null
#pragma once #include "common.h" #include "value.h" #define GROW_CAPACITY(capacity) \ ((capacity) < 8 ? 8 : (capacity) * 2) #define GROW_ARRAY(vm, type, pointer, oldCount, newCount) \ (type*)reallocate(vm, pointer, sizeof(type) * (oldCount), sizeof(type) * (newCount)) #define FREE_ARRAY(vm, type, pointer, oldCount) \ reallocate(vm, pointer, sizeof(type) * (oldCount), 0) #define ALLOCATE(vm, type, count) \ (type*)reallocate(vm, NULL, 0, sizeof(type) * (count)) #define FREE(vm, type, pointer) reallocate(vm, pointer, sizeof(type), 0) void* reallocate(VM* vm, void* pointer, size_t oldSize, size_t newSize); void markObject(VM* vm, Obj* object); void markValue(VM* vm, Value value); void collectGarbage(VM* vm); void freeObjects(VM* vm);
31.25
85
0.701333
[ "object" ]
88293dd5f023159b2e1974628ab0abf31871c962
4,855
h
C
tvos/static/YouboraLibTvOS.framework/Headers/YBCommunication.h
NicePeopleAtWork/Youbora-YouboraLib-iOS
5cf67520d32968357153288a197d7825a9b265c9
[ "MIT" ]
null
null
null
tvos/static/YouboraLibTvOS.framework/Headers/YBCommunication.h
NicePeopleAtWork/Youbora-YouboraLib-iOS
5cf67520d32968357153288a197d7825a9b265c9
[ "MIT" ]
null
null
null
tvos/static/YouboraLibTvOS.framework/Headers/YBCommunication.h
NicePeopleAtWork/Youbora-YouboraLib-iOS
5cf67520d32968357153288a197d7825a9b265c9
[ "MIT" ]
null
null
null
// // YBCommunication.h // YBPluginGeneric // // Created by Joan on 31/03/16. // Copyright © 2016 Nice People At Work. All rights reserved. // #import <Foundation/Foundation.h> #import "YBRequest.h" @class YBPluginGeneric; NS_ASSUME_NONNULL_BEGIN typedef NSMutableDictionary * _Nullable (^YBAdditionalOperationsCallback) (NSMutableDictionary * params); /** * YBCommunication implements the last abstraction layer against NQS calls. * Internally, YBCommunication implements an array of <YBRequest> objects, executing one after another. * All requests will be blocked until a first /data call is made, before context, any request sent will be queued. */ @interface YBCommunication : NSObject /// --------------------------------- /// @name Public properties /// --------------------------------- /// Ping time interval in milliseconds. @property (nonatomic, strong) NSNumber * pingTime; /// Host where all the requests will be made to. @property (nonatomic, strong) NSString * host; /// Boolean wich indicates wether to use https or not. @property (nonatomic, assign) NSValue * httpSecure; /** * If defined, and extra data may be required (such as resource parser info), YBCommunication * will call this callback to give the chance of completing the params. */ @property (nonatomic, copy) YBAdditionalOperationsCallback _Nullable additionalOperationsCallback; /// --------------------------------- /// @name Init /// --------------------------------- /** * Constructor method * * @param host The host where to send the requests * @param httpSecure Use https if @YES, http if @NO * @returns An instance of YBCommunication */ - (instancetype) initWithHost:(NSString *)host andHTTPSecure:(NSValue *) httpSecure; /// --------------------------------- /// @name Public methods /// --------------------------------- /** * @returns the current view code */ - (NSString *) getViewCode; /** * Creates and returns a new view code. * @param isLive If true the new code will have a leading "L", or a "V" otherwise. * @returns The newly-generated view code. */ - (NSString *) nextView:(NSValue *) isLive; /** * Convenience mehtod to call <requestDataWithParams:andCallback:> with no callback. * @param params An NSDictionary of parameters sent with the request. */ - (void) requestDataWithParams:(NSDictionary *) params; /** * Sends '/data' request. * * This has to be the first request and all * other requests will wait until we got the response from this one. * * @param params An NSDictionary of parameters sent with the request: * * - system: System code. * - pluginVersion: Something like "X.Y.Z-\<pluginName\>" * - live: true if the content is live. False if VOD. Do not set if unknown. * @param callback The success callback for the YBRequest object */ - (void) requestDataWithParams:(NSDictionary *) params andCallback:(_Nullable YBRequestSuccessBlock) callback; /** * Parse the /data params from the NSData got in a success callback * @param data The NSData to get the /data parameters from. This should be a jsonp. */ - (void) receiveDataFromData:(NSData *) data; /** * Sends a generic request. All the specific functions use this method. * * @param service A string with the service to be called. ie: 'nqs.nice264.com/data', '/joinTime'... * @param params An NSDictionary with the argumentss of the call. * @param callback The success callback for the <YBRequest> object */ - (void) sendRequestWithServiceName:(NSString *) service params:(NSDictionary *) params andCallback:(_Nullable YBRequestSuccessBlock) callback; /** * Sends a service request. * * @param service A string with the service to be called. ie: 'nqs.nice264.com/data', '/joinTime'... * @param params An NSDictionary with the argumentss of the call. * @param callback The success callback for the YBRequest object */ - (void) sendServiceWithServiceName:(NSString *) service params:(NSDictionary *) params andCallback:(_Nullable YBRequestSuccessBlock) callback; /** * Checks if a preloader exists. * * @param preloader Unique identifier of the blocker. ie: "CDNParser". * @returns true if the preloader is in the list, false otherwise */ - (bool) hasPreloader:(NSString *) preloader; /** * Adds a preloader to the queue. * * While this queue is not empty, all requests will be stoped. * @warning Remember to call removePreloader: to unblock the main queue * * @param preloader Unique identifier of the blocker. ie: 'CDNParser'. */ - (void) addPreloader:(NSString *) preloader; /** * Removes a preloader. * * The preloader has to be previously set with the addPreloader: method. * If it was the last preloader, all queued requests will be sent. * * @param preloader Unique identifier of the blocker. ie: 'CDNParser'. */ - (void) removePreloader:(NSString *) preloader; @end NS_ASSUME_NONNULL_END
33.027211
143
0.699485
[ "object" ]
883b25e629ee53791f0790180db76800147922a6
1,157
h
C
igl/dated_copy.h
sabinaRachev/3D-Snake-Game-Final-Project
5c1f2044d848f24d6ce60dc61411393b503c8da2
[ "Apache-2.0" ]
null
null
null
igl/dated_copy.h
sabinaRachev/3D-Snake-Game-Final-Project
5c1f2044d848f24d6ce60dc61411393b503c8da2
[ "Apache-2.0" ]
null
null
null
igl/dated_copy.h
sabinaRachev/3D-Snake-Game-Final-Project
5c1f2044d848f24d6ce60dc61411393b503c8da2
[ "Apache-2.0" ]
null
null
null
// This file is part of libigl, a simple c++ geometry processing library. // // Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com> // // 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/. // Known issues: This function does not work under windows #ifndef IGL_DATED_COPY_H #define IGL_DATED_COPY_H #include "igl_inline.h" #include <string> namespace igl { // Copy the given file to a new file with the same basename in `dir` // directory with the current date and time as a suffix. // // Inputs: // src_path path to source file // dir directory of destination file // Example: // dated_copy("/path/to/foo","/bar/"); // // copies /path/to/foo to /bar/foo-2013-12-12T18-10-56 IGL_INLINE bool dated_copy(const std::string & src_path, const std::string & dir); // Wrapper using directory of source file IGL_INLINE bool dated_copy(const std::string & src_path); } #ifndef IGL_STATIC_LIBRARY # include "dated_copy.cpp" #endif #endif
33.057143
85
0.686258
[ "geometry" ]
883c52da1a40bdfeac7996c1975768b0cdda6672
722
h
C
src/naive_rstore.h
Zomega/transverse
058b5dfc28a5ef1dab880f6112a27f2664725dff
[ "MIT" ]
null
null
null
src/naive_rstore.h
Zomega/transverse
058b5dfc28a5ef1dab880f6112a27f2664725dff
[ "MIT" ]
null
null
null
src/naive_rstore.h
Zomega/transverse
058b5dfc28a5ef1dab880f6112a27f2664725dff
[ "MIT" ]
null
null
null
// Copyright 2015 Will Oursler #ifndef NAIVE_RSTORE_H_ #define NAIVE_RSTORE_H_ #include <iostream> #include <vector> #include <utility> #include "bbox.h" #include "rstore.h" template <typename T> class NaiveRStore : public RStore<T> { private: std::vector<std::pair<T, BBox>> entries; public: explicit NaiveRStore(std::vector<std::pair<T, BBox>> entries) : entries(entries) {} range<RFilterIter<T>> overlapping(BBox rect) { overlapped_predicate<T> predicate(rect); RFilterIter<T> first(predicate, entries.begin(), entries.end()); RFilterIter<T> last(predicate, entries.end(), entries.end()); range<RFilterIter<T>> range(first, last); return range; } }; #endif // NAIVE_RSTORE_H_
21.878788
68
0.702216
[ "vector" ]
883fce1903de0f16817e2af8b8fe5efcdfe9a44a
914
h
C
GRA_RPG/View_Item.h
Boryszs/League_of_Warriors
ddeb8dba5d1f610fdb9d6d071d203d3925057a74
[ "MIT" ]
2
2021-02-10T16:11:54.000Z
2021-02-10T16:12:05.000Z
GRA_RPG/View_Item.h
Boryszs/League_of_Warriors
ddeb8dba5d1f610fdb9d6d071d203d3925057a74
[ "MIT" ]
null
null
null
GRA_RPG/View_Item.h
Boryszs/League_of_Warriors
ddeb8dba5d1f610fdb9d6d071d203d3925057a74
[ "MIT" ]
null
null
null
#pragma once #include <SFML/Graphics.hpp> using namespace std; using namespace sf; /// Class use to representation some graphics. class View_Item { public: /// Default constructor Class View_Item. View_Item(); /// Constructor Class View_Item. /// <param name="Path"> - Path to image</param> /// <param name="x"> - Width position</param> /// <param name="y"> - Height position</param> View_Item(String Path,int x ,int y); /// Default constructor Class View_Item. ~View_Item(); /// Image as Sprite. Sprite Image; /// Image as Texture. Texture item; /// Function return object to show graphic Sprite &getImage(); /// Function to set new image. /// <param name="Path"> - Path to new image</param> /// <param name="x"> - Width position</param> /// <param name="y"> - Height position</param> void set_Image(String Path, int x, int y); private: // value to represent position graphic int x,y; };
26.114286
52
0.679431
[ "object" ]
8843411d1a57a6fefac7a5326f3ea3835d72bee1
864
h
C
DeepMimicCore/util/IndexManager.h
0xflotus/DeepMimic
bd800ab7ec4d86d61f0cbb16667a9c20e4974cfb
[ "MIT" ]
1,812
2018-10-15T16:41:13.000Z
2022-03-31T13:22:40.000Z
DeepMimicCore/util/IndexManager.h
Arthur151/DeepMimic
ea26c3f2c35fb271d8bfefd53fd49397547c514d
[ "MIT" ]
168
2018-10-16T01:29:00.000Z
2022-03-28T07:42:40.000Z
DeepMimicCore/util/IndexManager.h
Arthur151/DeepMimic
ea26c3f2c35fb271d8bfefd53fd49397547c514d
[ "MIT" ]
445
2018-10-15T17:46:14.000Z
2022-03-30T09:35:14.000Z
#pragma once #include <vector> #include <mutex> #include <condition_variable> class cIndexManager { public: static const int gInvalidIndex; cIndexManager(); cIndexManager(int size); virtual ~cIndexManager(); virtual int GetSize() const; virtual int GetNumUsed() const; virtual void Reset(); virtual void Clear(); virtual void Resize(int size); virtual int RequestIndex(); virtual void FreeIndex(int idx); virtual bool IsFree(int idx) const; virtual bool IsFull() const; protected: int mFirstFree; std::vector<int> mIndices; std::vector<int> mPos; }; class cIndexManagerMT : public cIndexManager { public: cIndexManagerMT(); cIndexManagerMT(int size); virtual ~cIndexManagerMT(); virtual int RequestIndex(); virtual void FreeIndex(int idx); protected: std::mutex mIndexMutex; std::mutex mWaitMutex; std::condition_variable mCond; };
18.382979
44
0.748843
[ "vector" ]
8845c51aae9b7efa25e8623ac04fc3aafe6c6385
815
h
C
htop-2.0.2-custom/TraceScreen.h
jmagine/utils-configs
d141f32570d123ef6226ba853ac933042167ca48
[ "MIT" ]
39
2015-12-09T09:28:46.000Z
2021-11-16T12:57:25.000Z
htop-2.0.2-custom/TraceScreen.h
jmagine/utils-configs
d141f32570d123ef6226ba853ac933042167ca48
[ "MIT" ]
1
2020-10-17T02:23:42.000Z
2020-10-17T02:23:42.000Z
htop-2.0.2-custom/TraceScreen.h
jmagine/utils-configs
d141f32570d123ef6226ba853ac933042167ca48
[ "MIT" ]
8
2018-05-29T12:48:13.000Z
2022-02-27T01:45:57.000Z
/* Do not edit this file. It was automatically generated. */ #ifndef HEADER_TraceScreen #define HEADER_TraceScreen /* htop - TraceScreen.h (C) 2005-2006 Hisham H. Muhammad Released under the GNU GPL, see the COPYING file in the source distribution for its full text. */ #include "InfoScreen.h" typedef struct TraceScreen_ { InfoScreen super; bool tracing; int fdpair[2]; int child; FILE* strace; int fd_strace; bool contLine; bool follow; } TraceScreen; extern InfoScreenClass TraceScreen_class; TraceScreen* TraceScreen_new(Process* process); void TraceScreen_delete(Object* cast); void TraceScreen_draw(InfoScreen* this); bool TraceScreen_forkTracer(TraceScreen* this); void TraceScreen_updateTrace(InfoScreen* super); bool TraceScreen_onKey(InfoScreen* super, int ch); #endif
19.878049
60
0.764417
[ "object" ]
884b1dc16fc8a864af4ae175bfc95f1cc4d7067f
3,049
h
C
arduino/Blueboy/src/Blueboy.h
UWCubeSat/bairing
2cceafe2d1330c96773370b3738f3b276187095b
[ "MIT" ]
null
null
null
arduino/Blueboy/src/Blueboy.h
UWCubeSat/bairing
2cceafe2d1330c96773370b3738f3b276187095b
[ "MIT" ]
null
null
null
arduino/Blueboy/src/Blueboy.h
UWCubeSat/bairing
2cceafe2d1330c96773370b3738f3b276187095b
[ "MIT" ]
null
null
null
/*! * @file Blueboy.h * @author Sebastian S. * @brief Common data structures and command/telemetry constants for Blueboy. */ #ifndef BLUEBOY_H_ #define BLUEBOY_H_ #include <stdint.h> /* * Common data structures */ /*! * @struct Vector * @brief A 3D vector interpretable as x, y, z, or roll, pitch, heading * * A 16-byte vector with 3 floats and 4 bytes of padding. */ struct Vector { union { struct { float x; float y; float z; }; struct { float roll; float pitch; float heading; }; }; char reserved[4]; }; /*! * @struct Quaternion * @brief A quaternion interpretable as x, y, z, w */ struct Quaternion { float x; float y; float z; float w; }; // interpretable either as 3 vectors of raw data, a vector of euler angles, or a quaternion /*! * @struct AttitudeData * @brief A representation of a single attitude data packet. * * Interpretable either as three vectors of raw data, orientation in euler angles, or orientation as a quaternion. */ struct AttitudeData { union { struct { struct Vector magnetic; // uT struct Vector acceleration; // m/s^2 struct Vector gyro; // rad/s } raw; union { struct Vector euler; // radians struct Quaternion quaternion; // ??? } orientation; }; }; /*! * @enum Device * Device id */ enum class Device { /*! * @var Device Device::Own * Represents the Blueboy system itself. */ Own = 0x01, /*! * @var Device Device::Test * Represents the mounted test system. */ Test = 0x02 }; /* * Command and telemetry constants */ /*! * @var uint32_t SYNC_PATTERN * The 32-bit sync pattern that should be sent or recognized before every packet. Bytes should be sent/received in little endian. */ constexpr uint32_t SYNC_PATTERN = 0xDEADBEEF; /*! * @enum CommandID * IDs of commands that can be recognized. */ enum class CommandID { Reset = 0x00, Echo = 0x01, BeginOwnAttitude = 0x10, EndOwnAttitude = 0x11, EndOwnAll = 0x1F, BeginTestAttitude = 0x20, EndTestAttitude = 0x21, EndTestAll = 0x2F, BeginCalibMag = 0xE0, EndCalibMag = 0xE1, ClearCalibMag = 0xE2, BeginCalibAcc = 0xE3, EndCalibAcc = 0xE4, ClearCalibAcc = 0xE5, BeginCalibGyro = 0xE6, EndCalibGyro = 0xE7, ClearCalibGyro = 0xE8, Invalid = 0xFF, }; /*! * @enum TelemetryID * IDs of telemetry packets to use. */ enum class TelemetryID { Status = 0x00, Message = 0x01, OwnAttitudeRaw = 0x10, OwnAttitudeEuler = 0x11, OwnAttitudeQuaternion = 0x12, TestAttitudeRaw = 0x10, TestAttitudeEuler = 0x11, TestAttitudeQuaternion = 0x12, }; /*! * @enum AttitudeMode * Mode to send attitude data in over bluetooth. */ enum class AttitudeMode { Raw = 0x00, Euler = 0x01, Quaternion = 0x02 }; #endif
19.176101
129
0.604788
[ "vector", "3d" ]
885b8014ed9e266806f071386ecd4e1a761e9010
3,099
c
C
src/normalizer/normalizer_rgb.c
shigedangao/lymui-node
099f525b284369fcd85f89ebe6c20115648f3a3e
[ "MIT" ]
null
null
null
src/normalizer/normalizer_rgb.c
shigedangao/lymui-node
099f525b284369fcd85f89ebe6c20115648f3a3e
[ "MIT" ]
null
null
null
src/normalizer/normalizer_rgb.c
shigedangao/lymui-node
099f525b284369fcd85f89ebe6c20115648f3a3e
[ "MIT" ]
null
null
null
// // normalizer_rgb.c // lymui // // Created by Marc Intha on 24/11/2018. // Copyright © 2018 Marc. All rights reserved. // #include "normalizer_rgb.h" #include <node_api.h> #include <string.h> #include <stdlib.h> #include "hex.h" #include "binding_util.h" #include "bridge.h" #include "factory_regular.h" napi_value normalizeHex(napi_env env, napi_value color) { char *hex = getHEXFromJSObj(env, color); if (hex == NULL) { return NULL; } if (hex[3]) { Rgb *rgb = getRGBFromHex(hex); napi_value object = RgbJSObjFactory(env, rgb); return object; } char *smallHex = malloc(sizeof(char) * 4); if (smallHex == NULL) { return NULL; } snprintf(smallHex, 4, "%c%c%c", hex[0], hex[1], hex[2]); Rgb *tinyRgb = getRGBFromHex(smallHex); napi_value object = RgbJSObjFactory(env, tinyRgb); return object; } napi_value normalizeHsl(napi_env env, napi_value color) { Hsl *hsl = getHslFromJSObj(env, color); if (hsl == NULL) { return NULL; } Rgb *rgb = getRgbFromHsl(hsl); napi_value object = RgbJSObjFactory(env, rgb); return object; } napi_value normalizeHsv(napi_env env, napi_value color) { Hsv *hsv = getHsvFromJSObj(env, color); if (hsv == NULL) { return NULL; } Rgb *rgb = getRgbFromHsv(hsv); napi_value object = RgbJSObjFactory(env, rgb); return object; } napi_value normalizeCymk(napi_env env, napi_value color) { Cymk *cymk = getCymkFromJSObj(env, color); if (cymk == NULL) { return NULL; } Rgb *rgb = getRgbFromCymk(cymk); napi_value object = RgbJSObjFactory(env, rgb); return object; } napi_value normalizeYcbcr(napi_env env, napi_value color) { Ycbcr *ycbcr = getYcbcrFromJSObj(env, color); if (ycbcr == NULL) { return NULL; } Rgb *rgb = getRgbFromYcbcr(ycbcr); napi_value object = RgbJSObjFactory(env, rgb); return object; } napi_value normalizeYuv(napi_env env, napi_value color) { Yuv *yuv = getYuvFromJSObj(env, color); if (yuv == NULL) { return NULL; } Rgb *rgb = getRgbFromYuv(yuv); napi_value object = RgbJSObjFactory(env, rgb); return object; } napi_value normalizeHwb(napi_env env, napi_value color) { Hwb *hwb = getHwbFromJSObj(env, color); if (hwb == NULL) { return NULL; } Rgb *rgb = getRgbFromHwb(hwb); napi_value object = RgbJSObjFactory(env, rgb); return object; } napi_value normalizeTsl(napi_env env, napi_value color) { Tsl *tsl = getTslFromJSObj(env, color); if (tsl == NULL) { return NULL; } Rgb *rgb = getRgbFromTsl(tsl); napi_value object = RgbJSObjFactory(env, rgb); return object; } napi_value normalizeXyz(napi_env env, napi_value color, char *m) { Matrix mx = getEnumFromStr(m); Xyz *xyz = getXyzFromJSObj(env, color); if (xyz == NULL) { return NULL; } Rgb *rgb = getRgbFromXyz(xyz, mx); napi_value object = RgbJSObjFactory(env, rgb); return object; }
22.786765
66
0.627944
[ "object" ]
32a32a0d18265b93037fcf5ae0cd3d797bc0e97d
4,577
h
C
inc/behaviac/base/core/logging/consoleout.h
pjkui/behaviac_2.0.7
db4bec559c184c4af125005bf07bc0b25e2c6e66
[ "BSD-3-Clause" ]
1
2016-07-25T10:38:38.000Z
2016-07-25T10:38:38.000Z
inc/behaviac/base/core/logging/consoleout.h
pjkui/behaviac_2.0.7
db4bec559c184c4af125005bf07bc0b25e2c6e66
[ "BSD-3-Clause" ]
null
null
null
inc/behaviac/base/core/logging/consoleout.h
pjkui/behaviac_2.0.7
db4bec559c184c4af125005bf07bc0b25e2c6e66
[ "BSD-3-Clause" ]
2
2016-03-17T11:19:16.000Z
2020-03-16T16:17:56.000Z
///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Tencent is pleased to support the open source community by making behaviac available. // // Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at http://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed under the License is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and limitations under the License. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef BEHAVIAC_BASE_LOGGING_CONSOLEOUT_H #define BEHAVIAC_BASE_LOGGING_CONSOLEOUT_H #include "behaviac/base/core/config.h" #include "behaviac/base/core/assert_t.h" #include "behaviac/base/core/thread/mutex.h" #include <stdarg.h> namespace behaviac { namespace Private { class SafeLock; } enum ELogOutput { ELOG_CONSOLE = 1, ELOG_FILE = 2, ELOG_VCOUTPUT = 4 }; /// ConsoleOut is a class that implements a basic ouput console mechanism /*! ConsoleOut can be hooked to output on devices */ class BEHAVIAC_API ConsoleOut { public: // Type of a console out callback function typedef void(*ConsoleOutCallBack)(uint32_t, const char*); /** to pass ELogOutput enum as mask you can call ConsoleOut::SetEnableMask(0) to disable the output you can call ConsoleOut::SetEnableMask(ELOG_CONSOLE) to enable only the console output */ static void SetEnableMask(uint32_t enableMask); /// Send a formatted behaviac::string to the console hook chain. static void Print(uint32_t LogFilter, const char* format, ...); static void Print(const char* format, ...); static void VPrint(const char* format, va_list& argList); static void VPrint(uint32_t LogFilter, const char* format, va_list& argList); /// Send a single behaviac::string to the console hook chain (faster than Print) static void PrintLines(uint32_t LogFilter, const char* pStr); static void PrintLines(const char* pStr); /// Send a memory dump on the console hook chain /*! Here's a example of Dump(pMyDataAt340000, 32) \code 00340000 4D 45 4D 4F 52 59 4C 4F 47 47 45 51 01 20 02 64 MEMORYLOGGER. .d 00240010 10 01 38 26 3E 41 01 00 00 34 00 00 10 00 00 00 ..8&>A...4...... \endcode \param LogFilter Filter to apply to the dump \param pData A pointer on the section of memory to dump (Must be != NULL) \param Size The size in byte of the memory dump \return None */ static void Dump(uint32_t LogFilter, const void* pData, size_t size); static void Dump(const void* pData, size_t size); /// Tell the consoleout module that the initialization of behaviac is now completed static void InitializationCompleted(void); /// Default console out target. /// To remove this default hook, call RemoveHook(ConsoleOut::DefaultConsoleOutput); static void DefaultConsoleOutput(uint32_t Filter, const char* pMsg); /// Default std console out target. /// To remove this default hook, call RemoveHook(ConsoleOut::DefaultStdConsoleOutput); static void DefaultStdConsoleOutput(uint32_t Filter, const char* pMsg); protected: // Output a single behaviac::string to the hook chain static void Output(uint32_t Filter, const char* pStr); static void OutputLine(const char* pStr); static void OutputDecoratedLine(uint32_t LogFilter, const char* pStr); // Test if init, and if not, init the object. Should be @ beginning of every public function // since ConsoleOut can be called before behaviac is even initialized. static void TestInit(void); static bool IsInit; static uint32_t EnableMask; private: // This is the hook for Assert. static int ConsoleAssertCb(const char* cond, const char* msg, const char* file, int line, int extra); }; } #endif//BEHAVIAC_BASE_LOGGING_CONSOLEOUT_H
41.609091
113
0.643435
[ "object" ]
32a34377721c63de78b67d6a1ee1dc8ffa0c448f
2,339
h
C
MLN-iOS/MLN/Classes/MUIKit/DataBinding/MLNUIDataBinding.h
jinjinhuanglucky/MLN
7b6a6dd3d722affa160927c88549700bd848b161
[ "MIT" ]
null
null
null
MLN-iOS/MLN/Classes/MUIKit/DataBinding/MLNUIDataBinding.h
jinjinhuanglucky/MLN
7b6a6dd3d722affa160927c88549700bd848b161
[ "MIT" ]
null
null
null
MLN-iOS/MLN/Classes/MUIKit/DataBinding/MLNUIDataBinding.h
jinjinhuanglucky/MLN
7b6a6dd3d722affa160927c88549700bd848b161
[ "MIT" ]
null
null
null
// // MLNUIDataBinding.h // MLNUI // // Created by Dai Dongpeng on 2020/3/3. // #import <Foundation/Foundation.h> #import "MLNUIKVOObserverProtocol.h" #define MLNUIKVOOrigin2DArrayKey @"MLNUIKVOOrigin2DArrayKey" NS_ASSUME_NONNULL_BEGIN @interface MLNUIDataBinding : NSObject - (void)bindData:(nullable NSObject *)data forKey:(NSString *)key; //- (void)addDataObserver:(NSObject<MLNUIKVOObserverProtol> *)observer forKeyPath:(NSString *)keyPath; //- (void)removeDataObserver:(NSObject<MLNUIKVOObserverProtol> *)observer forKeyPath:(NSString *)keyPath; //- (NSArray <NSObject<MLNUIKVOObserverProtol> *> *)dataObserversForKeyPath:(NSString *)keyPath; //- (NSArray <NSObject<MLNUIKVOObserverProtol> *> *)arrayObserversForKeyPath:(NSString *)keyPath; - (NSString *)addMLNUIObserver:(NSObject<MLNUIKVOObserverProtol> *)observer forKeyPath:(NSString *)keyPath; //- (void)removeMLNUIObserver:(NSObject<MLNUIKVOObserverProtol> *)observer forKeyPath:(NSString *)keyPath; - (void)removeMLNUIObserverByID:(NSString *)observerID; @end // for array @interface MLNUIDataBinding () - (void)bindArray:(NSArray *)array forKey:(NSString *)key; @end // for lua @interface MLNUIDataBinding () - (id __nullable)dataForKeyPath:(NSString *)keyPath; - (void)updateDataForKeyPath:(NSString *)keyPath value:(id)value; // for bind cell - (id)dataForKeyPath:(NSString *)keyPath userCache:(BOOL)useCache; // keys //- (id __nullable)dataForKeys:(NSArray *)keys; - (id __nullable)dataForKeys:(NSArray *)keys frontValue:(NSObject *_Nullable *_Nullable)front; - (void)updateDataForKeys:(NSArray *)keys value:(id)value; //- (NSString *)addMLNUIObserver:(NSObject<MLNUIKVOObserverProtol> *)observer forKeys:(NSArray *)keys; //- (void)removeMLNUIObserver:(NSObject<MLNUIKVOObserverProtol> *)observer forKeys:(NSArray *)keys; //缓存listView及对应的tag - (void)setListView:(UIView *)view tag:(NSString *)tag; - (UIView *)listViewForTag:(NSString *)tag; // only for bind cell - (BOOL)_realAddDataObserver:(NSObject<MLNUIKVOObserverProtol> *)observer forObject:(id)object observerID:(NSString *)obID path:(NSString *)path; - (BOOL)_realAddArrayObserver:(NSObject<MLNUIKVOObserverProtol> *)observer forObject:(NSObject *)object observerID:(NSString *)obID keyPath:(NSString *)keyPath; @property (nonatomic, strong)void(^errorLog)(NSString *); @end NS_ASSUME_NONNULL_END
38.983333
160
0.770415
[ "object" ]
32b180a8a477558333272366546d0db8dde8fe62
2,077
c
C
K32L2B31A_Project/iot_sdk/irq/iot_sdk_irq_lptimer0.c
jhondyyfre/LEDS_LAB1
c141a2c1d20c9750dd6001051367eebe5278187d
[ "MIT" ]
1
2021-12-23T00:12:09.000Z
2021-12-23T00:12:09.000Z
K32L2B31A_Project/iot_sdk/irq/iot_sdk_irq_lptimer0.c
jhondyyfre/LEDS_LAB1
c141a2c1d20c9750dd6001051367eebe5278187d
[ "MIT" ]
null
null
null
K32L2B31A_Project/iot_sdk/irq/iot_sdk_irq_lptimer0.c
jhondyyfre/LEDS_LAB1
c141a2c1d20c9750dd6001051367eebe5278187d
[ "MIT" ]
1
2021-12-04T04:08:51.000Z
2021-12-04T04:08:51.000Z
/*! @file : iot_sdk_irq_lptimer0.c * @author Ernesto Andres Rincon Cruz * @version 1.0.0 * @date 1 sept. 2021 * @brief IRQ ejecutado cada que ocurre interrupción por timer 0 * @details * */ /******************************************************************************* * Includes ******************************************************************************/ #include "iot_sdk_ irq_lptimer0.h" /******************************************************************************* * Definitions ******************************************************************************/ /******************************************************************************* * Private Prototypes ******************************************************************************/ /******************************************************************************* * External vars ******************************************************************************/ /******************************************************************************* * Local vars ******************************************************************************/ volatile uint32_t lptmr0_ticks=0; /******************************************************************************* * Private Source Code ******************************************************************************/ /******************************************************************************* * Public Source Code ******************************************************************************/ /* LPTMR0_IRQn interrupt handler */ void LPTMR0_IRQHANDLER(void) { uint32_t intStatus; /* Reading all interrupt flags of status register */ intStatus = LPTMR_GetStatusFlags(LPTMR0_PERIPHERAL); LPTMR_ClearStatusFlags(LPTMR0_PERIPHERAL, intStatus); /* Place your code here */ lptmr0_ticks++; /* Add for ARM errata 838869, affects Cortex-M4, Cortex-M4F Store immediate overlapping exception return operation might vector to incorrect interrupt. */ #if defined __CORTEX_M && (__CORTEX_M == 4U) __DSB(); #endif }
36.438596
99
0.327395
[ "vector" ]
32b95234a3532b3d2ba95d2ab5ce520dbff67c76
1,898
h
C
vtkALBA/vtkALBALocalAxisCoordinate.h
IOR-BIC/ALBA
b574968b05d9a3a2756dd2ac61d015a0d20232a4
[ "Apache-2.0", "BSD-3-Clause" ]
9
2018-11-19T10:15:29.000Z
2021-08-30T11:52:07.000Z
vtkALBA/vtkALBALocalAxisCoordinate.h
IOR-BIC/ALBA
b574968b05d9a3a2756dd2ac61d015a0d20232a4
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
vtkALBA/vtkALBALocalAxisCoordinate.h
IOR-BIC/ALBA
b574968b05d9a3a2756dd2ac61d015a0d20232a4
[ "Apache-2.0", "BSD-3-Clause" ]
3
2018-06-10T22:56:29.000Z
2019-12-12T06:22:56.000Z
/*========================================================================= Program: ALBA (Agile Library for Biomedical Applications) Module: vtkALBALocalAxisCoordinate Authors: Silvano Imboden Copyright (c) BIC All rights reserved. See Copyright.txt or This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #ifndef __vtkALBALocalAxisCoordinate_h #define __vtkALBALocalAxisCoordinate_h #include "albaConfigure.h" #include "vtkCoordinate.h" #include "vtkProp3D.h" #include "vtkMatrix4x4.h" #include "vtkDataSet.h" class vtkViewport; /** class name: vtkALBALocalAxisCoordinate. */ class ALBA_EXPORT vtkALBALocalAxisCoordinate : public vtkCoordinate { public: //vtkTypeRevisionMacro(vtkALBALocalAxisCoordinate,vtkCoordinate); /** destructor */ virtual ~vtkALBALocalAxisCoordinate(); /** create an instance of the object */ static vtkALBALocalAxisCoordinate* New(); /** macro Set for DataSet member */ vtkSetObjectMacro(DataSet,vtkDataSet); /** macro Get for DataSet member */ vtkGetObjectMacro(DataSet,vtkDataSet); /** macro Set for Mactrix member */ vtkSetObjectMacro(Matrix,vtkMatrix4x4); /** macro Get for Mactrix member */ vtkGetObjectMacro(Matrix,vtkMatrix4x4); /** used only when the coordinate system is VTK_USERDEFINED */ virtual double *GetComputedUserDefinedValue(vtkViewport *viewport); protected: /** constructor */ vtkALBALocalAxisCoordinate(); private: vtkDataSet *DataSet; vtkMatrix4x4 *Matrix; /** Copy Constructor , not implemented */ vtkALBALocalAxisCoordinate(const vtkALBALocalAxisCoordinate&); /** operator =, not implemented */ void operator=(const vtkALBALocalAxisCoordinate&); }; #endif
28.328358
75
0.709694
[ "object" ]
32ba40547e72bc1632b8a5391dbab4d1b68879d8
9,930
h
C
moses/trees/semantic_sampler.h
moshelooks/moses
81568276877f24c2cb1ca5649d44e22fba6f44b2
[ "Apache-2.0" ]
null
null
null
moses/trees/semantic_sampler.h
moshelooks/moses
81568276877f24c2cb1ca5649d44e22fba6f44b2
[ "Apache-2.0" ]
null
null
null
moses/trees/semantic_sampler.h
moshelooks/moses
81568276877f24c2cb1ca5649d44e22fba6f44b2
[ "Apache-2.0" ]
null
null
null
/**** Copyright 2005-2007, Moshe Looks 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 SEMANTIC_SAMPLER_H #define SEMANTIC_SAMPLER_H #include <iterator> #include <ext/hash_set> #include <vector> #include <boost/bind.hpp> #include <boost/iterator/indirect_iterator.hpp> #include <boost/iterator/transform_iterator.hpp> #include "hash_util.h" #include "io_util.h" #include "tree.h" #include "selection.h" #include <boost/iterator/counting_iterator.hpp> /*#include "tree_enumeration.h"*/ #include "uniform_tree_sampling.h" #include "tree_util.h" #include "TreeComp.h" #include "id.h" #include "Vertex.h" #include <set> namespace trees { using namespace std; using namespace __gnu_cxx; using namespace boost; template<typename T> struct root_shape { root_shape(const T& t) : root(t) { } root_shape(const T& t,int n0,int n1) : root(t),sizes(2) { (*const_cast<std::vector<int>* >(&sizes))[0]=n0; (*const_cast<std::vector<int>* >(&sizes))[1]=n1; } template<typename It> root_shape(const T& t,It from,It to) : root(t),sizes(from,to) { } int arity() const { return sizes.size(); } T root; std::vector<int> sizes; }; } template<typename T> std::ostream& operator<<(std::ostream& out,const trees::root_shape<T>& rs) { return (out << rs.root << "(" << rs.sizes << ")"); } namespace trees { template<typename T> root_shape<T> select_shape(const NodeSelector<T>& s,int n) { if (n==0) return root_shape<T>(s.select_with_arity(0)); int split=select_by_catalan(n-1); return root_shape<T>(s.select_with_arity(2),split,n-1-split); } struct treehashhack { size_t operator()(const vtree& tr) const { return boost::hash_range(tr.begin(),tr.end()); } }; template<typename T,typename Simplify> class semantic_sampler { public: typedef tree<T> Tree; typedef typename Tree::sibling_iterator sib_it; typedef hash_set<Tree,treehashhack> TreeSet; typedef vector<Tree> TreeSeq; struct Repository : public vector<TreeSeq> { typedef typename vector<TreeSeq>::iterator iterator; typedef typename vector<TreeSeq>::const_iterator const_iterator; Repository(int sz=0) : vector<TreeSeq>(sz) { } //could be made faster by using move_ontop - same with copying uniq (?) void splice(Repository& r) { assert(r.size()==vector<TreeSeq>::size()); for (iterator src=r.begin(),dst=vector<TreeSeq>::begin(); dst!=vector<TreeSeq>::end();++src,++dst) { dst->insert(dst->end(),src->begin(),src->end()); //dst->insert(dst->end(),src->size(),Tree()); //copy(src->begin(),src->end(),dst->end()-src->size()); /*for_each(src->begin(),src->end(),dst->end()-src->size(), bind(&Tree::move_ontop, bind(&Tree::begin,_2),bind(&Tree::begin,_1)));*/ //cout << distance(begin(),dst) << " " << dst->size() << endl; } } void splice(int n,sib_it it) { TreeSeq& v((*this)[n]); v.push_back(Tree(*it)); v.back().move_ontop(sib_it(v.back().begin()),it); } }; semantic_sampler(const NodeSelector<T>& s, const Simplify& simplify=Simplify(), int c=10000) : _s(s),_simplify(simplify),_cutoff(c) { } void uniform_sample(unsigned int maxSize,unsigned int m) { assert(m<_cutoff); if (maxSize+1>_full.size()) { _full.resize(maxSize+1); _repository.resize(maxSize+1); } /*for_each(_repository.begin(),_repository.end(), bind(&Repository::reserve,_1,m));*/ unsigned int minSize=enumerate_small_trees(maxSize); for (int i=0;i<minSize;++i) random_shuffle(_repository[i].begin(),_repository[i].end()); for (;maxSize>=minSize;--maxSize) { //sample trees until we have enough while (_repository[maxSize].size()<m) { generate_tree(maxSize); } } } const TreeSeq& trees(int i) const { return _repository[i]; } TreeSeq& trees(int i) { return _repository[i]; } int cutoff() const { return _cutoff; } bool isFull(int i) const { return _full[i]; } void generate_tree(int n) { Repository unused(_repository.size()); while (true) { root_shape<T> shape(select_shape(_s,n)); tree<T> tr(shape.root); for (vector<int>::const_iterator sz=shape.sizes.begin(); sz!=shape.sizes.end();++sz) draw(*sz,tr,tr.append_child(tr.begin())); if (minimal(n,tr)) { _repository.splice(unused); _repository.splice(n,tr.begin()); return; } for (vector<int>::const_iterator sz=shape.sizes.begin(); sz!=shape.sizes.end();++sz) if (!_full[*sz]) //splice out and for later unused.splice(*sz,tr.begin().begin()); else tr.erase(tr.begin().begin()); assert(tr.begin().number_of_children()==0); } } private: const NodeSelector<T>& _s; Simplify _simplify; const unsigned int _cutoff; vector<bool> _full; Repository _repository; int enumerate_small_trees(unsigned int maxSize) { unsigned int minSize=0; while (_full[minSize]) ++minSize; for (;minSize<=min(maxSize,catalan_bigness_bound);++minSize) { unsigned long int nWithSize=number_of_binary_trees(minSize,_s); if (nWithSize>10*_cutoff) break; TreeSeq all(nWithSize); enumerate_all_binary_trees(minSize,_s,all.begin()); //simplify and remove all duplicate trees for_each(all.begin(),all.end(),_simplify); TreeSet uniq; for (typename TreeSeq::const_iterator it=all.begin(); it!=all.end();++it) if (complexity(it->begin())==minSize) uniq.insert(*it); /* for (TreeSet::const_iterator it=uniq.begin();it!=uniq.end();++it) if (complexity(it->begin())>minSize) { cout << *it << endl; assert(false); }*/ if (uniq.size()<=_cutoff) { _repository[minSize].resize(uniq.size()); copy(uniq.begin(),uniq.end(),_repository[minSize].begin()); _full[minSize]=true; //cout << "created " << _sample[minSize].size() << endl; } else { break; } } //cout << "pop" << endl; return min(minSize,maxSize); /*for (;minSize<maxSize;++minSize) { if (_sample[minSize].size()>=_cutoff || _full[minSize]) //already full continue; //fix based on how enumerate_trees is implemented TreeSet tmp; tmp.reserve(_cutoff); if (!enumerate_trees(_s,_simplify,minSize,_cutoff,back_inserter(tmp))) break; //update the sample swap(tmp,_sample[minSize]); _full[minSize]=true; }*/ } /* place randtree(int n) { place tmp=_sample[n].begin(); advance(tmp,randint(_sample[n].size())); return tmp; } place sample(int n) { while (!_full[n] && _sample[n].size()<_m) generate_tree(n); //cout << "blarg" << endl; return randtree(n); } void release(int n,place p) { if (!_full[n]) _sample[n].erase(p); } */ //splice a tree out of the repository (if available) else create one //dst gets invalidated void draw(int n,Tree& tr,sib_it dst) { if (_full[n]) { assert(_repository[n].size()>0); int idx=randint(_repository[n].size()); tr.replace(dst,_repository[n][idx].begin()); } else { if (_repository[n].empty()) generate_tree(n); tr.move_ontop(dst,sib_it(_repository[n].back().begin())); _repository[n].pop_back(); } } bool minimal(int n,tree<T>& tr) { tree<T> test(tr); _simplify(test); int k=complexity(test.begin()); assert(k<=n); if (k==n) { swap(test,tr); return true; } return false; } #if 0 vector<tree<T> > subtrees(shape.arity()); for (unsigned int i=0;i<subtrees.size();++i) { subtrees[i]=*sample(shape.sizes[i]); /*transform(shape.sizes.begin(),shape.sizes.end(),subtrees.begin(), bind(&semantic_sampler<T,Simplify>::sample,this,_1));*/ //cout << "puke" << endl; for (typename vector<tree<T> >::const_iterator it=subtrees.begin(); it!=subtrees.end();++it) tmp.append_child(tmp.begin(),it->begin()); int maxSize=(n==0 ? -1 : *max_element(shape.sizes.begin(),shape.sizes.end())); //cout << "mook" << tmp << endl; _simplify(tmp); int k=complexity(tmp.begin()); if (k>n) { //cout << "XXX " << k << "!" << n << " " << tmp << endl; exit(84); } if (k>maxSize) { //worth keeping //cout << "book" << k << endl; if (_sample[k].insert(tmp).second) { if (k==n) { //done! cout << "success " << n << endl; return; } else { cout << "Xccess " << k << endl; } } } for (unsigned int i=0;i<subtrees.size();++i) _sample[shape.sizes[i]].insert(subtrees[i]); //put em back //cout << "failure " << n << " - " << k << endl; generate_tree(n); //try again } #endif }; template<typename T,typename Simplify,typename Out> Out enumerate_minimal_trees(int k,const NodeSelector<T>& sel, const Simplify& simplify,Out out) { typedef typename semantic_sampler<T,Simplify>::TreeSeq TreeSeq; set<tree<T>,trees::SubtreeOrder<T> > tmp; semantic_sampler<T,Simplify> ss(sel,simplify); ss.uniform_sample(k,ss.cutoff()-1); for (int i=0;i<k;++i) { for (typename TreeSeq::const_iterator it=ss.trees(i).begin(); it!=ss.trees(i).end();++it) { tree<T> neg(id::create_not<T>()); neg.append_child(neg.begin(),it->begin()); simplify(neg); if (tmp.find(neg)==tmp.end()) tmp.insert(*it); } } return copy(tmp.begin(),tmp.end(),out); } } //~namespace trees #endif
28.452722
77
0.627492
[ "shape", "vector", "transform" ]
32bd0316faed404d01b29791f999c7e1eeb725d6
6,601
h
C
libraries/stdlib/osl/oslutil.h
willmuto-lucasfilm/MaterialX
589dbcb5ef292b5e5b64f30aa3fea442a8498ef6
[ "BSD-3-Clause" ]
1,907
2015-01-04T00:13:22.000Z
2022-03-30T15:14:00.000Z
libraries/stdlib/osl/oslutil.h
willmuto-lucasfilm/MaterialX
589dbcb5ef292b5e5b64f30aa3fea442a8498ef6
[ "BSD-3-Clause" ]
1,196
2015-01-04T10:50:01.000Z
2022-03-04T09:18:22.000Z
libraries/stdlib/osl/oslutil.h
willmuto-lucasfilm/MaterialX
589dbcb5ef292b5e5b64f30aa3fea442a8498ef6
[ "BSD-3-Clause" ]
373
2015-01-06T10:08:53.000Z
2022-03-12T10:25:57.000Z
///////////////////////////////////////////////////////////////////////////// // Copyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al. 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 Sony Pictures Imageworks nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ///////////////////////////////////////////////////////////////////////////// #ifndef OSLUTIL_H #define OSLUTIL_H // Return wireframe opacity factor [0, 1] given a geometry type in // ("triangles", "polygons" or "patches"), and a line_width in raster // or world space depending on the last (raster) boolean argument. // float wireframe(string edge_type, float line_width, int raster) { // ray differentials are so big in diffuse context that this function would always return "wire" if (raytype("path:diffuse")) return 0.0; int np = 0; point p[64]; float pixelWidth = 1; if (edge_type == "triangles") { np = 3; if (!getattribute("geom:trianglevertices", p)) return 0.0; } else if (edge_type == "polygons" || edge_type == "patches") { getattribute("geom:numpolyvertices", np); if (np < 3 || !getattribute("geom:polyvertices", p)) return 0.0; } if (raster) { // Project the derivatives of P to the viewing plane defined // by I so we have a measure of how big is a pixel at this point float pixelWidthX = length(Dx(P) - dot(Dx(P), I) * I); float pixelWidthY = length(Dy(P) - dot(Dy(P), I) * I); // Take the average of both axis' length pixelWidth = (pixelWidthX + pixelWidthY) / 2; } // Use half the width as the neighbor face will render the // other half. And take the square for fast comparison pixelWidth *= 0.5 * line_width; pixelWidth *= pixelWidth; for (int i = 0; i < np; i++) { int i2 = i ? i - 1 : np - 1; vector dir = P - p[i]; vector edge = p[i] - p[i2]; vector crs = cross(edge, dir); // At this point dot(crs, crs) / dot(edge, edge) is // the square of area / length(edge) == square of the // distance to the edge. if (dot(crs, crs) < (dot(edge, edge) * pixelWidth)) return 1; } return 0; } float wireframe(string edge_type, float line_width) { return wireframe(edge_type, line_width, 1); } float wireframe(string edge_type) { return wireframe(edge_type, 1.0, 1); } float wireframe() { return wireframe("polygons", 1.0, 1); } float draw_string(string str, float s, float t, int wrap_s, int wrap_t, int jitter) { // Glyphs from http://font.gohu.org/ (8x14 version, most common ascii characters only) int glyph_pixel(int c, int x, int y) { c -= 33; x--; // nudge to origin if (c < 0 || x < 0 || y < 0 ) return 0; if (c > 93 || x > 6 || y > 13) return 0; int i = 98 * c + 7 * y + x; return ((getchar("0@P01248@00120000P49B0000000000000:DXlW2UoDX@10008@h;IR4n@R<Y?48000PYDF" "PP011J:U1000<T8QQQDAR4a50000@P012000000000000222448@P024@010028P0148@PP011100000" "ABELDU410000000048@l7124000000000000000H`01100000000n10000000000000000006<0000@P" "P011224488@00000`CXHY:=:D8?0000004<DT01248@000000l4:444444h700000`C8@Ph02D8?0000" "008HX89b?8@P000000n58`7@P05b300000`CP0O25:D8?00000POPP0112248000000l4:D8?Q25b300" "000`CX@Ql1244700000000H`0000<H00000000`P1000H`0110000044444@014@0000000n100PO000" "0000004@014@@@@@0000h948@@@@00120000`G`l5;F\\Lf0n100000l4:DXOQ25:400000hCX@Qn4:D" "X?000000?Q248@P0Ql000000N49DX@Q25i100000hGP01N48@PO00000PO124hAP012000000l4:@PLQ" "25b3000008DX@Qn5:DX@000000748@P0124L00000001248@P25b3000008DT456D8AT@00000P01248" "@P01n10000017G=IbP1364000008dXAU:U:E\\H000000?Q25:DX@Ql000000n4:DX?1248000000`CX" "@Q2U:E4GP0000P?Q25jCR8Q2100000l4:@0?P05b300000l71248@P01200000P@Q25:DX@Ql0000002" "5:D89BT`P1000004<HbT9[:BT800000P@QT8QQ49Q210000013:B4548@P000000h7888888@PO00000" "7248@P01248`10P0148P0148P0148000h01248@P0124>000015A000000000000000000000000h?00" "04@010000000000000000l0bGX@aL10000124XcX@Q25j300000000?Q248@8?000008@Pl5:DX@aL10" "000000`CX@o24`70000`AP01N48@P0100000000l5:DX@aL12T70124XcX@Q25:40000@P0P348@P01>" "00000240HP01248@P0a101248@T47B4940000HP01248@P01L00000000oBV<IbT910000000hCX@Q25" ":400000000?Q25:D8?00000000j<:DX@Qn48@00000`GX@Q25c58@P0000P>S248@P000000000l48P7" "@Pn0000048@`31248@030000000P@Q25:D<G0000000025:T49<H000000004<HbTE5920000000P@QT" "`@BX@0000000025:DX@aL12T70000h744444h70000PS01248>P0124`1001248@P01248@P0007@P01" "24`@P01R30000000S9S10000000", i / 6) - 48) >> (i % 6)) & 1; } int modp(int a, int b) { int x = a % b; return x < 0 ? x + b : x; } int len = strlen(str); int jit = jitter ? hash(str) : 0; int pix_w = len * 8; int pix_h = 14; int x = int(floor(s)); int y = int(floor(t)); if (wrap_s) x = modp(x + ( jitter & 15), pix_w + pix_h); if (wrap_t) y = modp(y + ((jitter >> 16) & 15), pix_h + pix_h); return float(glyph_pixel(getchar(str, x / 8), x - (x / 8) * 8, y)); } #endif /* OSLUTIL_H */
48.536765
99
0.658537
[ "geometry", "render", "vector" ]
32c261f6db10733d37bd27716143217ac10a45ac
5,748
h
C
pic_png.h
SamuNatsu/PictureSimplify
b1bdaa9121deeab8c4279428e8115bf23ab49a2c
[ "MIT" ]
null
null
null
pic_png.h
SamuNatsu/PictureSimplify
b1bdaa9121deeab8c4279428e8115bf23ab49a2c
[ "MIT" ]
null
null
null
pic_png.h
SamuNatsu/PictureSimplify
b1bdaa9121deeab8c4279428e8115bf23ab49a2c
[ "MIT" ]
null
null
null
/* MIT License Copyright (c) 2020 SamuNatsu 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. */ /* Tutorial: Just use like this: #define PIC_PNG_IMPLEMENTATION #include "pic_png.h" int main() { PIC::PNG_CleanAndSave("Source.png", "Destination.png"); return 0; } You SHOULD use "#define PIC_PNG_IMPLEMENTATION" at least once in any .cpp file for compiling. Or you can try other functions for fun, my code is very easy to understand :) */ #ifndef PIC_PNG_INCLUDED #define PIC_PNG_INCLUDED #include <cstdio> #include <cstring> #include <vector> namespace PIC { struct PNG_Chunk { unsigned int m_Size = 0x0; char m_Type[4] = {0x0, 0x0, 0x0, 0x0}; unsigned char *m_Data = nullptr; unsigned int m_CRC = 0x0; PNG_Chunk() = default; PNG_Chunk(const PNG_Chunk&); ~PNG_Chunk(); PNG_Chunk& operator=(const PNG_Chunk&); }; bool PNG_CheckHeader(FILE*); bool PNG_GetChunk(FILE*, PNG_Chunk&); bool PNG_CleanAndSave(const char*, std::vector<PNG_Chunk>&); bool PNG_CleanAndSave(const char*, const char*); } #endif /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #ifdef PIC_PNG_IMPLEMENTATION namespace PIC { PNG_Chunk::PNG_Chunk(const PNG_Chunk& tmp) { m_Size = tmp.m_Size; memcpy(m_Type, tmp.m_Type, 4); if (m_Size) { m_Data = new unsigned char[m_Size]; memcpy(m_Data, tmp.m_Data, m_Size); } m_CRC = tmp.m_CRC; } PNG_Chunk::~PNG_Chunk() { if (m_Size) delete m_Data; } PNG_Chunk& PNG_Chunk::operator=(const PNG_Chunk& tmp) { if (m_Size) delete m_Data; m_Size = tmp.m_Size; memcpy(m_Type, tmp.m_Type, 4); if (m_Size) { m_Data = new unsigned char[m_Size]; memcpy(m_Data, tmp.m_Data, m_Size); } m_CRC = tmp.m_CRC; return *this; } bool PNG_CheckHeader(FILE* fin) { const unsigned char s_Header[] = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}; unsigned char _tmp[8]; if (fread(_tmp, 1, 8, fin) != 8) return false; for (int i= 0; i < 8; ++i) if (s_Header[i] != _tmp[i]) return false; return true; } bool PNG_GetChunk(FILE* fin, PNG_Chunk& chunk) { unsigned char _tmp[4]; if (fread(_tmp, 1, 4, fin) != 4) return false; chunk.m_Size = 0x0; for (int i = 0, j = 24; i < 4; ++i, j -= 8) chunk.m_Size |= _tmp[i] << j; if (fread(chunk.m_Type, 1, 4, fin) != 4) return false; if (chunk.m_Size) { chunk.m_Data = new unsigned char[chunk.m_Size]; if (fread(chunk.m_Data, 1, chunk.m_Size, fin) != chunk.m_Size) return false; } if (fread(_tmp, 1, 4, fin) != 4) return false; chunk.m_CRC = 0x0; for (int i = 0, j = 24; i < 4; ++i, j -= 8) chunk.m_CRC |= _tmp[i] << j; return true; } bool PNG_CleanAndSave(const char* path, std::vector<PNG_Chunk>& chunks) { FILE *fout = fopen(path, "wb"); if (!fout) return false; const unsigned char s_Header[] = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}; if (fwrite(s_Header, 1, 8, fout) != 8) { fclose(fout); return false; } unsigned char _tmp[4]; for (auto& i : chunks) if (i.m_Type[0] == 'I' || i.m_Type[0] == 'P') { for (int j = 0, k = 24; j < 4; ++j, k -= 8) _tmp[j] = (unsigned char)((i.m_Size >> k) & 0xFF); if (fwrite(_tmp, 1, 4, fout) != 4) { fclose(fout); return false; } if (fwrite(i.m_Type, 1, 4, fout) != 4) { fclose(fout); return false; } if (fwrite(i.m_Data, 1, i.m_Size, fout) != i.m_Size) { fclose(fout); return false; } for (int j = 0, k = 24; j < 4; ++j, k -= 8) _tmp[j] = (unsigned char)((i.m_CRC >> k) & 0xFF); if (fwrite(_tmp, 1, 4, fout) != 4) { fclose(fout); return false; } } return true; } bool PNG_CleanAndSave(const char* src, const char* dst) { FILE *fin = fopen(src, "rb"); if (!fin) return false; if (!PNG_CheckHeader(fin)) { fclose(fin); return false; } PNG_Chunk _tmp; std::vector<PNG_Chunk> _chunks; while (!feof(fin)) { if (!PNG_GetChunk(fin, _tmp)) { if (feof(fin)) break; fclose(fin); return false; } _chunks.emplace_back(_tmp); _tmp.m_Size = 0x0; } fclose(fin); if (!PNG_CleanAndSave(dst, _chunks)) return false; return true; } } #endif
27.768116
127
0.576548
[ "vector" ]
32c44f83d4bd58ab0165ea405e814204ef7c81ae
4,995
h
C
Code/Framework/AzFramework/AzFramework/Input/Events/InputTextEventListener.h
sandeel31/o3de
db88812d61eef77c6f4451b7f8c7605d6db07412
[ "Apache-2.0", "MIT" ]
1
2021-08-08T19:54:51.000Z
2021-08-08T19:54:51.000Z
Code/Framework/AzFramework/AzFramework/Input/Events/InputTextEventListener.h
sandeel31/o3de
db88812d61eef77c6f4451b7f8c7605d6db07412
[ "Apache-2.0", "MIT" ]
2
2022-01-13T04:29:38.000Z
2022-03-12T01:05:31.000Z
Code/Framework/AzFramework/AzFramework/Input/Events/InputTextEventListener.h
sandeel31/o3de
db88812d61eef77c6f4451b7f8c7605d6db07412
[ "Apache-2.0", "MIT" ]
null
null
null
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #pragma once #include <AzFramework/Input/Buses/Notifications/InputTextNotificationBus.h> // Start: fix for windows defining max/min macros #pragma push_macro("max") #pragma push_macro("min") #undef max #undef min //////////////////////////////////////////////////////////////////////////////////////////////////// namespace AzFramework { //////////////////////////////////////////////////////////////////////////////////////////////// //! Class that handles input text event notifications by priority class InputTextEventListener : public InputTextNotificationBus::Handler { public: //////////////////////////////////////////////////////////////////////////////////////////// ///@{ //! Predefined text event listener priority, used to sort handlers from highest to lowest inline static AZ::s32 GetPriorityFirst() { return std::numeric_limits<AZ::s32>::max(); } inline static AZ::s32 GetPriorityDebug() { return (GetPriorityFirst() / 4) * 3; } inline static AZ::s32 GetPriorityUI() { return GetPriorityFirst() / 2; } inline static AZ::s32 GetPriorityDefault() { return 0; } inline static AZ::s32 GetPriorityLast() { return std::numeric_limits<AZ::s32>::min(); } ///@} //////////////////////////////////////////////////////////////////////////////////////////// //! Constructor explicit InputTextEventListener(); //////////////////////////////////////////////////////////////////////////////////////////// //! Constructor //! \param[in] autoConnect Whether to connect to the input notification bus on construction explicit InputTextEventListener(bool autoConnect); //////////////////////////////////////////////////////////////////////////////////////////// //! Constructor //! \param[in] priority The priority used to sort relative to other text event listeners explicit InputTextEventListener(AZ::s32 priority); //////////////////////////////////////////////////////////////////////////////////////////// //! Constructor //! \param[in] priority The priority used to sort relative to other text event listeners //! \param[in] autoConnect Whether to connect to the input notification bus on construction explicit InputTextEventListener(AZ::s32 priority, bool autoConnect); //////////////////////////////////////////////////////////////////////////////////////////// // Default copying AZ_DEFAULT_COPY(InputTextEventListener); //////////////////////////////////////////////////////////////////////////////////////////// //! Default destructor ~InputTextEventListener() override = default; //////////////////////////////////////////////////////////////////////////////////////////// //! \ref AzFramework::InputTextNotifications::GetPriority AZ::s32 GetPriority() const override; //////////////////////////////////////////////////////////////////////////////////////////// //! Connect to the input notification bus to start receiving input notifications void Connect(); //////////////////////////////////////////////////////////////////////////////////////////// //! Disconnect from the input notification bus to stop receiving input notifications void Disconnect(); protected: //////////////////////////////////////////////////////////////////////////////////////////// //! \ref AzFramework::InputTextNotifications::OnInputTextEvent void OnInputTextEvent(const AZStd::string& textUTF8, bool& o_hasBeenConsumed) final; //////////////////////////////////////////////////////////////////////////////////////////// //! Override to be notified when input text events are generated, but not those already been //! consumed by a higher priority listener, or those that do not pass this listener's filter. //! \param[in] textUTF8 The text to process (encoded using UTF-8) //! \return True if the text event has been consumed, false otherwise //////////////////////////////////////////////////////////////////////////////////////////// virtual bool OnInputTextEventFiltered(const AZStd::string& textUTF8) = 0; private: //////////////////////////////////////////////////////////////////////////////////////////// // Variables AZ::s32 m_priority; //!< The priority used to sort relative to other input event listeners }; } // namespace AzFramework // End: fix for windows defining max/min macros #pragma pop_macro("max") #pragma pop_macro("min")
50.454545
101
0.457057
[ "3d" ]
32c8a42fa6e659f4d76c67600b058d159cbc9195
1,640
h
C
src/include/misc_vector.h
bartvanerp/visqol
9115ad9dbc29ae5f9cc5a55d2bb07befce2153cb
[ "Apache-2.0" ]
292
2020-01-30T04:03:17.000Z
2022-03-31T14:55:59.000Z
src/include/misc_vector.h
bartvanerp/visqol
9115ad9dbc29ae5f9cc5a55d2bb07befce2153cb
[ "Apache-2.0" ]
52
2020-04-04T13:31:28.000Z
2022-03-31T00:31:55.000Z
src/include/misc_vector.h
bartvanerp/visqol
9115ad9dbc29ae5f9cc5a55d2bb07befce2153cb
[ "Apache-2.0" ]
76
2020-04-04T13:07:48.000Z
2022-03-29T09:08:20.000Z
/* * Copyright 2019 Google LLC, Andrew Hines * * 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 VISQOL_INCLUDE_MISCVECTOR_H #define VISQOL_INCLUDE_MISCVECTOR_H #include <fstream> #include <string> #include <vector> #include "amatrix.h" namespace Visqol { class MiscVector { public: static double Sum(const AMatrix<double>& mat); static double Mean(const AMatrix<double>& mat); static std::vector<double> ConvertVecOfVecToVec( const std::vector<std::vector<double>>& mat) { std::vector<double> targets_vec; targets_vec.reserve(mat.size()); for (size_t i = 0; i < mat.size(); i++) { targets_vec.push_back(mat[i][0]); } return targets_vec; } static std::vector<double> ReadVectorFromTxtFile(const std::string& path, size_t num_samples) { std::fstream vec_file(path, std::ios_base::in); std::vector<double> v; v.reserve(num_samples); double d; while (vec_file >> d) { v.push_back(d); } vec_file.close(); return v; } }; } // namespace Visqol #endif // VISQOL_INCLUDE_MISCVECTOR_H
27.79661
75
0.677439
[ "vector" ]
32db6414092637e967e46018f85cecb8ae2deed3
4,956
h
C
external/Angelscript/include/Angelscript/util/CASBaseClass.h
HLSources/HLEnhanced
7510a8f7049293b5094b9c6e14e0aa0869c8dba2
[ "Unlicense" ]
83
2016-06-10T20:49:23.000Z
2022-02-13T18:05:11.000Z
external/Angelscript/include/Angelscript/util/CASBaseClass.h
HLSources/HLEnhanced
7510a8f7049293b5094b9c6e14e0aa0869c8dba2
[ "Unlicense" ]
26
2016-06-16T22:27:24.000Z
2019-04-30T19:25:51.000Z
external/Angelscript/include/Angelscript/util/CASBaseClass.h
HLSources/HLEnhanced
7510a8f7049293b5094b9c6e14e0aa0869c8dba2
[ "Unlicense" ]
58
2016-06-10T23:52:33.000Z
2021-12-30T02:30:50.000Z
#ifndef ANGELSCRIPT_CASBASECLASS_H #define ANGELSCRIPT_CASBASECLASS_H #include <angelscript.h> /** * @defgroup ASBaseClass Angelscript Base classes * * @{ */ /** * Base class for Angelscript classes that require one. */ class CASBaseClass { public: CASBaseClass() = default; CASBaseClass( const CASBaseClass& other ) = default; CASBaseClass& operator=( const CASBaseClass& other ) = default; ~CASBaseClass() = default; }; /** * Base class for all Angelscript classes that are reference counted */ class CASRefCountedBaseClass : public CASBaseClass { public: /** * Constructor. */ CASRefCountedBaseClass() : CASBaseClass() , m_iRefCount( 1 ) { } /** * Copy constructor. */ CASRefCountedBaseClass( const CASRefCountedBaseClass& other ) : CASBaseClass( other ) , m_iRefCount( 1 ) { } CASRefCountedBaseClass& operator=( const CASRefCountedBaseClass& other ) = default; ~CASRefCountedBaseClass() = default; /** * @return The reference count. */ int GetRefCount() const { return m_iRefCount; } /** * Adds a reference. */ void AddRef() const; protected: /** * Releases a reference. * @return true if the reference count has become 0 */ bool InternalRelease() const; protected: mutable int m_iRefCount; }; /** * Base class for all Angelscript classes that are reference counted and are used acrosss threads */ class CASAtomicRefCountedBaseClass : public CASRefCountedBaseClass { public: CASAtomicRefCountedBaseClass() = default; CASAtomicRefCountedBaseClass( const CASAtomicRefCountedBaseClass& other ) = default; CASAtomicRefCountedBaseClass& operator=( const CASAtomicRefCountedBaseClass& other ) = default; ~CASAtomicRefCountedBaseClass() = default; /** * @copydoc CASRefCountedBaseClass::AddRef() const * Thread-safe. */ void AddRef() const; protected: /** * @copydoc CASRefCountedBaseClass::InternalRelease() const * Thread-safe. */ bool InternalRelease() const; }; /** * Garbage collected base class * Pass in either CASRefCountedBaseClass or CASAtomicRefCountedBaseClass as the base class */ template<typename BASECLASS> class CASGCBaseClass : public BASECLASS { public: CASGCBaseClass() = default; CASGCBaseClass( const CASGCBaseClass& other ) = default; CASGCBaseClass& operator=( const CASGCBaseClass& other ) = default; ~CASGCBaseClass() = default; /** * @return The garbage collector flag. */ bool GetGCFlag() const { return m_fGCFlag; } /** * Sets the garbage collector flag. */ void SetGCFlag() const { m_fGCFlag = true; } /** * Adds a reference and clears the garbage collector flag. */ void AddRef() const { m_fGCFlag = false; BASECLASS::AddRef(); } protected: /** * Releases a reference and clears the garbage collector flag. */ bool InternalRelease() const { m_fGCFlag = false; return BASECLASS::InternalRelease(); } private: mutable bool m_fGCFlag = false; }; /** * Base class for garbage collected classes. */ typedef CASGCBaseClass<CASRefCountedBaseClass> CASGCRefCountedBaseClass; /** * Base class for thread-safe garbage collected classes. */ typedef CASGCBaseClass<CASAtomicRefCountedBaseClass> CASGCAtomicRefCountedBaseClass; namespace as { /** * Registers a ref counted class's ref counting behaviors. * @param pEngine Script engine. * @param pszObjectName Object name. */ template<typename CLASS> void RegisterRefCountedBaseClass( asIScriptEngine* pEngine, const char* pszObjectName ) { pEngine->RegisterObjectBehaviour( pszObjectName, asBEHAVE_ADDREF, "void AddRef()", asMETHODPR( CLASS, AddRef, ( ) const, void ), asCALL_THISCALL ); pEngine->RegisterObjectBehaviour( pszObjectName, asBEHAVE_RELEASE, "void Release()", asMETHODPR( CLASS, Release, ( ) const, void ), asCALL_THISCALL ); } /** * Registers a garbage collected, ref counted class's ref counting and gc behaviors. * @param pEngine Script engine. * @param pszObjectName Object name. */ template<typename CLASS> void RegisterGCRefCountedBaseClass( asIScriptEngine* pEngine, const char* pszObjectName ) { RegisterRefCountedBaseClass<CLASS>( pEngine, pszObjectName ); pEngine->RegisterObjectBehaviour( pszObjectName, asBEHAVE_GETREFCOUNT, "int GetRefCount() const", asMETHODPR( CLASS, GetRefCount, ( ) const, int ), asCALL_THISCALL ); pEngine->RegisterObjectBehaviour( pszObjectName, asBEHAVE_GETGCFLAG, "bool GetGCFlag() const", asMETHODPR( CLASS, GetGCFlag, ( ) const, bool ), asCALL_THISCALL ); pEngine->RegisterObjectBehaviour( pszObjectName, asBEHAVE_SETGCFLAG, "void SetGCFlag()", asMETHODPR( CLASS, SetGCFlag, ( ) const, void ), asCALL_THISCALL ); pEngine->RegisterObjectBehaviour( pszObjectName, asBEHAVE_ENUMREFS, "void EnumReferences(int& in)", asMETHOD( CLASS, EnumReferences ), asCALL_THISCALL ); pEngine->RegisterObjectBehaviour( pszObjectName, asBEHAVE_RELEASEREFS, "void ReleaseReferences(int& in)", asMETHOD( CLASS, ReleaseReferences ), asCALL_THISCALL ); } } /** @} */ #endif //ANGELSCRIPT_CASBASECLASS_H
23.6
96
0.744754
[ "object" ]
32e45b63bcd0e1024103ad100e63c073e4ee13c3
3,510
h
C
Engine/Source/Developer/RealtimeProfiler/Private/SRealtimeProfilerTimeline.h
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
Engine/Source/Developer/RealtimeProfiler/Private/SRealtimeProfilerTimeline.h
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
2
2015-06-21T17:38:11.000Z
2015-06-22T20:54:42.000Z
Engine/Source/Developer/RealtimeProfiler/Private/SRealtimeProfilerTimeline.h
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #pragma once class SRealtimeProfilerVisualizer; class SRealtimeProfilerLineGraph; class STimeline; struct FRealtimeProfilerFPSChartFrame; struct VisualizerEvents; class SRealtimeProfilerTimeline : public SCompoundWidget { public: SLATE_BEGIN_ARGS( SRealtimeProfilerTimeline ) : _Visualizer() {} SLATE_ATTRIBUTE( SRealtimeProfilerVisualizer *, Visualizer ) SLATE_END_ARGS() /** * Construct the widget * * @param InArgs A declaration from which to construct the widget */ void Construct( const FArguments& InArgs ); /** * Handles selection change in the events tree * * @param Selection selected event */ void HandleEventSelectionChanged( TSharedPtr< FVisualizerEvent > Selection ); void AppendData(TSharedPtr< FVisualizerEvent > ProfileData, FRealtimeProfilerFPSChartFrame * InFPSChartFrame); bool IsProfiling(); protected: /** * Gets the maximum scroll offset fraction value for the horizontal scrollbar * * @return Maximum scroll offset fraction */ float GetMaxScrollOffsetFraction() const { return 1.0f - 1.0f / GetZoom(); } /** * Gets the maximum graph offset value for the graph bars * * @return Maximum graph offset */ float GetMaxGraphOffset() const { return GetZoom() - 1.0f; } /** * Gets the actual zoom level for the graph bars * * @return Zoom level */ float GetZoom() const { const float MinZoom = 1.0f; const float MaxZoom = 20.0f; return MinZoom + ZoomSliderValue * ( MaxZoom - MinZoom ); } /** * Callback for scrolling the horizontal scrollbar * * @param InScrollOffsetFraction Scrollbar offset fraction */ void ScrollBar_OnUserScrolled( float InScrollOffsetFraction ); /** * Constructs the zoom label string based on the current zoom level value. * * @return Zoom label text */ FText GetZoomLabel() const; /** * Callback used to get the current zoom slider value. * * @return Zoom slider value */ float GetZoomValue() const; /** * Callback used to handle zoom slider * * @param NewValue New Zoom slider value */ void OnSetZoomValue( float NewValue ); /** * Sets the current view mode * * @param InMode New view mode */ void SetViewMode( EVisualizerViewMode::Type InMode ); /** * Given a view mode checks if it's the currently selected one * * @param InMode View mode to check */ bool CheckViewMode( EVisualizerViewMode::Type InMode ) const { return (ViewMode == InMode); } /** Called when line graph geometry (size) changes */ void OnLineGraphGeometryChanged( FGeometry Geometry ); /** Adjusts timeline to match the selected event's start and duration */ void AdjustTimeline( TSharedPtr< FVisualizerEvent > InEvent ); /** A pointer to the SRealtimeProfilerLineGraph */ TSharedPtr< SRealtimeProfilerLineGraph > LineGraph; /** Pointer to the visualizer */ TAttribute< SRealtimeProfilerVisualizer * > Visualizer; /** Profiler data view (filtered data) */ TArray< TSharedPtr< FVisualizerEvent > > ProfileDataView; /** A pointer to the Zoom Label widget */ TSharedPtr< STextBlock > ZoomLabel; /** A pointer to the horizontal scrollbar widget */ TSharedPtr< SScrollBar > ScrollBar; /** A pointer to the horizontal scrollbar widget */ TSharedPtr< STimeline > Timeline; /** Zoom slider value */ float ZoomSliderValue; /** Scrollbar offset */ float ScrollbarOffset; /** Bar visualizer view mode */ EVisualizerViewMode::Type ViewMode; };
22.075472
111
0.718803
[ "geometry" ]
32ebe70cb953cecc1cb0daeb58faaa36c7fbc2ca
1,640
h
C
vulkantest/base.h
CreativeMetalCat/vulkan_engine
1815b2992832c639af92969519d853cd6111c48c
[ "MIT" ]
null
null
null
vulkantest/base.h
CreativeMetalCat/vulkan_engine
1815b2992832c639af92969519d853cd6111c48c
[ "MIT" ]
null
null
null
vulkantest/base.h
CreativeMetalCat/vulkan_engine
1815b2992832c639af92969519d853cd6111c48c
[ "MIT" ]
null
null
null
#pragma once #define OUT #define IN struct Vertex { glm::vec3 pos; glm::vec3 color; glm::vec2 texCoord; static VkVertexInputBindingDescription getBindingDescription() { VkVertexInputBindingDescription bindingDescription = {}; bindingDescription.binding = 0; bindingDescription.stride = sizeof(Vertex); bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX; return bindingDescription; } bool operator==(const Vertex& other) const { return pos == other.pos && color == other.color && texCoord == other.texCoord; } static std::array<VkVertexInputAttributeDescription, 3> getAttributeDescriptions() { std::array<VkVertexInputAttributeDescription, 3> attributeDescriptions = {}; attributeDescriptions[0].binding = 0; attributeDescriptions[0].location = 0; attributeDescriptions[0].format = VK_FORMAT_R32G32B32_SFLOAT; attributeDescriptions[0].offset = offsetof(Vertex, pos); attributeDescriptions[1].binding = 0; attributeDescriptions[1].location = 1; attributeDescriptions[1].format = VK_FORMAT_R32G32B32_SFLOAT; attributeDescriptions[1].offset = offsetof(Vertex, color); attributeDescriptions[2].binding = 0; attributeDescriptions[2].location = 2; attributeDescriptions[2].format = VK_FORMAT_R32G32_SFLOAT; attributeDescriptions[2].offset = offsetof(Vertex, texCoord); return attributeDescriptions; } }; struct UniformBufferObject { glm::mat4 model; glm::mat4 view; glm::mat4 proj; }; struct BufferInfo { public: VkBuffer buffer; VkDeviceMemory memory; }; struct Point { public: float x; float y; };
24.117647
86
0.731098
[ "model" ]
32ec5532f019f516b2311d5cfe5fbe15c6f7c577
560
h
C
Trigger.h
wang2324/zork
105ebb0aec01622709c22acaa75a9b8cfe7b653a
[ "MIT" ]
2
2017-10-23T18:23:48.000Z
2017-10-23T18:23:55.000Z
Trigger.h
wang2324/zork
105ebb0aec01622709c22acaa75a9b8cfe7b653a
[ "MIT" ]
null
null
null
Trigger.h
wang2324/zork
105ebb0aec01622709c22acaa75a9b8cfe7b653a
[ "MIT" ]
1
2017-11-25T05:11:20.000Z
2017-11-25T05:11:20.000Z
#ifndef TRIGGER_H_ #define TRIGGER_H_ #include <string> #include <vector> #include "rapidxml.hpp" #include "rapidxml_print.hpp" #include "rapidxml_utils.hpp" #include "TriggerOwner.h" #include "TriggerStatus.h" using namespace std; using namespace rapidxml; class Trigger{ public: string type; string command; int dirty; bool override; vector<string> prints; vector<string> actions; TriggerOwner* owner; TriggerStatus* status; Trigger(xml_node<> *node); virtual ~Trigger(); private: bool determineConditionType(xml_node<>* node); }; #endif
16
47
0.751786
[ "vector" ]
32f5ccf9afdef6b22b66ec60bd5d5ec5f8cdfbf5
3,713
h
C
iraf.v2161/vendor/x11iraf/obm/ObmW/Xraw/SimpleMenP.h
ysBach/irafdocgen
b11fcd75cc44b01ae69c9c399e650ec100167a54
[ "MIT" ]
2
2019-12-01T15:19:09.000Z
2019-12-02T16:48:42.000Z
iraf.v2161/vendor/x11iraf/obm/ObmW/Xraw/SimpleMenP.h
ysBach/irafdocgen
b11fcd75cc44b01ae69c9c399e650ec100167a54
[ "MIT" ]
1
2019-11-30T13:48:50.000Z
2019-12-02T19:40:25.000Z
iraf.v2161/vendor/x11iraf/obm/ObmW/zz/SimpleMenP.h
ysBach/irafdocgen
b11fcd75cc44b01ae69c9c399e650ec100167a54
[ "MIT" ]
null
null
null
/* * $XConsortium: SimpleMenP.h,v 1.12 89/12/11 15:01:39 kit Exp $ * * Copyright 1989 Massachusetts Institute of Technology * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, 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 M.I.T. not be used in advertising or * publicity pertaining to distribution of the software without specific, * written prior permission. M.I.T. makes no representations about the * suitability of this software for any purpose. It is provided "as is" * without express or implied warranty. * * M.I.T. DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL M.I.T. * 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. * */ /* * SimpleMenuP.h - Private Header file for SimpleMenu widget. * * Date: April 3, 1989 * * By: Chris D. Peterson * MIT X Consortium * kit@expo.lcs.mit.edu */ #ifndef _SimpleMenuP_h #define _SimpleMenuP_h #include <X11/ShellP.h> #include <X11/Xraw/3d.h> #include <X11/Xraw/SimpleMenu.h> #include <X11/Xraw/SmeP.h> #define SMW(w) ((SimpleMenuWidget)w)->simple_menu typedef struct { XtPointer extension; /* For future needs. */ } SimpleMenuClassPart; typedef struct _SimpleMenuClassRec { CoreClassPart core_class; CompositeClassPart composite_class; ShellClassPart shell_class; OverrideShellClassPart override_shell_class; SimpleMenuClassPart simpleMenu_class; } SimpleMenuClassRec; extern SimpleMenuClassRec simpleMenuClassRec; typedef struct _SimpleMenuPart { /* resources */ Dimension shadow_thickness; Dimension bsb_shadow_thickness; Pixel top_shadow_color; Pixmap top_shadow_pixmap; Pixel bottom_shadow_color; Pixmap bottom_shadow_pixmap; GC top_shadow_GC; GC bottom_shadow_GC; XawFrameType frame_type; XtPointer user_data; /* resources */ String label_string; /* The string for the label or NULL. */ SmeObject label; /* If label_string is non-NULL then this is the label widget. */ WidgetClass label_class; /* Widget Class of the menu label object. */ Dimension top_margin; /* Top and bottom margins. */ Dimension bottom_margin; Dimension row_height; /* height of each row (menu entry) */ Cursor cursor; /* The menu's cursor. */ SmeObject popup_entry; /* The entry to position the cursor on for when using XawPositionSimpleMenu. */ Boolean menu_on_screen; /* Force the menus to be fully on the screen.*/ int backing_store; /* What type of backing store to use. */ /* private state */ Boolean recursive_set_values; /* contain a possible infinite loop. */ Boolean menu_width; /* If true then force width to remain core.width */ Boolean menu_height; /* Just like menu_width, but for height. */ SmeObject entry_set; /* The entry that is currently set or highlighted. */ } SimpleMenuPart; typedef struct _SimpleMenuRec { CorePart core; CompositePart composite; ShellPart shell; OverrideShellPart override; SimpleMenuPart simple_menu; } SimpleMenuRec, *SimpleMenu; #endif /* _SimpleMenuP_h */
32.570175
79
0.713978
[ "object", "3d" ]
32fc2fb65772e0dcedfa4e6667c011aafd5919eb
2,675
c
C
src/sha256hasher.c
chris-wood/fib-performance
f21773610d6e6447b8f0418922b9d8813495aee8
[ "MIT" ]
null
null
null
src/sha256hasher.c
chris-wood/fib-performance
f21773610d6e6447b8f0418922b9d8813495aee8
[ "MIT" ]
null
null
null
src/sha256hasher.c
chris-wood/fib-performance
f21773610d6e6447b8f0418922b9d8813495aee8
[ "MIT" ]
1
2021-08-28T08:53:43.000Z
2021-08-28T08:53:43.000Z
// // Created by Christopher Wood on 12/5/16. // #include "sha256hasher.h" #include <parc/security/parc_CryptoHasher.h> struct sha256hasher { PARCCryptoHasher *hasher; }; SHA256Hasher * sha256hasher_Create() { SHA256Hasher *hasher = (SHA256Hasher *) malloc(sizeof(SHA256Hasher)); if (hasher != NULL) { hasher->hasher = parcCryptoHasher_Create(PARCCryptoHashType_SHA256); } return hasher; } void sha256hasher_Destroy(SHA256Hasher **hasherP) { SHA256Hasher *hasher = *hasherP; parcCryptoHasher_Release(&hasher->hasher); free(hasher); *hasherP = NULL; } PARCBuffer * sha256hasher_Hash(SHA256Hasher *hasher, PARCBuffer *input) { parcCryptoHasher_Init(hasher->hasher); parcCryptoHasher_UpdateBuffer(hasher->hasher, input); PARCCryptoHash *hash = parcCryptoHasher_Finalize(hasher->hasher); PARCBuffer *digest = parcBuffer_Acquire(parcCryptoHash_GetDigest(hash)); parcCryptoHash_Release(&hash); return digest; } PARCBuffer * sha256hasher_HashArray(SHA256Hasher *hasher, size_t length, uint8_t input[length]) { parcCryptoHasher_Init(hasher->hasher); parcCryptoHasher_UpdateBytes(hasher->hasher, input, length); PARCCryptoHash *hash = parcCryptoHasher_Finalize(hasher->hasher); PARCBuffer *digest = parcBuffer_Acquire(parcCryptoHash_GetDigest(hash)); parcCryptoHash_Release(&hash); return digest; } Bitmap * sha256hasher_HashToVector(SHA256Hasher *hasher, PARCBuffer *input, int range) { Bitmap *vector = bitmap_Create(range); PARCBuffer *hashOutput = sha256hasher_Hash(hasher, input); size_t index = parcBuffer_GetUint64(hashOutput) % range; bitmap_Set(vector, index); parcBuffer_Release(&hashOutput); return vector; } Bitmap * sha256hasher_HashArrayToVector(SHA256Hasher *hasher, size_t length, uint8_t input[length], int range) { Bitmap *vector = bitmap_Create(range); PARCBuffer *hashOutput = sha256hasher_HashArray(hasher, length, input); size_t index = parcBuffer_GetUint64(hashOutput) % range; bitmap_Set(vector, index); parcBuffer_Release(&hashOutput); return vector; } HasherInterface *SHA256HashAsHasher = &(HasherInterface) { .Hash = (PARCBuffer *(*)(void *, PARCBuffer *)) sha256hasher_Hash, .HashArray = (PARCBuffer *(*)(void *hasher, size_t length, uint8_t *input)) sha256hasher_HashArray, .HashToVector = (Bitmap *(*)(void*hasher, PARCBuffer *input, int range)) sha256hasher_HashToVector, .HashArrayToVector = (Bitmap *(*)(void*hasher, size_t length, uint8_t *input, int range)) sha256hasher_HashArrayToVector, .Destroy = (void (*)(void **instance)) sha256hasher_Destroy, };
30.747126
129
0.733458
[ "vector" ]
fd01085b87b966dda6688b17d1100498faf83d6b
4,979
h
C
Code/CardData.h
steveseguin/cardspotter
633da4c94555a3d2c4c446ab8643bf55b8d19864
[ "BSD-3-Clause" ]
19
2019-12-15T10:57:11.000Z
2021-12-01T04:59:01.000Z
Code/CardData.h
steveseguin/cardspotter
633da4c94555a3d2c4c446ab8643bf55b8d19864
[ "BSD-3-Clause" ]
3
2020-02-04T16:00:33.000Z
2020-04-21T21:02:15.000Z
Code/CardData.h
steveseguin/cardspotter
633da4c94555a3d2c4c446ab8643bf55b8d19864
[ "BSD-3-Clause" ]
8
2020-01-07T04:13:45.000Z
2021-12-11T05:21:44.000Z
#pragma once #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/features2d/features2d.hpp> #include <opencv2/photo/photo.hpp> #include <vector> #include <memory> #pragma warning(disable:4996) inline int median(int *data, int n) { int sorted[32 * 32]; int result; memcpy(sorted, data, n * sizeof(int)); std::nth_element(&sorted[0], &sorted[n / 2], &sorted[n]); result = (int)sorted[n / 2]; if (n % 2 == 1) { std::nth_element(&sorted[0], &sorted[(n / 2) + 1], &sorted[n]); result = (result + sorted[(n / 2) + 1]) / 2; } return result; } inline int NumberOfSetBits(uint32_t i) { i = i - ((i >> 1) & 0x55555555); i = (i & 0x33333333) + ((i >> 2) & 0x33333333); return (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24; } inline int hammingDistance(const int* hash, const int* hash2, int length) { int distance = 0; for (int i = 0; i < length; ++i) { int xord = hash[i] ^ hash2[i]; int offbits = NumberOfSetBits(xord); distance += offbits; } return distance; } // #pragma optimize("",off) int getFileNames(const char* folder, std::vector<std::string>& filenames); struct ImageHash { ImageHash() { memset(myHash32, 0, 32 * sizeof(int32_t)); } explicit ImageHash(const cv::Mat& iImage) { memset(myHash32, 0, 32 * sizeof(int32_t)); MakeHash(iImage); } bool IsValid() const { for (int i = 0; i < 32; ++i) if (myHash32[i] != 0) return true; return false; } int32_t myHash32[32]; static const int BITS = 32; static const int mysize = 32; static const int GRID = 4; static const int CELLBITS = 32 / GRID; static const int CELLINTS = mysize / (GRID*GRID); inline static int GetBitIndexFromGridPosition(int x, int y) { return (y*GRID + x)*CELLBITS*CELLBITS; } inline static int GetIntIndexFromGridPosition(int x, int y) { return GetBitIndexFromGridPosition(x, y) / 32; } inline int GetGridDistance(const ImageHash& anOther, const int x, const int y) const { return hammingDistance(&myHash32[GetIntIndexFromGridPosition(x, y)], &anOther.myHash32[GetIntIndexFromGridPosition(x, y)], CELLINTS); } inline int QuickHammingDistance(const ImageHash& anOther) const { return GetGridDistance(anOther, 1, 1); } int HammingDistance(const ImageHash& anOther) const { return hammingDistance(&myHash32[0], &anOther.myHash32[0], mysize); } void Make32(int* hash32, const int* hash, const int aLength) const { for (int i = 0; i < aLength; ++i) { const int bit = i % 32; const int index = i / 32; int& hashValue = hash32[index]; if (bit == 0) { hashValue = 0; } if (hash[i]) { hashValue |= ((int)1) << bit; } } } void MakeHash(const cv::Mat& iImage); }; struct CardInput; struct CardData { std::string myCardName; std::string myCardId; std::string mySetCode; std::string myImgCoreUrl; int myFormat; int mySetIndex; cv::Mat myDisplayImage; cv::Mat myInputImage; cv::Mat myIcon; private: ImageHash myImageHash; public: void MakeHash(); const ImageHash& GetHash() const { return myImageHash; } CardData() {} CardData(const cv::Mat& anInputImage); enum Type { OLD = 1 << 0, BASIC = 1 << 1, NEW = 1 << 2, EXTRAS = 1 << 3, }; void Save(cv::FileStorage& fs) const; void Load(const cv::FileNode& node); bool LoadDisplayImage(const char* directory); void BuildMatchData(); static bool ToGray(const cv::Mat& anInput, cv::Mat& output) { if (anInput.channels() == 3) { cv::cvtColor(anInput, output, cv::COLOR_BGR2GRAY); return true; } cv::cvtColor(anInput, output, cv::COLOR_BGRA2GRAY); return true; } void setImgCoreUrlFromUri(const char* imgUri); }; struct CardInput { CardInput() :myDebugTagged(false) {} CardInput(const cv::RotatedRect& rect, const cv::Mat& aMat, const char* aPath) :myDebugTagged(false) { myRect = rect; #if _WIN32 if (aMat.rows < aMat.cols) { int * crash = NULL; *crash = 1; } #endif myQuery.myInputImage = aMat; myDebugPath += aPath; } CardData myQuery; std::string myDebugPath; cv::RotatedRect myRect; bool myDebugTagged; }; static void GrabFullCardFlips(const cv::Mat& aCard, const cv::RotatedRect& baseRect, std::vector<CardInput>& oList, bool shouldFlip, const char* comment) { cv::Mat card; if (aCard.rows < aCard.cols) { cv::transpose(aCard, card); cv::flip(card, card, 0); } else { card = aCard.clone(); } CardInput cInput(baseRect, card.clone(), comment); oList.push_back(cInput); if (shouldFlip) { cv::flip(card, card, -1); CardInput cInputF(baseRect, card, comment); oList.push_back(cInputF); } } struct Match { Match() :myDatabaseCard(0) { memset(myScore, 0, sizeof(float)*SCORES); } Match(const CardData* data) :myDatabaseCard(data) { memset(myScore, 0, sizeof(float)*SCORES); } const CardData* myDatabaseCard; int myIteration; int myPotentialRectIndex; const static int SCORES = 2; float myScore[SCORES]; int myVariant; CardInput myInput; };
21.647826
153
0.670817
[ "vector" ]
fd05de8176efd810e4a4f815364ae54cf168d8b8
3,155
h
C
RecoMTD/DetLayers/interface/MTDDetSector.h
Purva-Chaudhari/cmssw
32e5cbfe54c4d809d60022586cf200b7c3020bcf
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
RecoMTD/DetLayers/interface/MTDDetSector.h
Purva-Chaudhari/cmssw
32e5cbfe54c4d809d60022586cf200b7c3020bcf
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
RecoMTD/DetLayers/interface/MTDDetSector.h
Purva-Chaudhari/cmssw
32e5cbfe54c4d809d60022586cf200b7c3020bcf
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#ifndef RecoMTD_DetLayers_MTDDetSector_H #define RecoMTD_DetLayers_MTDDetSector_H #include "TrackingTools/DetLayers/interface/GeometricSearchDet.h" #include "DataFormats/GeometrySurface/interface/BoundDiskSector.h" #include "Geometry/MTDNumberingBuilder/interface/MTDTopology.h" #include <ostream> class GeomDet; class MTDDetSector : public GeometricSearchDet { public: using GeometricSearchDet::GeometricSearchDet; /// Construct from iterators on GeomDet* MTDDetSector(std::vector<const GeomDet*>::const_iterator first, std::vector<const GeomDet*>::const_iterator last, const MTDTopology& topo); /// Construct from a vector of GeomDet* MTDDetSector(const std::vector<const GeomDet*>& dets, const MTDTopology& topo); ~MTDDetSector() override{}; // GeometricSearchDet structure const std::vector<const GeomDet*>& basicComponents() const override { return theDets; } const BoundSurface& surface() const final { return *theDiskS; } const std::vector<const GeometricSearchDet*>& components() const override; std::pair<bool, TrajectoryStateOnSurface> compatible(const TrajectoryStateOnSurface& ts, const Propagator& prop, const MeasurementEstimator& est) const override; std::vector<DetWithState> compatibleDets(const TrajectoryStateOnSurface& startingState, const Propagator& prop, const MeasurementEstimator& est) const override; void compatibleDetsV(const TrajectoryStateOnSurface& startingState, const Propagator& prop, const MeasurementEstimator& est, std::vector<DetWithState>& result) const override; std::vector<DetGroup> groupedCompatibleDets(const TrajectoryStateOnSurface& startingState, const Propagator& prop, const MeasurementEstimator& est) const override; // GeometricSearchDet extension const BoundDiskSector& specificSurface() const { return *theDiskS; } void compatibleDetsLine(const size_t idetMin, std::vector<DetWithState>& result, const TrajectoryStateOnSurface& tsos, const Propagator& prop, const MeasurementEstimator& est) const; size_t hshift(const uint32_t detid, const int horizontalShift) const; size_t vshift(const uint32_t detid, const int verticalShift, size_t& closest) const; protected: void setDisk(BoundDiskSector* diskS) { theDiskS = diskS; } bool add(size_t idet, std::vector<DetWithState>& result, const TrajectoryStateOnSurface& tsos, const Propagator& prop, const MeasurementEstimator& est) const; private: ReferenceCountingPointer<BoundDiskSector> theDiskS; std::vector<const GeomDet*> theDets; const MTDTopology* topo_; void init(); }; std::ostream& operator<<(std::ostream&, const MTDDetSector&); #endif
37.117647
103
0.658954
[ "geometry", "vector" ]
fd16fdae27a96c2e8dee9a25654fae09320a0584
3,385
c
C
simulator/simulator/TestHovorkaModelSimulationSingelStep.c
tidepool-org/labs
34c7fa9aef9eef05f9d57cc55f79024d7b41dacf
[ "BSD-2-Clause" ]
4
2015-11-05T06:24:56.000Z
2019-03-28T04:02:23.000Z
ap/simulator/simulator/TestHovorkaModelSimulationSingelStep.c
tidepool-org/labs
34c7fa9aef9eef05f9d57cc55f79024d7b41dacf
[ "BSD-2-Clause" ]
null
null
null
ap/simulator/simulator/TestHovorkaModelSimulationSingelStep.c
tidepool-org/labs
34c7fa9aef9eef05f9d57cc55f79024d7b41dacf
[ "BSD-2-Clause" ]
5
2015-02-06T00:15:17.000Z
2019-04-02T18:31:31.000Z
/* The MIT License (MIT) Copyright (c) 2013 Diacon Group 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. */ //#define DEBUG 0 #include <stdio.h> #include <time.h> #include <stdlib.h> #include "HovorkaModel.h" int main(int argc, char *argv[]) { // Parse parameters -u [y] -d [y] -x [10] where [] is a space sepereated list of numbers int dIndex; int samples; for(int i = 1; i < argc; i++) { if(argv[i][1] == 'd') { dIndex = i; samples = dIndex - 2; break; } } double u[samples];// = atof(argv[2]); double d[samples];// = atof(argv[4]); double x0[10]; // get u and d from argv for(int i = 0; i < samples; i++) { u[i] = atof(argv[2 + i]); d[i] = atof(argv[dIndex + 1 + i]); #ifdef DEBUG printf("its a u at index %i : %10.6f\n", i, u[i]); printf("its a d at index %i : %10.6f\n", i, d[i]); #endif } // get x from argv for(int i = 0; i < 10; i++) { x0[i] = atof(argv[dIndex + samples + 2 + i]); #ifdef DEBUG printf("its a x0 at index %i : %10.6f\n", i, x0[i]); #endif } // Build default parameters for BW 70 kg double BW = 70.0; HovorkaModelParameters_t par; HovorkaModelDefaultParameters(BW, &par); // Define steady state (for BW 70 kg) int nx = 10; double t=0; double uss = 6.68; double dss = 0.00; double xss[nx]; double fss[nx]; xss[0] = 0.0; xss[1] = 0.0; xss[2] = 367.4; xss[3] = 367.4; xss[4] = 55.9483; xss[5] = 23.3399; xss[6] = 5.7626; xss[7] = 0.0295; xss[8] = 0.0047; xss[9] = 0.2997; HovorkaModel(t, xss, &uss, &dss, &par, fss); // Simulation Step double t0 = 0.0; double t1 = 5.0; double dT = t1-t0; int Nsamples = 10; double G; double I; double x1[10]; double work[10]; double GG[samples]; double II[samples]; double uu; double dd; //Simulation of the Hovorka Model for(int i=0; i<samples; i++){ uu = u[i]; dd = d[i]; HovorkaModelSimulationStep( t0, t1, Nsamples, x0, x1, &uu, &dd, &par, &G, &I, work); t0 = t1; t1 = t1 + dT; for(int j=0; j<10; j++) x0[j] = x1[j]; GG[i] = G; II[i] = I; } // print G printf("-G\n"); for(int i=0; i<samples; i++){ printf("%10.6f\n", GG[i]); } // print I printf("-I\n"); for(int i=0; i<samples; i++){ printf("%10.6f\n", II[i]); } printf("-X\n %10.6f\n %10.6f\n %10.6f\n %10.6f\n %10.6f\n %10.6f\n %10.6f\n %10.6f\n %10.6f\n %10.6f\n", x1[0], x1[1], x1[2], x1[3], x1[4], x1[5], x1[6], x1[7], x1[8], x1[9]); }
23.506944
176
0.629838
[ "model" ]
fd1b15f6463c915e0418a13962b531e7f2e722a1
392
c
C
model/compare/fail_compare_bool_nullx.c
VeloPayments/v-portable-runtime
0810b249f78b04c9003db47782eb6a5bbb95f028
[ "MIT" ]
null
null
null
model/compare/fail_compare_bool_nullx.c
VeloPayments/v-portable-runtime
0810b249f78b04c9003db47782eb6a5bbb95f028
[ "MIT" ]
null
null
null
model/compare/fail_compare_bool_nullx.c
VeloPayments/v-portable-runtime
0810b249f78b04c9003db47782eb6a5bbb95f028
[ "MIT" ]
1
2020-07-03T18:18:24.000Z
2020-07-03T18:18:24.000Z
/** * \file fail_compare_bool_nullx.c * * A null left hand side argument causes a model assertion. * * \copyright 2017 Velo Payments, Inc. All rights reserved. */ #include <stdlib.h> #include <cbmc/model_assert.h> #include <vpr/compare.h> bool nondet_arg2(); int main(int argc, char* argv[]) { bool y = nondet_arg2(); compare_bool(NULL, &y, sizeof(bool)); return 0; }
17.043478
60
0.668367
[ "model" ]
fd28fd3ecc3882e80d0e4d3f5db793bad569696d
31,915
c
C
MakefileBasedBuild/Atmel/sam3x/sam3x-ek/libraries/memories/nandflash/ManagedNandFlash.c
bhargavkumar040/android-source-browsing.device--google--accessory--adk2012-demo
d1d4908ee7e35973b3215eb04ddcea2022ceebc1
[ "Apache-2.0" ]
null
null
null
MakefileBasedBuild/Atmel/sam3x/sam3x-ek/libraries/memories/nandflash/ManagedNandFlash.c
bhargavkumar040/android-source-browsing.device--google--accessory--adk2012-demo
d1d4908ee7e35973b3215eb04ddcea2022ceebc1
[ "Apache-2.0" ]
null
null
null
MakefileBasedBuild/Atmel/sam3x/sam3x-ek/libraries/memories/nandflash/ManagedNandFlash.c
bhargavkumar040/android-source-browsing.device--google--accessory--adk2012-demo
d1d4908ee7e35973b3215eb04ddcea2022ceebc1
[ "Apache-2.0" ]
null
null
null
/* ---------------------------------------------------------------------------- * ATMEL Microcontroller Software Support * ---------------------------------------------------------------------------- * Copyright (c) 2010, Atmel 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: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the disclaimer below. * * Atmel's name may not be used to endorse or promote products derived from * this software without specific prior written permission. * * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE * DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ---------------------------------------------------------------------------- */ /** * \file * * The lower layer of nandflash block management, it is called by MappedNandFlash layer, and * it will call EccNandFlash layer. */ /*---------------------------------------------------------------------------- * Headers *----------------------------------------------------------------------------*/ #include "memories.h" #include <string.h> #include <assert.h> /*---------------------------------------------------------------------------- * Local definitions *----------------------------------------------------------------------------*/ /** Casts */ #define ECC(managed) ((struct EccNandFlash *) managed) #define RAW(managed) ((struct RawNandFlash *) managed) #define MODEL(managed) ((struct NandFlashModel *) managed) /** Values returned by the CheckBlock() function */ #define BADBLOCK 255 #define GOODBLOCK 254 /*---------------------------------------------------------------------------- * Local functions *----------------------------------------------------------------------------*/ /** * \brief Check if the device is virgin. * * \param managed Pointer to a ManagedNandFlash instance. * \param spare Pointer to allocated spare area (must be assigned) * \return 1 if a nandflash device is virgin (i.e. has never been used as a * managed nandflash); otherwise return 0. */ static uint8_t IsDeviceVirgin( const struct ManagedNandFlash *managed, uint8_t* spare ) { struct NandBlockStatus blockStatus; const struct NandSpareScheme *scheme = NandFlashModel_GetScheme(MODEL(managed)); uint16_t baseBlock = managed->baseBlock; uint8_t badBlockMarker; uint8_t error; /* Read spare area of page #0. */ error = RawNandFlash_ReadPage(RAW(managed), baseBlock, 0, 0, spare); if( error ) { TRACE_ERROR("ManagedNandFlash_IsDeviceVirgin: Failed to read page #0\n\r");\ return 0; } /* Retrieve bad block marker and block status from spare area*/ NandSpareScheme_ReadBadBlockMarker(scheme, spare, &badBlockMarker); NandSpareScheme_ReadExtra(scheme, spare, &blockStatus, 4, 0); /* Check if block is marked as bad*/ if ( badBlockMarker != 0xFF ) { /* Device is not virgin, since page #0 is guaranteed to be good*/ return 0 ; } /* If device is not virgin, then block status will be set to either FREE, DIRTY or LIVE */ else { if ( blockStatus.status != NandBlockStatus_DEFAULT ) { /* Device is not virgin */ return 0 ; } } return 1 ; } /** * \brief Check if the given block is bad. * * \param managed Pointer to a ManagedNandFlash instance. * \param block Raw block to check. * \param spare Pointer to allocated spare area (must be assigned) * \return 1 if a nandflash device is virgin (i.e. has never been used as a * managed nandflash); otherwise return 0. */ static uint8_t CheckBlock( const struct ManagedNandFlash *managed, uint16_t block, uint8_t* spare ) { uint8_t error ; uint32_t i ; uint8_t pageSpareSize = NandFlashModel_GetPageSpareSize( MODEL( managed ) ) ; /* Read spare area of first page of block */ error = RawNandFlash_ReadPage( RAW( managed ), block, 0, 0, spare ) ; if ( error ) { TRACE_ERROR( "CheckBlock: Cannot read page #0 of block #%d\n\r", block ) ; return error ; } /* Make sure it is all 0xFF */ for ( i=0 ; i < pageSpareSize ; i++ ) { if ( spare[i] != 0xFF ) { return BADBLOCK ; } } /* Read spare area of second page of block */ error = RawNandFlash_ReadPage( RAW( managed ), block, 1, 0, spare ) ; if ( error ) { TRACE_ERROR( "CheckBlock: Cannot read page #1 of block #%d\n\r", block ) ; return error ; } /* Make sure it is all 0xFF */ for ( i=0 ; i < pageSpareSize ; i++ ) { if ( spare[i] != 0xFF ) { return BADBLOCK ; } } return GOODBLOCK ; } /** * \brief Physically writes the status of a block inside its first page spare area. * * \param managed Pointer to a ManagedNandFlash instance. * \param block Raw block to check. * \param pStatus Pointer to status data. * \param spare Pointer to allocated spare area (must be assigned) * \return 0 if successful; otherwise returns a NandCommon_ERROR_xx code. */ static uint8_t WriteBlockStatus( const struct ManagedNandFlash *managed, uint16_t block, struct NandBlockStatus *pStatus, uint8_t *spare ) { assert( spare != NULL ) ; /* "ManagedNandFlash_WriteBlockStatus: spare\n\r" */ memset( spare, 0xFF, NandCommon_MAXPAGESPARESIZE ) ; NandSpareScheme_WriteExtra( NandFlashModel_GetScheme( MODEL( managed ) ), spare, pStatus, 4, 0 ) ; return RawNandFlash_WritePage( RAW( managed ), block, 0, 0, spare ) ; } /*---------------------------------------------------------------------------- * Exported functions *----------------------------------------------------------------------------*/ /** * \brief Initializes a ManagedNandFlash instance. Scans the device to retrieve or * create block status information. * * \param managed Pointer to a ManagedNandFlash instance. * \param model Pointer to the underlying nand chip model. Can be 0. * \param commandAddress Address at which commands are sent. * \param addressAddress Address at which addresses are sent. * \param dataAddress Address at which data is sent. * \param pinChipEnable Pin controlling the CE signal of the NandFlash. * \param pinReadyBusy Pin used to monitor the ready/busy signal of the Nand. * \param baseBlock Base physical block address of managed area, managed 0. * \param sizeInBlocks Number of blocks that is managed. * \return 0 if the initialization is done; or returns a error code. */ uint8_t ManagedNandFlash_Initialize( struct ManagedNandFlash *managed, const struct NandFlashModel *model, uint32_t commandAddress, uint32_t addressAddress, uint32_t dataAddress, const Pin pinChipEnable, const Pin pinReadyBusy, uint16_t baseBlock, uint16_t sizeInBlocks) { uint8_t error; uint8_t spare[NandCommon_MAXPAGESPARESIZE]; uint32_t numBlocks; //uint32_t pageSpareSize; const struct NandSpareScheme *scheme; int32_t block, phyBlock; struct NandBlockStatus blockStatus; uint8_t badBlockMarker; uint32_t eraseCount, minEraseCount, maxEraseCount; TRACE_DEBUG("ManagedNandFlash_Initialize()\n\r"); /* Initialize EccNandFlash */ error = EccNandFlash_Initialize(ECC(managed), model, commandAddress, addressAddress, dataAddress, pinChipEnable, pinReadyBusy); if (error) { return error; } /* Retrieve model information */ numBlocks = NandFlashModel_GetDeviceSizeInBlocks(MODEL(managed)); //pageSpareSize = NandFlashModel_GetPageSpareSize(MODEL(managed)); scheme = NandFlashModel_GetScheme(MODEL(managed)); /* Initialize base & size */ if (sizeInBlocks == 0) sizeInBlocks = numBlocks; if (baseBlock > numBlocks) { baseBlock = 0; } else if (baseBlock + sizeInBlocks > numBlocks) { sizeInBlocks = numBlocks - baseBlock; } TRACE_INFO("Managed NF area: %d + %d\n\r", baseBlock, sizeInBlocks); if (sizeInBlocks > NandCommon_MAXNUMBLOCKS) { TRACE_ERROR("Out of Maxmized Managed Size: %d > %d\n\r", sizeInBlocks, NandCommon_MAXNUMBLOCKS); TRACE_INFO("Change NandCommon_MAXNUMBLOCKS or sizeInBlocks\n\r"); return NandCommon_ERROR_OUTOFBOUNDS; } managed->baseBlock = baseBlock; managed->sizeInBlocks = sizeInBlocks; /* Initialize block statuses */ /* First, check if device is virgin*/ if (IsDeviceVirgin(managed, spare)) { TRACE_WARNING("Device is virgin, doing initial block scanning ...\n\r"); /* Perform initial scan of the device area */ for (block=0; block < sizeInBlocks; block++) { phyBlock = baseBlock + block; /* Check if physical block is bad */ error = CheckBlock(managed, phyBlock, spare); if (error == BADBLOCK) { /* Mark block as bad */ TRACE_DEBUG("Block #%d is bad\n\r", block); managed->blockStatuses[block].status = NandBlockStatus_BAD; } else if (error == GOODBLOCK) { /* Mark block as free with erase count 0 */ TRACE_DEBUG("Block #%d is free\n\r", block); managed->blockStatuses[block].status = NandBlockStatus_FREE; managed->blockStatuses[block].eraseCount = 0; /* Write status in spare of block first page */ error = WriteBlockStatus(managed, phyBlock, &(managed->blockStatuses[block]), spare); if (error) { TRACE_ERROR("ManagedNandFlash_Initialize: WR spare\n\r"); return error; } } else { TRACE_ERROR("ManagedNandFlash_Initialize: Scan device\n\r"); return error; } } } else { TRACE_INFO("Managed, retrieving information ...\n\r"); /* Retrieve block statuses from their first page spare area (find maximum and minimum wear at the same time) */ minEraseCount = 0xFFFFFFFF; maxEraseCount = 0; for ( block=0 ; block < sizeInBlocks; block++ ) { phyBlock = baseBlock + block; /* Read spare of first page */ error = RawNandFlash_ReadPage(RAW(managed), phyBlock, 0, 0, spare); if ( error ) { TRACE_ERROR("ManagedNandFlash_Initialize: Read block #%d(%d)\n\r", block, phyBlock); } /* Retrieve bad block marker and block status */ NandSpareScheme_ReadBadBlockMarker(scheme, spare, &badBlockMarker); NandSpareScheme_ReadExtra(scheme, spare, &blockStatus, 4, 0); /* If they do not match, block must be bad */ if ( (badBlockMarker != 0xFF) && (blockStatus.status != NandBlockStatus_BAD) ) { TRACE_DEBUG("Block #%d(%d) is bad\n\r", block, phyBlock); managed->blockStatuses[block].status = NandBlockStatus_BAD; } /* Check that block status is not default (meaning block is not managed) */ else { if ( blockStatus.status == NandBlockStatus_DEFAULT ) { assert( 0 ) ; /* "Block #%d(%d) is not managed\n\r", block, phyBlock */ } /* Otherwise block status is accurate */ else { TRACE_DEBUG("Block #%03d(%d) : status = %2d | eraseCount = %d\n\r", block, phyBlock, blockStatus.status, blockStatus.eraseCount); managed->blockStatuses[block] = blockStatus; /* Check for min/max erase counts */ if ( blockStatus.eraseCount < minEraseCount ) { minEraseCount = blockStatus.eraseCount; } if ( blockStatus.eraseCount > maxEraseCount ) { maxEraseCount = blockStatus.eraseCount; } /* Clean block*/ /*Release LIVE blocks */ /* if (managed->blockStatuses[block].status == NandBlockStatus_LIVE) { ManagedNandFlash_ReleaseBlock(managed, block); } Erase DIRTY blocks if (managed->blockStatuses[block].status == NandBlockStatus_DIRTY) { ManagedNandFlash_EraseBlock(managed, block); }*/ } } } /* Display erase count information*/ TRACE_ERROR_WP("|--------|------------|--------|--------|--------|\n\r"); TRACE_ERROR_WP("| Wear | Count | Free | Live | Dirty |\n\r"); TRACE_ERROR_WP("|--------|------------|--------|--------|--------|\n\r"); for ( eraseCount=minEraseCount ; eraseCount <= maxEraseCount ; eraseCount++ ) { uint32_t count = 0 ; uint32_t live = 0 ; uint32_t dirty = 0 ; uint32_t free = 0 ; for ( block=0 ; block < sizeInBlocks ; block++ ) { if ( (managed->blockStatuses[block].eraseCount == eraseCount) && (managed->blockStatuses[block].status != NandBlockStatus_BAD) ) { count++ ; switch ( managed->blockStatuses[block].status ) { case NandBlockStatus_LIVE: live++ ; break ; case NandBlockStatus_DIRTY: dirty++ ; break ; case NandBlockStatus_FREE: free++ ; break ; } } } if ( count > 0 ) { TRACE_ERROR_WP( "| %4u | %8u | %4u | %4u | %4u |\n\r", eraseCount, count, free, live, dirty); } } TRACE_ERROR_WP("|--------|------------|--------|--------|--------|\n\r"); } return 0; } /** * \brief Allocates a FREE block of a managed nandflash and marks it as LIVE. * create block status information. * * \param managed Pointer to a ManagedNandFlash instance. * \param block Block to allocate, in managed area. * \return 0 if successful; otherwise returns NandCommon_ERROR_WRONGSTATUS if * the block is not FREE. */ uint8_t ManagedNandFlash_AllocateBlock( struct ManagedNandFlash *managed, uint16_t block) { uint8_t spare[NandCommon_MAXPAGESPARESIZE]; TRACE_INFO("ManagedNandFlash_AllocateBlock(%d)\n\r", block); /* Check that block is FREE*/ if (managed->blockStatuses[block].status != NandBlockStatus_FREE) { TRACE_ERROR("ManagedNandFlash_AllocateBlock: Block must be FREE\n\r"); return NandCommon_ERROR_WRONGSTATUS; } /* Change block status to LIVE*/ managed->blockStatuses[block].status = NandBlockStatus_LIVE; return WriteBlockStatus(managed, managed->baseBlock + block, &(managed->blockStatuses[block]), spare); } /** * \brief Releases a LIVE block of a nandflash and marks it as DIRTY. * create block status information. * * \param managed Pointer to a ManagedNandFlash instance. * \param block Block to release, based on managed area. * \return 0 if successful; otherwise returns NandCommon_ERROR_WRONGSTATUS if * the block is not LIVE, or a RawNandFlash_WritePage error. */ uint8_t ManagedNandFlash_ReleaseBlock( struct ManagedNandFlash *managed, uint16_t block) { uint8_t spare[NandCommon_MAXPAGESPARESIZE]; TRACE_INFO("ManagedNandFlash_ReleaseBlock(%d)\n\r", block); /* Check that block is LIVE*/ if (managed->blockStatuses[block].status != NandBlockStatus_LIVE) { TRACE_ERROR("ManagedNandFlash_ReleaseBlock: Block must be LIVE\n\r"); return NandCommon_ERROR_WRONGSTATUS; } /* Change block status to DIRTY*/ managed->blockStatuses[block].status = NandBlockStatus_DIRTY; return WriteBlockStatus(managed, managed->baseBlock + block, &(managed->blockStatuses[block]), spare); } /** * \brief Erases a DIRTY block of a managed NandFlash. * create block status information. * * \param managed Pointer to a ManagedNandFlash instance. * \param block Block to erase, in managed area. * \return the RawNandFlash_EraseBlock code or NandCommon_ERROR_WRONGSTATUS. */ uint8_t ManagedNandFlash_EraseBlock( struct ManagedNandFlash *managed, uint16_t block) { uint32_t phyBlock = managed->baseBlock + block; uint8_t spare[NandCommon_MAXPAGESPARESIZE]; uint8_t error; TRACE_INFO("ManagedNandFlash_EraseBlock(%d)\n\r", block); /* Check block status*/ if (managed->blockStatuses[block].status != NandBlockStatus_DIRTY) { TRACE_ERROR("ManagedNandFlash_EraseBlock: Block must be DIRTY\n\r"); return NandCommon_ERROR_WRONGSTATUS; } /* Erase block*/ error = RawNandFlash_EraseBlock(RAW(managed), phyBlock); if (error) { return error; } /* Update block status*/ managed->blockStatuses[block].status = NandBlockStatus_FREE; managed->blockStatuses[block].eraseCount++; return WriteBlockStatus(managed, phyBlock, &(managed->blockStatuses[block]), spare); } /** * \brief Reads the data and/or the spare area of a page on a managed nandflash. If * the data pointer is not 0, then the block MUST be LIVE. * \param managed Pointer to a ManagedNandFlash instance. * \param block Number of block to read from. * \param page Number of page to read inside given block. * \param data Data area buffer, can be 0. * \param spare Spare area buffer, can be 0. * \return NandCommon_ERROR_WRONGSTATUS if the block is not LIVE and the data * pointer is not null; Otherwise, returns EccNandFlash_ReadPage(). */ uint8_t ManagedNandFlash_ReadPage( const struct ManagedNandFlash *managed, uint16_t block, uint16_t page, void *data, void *spare) { /* Check that the block is LIVE if data is requested*/ if ((managed->blockStatuses[block].status != NandBlockStatus_LIVE) && (managed->blockStatuses[block].status != NandBlockStatus_DIRTY)) { TRACE_ERROR("ManagedNandFlash_ReadPage: Block must be LIVE or DIRTY.\n\r"); return NandCommon_ERROR_WRONGSTATUS; } /* Read data with ECC verification*/ return EccNandFlash_ReadPage(ECC(managed), managed->baseBlock + block, page, data, spare); } /** * \brief Writes the data and/or spare area of a LIVE page on a managed NandFlash. * ECC for the data area and storing it in the spare. If no data buffer is * provided, the ECC is read from the existing page spare. If no spare buffer * is provided, the spare area is still written with the ECC information * calculated on the data buffer. * \param managed Pointer to a ManagedNandFlash instance. * \param block Number of block to read from. * \param page Number of page to read inside given block. * \param data Data area buffer. * \param spare Spare area buffer. * \return NandCommon_ERROR_WRONGSTATUS if the page is not LIVE; otherwise, * returns EccNandFlash_WritePage(). */ uint8_t ManagedNandFlash_WritePage( const struct ManagedNandFlash *managed, uint16_t block, uint16_t page, void *data, void *spare) { /* Check that the block is LIVE*/ if (managed->blockStatuses[block].status != NandBlockStatus_LIVE) { TRACE_ERROR("ManagedNandFlash_WritePage: Block must be LIVE.\n\r"); return NandCommon_ERROR_WRONGSTATUS; } /* Write data with ECC calculation*/ return EccNandFlash_WritePage(ECC(managed), managed->baseBlock + block, page, data, spare); } /** * \brief Copy the data & spare area of one page to another page. The source block * can be either LIVE or DIRTY, and the destination block must be LIVE; they * must both have the same parity. * \param managed Pointer to a ManagedNandFlash instance. * \param sourceBlock Source block number based on managed area. * \param sourcePage Number of source page inside the source block. * \param destBlock Destination block number based on managed area. * \param destPage Number of destination page inside the dest block. * \return 0 if successful; NandCommon_ERROR_WRONGSTATUS if one or more page * is not live; otherwise returns an NandCommon_ERROR_xxx code. */ uint8_t ManagedNandFlash_CopyPage( const struct ManagedNandFlash *managed, uint16_t sourceBlock, uint16_t sourcePage, uint16_t destBlock, uint16_t destPage) { uint8_t error; assert( (sourcePage & 1) == (destPage & 1) ) ; /* "ManagedNandFlash_CopyPage: source & dest pages must have the same parity\n\r" */ TRACE_INFO("ManagedNandFlash_CopyPage(B#%d:P#%d -> B#%d:P#%d)\n\r", sourceBlock, sourcePage, destBlock, destPage); /* Check block statuses */ if ((managed->blockStatuses[sourceBlock].status != NandBlockStatus_LIVE) && (managed->blockStatuses[sourceBlock].status != NandBlockStatus_DIRTY)) { TRACE_ERROR("ManagedNandFlash_CopyPage: Source block must be LIVE or DIRTY.\n\r"); return NandCommon_ERROR_WRONGSTATUS; } if (managed->blockStatuses[destBlock].status != NandBlockStatus_LIVE) { TRACE_ERROR("ManagedNandFlash_CopyPage: Destination block must be LIVE.\n\r"); return NandCommon_ERROR_WRONGSTATUS; } /* If destination page is page #0, block status information must not be overwritten*/ if (destPage == 0) { uint8_t data[NandCommon_MAXPAGEDATASIZE]; uint8_t spare[NandCommon_MAXPAGESPARESIZE]; /* Read data & spare to copy*/ error = EccNandFlash_ReadPage(ECC(managed), managed->baseBlock + sourceBlock, sourcePage, data, spare); if (error) { return error; } /* Write destination block status information in spare*/ NandSpareScheme_WriteExtra(NandFlashModel_GetScheme(MODEL(managed)), spare, &(managed->blockStatuses[destBlock]), 4, 0); /* Write page*/ error = RawNandFlash_WritePage(RAW(managed), managed->baseBlock + destBlock, destPage, data, spare); if (error) { return error; } } /* Otherwise, a normal copy can be done*/ else { return RawNandFlash_CopyPage(RAW(managed), managed->baseBlock + sourceBlock, sourcePage, managed->baseBlock + destBlock, destPage); } return 0; } /** * \brief Copies the data from a whole block to another block on a nandflash. Both * blocks must be LIVE. * \param managed Pointer to a ManagedNandFlash instance. * \param sourceBlock Source block number. * \param destBlock Destination block number. * \return 0 if successful; NandCommon_ERROR_WRONGSTATUS if one or more page * is not live; otherwise returns an NandCommon_ERROR_xxx code. */ uint8_t ManagedNandFlash_CopyBlock( const struct ManagedNandFlash *managed, uint16_t sourceBlock, uint16_t destBlock) { uint16_t numPages = NandFlashModel_GetBlockSizeInPages(MODEL(managed)); uint8_t error; uint16_t page; assert( sourceBlock != destBlock ) ; /* "ManagedNandFlash_CopyBlock: Source block must be different from dest. block\n\r" */ TRACE_INFO( "ManagedNandFlash_CopyBlock(B#%d->B#%d)\n\r", sourceBlock, destBlock ) ; /* Copy all pages*/ for ( page=0 ; page < numPages ; page++ ) { error = ManagedNandFlash_CopyPage( managed, sourceBlock, page, destBlock, page ) ; if ( error ) { TRACE_ERROR( "ManagedNandFlash_CopyPage: Failed to copy page %d\n\r", page ) ; return error ; } } return 0; } /** * \brief Erases all the blocks which are currently marked as DIRTY. * \param managed Pointer to a ManagedNandFlash instance. * \return 0 if successful; otherwise, returns a NandCommon_ERROR code. * is not live; otherwise returns an NandCommon_ERROR_xxx code. */ uint8_t ManagedNandFlash_EraseDirtyBlocks( struct ManagedNandFlash *managed ) { uint32_t i ; uint8_t error ; /* Erase all dirty blocks*/ for ( i=0 ; i < managed->sizeInBlocks ; i++ ) { if ( managed->blockStatuses[i].status == NandBlockStatus_DIRTY ) { error = ManagedNandFlash_EraseBlock( managed, i ) ; if ( error ) { return error ; } } } return 0 ; } /** * \brief Looks for the youngest block having the desired status among the blocks * of a managed nandflash. If a block is found, its index is stored inside * the provided variable (if pointer is not 0). * * \param managed Pointer to a ManagedNandFlash instance. * \param block Pointer to the block number variable, based on managed area. * \return 0 if a block has been found; otherwise returns either status. */ uint8_t ManagedNandFlash_FindYoungestBlock( const struct ManagedNandFlash *managed, uint8_t status, uint16_t *block ) { uint8_t found = 0; uint16_t bestBlock = 0; uint32_t i; /* Go through the block array*/ for ( i=0 ; i < managed->sizeInBlocks ; i++ ) { /* Check status*/ if ( managed->blockStatuses[i].status == status ) { /* If no block was found, i becomes the best block*/ if ( !found ) { found = 1; bestBlock = i; } /* Compare the erase counts otherwise*/ else { if ( managed->blockStatuses[i].eraseCount < managed->blockStatuses[bestBlock].eraseCount ) { bestBlock = i; } } } } if ( found ) { if ( block ) { *block = bestBlock ; } return 0 ; } else { return NandCommon_ERROR_NOBLOCKFOUND ; } } /** * \brief Counts and returns the number of blocks having the given status in a * managed nandflash. * * \param managed Pointer to a ManagedNandFlash instance. * \param status Desired block status. * \return the number of blocks. */ uint16_t ManagedNandFlash_CountBlocks( const struct ManagedNandFlash *managed, uint8_t status) { uint32_t i; uint16_t count = 0; /* Examine each block*/ for (i=0; i < managed->sizeInBlocks; i++) { if (managed->blockStatuses[i].status == status) { count++; } } return count; } /** * \brief Returns the number of available blocks in a managed nandflash. * * \param managed Pointer to a ManagedNandFlash instance. * \return the number of blocks. */ uint16_t ManagedNandFlash_GetDeviceSizeInBlocks( const struct ManagedNandFlash *managed) { return managed->sizeInBlocks; } /** * \brief Erase all blocks in the managed area of nand flash. * * \param managed Pointer to a ManagedNandFlash instance. * \param level Erase level. * \return the RawNandFlash_EraseBlock code or NandCommon_ERROR_WRONGSTATUS. */ uint8_t ManagedNandFlash_EraseAll(struct ManagedNandFlash *managed, uint8_t level) { uint32_t i; uint8_t error = 0; if (level == NandEraseFULL) { for (i=0; i < managed->sizeInBlocks; i++) { error = RawNandFlash_EraseBlock(RAW(managed), managed->baseBlock + i); /* Reset block status*/ managed->blockStatuses[i].eraseCount = 0; if (error) { TRACE_WARNING("Managed_FullErase: %u(%u)\n\r", i, managed->baseBlock + i); managed->blockStatuses[i].status = NandBlockStatus_BAD; continue; } managed->blockStatuses[i].status = NandBlockStatus_FREE; } } else if (level == NandEraseDATA) { for (i=0; i < managed->sizeInBlocks; i++) { error = ManagedNandFlash_EraseBlock(managed, i); if (error) { TRACE_WARNING("Managed_DataErase: %u(%u)\n\r", i, managed->baseBlock + i); } } } else { for (i=0; i < managed->sizeInBlocks; i++) { if (managed->blockStatuses[i].status == NandBlockStatus_DIRTY) { error = ManagedNandFlash_EraseBlock(managed, i); if (error) { TRACE_WARNING("Managed_DirtyErase: %u(%u)\n\r", i, managed->baseBlock + i); } } } } return error; }
35.940315
145
0.565878
[ "model" ]
fd2a225ce31c8d37250b57023156a4178785f4a6
5,339
c
C
subsys/net/lib/lwm2m/ucifi_battery.c
psychogenic/zephyr
b0e05e8cac3a24bfee2901898a15aa4306f01d66
[ "Apache-2.0" ]
21
2019-02-13T02:11:04.000Z
2020-04-23T19:09:17.000Z
subsys/net/lib/lwm2m/ucifi_battery.c
psychogenic/zephyr
b0e05e8cac3a24bfee2901898a15aa4306f01d66
[ "Apache-2.0" ]
189
2018-12-14T11:44:08.000Z
2020-05-20T15:14:35.000Z
subsys/net/lib/lwm2m/ucifi_battery.c
psychogenic/zephyr
b0e05e8cac3a24bfee2901898a15aa4306f01d66
[ "Apache-2.0" ]
186
2018-12-14T11:56:22.000Z
2020-05-15T12:51:11.000Z
/* * Copyright (c) 2017 Linaro Limited * Copyright (c) 2018-2019 Foundries.io * Copyright (c) 2022 Laird Connectivity * * SPDX-License-Identifier: Apache-2.0 */ /* * Source material for uCIFI battery object (3411): * https://raw.githubusercontent.com/OpenMobileAlliance/lwm2m-registry/prod/3411.xml */ #define LOG_MODULE_NAME net_ucifi_battery #define LOG_LEVEL CONFIG_LWM2M_LOG_LEVEL #include <logging/log.h> LOG_MODULE_REGISTER(LOG_MODULE_NAME); #include <stdint.h> #include <init.h> #include "lwm2m_object.h" #include "lwm2m_engine.h" #include "lwm2m_resource_ids.h" #include "ucifi_battery.h" #define BATTERY_VERSION_MAJOR 1 #define BATTERY_VERSION_MINOR 0 #define MAX_INSTANCE_COUNT CONFIG_LWM2M_UCIFI_BATTERY_INSTANCE_COUNT #define BATTERY_MAX_ID 12 #define RESOURCE_INSTANCE_COUNT (BATTERY_MAX_ID) /* resource state variables */ static uint8_t battery_level[MAX_INSTANCE_COUNT]; static uint32_t supply_loss_counter[MAX_INSTANCE_COUNT]; static struct lwm2m_engine_obj battery; static struct lwm2m_engine_obj_field fields[] = { OBJ_FIELD_DATA(UCIFI_BATTERY_LEVEL_RID, R, U8), OBJ_FIELD_DATA(UCIFI_BATTERY_CAPACITY_RID, R_OPT, FLOAT), OBJ_FIELD_DATA(UCIFI_BATTERY_VOLTAGE_RID, R_OPT, FLOAT), OBJ_FIELD_DATA(UCIFI_BATTERY_TYPE_RID, RW_OPT, STRING), OBJ_FIELD_DATA(UCIFI_BATTERY_LOW_THESHOLD_RID, RW_OPT, U8), OBJ_FIELD_DATA(UCIFI_BATTERY_LEVEL_TOO_LOW_RID, R_OPT, BOOL), OBJ_FIELD_DATA(UCIFI_BATTERY_SHUTDOWN_RID, RW_OPT, BOOL), OBJ_FIELD_DATA(UCIFI_BATTERY_NUM_CYCLES_RID, R_OPT, U32), OBJ_FIELD_DATA(UCIFI_BATTERY_SUPPLY_LOSS_RID, R_OPT, BOOL), OBJ_FIELD_DATA(UCIFI_BATTERY_SUPPLY_LOSS_COUNTER_RID, R_OPT, U32), OBJ_FIELD_EXECUTE_OPT(UCIFI_BATTERY_SUPPLY_LOSS_COUNTER_RESET_RID), OBJ_FIELD_DATA(UCIFI_BATTERY_SUPPLY_LOSS_REASON_RID, R_OPT, STRING), }; static struct lwm2m_engine_obj_inst inst[MAX_INSTANCE_COUNT]; static struct lwm2m_engine_res res[MAX_INSTANCE_COUNT][BATTERY_MAX_ID]; static struct lwm2m_engine_res_inst res_inst[MAX_INSTANCE_COUNT][RESOURCE_INSTANCE_COUNT]; static void clear_supply_loss_counter(uint16_t obj_inst_id, int index) { supply_loss_counter[index] = 0; NOTIFY_OBSERVER(UCIFI_OBJECT_BATTERY_ID, obj_inst_id, UCIFI_BATTERY_SUPPLY_LOSS_COUNTER_RID); } static int supply_loss_counter_reset_cb(uint16_t obj_inst_id, uint8_t *args, uint16_t args_len) { int i; LOG_DBG("RESET supply loss counter %d", obj_inst_id); for (i = 0; i < MAX_INSTANCE_COUNT; i++) { if (inst[i].obj && inst[i].obj_inst_id == obj_inst_id) { clear_supply_loss_counter(obj_inst_id, i); return 0; } } return -ENOENT; } static struct lwm2m_engine_obj_inst *battery_create(uint16_t obj_inst_id) { int index, i = 0, j = 0; /* Check that there is no other instance with this ID */ for (index = 0; index < MAX_INSTANCE_COUNT; index++) { if (inst[index].obj && inst[index].obj_inst_id == obj_inst_id) { LOG_ERR("Can not create instance - " "already existing: %u", obj_inst_id); return NULL; } } for (index = 0; index < MAX_INSTANCE_COUNT; index++) { if (!inst[index].obj) { break; } } if (index >= MAX_INSTANCE_COUNT) { LOG_ERR("Can not create instance - no more room: %u", obj_inst_id); return NULL; } /* Set default values */ battery_level[index] = 0; supply_loss_counter[index] = 0; (void)memset(res[index], 0, sizeof(res[index][0]) * ARRAY_SIZE(res[index])); init_res_instance(res_inst[index], ARRAY_SIZE(res_inst[index])); /* initialize instance resource data */ INIT_OBJ_RES_DATA(UCIFI_BATTERY_LEVEL_RID, res[index], i, res_inst[index], j, &battery_level[index], sizeof(*battery_level)); INIT_OBJ_RES_OPTDATA(UCIFI_BATTERY_CAPACITY_RID, res[index], i, res_inst[index], j); INIT_OBJ_RES_OPTDATA(UCIFI_BATTERY_VOLTAGE_RID, res[index], i, res_inst[index], j); INIT_OBJ_RES_OPTDATA(UCIFI_BATTERY_TYPE_RID, res[index], i, res_inst[index], j); INIT_OBJ_RES_OPTDATA(UCIFI_BATTERY_LOW_THESHOLD_RID, res[index], i, res_inst[index], j); INIT_OBJ_RES_OPTDATA(UCIFI_BATTERY_LEVEL_TOO_LOW_RID, res[index], i, res_inst[index], j); INIT_OBJ_RES_OPTDATA(UCIFI_BATTERY_SHUTDOWN_RID, res[index], i, res_inst[index], j); INIT_OBJ_RES_OPTDATA(UCIFI_BATTERY_NUM_CYCLES_RID, res[index], i, res_inst[index], j); INIT_OBJ_RES_OPTDATA(UCIFI_BATTERY_SUPPLY_LOSS_RID, res[index], i, res_inst[index], j); INIT_OBJ_RES_DATA(UCIFI_BATTERY_SUPPLY_LOSS_COUNTER_RID, res[index], i, res_inst[index], j, &supply_loss_counter[index], sizeof(*supply_loss_counter)); INIT_OBJ_RES_EXECUTE(UCIFI_BATTERY_SUPPLY_LOSS_COUNTER_RESET_RID, res[index], i, supply_loss_counter_reset_cb); INIT_OBJ_RES_OPTDATA(UCIFI_BATTERY_SUPPLY_LOSS_REASON_RID, res[index], i, res_inst[index], j); inst[index].resources = res[index]; inst[index].resource_count = i; LOG_DBG("Create uCIFI Battery instance: %d", obj_inst_id); return &inst[index]; } static int ucifi_battery_init(const struct device *dev) { battery.obj_id = UCIFI_OBJECT_BATTERY_ID; battery.version_major = BATTERY_VERSION_MAJOR; battery.version_minor = BATTERY_VERSION_MINOR; battery.is_core = false; battery.fields = fields; battery.field_count = ARRAY_SIZE(fields); battery.max_instance_count = MAX_INSTANCE_COUNT; battery.create_cb = battery_create; lwm2m_register_obj(&battery); return 0; } SYS_INIT(ucifi_battery_init, APPLICATION, CONFIG_KERNEL_INIT_PRIORITY_DEFAULT);
34.668831
95
0.783105
[ "object" ]
b0378a6d40d5297d76f554155c83212ecede7465
6,185
h
C
eval/compiler/flat_expr_builder.h
google/cel-cpp
ab1252312e85c554aedec68394cf01653819604c
[ "Apache-2.0" ]
114
2018-02-19T01:05:59.000Z
2022-03-30T17:36:57.000Z
eval/compiler/flat_expr_builder.h
google/cel-cpp
ab1252312e85c554aedec68394cf01653819604c
[ "Apache-2.0" ]
123
2018-03-09T18:43:41.000Z
2022-02-08T21:47:35.000Z
eval/compiler/flat_expr_builder.h
google/cel-cpp
ab1252312e85c554aedec68394cf01653819604c
[ "Apache-2.0" ]
39
2018-06-18T15:22:08.000Z
2021-12-09T20:11:02.000Z
/* * Copyright 2021 Google LLC * * 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 * * https://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 THIRD_PARTY_CEL_CPP_EVAL_COMPILER_FLAT_EXPR_BUILDER_H_ #define THIRD_PARTY_CEL_CPP_EVAL_COMPILER_FLAT_EXPR_BUILDER_H_ #include "google/api/expr/v1alpha1/checked.pb.h" #include "google/api/expr/v1alpha1/syntax.pb.h" #include "absl/status/statusor.h" #include "eval/public/cel_expression.h" namespace google::api::expr::runtime { // CelExpressionBuilder implementation. // Builds instances of CelExpressionFlatImpl. class FlatExprBuilder : public CelExpressionBuilder { public: FlatExprBuilder() : enable_unknowns_(false), enable_unknown_function_results_(false), enable_missing_attribute_errors_(false), shortcircuiting_(true), constant_folding_(false), constant_arena_(nullptr), enable_comprehension_(true), comprehension_max_iterations_(0), fail_on_warnings_(true), enable_qualified_type_identifiers_(false), enable_comprehension_list_append_(false), enable_comprehension_vulnerability_check_(false) {} // set_enable_unknowns controls support for unknowns in expressions created. void set_enable_unknowns(bool enabled) { enable_unknowns_ = enabled; } // set_enable_missing_attribute_errors support for error injection in // expressions created. void set_enable_missing_attribute_errors(bool enabled) { enable_missing_attribute_errors_ = enabled; } // set_enable_unknown_function_results controls support for unknown function // results. void set_enable_unknown_function_results(bool enabled) { enable_unknown_function_results_ = enabled; } // set_shortcircuiting regulates shortcircuiting of some expressions. // Be default shortcircuiting is enabled. void set_shortcircuiting(bool enabled) { shortcircuiting_ = enabled; } // Toggle constant folding optimization. By default it is not enabled. // The provided arena is used to hold the generated constants. void set_constant_folding(bool enabled, google::protobuf::Arena* arena) { constant_folding_ = enabled; constant_arena_ = arena; } void set_enable_comprehension(bool enabled) { enable_comprehension_ = enabled; } void set_comprehension_max_iterations(int max_iterations) { comprehension_max_iterations_ = max_iterations; } // Warnings (e.g. no function bound) fail immediately. void set_fail_on_warnings(bool should_fail) { fail_on_warnings_ = should_fail; } // set_enable_qualified_type_identifiers controls whether select expressions // may be treated as constant type identifiers during CelExpression creation. void set_enable_qualified_type_identifiers(bool enabled) { enable_qualified_type_identifiers_ = enabled; } // set_enable_comprehension_list_append controls whether the FlatExprBuilder // will attempt to optimize list concatenation within map() and filter() // macro comprehensions as an append of results on the `accu_var` rather than // as a reassignment of the `accu_var` to the concatenation of // `accu_var` + [elem]. // // Before enabling, ensure that `#list_append` is not a function declared // within your runtime, and that your CEL expressions retain their integer // identifiers. // // This option is not safe for use with hand-rolled ASTs. void set_enable_comprehension_list_append(bool enabled) { enable_comprehension_list_append_ = enabled; } // set_enable_comprehension_vulnerability_check inspects comprehension // sub-expressions for the presence of potential memory exhaustion. // // Note: This flag is not necessary if you are only using Core CEL macros. // // Consider enabling this feature when using custom comprehensions, and // absolutely enable the feature when using hand-written ASTs for // comprehension expressions. void set_enable_comprehension_vulnerability_check(bool enabled) { enable_comprehension_vulnerability_check_ = enabled; } absl::StatusOr<std::unique_ptr<CelExpression>> CreateExpression( const google::api::expr::v1alpha1::Expr* expr, const google::api::expr::v1alpha1::SourceInfo* source_info) const override; absl::StatusOr<std::unique_ptr<CelExpression>> CreateExpression( const google::api::expr::v1alpha1::Expr* expr, const google::api::expr::v1alpha1::SourceInfo* source_info, std::vector<absl::Status>* warnings) const override; absl::StatusOr<std::unique_ptr<CelExpression>> CreateExpression( const google::api::expr::v1alpha1::CheckedExpr* checked_expr) const override; absl::StatusOr<std::unique_ptr<CelExpression>> CreateExpression( const google::api::expr::v1alpha1::CheckedExpr* checked_expr, std::vector<absl::Status>* warnings) const override; absl::StatusOr<std::unique_ptr<CelExpression>> CreateExpressionImpl( const google::api::expr::v1alpha1::Expr* expr, const google::api::expr::v1alpha1::SourceInfo* source_info, const google::protobuf::Map<int64_t, google::api::expr::v1alpha1::Reference>* reference_map, std::vector<absl::Status>* warnings) const; private: bool enable_unknowns_; bool enable_unknown_function_results_; bool enable_missing_attribute_errors_; bool shortcircuiting_; bool constant_folding_; google::protobuf::Arena* constant_arena_; bool enable_comprehension_; int comprehension_max_iterations_; bool fail_on_warnings_; bool enable_qualified_type_identifiers_; bool enable_comprehension_list_append_; bool enable_comprehension_vulnerability_check_; }; } // namespace google::api::expr::runtime #endif // THIRD_PARTY_CEL_CPP_EVAL_COMPILER_FLAT_EXPR_BUILDER_H_
39.14557
98
0.766047
[ "vector" ]
b045d9ae91c981bfb3081a749104e0205b512cf3
10,954
c
C
MPlayer-1.3.0/gui/ui/playbar.c
xu5343/ffmpegtoolkit_CentOS7
974496c709a1c8c69034e46ae5ce7101cf03716f
[ "Apache-2.0" ]
null
null
null
MPlayer-1.3.0/gui/ui/playbar.c
xu5343/ffmpegtoolkit_CentOS7
974496c709a1c8c69034e46ae5ce7101cf03716f
[ "Apache-2.0" ]
null
null
null
MPlayer-1.3.0/gui/ui/playbar.c
xu5343/ffmpegtoolkit_CentOS7
974496c709a1c8c69034e46ae5ce7101cf03716f
[ "Apache-2.0" ]
1
2021-04-15T18:27:37.000Z
2021-04-15T18:27:37.000Z
/* * This file is part of MPlayer. * * MPlayer 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. * * MPlayer 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 MPlayer; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ /* playbar window */ #include <math.h> #include <stdlib.h> #include <stdio.h> #include <sys/stat.h> #include <unistd.h> #include <string.h> #include "gui/app/app.h" #include "gui/app/gui.h" #include "gui/interface.h" #include "gui/skin/font.h" #include "gui/skin/skin.h" #include "gui/util/mem.h" #include "gui/util/misc.h" #include "gui/wm/ws.h" #include "help_mp.h" #include "mp_msg.h" #include "mp_core.h" #include "libvo/x11_common.h" #include "libvo/fastmemcpy.h" #include "stream/stream.h" #include "mixer.h" #include "sub/sub.h" #include "libmpdemux/demuxer.h" #include "libmpdemux/stheader.h" #include "codec-cfg.h" #include "ui.h" #include "actions.h" #include "gui/dialog/dialog.h" #include "render.h" unsigned int GetTimerMS( void ); unsigned int GetTimer( void ); unsigned char * playbarDrawBuffer = NULL; int playbarVisible = False; int playbarLength = 0; int uiPlaybarFade = 0; static void uiPlaybarDraw( void ) { int x; if ( !guiApp.videoWindow.isFullScreen ) return; if ( !playbarVisible || !guiApp.playbarIsPresent ) return; // guiApp.playbar.x=( guiApp.videoWindow.Width - guiApp.playbar.width ) / 2; switch( guiApp.playbar.x ) { case -1: x=( guiApp.videoWindow.Width - guiApp.playbar.width ) / 2; break; case -2: x=( guiApp.videoWindow.Width - guiApp.playbar.width ); break; default: x=guiApp.playbar.x; } switch ( uiPlaybarFade ) { case 1: // fade in playbarLength--; if ( guiApp.videoWindow.Height - guiApp.playbar.height >= playbarLength ) { playbarLength=guiApp.videoWindow.Height - guiApp.playbar.height; uiPlaybarFade=0; wsMouseVisibility(&guiApp.videoWindow, wsShowMouseCursor); } wsWindowMove( &guiApp.playbarWindow,True,x,playbarLength ); break; case 2: // fade out playbarLength+=10; if ( playbarLength > guiApp.videoWindow.Height ) { playbarLength=guiApp.videoWindow.Height; uiPlaybarFade=0; playbarVisible=False; wsMouseVisibility(&guiApp.videoWindow, wsHideMouseCursor); wsWindowVisibility( &guiApp.playbarWindow,wsHideWindow ); return; } wsWindowMove( &guiApp.playbarWindow,True,x,playbarLength ); break; } /* render */ if ( guiApp.playbarWindow.State == wsWindowExpose ) { btnModify( evSetMoviePosition,guiInfo.Position ); btnModify( evSetVolume,guiInfo.Volume ); btnModify( evSetBalance,guiInfo.Balance ); wsMouseVisibility(&guiApp.videoWindow, wsShowMouseCursor); fast_memcpy( playbarDrawBuffer,guiApp.playbar.Bitmap.Image,guiApp.playbar.Bitmap.ImageSize ); RenderAll( &guiApp.playbarWindow,guiApp.playbarItems,guiApp.IndexOfPlaybarItems,playbarDrawBuffer ); wsImageRender( &guiApp.playbarWindow,playbarDrawBuffer ); } wsImageDraw( &guiApp.playbarWindow ); } static void uiPlaybarMouse( int Button, int X, int Y, int RX, int RY ) { static int itemtype = 0; int i; guiItem * item = NULL; static double prev_point; double point; float value = 0.0f; static int SelectedItem = -1; int currentselected = -1; static int endstop; for ( i=0;i <= guiApp.IndexOfPlaybarItems;i++ ) if ( ( guiApp.playbarItems[i].pressed != btnDisabled )&& ( isInside( X,Y,guiApp.playbarItems[i].x,guiApp.playbarItems[i].y,guiApp.playbarItems[i].x+guiApp.playbarItems[i].width,guiApp.playbarItems[i].y+guiApp.playbarItems[i].height ) ) ) { currentselected=i; break; } switch ( Button ) { case wsPMMouseButton: gtkShow( ivHidePopUpMenu,NULL ); uiMenuShow( RX,RY ); break; case wsRMMouseButton: uiMenuHide( RX,RY,0 ); break; case wsRRMouseButton: gtkShow( ivShowPopUpMenu,NULL ); break; /* --- */ case wsPLMouseButton: gtkShow( ivHidePopUpMenu,NULL ); SelectedItem=currentselected; if ( SelectedItem == -1 ) break; // yeees, i'm move the fucking window item=&guiApp.playbarItems[SelectedItem]; itemtype=item->type; item->pressed=btnPressed; switch( item->type ) { // NOTE TO MYSELF: commented, because the expression can never be true /*case itButton: if ( ( SelectedItem > -1 ) && ( ( ( item->message == evPlaySwitchToPause && item->message == evPauseSwitchToPlay ) ) || ( ( item->message == evPauseSwitchToPlay && item->message == evPlaySwitchToPause ) ) ) ) { item->pressed=btnDisabled; } break;*/ case itRPotmeter: prev_point=appRadian( item, X - item->x, Y - item->y ) - item->zeropoint; if ( prev_point < 0.0 ) prev_point+=2*M_PI; if ( prev_point <= item->arclength ) endstop=False; else endstop=STOPPED_AT_0 + STOPPED_AT_100; // block movement break; } break; case wsRLMouseButton: if ( SelectedItem != -1 ) // NOTE TO MYSELF: only if hasButton { item=&guiApp.playbarItems[SelectedItem]; item->pressed=btnReleased; } if ( currentselected == - 1 || SelectedItem == -1 ) { itemtype=0; break; } SelectedItem=-1; value=0; switch( itemtype ) { case itHPotmeter: value=100.0 * ( X - item->x ) / item->width; break; case itVPotmeter: value=100.0 - 100.0 * ( Y - item->y ) / item->height; break; case itRPotmeter: if ( endstop ) { itemtype=0; return; } point=appRadian( item, X - item->x, Y - item->y ) - item->zeropoint; if ( point < 0.0 ) point+=2*M_PI; value=100.0 * point / item->arclength; break; } uiEvent( item->message,value ); itemtype=0; break; /* --- */ case wsP5MouseButton: value=-2.5f; goto rollerhandled; case wsP4MouseButton: value= 2.5f; rollerhandled: if (currentselected != - 1) { item=&guiApp.playbarItems[currentselected]; if ( ( item->type == itHPotmeter )||( item->type == itVPotmeter )||( item->type == itRPotmeter ) ) { item->value=constrain(item->value + value); uiEvent( item->message,item->value ); } } break; /* --- */ case wsMoveMouse: item=&guiApp.playbarItems[SelectedItem]; switch ( itemtype ) { case itPRMButton: if (guiApp.menuIsPresent) guiApp.menuWindow.MouseHandler( 0,RX,RY,0,0 ); break; case itRPotmeter: point=appRadian( item, X - item->x, Y - item->y ) - item->zeropoint; if ( point < 0.0 ) point+=2*M_PI; if ( item->arclength < 2 * M_PI ) /* a potmeter with separated 0% and 100% positions */ { value=item->value; if ( point - prev_point > M_PI ) /* turned beyond the 0% position */ { if ( !endstop ) { endstop=STOPPED_AT_0; value=0.0f; } } else if ( prev_point - point > M_PI ) /* turned back from beyond the 0% position */ { if ( endstop == STOPPED_AT_0 ) endstop=False; } else if ( prev_point <= item->arclength && point > item->arclength ) /* turned beyond the 100% position */ { if ( !endstop ) { endstop=STOPPED_AT_100; value=100.0f; } } else if ( prev_point > item->arclength && point <= item->arclength ) /* turned back from beyond the 100% position */ { if ( endstop == STOPPED_AT_100 ) endstop=False; } } if ( !endstop ) value=100.0 * point / item->arclength; prev_point=point; goto potihandled; case itVPotmeter: value=100.0 - 100.0 * ( Y - item->y ) / item->height; goto potihandled; case itHPotmeter: value=100.0 * ( X - item->x ) / item->width; potihandled: item->value=constrain(value); uiEvent( item->message,item->value ); break; } break; } } void uiPlaybarInit( void ) { if ( !guiApp.playbarIsPresent ) return; if ( ( playbarDrawBuffer = malloc( guiApp.playbar.Bitmap.ImageSize ) ) == NULL ) { gmp_msg( MSGT_GPLAYER,MSGL_FATAL,"[playbar] " MSGTR_GUI_MSG_MemoryErrorWindow ); mplayer( MPLAYER_EXIT_GUI, EXIT_ERROR, 0 ); } guiApp.playbarWindow.Parent=guiApp.videoWindow.WindowID; wsWindowCreate( &guiApp.playbarWindow, guiApp.playbar.x,guiApp.playbar.y,guiApp.playbar.width,guiApp.playbar.height, wsHideFrame|wsHideWindow,wsShowMouseCursor|wsHandleMouseButton|wsHandleMouseMove,"PlayBar" ); mp_msg( MSGT_GPLAYER,MSGL_DBG2,"[playbar] playbarWindow ID: 0x%x\n",(int)guiApp.playbarWindow.WindowID ); wsWindowShape( &guiApp.playbarWindow,guiApp.playbar.Mask.Image ); guiApp.playbarWindow.DrawHandler=uiPlaybarDraw; guiApp.playbarWindow.MouseHandler=uiPlaybarMouse; guiApp.playbarWindow.KeyHandler=guiApp.mainWindow.KeyHandler; playbarLength=guiApp.videoWindow.Height; } void uiPlaybarDone( void ) { nfree(playbarDrawBuffer); wsWindowDestroy(&guiApp.playbarWindow); wsEvents(); } void uiPlaybarShow( int y ) { if ( !guiApp.playbarIsPresent || !gtkEnablePlayBar ) return; if ( !guiApp.videoWindow.isFullScreen ) return; if ( y > guiApp.videoWindow.Height - guiApp.playbar.height ) { if ( !uiPlaybarFade ) wsWindowVisibility( &guiApp.playbarWindow,wsShowWindow ); uiPlaybarFade=1; playbarVisible=True; wsWindowRedraw( &guiApp.playbarWindow ); } else if ( !uiPlaybarFade ) uiPlaybarFade=2; }
33.396341
186
0.596494
[ "render" ]
b0461bac79fe3eba43c97702a0690c557fb8b305
6,457
h
C
OpenGLLearning/include/GLGeometry.h
jfelip/experiments-and-learning
f9c5ac10b7d4990723dece5860c7ddfb8b4cca5d
[ "MIT" ]
null
null
null
OpenGLLearning/include/GLGeometry.h
jfelip/experiments-and-learning
f9c5ac10b7d4990723dece5860c7ddfb8b4cca5d
[ "MIT" ]
null
null
null
OpenGLLearning/include/GLGeometry.h
jfelip/experiments-and-learning
f9c5ac10b7d4990723dece5860c7ddfb8b4cca5d
[ "MIT" ]
null
null
null
#ifndef GL_GEOMETRY_PRIMITIVES_H #define GL_GEOMETRY_PRIMITIVES_H #include <vector> #include <memory> #include <string> #define GLEW_STATIC #include <GL/glew.h> #include <GLFW/glfw3.h> #include <Transform.h> #include <CGLShader.hpp> template<typename T_real=double, typename T_vertex=GLfloat, typename T_indices=GLuint> class COpenGLGeometry { public: typedef std::shared_ptr<COpenGLGeometry> Ptr; typedef const std::shared_ptr<COpenGLGeometry> ConstPtr; public: COpenGLGeometry(T_indices draw_type = GL_TRIANGLES); ~COpenGLGeometry(); bool updateBuffers(); bool draw(Shader *shader); std::vector<T_vertex>& getVertices() {return m_vertices;} std::vector<T_vertex>& getNormals() {return m_normals;} std::vector<T_indices>& getIndices() {return m_indices;} std::vector<T_vertex>& getTextureCoords() {return m_textureCoords;} std::vector<T_vertex>& getColors() {return m_colors;} CTransform<T_real>& getTransform() {return m_transform;} T_indices& getDrawType() {return m_draw_type;} void setVertices( const std::vector<T_vertex>& vertices ) {m_vertices = vertices;} void setNormals( const std::vector<T_vertex>& normals ) {m_normals = normals;} void setIndices( const std::vector<T_indices>& indices ) {m_indices = indices;} void setTextureCoords( const std::vector<T_vertex>& textureCoords ) {m_textureCoords = textureCoords;} void setColors( const std::vector<T_vertex>& colors ) {m_colors = colors;} void setTransform( const CTransform<T_real>& transform ) { m_transform = transform;} void rotate (const T_real r[4]) {m_transform.rotate(r);} void translate (const T_real t[3]) {m_transform.translate(t);} void setDrawType( const T_indices& draw_type) {m_draw_type = draw_type;} protected: std::vector<T_vertex> m_vertices; std::vector<T_vertex> m_normals; std::vector<T_indices> m_indices; std::vector<T_vertex> m_textureCoords; std::vector<T_vertex> m_colors; std::vector<T_vertex> m_vertexBufferData; CTransform<T_real> m_transform; GLuint VBO, VAO, EBO; T_indices m_draw_type; }; template<class T_real, class T_vertex, class T_indices> COpenGLGeometry<T_real,T_vertex,T_indices>::COpenGLGeometry(T_indices draw_type) { glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); m_draw_type = draw_type; } template<class T_real, class T_vertex, class T_indices> COpenGLGeometry<T_real,T_vertex,T_indices>::~COpenGLGeometry() { glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); glDeleteBuffers(1, &EBO); } template<class T_real, class T_vertex, class T_indices> bool COpenGLGeometry<T_real,T_vertex,T_indices>::updateBuffers() { //Vertices and indices must have data if (m_vertices.size()==0 || m_indices.size()==0) { _GENERIC_ERROR_("Trying to update object buffers with no vertices or indices"); return false; } //TODO: Check attribute sizes and initialize them if necessary if (m_vertices.size() != m_normals.size()) { _GENERIC_ERROR_("Vertices and normal sizes do not match. Filling with zeros."); m_normals.resize(m_vertices.size(),0); } if (m_vertices.size() != m_colors.size()) { _GENERIC_ERROR_("Vertices and color sizes do not match. Filling with zeros."); m_colors.resize(m_vertices.size(),0); } if (m_vertices.size()/3 != m_textureCoords.size()/2) { _GENERIC_ERROR_("Vertices and texureCoord sizes do not match. Filling with zeros."); m_textureCoords.resize(2*(m_vertices.size()/3),0); } m_vertexBufferData.clear(); uint t=0; for (uint i=0; i<m_vertices.size(); i+=3) { m_vertexBufferData.push_back(m_vertices[i]); m_vertexBufferData.push_back(m_vertices[i+1]); m_vertexBufferData.push_back(m_vertices[i+2]); m_vertexBufferData.push_back(m_normals[i]); m_vertexBufferData.push_back(m_normals[i+1]); m_vertexBufferData.push_back(m_normals[i+2]); m_vertexBufferData.push_back(m_colors[i]); m_vertexBufferData.push_back(m_colors[i+1]); m_vertexBufferData.push_back(m_colors[i+2]); m_vertexBufferData.push_back(m_textureCoords[t]); m_vertexBufferData.push_back(m_textureCoords[t+1]); t += 2; } // Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s). glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(T_vertex) * m_vertexBufferData.size(), m_vertexBufferData.data(), GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER,sizeof(T_indices) * m_indices.size() , m_indices.data(), GL_STATIC_DRAW); //TODO: Change the GL_FLOAT type according to the T_vertex template //position glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 11 * sizeof(T_vertex), (GLvoid*)0); glEnableVertexAttribArray(0); //normals glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 11 * sizeof(T_vertex), (GLvoid*) (3 * sizeof(T_vertex))); glEnableVertexAttribArray(1); //color glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 11 * sizeof(T_vertex), (GLvoid*) (6 * sizeof(T_vertex))); glEnableVertexAttribArray(2); //texture glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, 11 * sizeof(T_vertex), (GLvoid*) (9 * sizeof(T_vertex))); glEnableVertexAttribArray(3); glBindBuffer(GL_ARRAY_BUFFER, 0); // Note that this is allowed, the call to glVertexAttribPointer registered VBO as the currently bound vertex buffer object so afterwards we can safely unbind glBindVertexArray(0); // Unbind VAO (it's always a good thing to unbind any buffer/array to prevent strange bugs) return true; } template<class T_real, class T_vertex, class T_indices> bool COpenGLGeometry<T_real,T_vertex,T_indices>::draw(Shader *shader) { shader->Use(); //Update transformation matrix m_transform.m_data.computeMatrix(); GLuint transformLoc = glGetUniformLocation(shader->Program, "model"); glUniformMatrix4fv(transformLoc, 1,GL_FALSE, m_transform.m_data.m_pMatrix); //TODO: Calculate the normal matrix to avoid the problem of scaling normals with not iso-scaling factors GLuint transformNorm = glGetUniformLocation(shader->Program, "normalMatrix"); glUniformMatrix4fv(transformNorm, 1,GL_FALSE, m_transform.m_data.m_pMatrix); glBindVertexArray(VAO); //TODO: Change the GL_UNSIGNED_INT type according to the T_index template glDrawElements(m_draw_type, m_vertices.size() , GL_UNSIGNED_INT, 0); glBindVertexArray(0); return true; } #endif
30.747619
193
0.746167
[ "object", "vector", "model", "transform" ]
b051b56de4a67c272d667ce806ad7bf52942edb7
12,384
h
C
platform/mt6592/kernel/drivers/ldvt/hdmitx/tmNxTypes.h
touxiong88/92_mediatek
5e96a7bb778fd9d9b335825584664e0c8b5ff2c7
[ "Apache-2.0" ]
1
2022-01-07T01:53:19.000Z
2022-01-07T01:53:19.000Z
custom/common/kernel/hdmi/nxp_tda19989/tmNxTypes.h
touxiong88/92_mediatek
5e96a7bb778fd9d9b335825584664e0c8b5ff2c7
[ "Apache-2.0" ]
null
null
null
custom/common/kernel/hdmi/nxp_tda19989/tmNxTypes.h
touxiong88/92_mediatek
5e96a7bb778fd9d9b335825584664e0c8b5ff2c7
[ "Apache-2.0" ]
1
2020-02-28T02:48:42.000Z
2020-02-28T02:48:42.000Z
/*==========================================================================*/ /* (Copyright (C) 2003 Koninklijke Philips Electronics N.V. */ /* All rights reserved. */ /* This source code and any compilation or derivative thereof is the */ /* proprietary information of Koninklijke Philips Electronics N.V. */ /* and is confidential in nature. */ /* Under no circumstances is this software to be exposed to or placed */ /* under an Open Source License of any type without the expressed */ /* written permission of Koninklijke Philips Electronics N.V. */ /*==========================================================================*/ /* * Copyright (C) 2000,2001 * Koninklijke Philips Electronics N.V. * All Rights Reserved. * * Copyright (C) 2000,2001 TriMedia Technologies, Inc. * All Rights Reserved. * *############################################################ * * Module name : tmNxTypes.h %version: 7 % * * Last Update : %date_modified: Tue Jul 8 18:08:00 2003 % * * Description: TriMedia/MIPS global type definitions. * * Document Ref: DVP Software Coding Guidelines Specification * DVP/MoReUse Naming Conventions specification * DVP Software Versioning Specification * DVP Device Library Architecture Specification * DVP Board Support Library Architecture Specification * DVP Hardware API Architecture Specification * * *############################################################ */ #ifndef TMNXTYPES_H #define TMNXTYPES_H //----------------------------------------------------------------------------- // Standard include files: //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- // Project include files: //----------------------------------------------------------------------------- // #include "tmFlags.h" // DVP common build control flags #ifdef __cplusplus extern "C" { #endif //----------------------------------------------------------------------------- // Types and defines: //----------------------------------------------------------------------------- // /*Under the TCS, <tmlib/tmtypes.h> may have been included by our client. In order to avoid errors, we take account of this possibility, but in order to support environments where the TCS is not available, we do not include the file by name.*/ #ifndef _TMtypes_h #define _TMtypes_h #define False 0 #define True 1 #ifdef __cplusplus #define Null 0 #else #define Null ((Void *) 0) #endif // // Standard Types // typedef signed char Int8; // 8 bit signed integer typedef signed short Int16; // 16 bit signed integer typedef signed long Int32; // 32 bit signed integer typedef unsigned char UInt8; // 8 bit unsigned integer typedef unsigned short UInt16; // 16 bit unsigned integer typedef unsigned long UInt32; // 32 bit unsigned integer typedef float Float; // 32 bit floating point typedef unsigned int Bool; // Boolean (True/False) typedef char Char; // character, character array ptr typedef int Int; // machine-natural integer typedef unsigned int UInt; // machine-natural unsigned integer typedef char *String; // Null terminated 8 bit char str //----------------------------------------------------------------------------- // Legacy TM Types/Structures (Not necessarily DVP Coding Guideline compliant) // NOTE: For DVP Coding Gudeline compliant code, do not use these types. // typedef char *Address; // Ready for address-arithmetic typedef char const *ConstAddress; typedef unsigned char Byte; // Raw byte typedef float Float32; // Single-precision float typedef double Float64; // Double-precision float typedef void *Pointer; // Pointer to anonymous object typedef void const *ConstPointer; typedef char const *ConstString; typedef Int Endian; #define BigEndian 0 #define LittleEndian 1 typedef UInt32 tmErrorCode_t; typedef UInt32 tmProgressCode_t; typedef struct tmVersion { UInt8 majorVersion; UInt8 minorVersion; UInt16 buildVersion; } tmVersion_t, *ptmVersion_t; #endif /*ndef _TMtypes_h*/ /*Define DVP types that are not TCS types.*/ /* ** ===== Updated from SDE2/2.3_Beta/sde_template/inc/tmNxTypes.h ===== ** ** NOTE: IBits32/UBits32 types are defined for use with 32 bit bitfields. ** This is done because ANSI/ISO compliant compilers require bitfields ** to be of type "int" else a large number of compiler warnings will ** result. To avoid the risks associated with redefining Int32/UInt32 ** to type "int" instead of type "long" (which are the same size on 32 ** bit CPUs) separate 32bit signed/unsigned bitfield types are defined. */ typedef signed int IBits32; /* 32 bit signed integer bitfields */ typedef unsigned int UBits32; /* 32 bit unsigned integer bitfields */ typedef IBits32 *pIBits32; /* 32 bit signed integer bitfield ptr */ typedef UBits32 *pUBits32; /* 32 bit unsigned integer bitfield ptr */ typedef Int8 *pInt8; // 8 bit signed integer typedef Int16 *pInt16; // 16 bit signed integer typedef Int32 *pInt32; // 32 bit signed integer typedef UInt8 *pUInt8; // 8 bit unsigned integer typedef UInt16 *pUInt16; // 16 bit unsigned integer typedef UInt32 *pUInt32; // 32 bit unsigned integer typedef void Void, *pVoid; // Void (typeless) typedef Float *pFloat; // 32 bit floating point typedef double Double, *pDouble; // 32/64 bit floating point typedef Bool *pBool; // Boolean (True/False) typedef Char *pChar; // character, character array ptr typedef Int *pInt; // machine-natural integer typedef UInt *pUInt; // machine-natural unsigned integer typedef String *pString; // Null terminated 8 bit char str, /*Assume that 64-bit integers are supported natively by C99 compilers and Visual C version 6.00 and higher. More discrimination in this area may be added here as necessary.*/ #if defined __STDC_VERSION__ && __STDC_VERSION__ > 199409L /*This can be enabled only when all explicit references to the hi and lo structure members are eliminated from client code.*/ #define TMFL_NATIVE_INT64 1 typedef signed long long int Int64, *pInt64; // 64-bit integer typedef unsigned long long int UInt64, *pUInt64; // 64-bit bitmask // #elif defined _MSC_VER && _MSC_VER >= 1200 // /*This can be enabled only when all explicit references to the hi and lo // structure members are eliminated from client code.*/ // #define TMFL_NATIVE_INT64 1 // typedef signed __int64 Int64, *pInt64; // 64-bit integer // typedef unsigned __int64 UInt64, *pUInt64; // 64-bit bitmask #else /*!(defined __STDC_VERSION__ && __STDC_VERSION__ > 199409L)*/ #define TMFL_NATIVE_INT64 0 typedef struct { /*Get the correct endianness (this has no impact on any other part of the system, but may make memory dumps easier to understand).*/ #if TMFL_ENDIAN == TMFL_ENDIAN_BIG Int32 hi; UInt32 lo; #else UInt32 lo; Int32 hi; #endif } Int64, *pInt64; // 64-bit integer typedef struct { #if TMFL_ENDIAN == TMFL_ENDIAN_BIG UInt32 hi; UInt32 lo; #else UInt32 lo; UInt32 hi; #endif } UInt64, *pUInt64; // 64-bit bitmask #endif /*defined __STDC_VERSION__ && __STDC_VERSION__ > 199409L*/ // Maximum length of device name in all BSP and capability structures #define HAL_DEVICE_NAME_LENGTH 16 /* timestamp definition */ typedef UInt64 tmTimeStamp_t, *ptmTimeStamp_t; //for backwards compatibility with the older tmTimeStamp_t definition #define ticks lo #define hiTicks hi typedef union tmColor3 // 3 byte color structure { UBits32 u32; #if (TMFL_ENDIAN == TMFL_ENDIAN_BIG) struct { UBits32 : 8; UBits32 red : 8; UBits32 green : 8; UBits32 blue : 8; } rgb; struct { UBits32 : 8; UBits32 y : 8; UBits32 u : 8; UBits32 v : 8; } yuv; struct { UBits32 : 8; UBits32 u : 8; UBits32 m : 8; UBits32 l : 8; } uml; #else struct { UBits32 blue : 8; UBits32 green : 8; UBits32 red : 8; UBits32 : 8; } rgb; struct { UBits32 v : 8; UBits32 u : 8; UBits32 y : 8; UBits32 : 8; } yuv; struct { UBits32 l : 8; UBits32 m : 8; UBits32 u : 8; UBits32 : 8; } uml; #endif } tmColor3_t, *ptmColor3_t; typedef union tmColor4 // 4 byte color structure { UBits32 u32; #if (TMFL_ENDIAN == TMFL_ENDIAN_BIG) struct { UBits32 alpha : 8; UBits32 red : 8; UBits32 green : 8; UBits32 blue : 8; } argb; struct { UBits32 alpha : 8; UBits32 y : 8; UBits32 u : 8; UBits32 v : 8; } ayuv; struct { UBits32 alpha : 8; UBits32 u : 8; UBits32 m : 8; UBits32 l : 8; } auml; #else struct { UBits32 blue : 8; UBits32 green : 8; UBits32 red : 8; UBits32 alpha : 8; } argb; struct { UBits32 v : 8; UBits32 u : 8; UBits32 y : 8; UBits32 alpha : 8; } ayuv; struct { UBits32 l : 8; UBits32 m : 8; UBits32 u : 8; UBits32 alpha : 8; } auml; #endif } tmColor4_t, *ptmColor4_t; //----------------------------------------------------------------------------- // Hardware device power states // typedef enum tmPowerState { tmPowerOn, // Device powered on (D0 state) tmPowerStandby, // Device power standby (D1 state) tmPowerSuspend, // Device power suspended (D2 state) tmPowerOff // Device powered off (D3 state) } tmPowerState_t, *ptmPowerState_t; //----------------------------------------------------------------------------- // Software Version Structure // typedef struct tmSWVersion { UInt32 compatibilityNr; // Interface compatibility number UInt32 majorVersionNr; // Interface major version number UInt32 minorVersionNr; // Interface minor version number } tmSWVersion_t, *ptmSWVersion_t; /*Under the TCS, <tm1/tmBoardDef.h> may have been included by our client. In order to avoid errors, we take account of this possibility, but in order to support environments where the TCS is not available, we do not include the file by name.*/ #ifndef _TMBOARDDEF_H_ #define _TMBOARDDEF_H_ //----------------------------------------------------------------------------- // HW Unit Selection // typedef Int tmUnitSelect_t, *ptmUnitSelect_t; #define tmUnitNone (-1) #define tmUnit0 0 #define tmUnit1 1 #define tmUnit2 2 #define tmUnit3 3 #define tmUnit4 4 /*+compatibility*/ #define unitSelect_t tmUnitSelect_t #define unit0 tmUnit0 #define unit1 tmUnit1 #define unit2 tmUnit2 #define unit3 tmUnit3 #define unit4 tmUnit4 #define DEVICE_NAME_LENGTH HAL_DEVICE_NAME_LENGTH /*-compatibility*/ #endif /*ndef _TMBOARDDEF_H_ */ //----------------------------------------------------------------------------- // Instance handle // typedef Int tmInstance_t, *ptmInstance_t; // Callback function declaration typedef Void (*ptmCallback_t) (UInt32 events, Void *pData, UInt32 userData); #define tmCallback_t ptmCallback_t /*compatibility*/ // Kernel debugging function declaration #ifdef TMFL_CFG_INTELCE4100 #define KERN_INFO void #define printk(fmt, args...) printf(fmt, ## args) #endif #ifdef __cplusplus } #endif #endif //ndef TMNXTYPES_H
33.743869
80
0.570494
[ "object" ]
b052e921b98c0854b3b83bc6c62ab5d313465222
8,272
h
C
SDPClassification/src/semantic_parser/SemanticOptions.h
Noahs-ARK/SPIGOT
f1e74019cb568420aacd7e30e21064756c725ca1
[ "MIT" ]
21
2018-05-19T09:58:49.000Z
2022-02-27T13:07:51.000Z
SDPClassification/src/semantic_parser/SemanticOptions.h
Noahs-ARK/SPIGOT
f1e74019cb568420aacd7e30e21064756c725ca1
[ "MIT" ]
1
2019-05-02T03:36:48.000Z
2019-05-02T03:36:48.000Z
SDPClassification/src/semantic_parser/SemanticOptions.h
Noahs-ARK/SPIGOT
f1e74019cb568420aacd7e30e21064756c725ca1
[ "MIT" ]
3
2019-04-16T20:46:40.000Z
2019-08-26T09:57:14.000Z
// Copyright (c) 2012-2015 Andre Martins // All Rights Reserved. // // This file is part of TurboParser 2.3. // // TurboParser 2.3 is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // TurboParser 2.3 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 TurboParser 2.3. If not, see <http://www.gnu.org/licenses/>. #ifndef SEMANTIC_OPTIONS_H_ #define SEMANTIC_OPTIONS_H_ #include "Options.h" #include "Utils.h" class SemanticOptions : public Options { public: SemanticOptions() {}; virtual ~SemanticOptions() {}; // Serialization functions. void Load(FILE *fs); void Save(FILE *fs); // Initialization: set options based on the flags. void Initialize(); bool labeled() { return labeled_; } bool deterministic_labels() { return deterministic_labels_; } bool allow_self_loops() { return allow_self_loops_; } bool allow_root_predicate() { return allow_root_predicate_; } bool allow_unseen_predicates() { return allow_unseen_predicates_; } bool use_predicate_senses() { return use_predicate_senses_; } bool prune_labels() { return prune_labels_; } bool prune_labels_with_senses() { return prune_labels_with_senses_; } bool prune_labels_with_relation_paths() { return prune_labels_with_relation_paths_; } bool prune_distances() { return prune_distances_; } bool prune_basic() { return prune_basic_; } const string &GetPrunerModelFilePath() { return file_pruner_model_; } double GetPrunerPosteriorThreshold() { return pruner_posterior_threshold_; } double GetPrunerMaxArguments() { return pruner_max_arguments_; } void train_off() { train_ = false; } void train_on() { train_ = true; } bool use_pretrained_embedding() { return use_pretrained_embedding_; } const string &GetEmbeddingFilePath(const string &task) { if (task == "parser") { return parser_file_embedding_; } else if (task == "classification") { return classification_file_embedding_; } } int pruner_num_lstm_layers() { return pruner_num_lstm_layers_; } int lemma_dim() { return lemma_dim_; } int pos_dim() { return pos_dim_; } int pruner_lstm_dim() { return pruner_lstm_dim_; } int word_dim(const string &formalism) { if (formalism == "parser") { return parser_word_dim_; } else if (formalism == "classification") { return classification_word_dim_; } else { CHECK(false) << "Unsupported formalism: " << formalism << ". Giving up..." << endl; } } float dropout(const string &formalism) { if (formalism == "parser") { return parser_dropout_; } else if (formalism == "classification") { return classification_dropout_; } else { CHECK(false) << "Unsupported formalism: " << formalism << ". Giving up..." << endl; } } float word_dropout(const string &formalism) { if (formalism == "parser") { return parser_word_dropout_; } else if (formalism == "classification") { return classification_word_dropout_; } else { CHECK(false) << "Unsupported formalism: " << formalism << ". Giving up..." << endl; } } int num_lstm_layers(const string &formalism) { if (formalism == "parser") { return parser_num_lstm_layers_; } else if (formalism == "classification") { return classification_num_lstm_layers_; } else { CHECK(false) << "Unsupported formalism: " << formalism << ". Giving up..." << endl; } } int lstm_dim(const string &formalism) { if (formalism == "parser") { return parser_lstm_dim_; } else if (formalism == "classification") { return classification_lstm_dim_; } else { CHECK(false) << "Unsupported formalism: " << formalism << ". Giving up..." << endl; } } int mlp_dim(const string &formalism) { if (formalism == "parser") { return parser_mlp_dim_; } else if (formalism == "classification") { return classification_mlp_dim_; } else { CHECK(false) << "Unsupported formalism: " << formalism << ". Giving up..." << endl; } } float eta0(const string &formalism) { if (formalism == "parser") { return eta0_; } else if (formalism == "classification") { return classification_eta0_; } else { CHECK(false) << "Unsupported formalism: " << formalism << ". Giving up..." << endl; } } int halve(const string &formalism) { if (formalism == "parser") { return parser_halve_; } else if (formalism == "classification") { return classification_halve_; } else { CHECK(false) << "Unsupported formalism: " << formalism << ". Giving up..." << endl; } } string trainer(const string &formalism) { if (formalism == "parser") { return parser_trainer_; } else if (formalism == "classification") { return classification_trainer_; } else { CHECK(false) << "Unsupported formalism: " << formalism << ". Giving up..." << endl; } } bool train_pruner() { return train_pruner_; } int pruner_mlp_dim() { return pruner_mlp_dim_; } int parser_epochs() { return parser_epochs_; } bool update_parser() { return update_parser_; } float parser_fraction() { return parser_fraction_; } void train_pruner_off() { train_pruner_ = false; } const string GetTrainingFilePath(const string &formalism) { if (formalism == "parser") { return file_train_; } else if (formalism == "classification") { return classification_file_train_; } else { CHECK(false) << "Unsupported formalism: " << formalism << ". Giving up..." << endl; } } const string GetTestFilePath(const string &formalism) { if (formalism == "parser") { return file_test_; } else if (formalism == "classification") { return classification_file_test_; } else { CHECK(false) << "Unsupported formalism: " << formalism << ". Giving up..." << endl; } } const string &feature() { return feature_; }; int batch_size() { return batch_size_; } bool proj() { return proj_; } bool pretrain_parser() { return pretrain_parser_; } const string &pretrained_parser_model() { return pretrained_parser_model_; } // temporary solution to weight_decay issue in dynet // TODO: save the weight_decay along with the model. uint64_t parser_num_updates_, classification_num_updates_; uint64_t pruner_num_updates_; float eta0_; float classification_eta0_; protected: string classification_file_train_; string classification_file_test_; bool labeled_; bool deterministic_labels_; bool allow_self_loops_; bool allow_root_predicate_; bool allow_unseen_predicates_; bool use_predicate_senses_; bool prune_labels_; bool prune_labels_with_senses_; bool prune_labels_with_relation_paths_; bool prune_distances_; bool prune_basic_; string file_pruner_model_; double pruner_posterior_threshold_; int pruner_max_arguments_; bool use_pretrained_embedding_; string parser_file_embedding_; string classification_file_embedding_; int lemma_dim_; int pos_dim_; int parser_word_dim_; int parser_lstm_dim_, pruner_lstm_dim_; int parser_mlp_dim_, pruner_mlp_dim_; int parser_num_lstm_layers_, pruner_num_lstm_layers_; int parser_halve_; string parser_trainer_; float parser_dropout_; float parser_word_dropout_; int classification_word_dim_; int classification_lstm_dim_; int classification_mlp_dim_; int classification_num_lstm_layers_; int classification_halve_; string classification_trainer_; float classification_dropout_; float classification_word_dropout_; bool train_pruner_; bool update_parser_; float parser_fraction_; int parser_epochs_; string feature_; int batch_size_; bool proj_; bool pretrain_parser_; string pretrained_parser_model_; }; #endif // SEMANTIC_OPTIONS_H_
27.03268
80
0.696204
[ "model" ]
b0621a5c0c8846e8baa77c23a9d8cf44e7109656
2,883
h
C
include/sot-pattern-generator/next-step-pg-sot.h
olivier-stasse/sot-pattern-generator
f4c07418ae26b7085b5fe2b0c8cbb3a61cbb611b
[ "0BSD" ]
null
null
null
include/sot-pattern-generator/next-step-pg-sot.h
olivier-stasse/sot-pattern-generator
f4c07418ae26b7085b5fe2b0c8cbb3a61cbb611b
[ "0BSD" ]
null
null
null
include/sot-pattern-generator/next-step-pg-sot.h
olivier-stasse/sot-pattern-generator
f4c07418ae26b7085b5fe2b0c8cbb3a61cbb611b
[ "0BSD" ]
1
2019-07-26T07:09:30.000Z
2019-07-26T07:09:30.000Z
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * Copyright Projet JRL-Japan, 2007 *+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * * File: NextStep.h * Project: SOT * Author: Nicolas Mansard * * Version control * =============== * * $Id$ * * Description * ============ * * * ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ #ifndef __SOT_NextStep_OHRP_H__ #define __SOT_NextStep_OHRP_H__ /* --------------------------------------------------------------------- */ /* --- INCLUDE --------------------------------------------------------- */ /* --------------------------------------------------------------------- */ /* Matrix */ #include <jrl/mal/boost.hh> namespace ml = maal::boost; /* SOT */ #include <sot-pattern-generator/next-step.h> #include <sot-pattern-generator/pg.h> /* STD */ #include <string> #include <deque> /* --------------------------------------------------------------------- */ /* --- API ------------------------------------------------------------- */ /* --------------------------------------------------------------------- */ #if defined (WIN32) # if defined (next_step_pg_sot_EXPORTS) # define NextStepPGSOT_EXPORT __declspec(dllexport) # else # define NextStepPGSOT_EXPORT __declspec(dllimport) # endif #else # define NextStepPGSOT_EXPORT #endif /* --------------------------------------------------------------------- */ /* --- CLASS ----------------------------------------------------------- */ /* --------------------------------------------------------------------- */ namespace dynamicgraph { namespace sot { class NextStepPGSOT_EXPORT NextStepPgSot :public NextStep { public: DYNAMIC_GRAPH_ENTITY_DECL(); static const unsigned int ADDING_STEP=0; static const unsigned int CHANGING_STEP=1; protected: typedef std::pair<unsigned int, PatternGeneratorJRL::FootAbsolutePosition> FootPrint_t; std::vector<FootPrint_t> stepbuf; Entity * pgEntity; unsigned int m_StepModificationMode; double m_NextStepTime; unsigned int m_NbOfFirstSteps; /*! \brief Pointer towards the interface of the pattern generator. */ pg::PatternGeneratorInterface * m_PGI; /*! \brief Pointer towards the entity which handle the pattern generator. */ PatternGenerator * m_sPG; public: /* --- CONSTRUCTION --- */ NextStepPgSot( const std::string& name ); virtual ~NextStepPgSot( void ) {} public: /* --- FUNCTIONS --- */ virtual void starter( const int & timeCurr ); virtual void stoper( const int & timeCurr ); virtual void introductionCallBack( const int & timeCurr ); public: /* --- ENTITY INHERITANCE --- */ }; } // namespace sot } // namespace dynamicgraph #endif // #ifndef __SOT_NextStep_OHRP_H__
26.694444
93
0.4641
[ "vector" ]
b062b02fc542efc6859d9a25c842bc3e85462301
8,769
c
C
devkitPro/examples/3ds/graphics/gpu/particles/source/main.c
TheMindVirus/codemii
33822905b99aa816eb346f8572a9f4906094352c
[ "MIT" ]
null
null
null
devkitPro/examples/3ds/graphics/gpu/particles/source/main.c
TheMindVirus/codemii
33822905b99aa816eb346f8572a9f4906094352c
[ "MIT" ]
null
null
null
devkitPro/examples/3ds/graphics/gpu/particles/source/main.c
TheMindVirus/codemii
33822905b99aa816eb346f8572a9f4906094352c
[ "MIT" ]
null
null
null
#include <3ds.h> #include <citro3d.h> #include <stdio.h> #include <string.h> #include "particle_shbin.h" #define CLEAR_COLOR 0 #define DISPLAY_TRANSFER_FLAGS \ (GX_TRANSFER_FLIP_VERT(0) | GX_TRANSFER_OUT_TILED(0) | GX_TRANSFER_RAW_COPY(0) | \ GX_TRANSFER_IN_FORMAT(GX_TRANSFER_FMT_RGBA8) | GX_TRANSFER_OUT_FORMAT(GX_TRANSFER_FMT_RGB8) | \ GX_TRANSFER_SCALING(GX_TRANSFER_SCALE_NO)) typedef struct { float center[3]; float radius[3]; float attrib[4]; } controlPoint; static const controlPoint point_list[] = { { { -1.0f, 0.0f, -2.0f }, { 0.0f, 0.0f, 0.0f }, { 3*8/240.0f, 3*8/400.0f, 0.0f, 1.0f } }, { { -0.3f, +1.5f, -4.0f }, { 0.0f, 0.1f, 0.1f }, { 3*12/240.0f, 3*12/400.0f, 0.0f, 1.0f } }, { { +0.3f, -1.5f, -4.0f }, { 0.1f, 0.3f, 0.3f }, { 3*16/240.0f, 3*16/400.0f, 0.0f, 0.8f } }, { { +1.0f, 0.0f, -2.0f }, { 0.2f, 0.5f, 0.5f }, { 3*32/240.0f, 3*32/400.0f, 0.0f, 0.0f } }, }; static const u8 point_index_list[] = { 0, 1, 2, 3 }; #define point_index_count (sizeof(point_index_list)/sizeof(point_index_list[0])) static DVLB_s* particle_dvlb; static shaderProgram_s program; static int uLoc_projection, uLoc_modelView; static int uLoc_gsh_param, uLoc_gsh_randParam, uLoc_gsh_randSeed, uLoc_gsh_uvCoords; static int uLoc_gsh_multiplyW, uLoc_gsh_randSphere, uLoc_gsh_noRespawn; static C3D_Mtx projection, modelView; static float curTime = 0.0f; static bool multiplyW = true, randSphere = true, noRespawn = false, additiveBlend = true; static void* vbo_data; static void* ibo_data; static C3D_ProcTex pt; static C3D_ProcTexLut pt_map; static C3D_ProcTexLut pt_noise; static C3D_ProcTexColorLut pt_clr; static void setupProcTex(void) { #define NUMCOLORS 2 C3D_ProcTexInit(&pt, 0, NUMCOLORS); C3D_ProcTexClamp(&pt, GPU_PT_MIRRORED_REPEAT, GPU_PT_MIRRORED_REPEAT); C3D_ProcTexNoiseCoefs(&pt, C3D_ProcTex_UV, 0.1f, 0.5f, 0.1f); C3D_ProcTexCombiner(&pt, false, GPU_PT_SQRT2, GPU_PT_SQRT2); C3D_ProcTexFilter(&pt, GPU_PT_LINEAR); C3D_ProcTexBind(0, &pt); float data[129]; int i; for (i = 0; i <= 128; i ++) { float x = i/128.0f; data[i] = x; } ProcTexLut_FromArray(&pt_map, data); C3D_ProcTexLutBind(GPU_LUT_RGBMAP, &pt_map); // Noise smooth step equation for (i = 0; i <= 128; i ++) { float x = i/128.0f; data[i] = x*x*(3-2*x); } ProcTexLut_FromArray(&pt_noise, data); C3D_ProcTexLutBind(GPU_LUT_NOISE, &pt_noise); u32 colors[NUMCOLORS]; colors[0] = 0xFFBABABA; colors[1] = 0x00888888; ProcTexColorLut_Write(&pt_clr, colors, 0, NUMCOLORS); C3D_ProcTexColorLutBind(&pt_clr); } static void sceneInit(void) { // Load the vertex shader, create a shader program and bind it particle_dvlb = DVLB_ParseFile((u32*)particle_shbin, particle_shbin_size); shaderProgramInit(&program); shaderProgramSetVsh(&program, &particle_dvlb->DVLE[0]); shaderProgramSetGsh(&program, &particle_dvlb->DVLE[1], 0); C3D_BindProgram(&program); // Get the location of the uniforms uLoc_projection = shaderInstanceGetUniformLocation(program.vertexShader, "projection"); uLoc_modelView = shaderInstanceGetUniformLocation(program.vertexShader, "modelView"); uLoc_gsh_param = shaderInstanceGetUniformLocation(program.geometryShader, "param"); uLoc_gsh_randParam = shaderInstanceGetUniformLocation(program.geometryShader, "randParam"); uLoc_gsh_randSeed = shaderInstanceGetUniformLocation(program.geometryShader, "randSeed"); uLoc_gsh_uvCoords = shaderInstanceGetUniformLocation(program.geometryShader, "uvCoords"); uLoc_gsh_multiplyW = shaderInstanceGetUniformLocation(program.geometryShader, "multiplyW"); uLoc_gsh_randSphere = shaderInstanceGetUniformLocation(program.geometryShader, "randSphere"); uLoc_gsh_noRespawn = shaderInstanceGetUniformLocation(program.geometryShader, "noRespawn"); // Configure attributes for use with the vertex shader C3D_AttrInfo* attrInfo = C3D_GetAttrInfo(); AttrInfo_Init(attrInfo); AttrInfo_AddLoader(attrInfo, 0, GPU_FLOAT, 3); // v0=center AttrInfo_AddLoader(attrInfo, 1, GPU_FLOAT, 3); // v1=radius AttrInfo_AddLoader(attrInfo, 2, GPU_FLOAT, 4); // v2=attrib // Create the VBO (vertex buffer object) vbo_data = linearAlloc(sizeof(point_list)); memcpy(vbo_data, point_list, sizeof(point_list)); ibo_data = linearAlloc(sizeof(point_index_list)); memcpy(ibo_data, point_index_list, sizeof(point_index_list)); // Configure buffers C3D_BufInfo* bufInfo = C3D_GetBufInfo(); BufInfo_Init(bufInfo); BufInfo_Add(bufInfo, vbo_data, sizeof(controlPoint), 3, 0x210); // Configure the first fragment shading substage to just pass through the proctex color // and blend the alpha coming from proctex and the vertex color // See https://www.opengl.org/sdk/docs/man2/xhtml/glTexEnv.xml for more insight C3D_TexEnv* env = C3D_GetTexEnv(0); C3D_TexEnvInit(env); C3D_TexEnvSrc(env, C3D_RGB, GPU_TEXTURE3, 0, 0); C3D_TexEnvSrc(env, C3D_Alpha, GPU_TEXTURE3, GPU_PRIMARY_COLOR, 0); C3D_TexEnvFunc(env, C3D_RGB, GPU_REPLACE); C3D_TexEnvFunc(env, C3D_Alpha, GPU_MODULATE); setupProcTex(); } static void sceneRender(float iod) { // Compute the matrices Mtx_PerspStereoTilt(&projection, C3D_AngleFromDegrees(40.0f), C3D_AspectRatioTop, 0.01f, 20.0f, iod, 3.0f, false); Mtx_Identity(&modelView); // Update the uniforms C3D_FVUnifMtx4x4(GPU_VERTEX_SHADER, uLoc_projection, &projection); C3D_FVUnifMtx4x4(GPU_VERTEX_SHADER, uLoc_modelView, &modelView); C3D_FVUnifSet (GPU_GEOMETRY_SHADER, uLoc_gsh_param, 100.0f, curTime, 1.0f, 1.0f); C3D_FVUnifSet (GPU_GEOMETRY_SHADER, uLoc_gsh_randParam, 17, 37, 65535, 1.0f/65535); C3D_FVUnifSet (GPU_GEOMETRY_SHADER, uLoc_gsh_randSeed, 45, 47.564, 46.15, 45.9875); C3D_FVUnifSet (GPU_GEOMETRY_SHADER, uLoc_gsh_uvCoords+0, 3.0, 1.0, 3.0, 3.0); C3D_FVUnifSet (GPU_GEOMETRY_SHADER, uLoc_gsh_uvCoords+1, 1.0, 1.0, 1.0, 3.0); C3D_BoolUnifSet (GPU_GEOMETRY_SHADER, uLoc_gsh_multiplyW, multiplyW); C3D_BoolUnifSet (GPU_GEOMETRY_SHADER, uLoc_gsh_randSphere, randSphere); C3D_BoolUnifSet (GPU_GEOMETRY_SHADER, uLoc_gsh_noRespawn, noRespawn); if (additiveBlend) C3D_AlphaBlend(GPU_BLEND_ADD, GPU_BLEND_ADD, GPU_SRC_ALPHA, GPU_ONE, GPU_SRC_ALPHA, GPU_ONE); else C3D_AlphaBlend(GPU_BLEND_ADD, GPU_BLEND_ADD, GPU_SRC_ALPHA, GPU_ONE_MINUS_SRC_ALPHA, GPU_SRC_ALPHA, GPU_ONE_MINUS_SRC_ALPHA); // Draw the particles C3D_DepthTest(true, GPU_GREATER, GPU_WRITE_COLOR); C3D_DrawElements(GPU_GEOMETRY_PRIM, point_index_count, C3D_UNSIGNED_BYTE, ibo_data); } static void sceneExit(void) { // Free the data linearFree(vbo_data); linearFree(ibo_data); // Free the shader program shaderProgramFree(&program); DVLB_Free(particle_dvlb); } int main() { // Initialize graphics gfxInitDefault(); gfxSet3D(true); // Enable stereoscopic 3D consoleInit(GFX_BOTTOM, NULL); C3D_Init(C3D_DEFAULT_CMDBUF_SIZE); // Initialize the render targets C3D_RenderTarget* targetLeft = C3D_RenderTargetCreate(240, 400, GPU_RB_RGBA8, GPU_RB_DEPTH24_STENCIL8); C3D_RenderTarget* targetRight = C3D_RenderTargetCreate(240, 400, GPU_RB_RGBA8, GPU_RB_DEPTH24_STENCIL8); C3D_RenderTargetSetOutput(targetLeft, GFX_TOP, GFX_LEFT, DISPLAY_TRANSFER_FLAGS); C3D_RenderTargetSetOutput(targetRight, GFX_TOP, GFX_RIGHT, DISPLAY_TRANSFER_FLAGS); // Initialize the scene sceneInit(); // Main loop while (aptMainLoop()) { hidScanInput(); // Respond to user input u32 kDown = hidKeysDown(); u32 kHeld = hidKeysHeld(); if (kDown & KEY_START) break; // break in order to return to hbmenu float slider = osGet3DSliderState(); float iod = slider/4; if (!(kHeld & KEY_L)) curTime += 1/128.0f; if (kDown & KEY_A) curTime = 0.0f; if (kDown & KEY_X) noRespawn = !noRespawn; if (kDown & KEY_Y) randSphere = !randSphere; if (kDown & KEY_B) multiplyW = !multiplyW; if (kDown & KEY_R) additiveBlend = !additiveBlend; printf("\x1b[3;1Htime: %f \n", curTime); printf("\x1b[4;1HnoRespawn: %s \n", noRespawn ? "Yes" : "No"); printf("\x1b[5;1HrandSphere: %s \n", randSphere ? "Yes" : "No"); printf("\x1b[6;1HmultiplyW: %s \n", multiplyW ? "Yes" : "No"); printf("\x1b[7;1HadditiveBlend: %s \n", additiveBlend ? "Yes" : "No"); printf("\x1b[29;1Hgpu: %5.2f%% cpu: %5.2f%% buf:%5.2f%%\n", C3D_GetDrawingTime()*6, C3D_GetProcessingTime()*6, C3D_GetCmdBufUsage()*100); // Render the scene C3D_FrameBegin(C3D_FRAME_SYNCDRAW); { C3D_RenderTargetClear(targetLeft, C3D_CLEAR_ALL, CLEAR_COLOR, 0); C3D_FrameDrawOn(targetLeft); sceneRender(-iod); if (iod > 0.0f) { C3D_RenderTargetClear(targetRight, C3D_CLEAR_ALL, CLEAR_COLOR, 0); C3D_FrameDrawOn(targetRight); sceneRender(iod); } } C3D_FrameEnd(0); } // Deinitialize the scene sceneExit(); // Deinitialize graphics C3D_Fini(); gfxExit(); return 0; }
35.358871
141
0.739423
[ "render", "object", "3d" ]
b064fc7de931add1b40a7a804b0b3248914efbed
2,571
c
C
src/cerinta1.c
sda-ab/lab-01-tasks
21a26ce4bcb6f55b6ff210486c951822a14bc473
[ "MIT" ]
null
null
null
src/cerinta1.c
sda-ab/lab-01-tasks
21a26ce4bcb6f55b6ff210486c951822a14bc473
[ "MIT" ]
null
null
null
src/cerinta1.c
sda-ab/lab-01-tasks
21a26ce4bcb6f55b6ff210486c951822a14bc473
[ "MIT" ]
null
null
null
#include "student.h" //----- Prelucrarea informatiilor pentru un student ----- /** * //TODO: Implementarea metodei ,,nr_restante" * @param stud - studentul a carui numar de restante trebuie aflat * @return numarul de restante */ int nr_restante (student stud) { } /** * //TODO: Implementarea metodei ,,medie" * @param stud - studentul a carei medie trebuie calculata * @return valoare mediei aritmetice */ double medie (student stud) { } //----- Instantierea & popularea vectorului de studenti ----- /** * //TODO: Implementarea metodei ,,alocare_memorie" * Hint: - numele si prenumele se aloca in timpul citirii datelor pentru fiecare student * @param vector - pointer catre vectorul de studenti * @param dimensiune - dimensiunea vectorului */ void alocare_memorie (student **vector, int dimensiune) { } /** * //TODO: Implementarea metodei ,,citire_fisier" (se citesc datele din fisier) * @param vector - vectorul de studenti * @param dimensiune - dimensiunea vectorului * @param input - fisierul de date */ void citire_fisier(student *vector, int dimensiune, FILE *input) { } /** * //TODO: Implementarea metodei ,,afisare_fisier" * @param vector - vectorul de studenti * @param dimensiune - dimensiunea vectorului */ void afisare_fisier(student *vector, int dimensiune) { /*Exemplu afisare in fisier: Nume: Petrescu Prenume: Camil Id: 99 Note: 10 10 10 10 10 Nume: Popesescu Prenume: Gigel Id: 100 Note: 4 12 12 12 12 Nr. restante: 1 Nume: Cineva Prenume: Marian Id: 101 Note: 5 5 5 5 5 */ } /** * //TODO: Implementarea metodei ,,citire" * Hint: - datele sunt citite de la tastatura * @param vector - vectorul de studenti ce trebuie populat cu date * @param dim - dimensiunea vectorului void populare_vector(student *vector, int dimensiune) { } * //TODO: Implementarea metodei ,,afisare" * De afisat: nume, prenume, id, note, nr_restante * @param stud - studentul a carui date o sa fie afisate void afisare_student(student stud) { } */ //----- Sortarea vectorului de studenti ----- /** * //TODO: Implementarea metodei ,,swap" (interschimba datele a 2 studenti) * @param first_stud - primul student * @param second_stud - al 2-lea student */ void swap(student *first_stud, student *second_stud) { } /** * //TODO: Implementarea metodei ,,sortare" (se sorteaza crescator in functie de medie) * Hint: - pentru sortare se foloseste metoda swap * @param vector - vectorul de studenti * @param dimensiune - dimensiunea vectorului */ void sortare_vector(student *vector, int dimensiune) { }
23.805556
87
0.704395
[ "vector" ]
b0651aaab13a3d12c47ea516e342a97bbddf0928
3,522
h
C
Code/Engine/Foundation/Types/UniquePtr.h
Tekh-ops/ezEngine
d6a5887d8709f267bf8f2943ef15054e29f6d3d5
[ "MIT" ]
703
2015-03-07T15:30:40.000Z
2022-03-30T00:12:40.000Z
Code/Engine/Foundation/Types/UniquePtr.h
Tekh-ops/ezEngine
d6a5887d8709f267bf8f2943ef15054e29f6d3d5
[ "MIT" ]
233
2015-01-11T16:54:32.000Z
2022-03-19T18:00:47.000Z
Code/Engine/Foundation/Types/UniquePtr.h
Tekh-ops/ezEngine
d6a5887d8709f267bf8f2943ef15054e29f6d3d5
[ "MIT" ]
101
2016-10-28T14:05:10.000Z
2022-03-30T19:00:59.000Z
#pragma once #include <Foundation/Basics.h> /// \brief A Unique ptr manages an object and destroys that object when it goes out of scope. It is ensure that only one unique ptr can /// manage the same object. template <typename T> class ezUniquePtr { EZ_DISALLOW_COPY_AND_ASSIGN(ezUniquePtr); public: EZ_DECLARE_MEM_RELOCATABLE_TYPE(); /// \brief Creates an empty unique ptr. ezUniquePtr(); /// \brief Creates a unique ptr from a freshly created instance through EZ_NEW or EZ_DEFAULT_NEW. template <typename U> ezUniquePtr(const ezInternal::NewInstance<U>& instance); /// \brief Creates a unique ptr from a pointer and an allocator. The passed allocator will be used to destroy the instance when the unique /// ptr goes out of scope. template <typename U> ezUniquePtr(U* pInstance, ezAllocatorBase* pAllocator); /// \brief Move constructs a unique ptr from another. The other unique ptr will be empty afterwards to guarantee that there is only one /// unique ptr managing the same object. template <typename U> ezUniquePtr(ezUniquePtr<U>&& other); /// \brief Initialization with nullptr to be able to return nullptr in functions that return unique ptr. ezUniquePtr(std::nullptr_t); /// \brief Destroys the managed object using the stored allocator. ~ezUniquePtr(); /// \brief Sets the unique ptr from a freshly created instance through EZ_NEW or EZ_DEFAULT_NEW. template <typename U> void operator=(const ezInternal::NewInstance<U>& instance); /// \brief Move assigns a unique ptr from another. The other unique ptr will be empty afterwards to guarantee that there is only one /// unique ptr managing the same object. template <typename U> void operator=(ezUniquePtr<U>&& other); /// \brief Same as calling 'Reset()' EZ_ALWAYS_INLINE void operator=(std::nullptr_t) { Clear(); } /// \brief Releases the managed object without destroying it. The unique ptr will be empty afterwards. T* Release(); /// \brief Releases the managed object without destroying it. The unique ptr will be empty afterwards. Also returns the allocator that /// should be used to destroy the object. T* Release(ezAllocatorBase*& out_pAllocator); /// \brief Borrows the managed object. The unique ptr stays unmodified. T* Borrow() const; /// \brief Destroys the managed object and resets the unique ptr. void Clear(); /// \brief Provides access to the managed object. T& operator*() const; /// \brief Provides access to the managed object. T* operator->() const; /// \brief Returns true if there is managed object and false if the unique ptr is empty. operator bool() const; /// \brief Compares the unique ptr against another unique ptr. bool operator==(const ezUniquePtr<T>& rhs) const; bool operator!=(const ezUniquePtr<T>& rhs) const; bool operator<(const ezUniquePtr<T>& rhs) const; bool operator<=(const ezUniquePtr<T>& rhs) const; bool operator>(const ezUniquePtr<T>& rhs) const; bool operator>=(const ezUniquePtr<T>& rhs) const; /// \brief Compares the unique ptr against nullptr. bool operator==(std::nullptr_t) const; bool operator!=(std::nullptr_t) const; bool operator<(std::nullptr_t) const; bool operator<=(std::nullptr_t) const; bool operator>(std::nullptr_t) const; bool operator>=(std::nullptr_t) const; private: template <typename U> friend class ezUniquePtr; T* m_pInstance = nullptr; ezAllocatorBase* m_pAllocator = nullptr; }; #include <Foundation/Types/Implementation/UniquePtr_inl.h>
36.309278
140
0.733106
[ "object" ]
b0735278ffb2be61413d9a7db006fbdbd1f0278f
2,184
c
C
d/antioch/greaterantioch/obj/gnollspear.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
13
2019-07-19T05:24:44.000Z
2021-11-18T04:08:19.000Z
d/antioch/greaterantioch/obj/gnollspear.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
4
2021-03-15T18:56:39.000Z
2021-08-17T17:08:22.000Z
d/antioch/greaterantioch/obj/gnollspear.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
13
2019-09-12T06:22:38.000Z
2022-01-31T01:15:12.000Z
#include <std.h> inherit "/d/common/obj/weapon/spear_lg.c"; create(){ ::create(); set_id(({"spear"})); set_name("gnollspear"); set_obvious_short("A finely-crafted tribal decorated spear"); set_short("%^BOLD%^%^BLUE%^Tr%^BOLD%^%^CYAN%^ib%^BOLD%^%^BLUE%^al %^BOLD%^%^RED%^Sp%^BOLD%^%^BLACK%^ea%^BOLD%^%^BLUE%^r%^RESET%^"); set_long( "%^RESET%^%^RED%^This long, %^BOLD%^%^CYAN%^steel%^RESET%^%^RED%^-tipped spear"+ " looks well crafted. A %^BOLD%^%^WHITE%^worn cloth %^RESET%^%^RED%^covers a large"+ " portion of the shaft. Two long pieces of %^RESET%^%^ORANGE%^leather %^RESET%^%^RED%^"+ " hang down, with %^BOLD%^%^YELLOW%^feathers %^RESET%^%^RED%^hanging from it. The spear"+ " is obviously tribally made, though looks quite vicious.%^RESET%^" ); set_property("enchantment",2); set_item_bonus("armor bonus",1); set_value(1300); set_wield((:TO,"wieldit":)); set_unwield((:TO,"unwieldit":)); set_hit((:TO,"hitit":)); } int wieldit() { tell_object(ETO,"%^BOLD%^%^YELLOW%^You grasp the spear tightly, prepared for battle.%^RESET%^"); tell_room(environment(ETO),"%^BOLD%^%^YELLOW%^"+ETO->query_cap_name()+" lifs the spear "+ETO->query_possessive()+" and prepares for battle.%^RESET%^",ETO); return 1; } int unwieldit() { tell_object(ETO,"%^BOLD%^%^YELLOW%^You relax your grip on the spear.%^RESET%^"); tell_room(environment(ETO),"%^BOLD%^%^YELLOW%^"+ETO->query_cap_name()+" relaxes their grip from the spear.%^RESET%^",ETO); return 1; } int hitit(object targ){ if(random(1000) < 200){ if(!objectp(targ)) { return roll_dice(1,6); } tell_object(ETO,"%^BOLD%^%^WHITE%^You stab deeply into "+targ->query_cap_name()+"'s flesh with the tip of %^BOLD%^%^RED%^spear%^BOLD%^%^WHITE%^!%^RESET%^"); tell_object(targ,"%^BOLD%^%^RED%^"+ETO->query_cap_name()+" stabs deep into your flesh with the spear!%^RESET%^"); tell_room(environment(query_wielded()),"%^BOLD%^%^WHITE%^" +ETO->query_cap_name()+" stabs deeply into "+targ->query_cap_name()+"'s flesh with "+ETO->query_possessive()+" spear!%^RESET%^",({ETO,targ})); return roll_dice(3,6)+2; } }
48.533333
209
0.621337
[ "object" ]
b078c57c2defed3e4dd309bea9babf6310ce3fa3
4,269
h
C
FSGDEngine-Student/EDMemoryManager/MMMallocAllocator.h
Cabrra/Engine-Development
cce5930e2264048b0be58b691729407ca507d1af
[ "MIT" ]
2
2019-03-30T11:14:01.000Z
2020-10-27T00:55:01.000Z
FSGDEngine-Student/EDMemoryManager/MMMallocAllocator.h
Cabrra/Engine-Development
cce5930e2264048b0be58b691729407ca507d1af
[ "MIT" ]
null
null
null
FSGDEngine-Student/EDMemoryManager/MMMallocAllocator.h
Cabrra/Engine-Development
cce5930e2264048b0be58b691729407ca507d1af
[ "MIT" ]
1
2019-01-29T20:12:24.000Z
2019-01-29T20:12:24.000Z
#pragma once //#include "MemoryManager.h" #include <memory> // TEMPLATE CLASS MMMallocAllocator template<class _Ty> class MMMallocAllocator : public std::_Allocator_base<_Ty> { // generic MMMallocAllocator for objects of class _Ty public: typedef std::_Allocator_base<_Ty> _Mybase; typedef typename _Mybase::value_type value_type; typedef value_type* pointer; typedef value_type& reference; typedef const value_type* const_pointer; typedef const value_type& const_reference; typedef size_t size_type; typedef ptrdiff_t difference_type; template<class _Other> struct rebind { // convert an MMMallocAllocator<_Ty> to an MMMallocAllocator <_Other> typedef MMMallocAllocator<_Other> other; }; pointer address(reference _Val) const { // return address of mutable _Val return (&_Val); } const_pointer address(const_reference _Val) const { // return address of nonmutable _Val return (&_Val); } MMMallocAllocator() _THROW0() { // construct default MMMallocAllocator (do nothing) } MMMallocAllocator(const MMMallocAllocator<_Ty>&) _THROW0() { // construct by copying (do nothing) } template<class _Other> MMMallocAllocator(const MMMallocAllocator<_Other>&) _THROW0() { // construct from a related MMMallocAllocator (do nothing) } template<class _Other> MMMallocAllocator<_Ty>& operator=(const MMMallocAllocator<_Other>&) { // assign from a related MMMallocAllocator (do nothing) return (*this); } void deallocate(pointer _Ptr, size_type) { // deallocate object at _Ptr, ignore size #if USE_MEMORY_MANAGER //EDMemoryManager::MemoryManager::GetInstance()->DeAllocate(_Ptr); free(_Ptr); #else //::operator delete(_Ptr); free(_Ptr); #endif } pointer allocate(size_type _Count) { // allocate array of _Count elements #if USE_MEMORY_MANAGER //return (_Ty *)EDMemoryManager::MemoryManager::GetInstance()->Allocate(_Count*sizeof(_Ty),false,0,__FILE__,__LINE__); return (_Ty *)malloc(_Count*sizeof(_Ty); #else //return (_Allocate(_Count, (pointer)0)); return (_Ty *)malloc(_Count*sizeof(_Ty)); #endif } pointer allocate(size_type _Count, const void *) { // allocate array of _Count elements, ignore hint #if USE_MEMORY_MANAGER //return (_Ty *)EDMemoryManager::MemoryManager::GetInstance()->Allocate(_Count*sizeof(_Ty),false,0,__FILE__,__LINE__); return (_Ty *)malloc(_Count*sizeof(_Ty); #else //return (allocate(_Count)); return (_Ty *)malloc(_Count*sizeof(_Ty)); #endif } void construct(pointer _Ptr, const _Ty& _Val) { // construct object at _Ptr with value _Val std::_Construct(_Ptr, _Val); } void destroy(pointer _Ptr) { // destroy object at _Ptr std::_Destroy(_Ptr); } size_t max_size() const _THROW0() { // estimate maximum array size size_t _Count = (size_t)(-1) / sizeof (_Ty); return (0 < _Count ? _Count : 1); } }; // MMMallocAllocator TEMPLATE OPERATORS template<class _Ty, class _Other> inline bool operator==(const MMMallocAllocator<_Ty>&, const MMMallocAllocator<_Other>&) _THROW0() { // test for MMMallocAllocator equality (always true) return (true); } template<class _Ty, class _Other> inline bool operator!=(const MMMallocAllocator<_Ty>&, const MMMallocAllocator<_Other>&) _THROW0() { // test for MMMallocAllocator inequality (always false) return (false); } // CLASS MMMallocAllocator<void> template<> class _CRTIMP2_PURE MMMallocAllocator<void> { // generic MMMallocAllocator for type void public: typedef void _Ty; typedef _Ty *pointer; typedef const _Ty *const_pointer; typedef _Ty value_type; template<class _Other> struct rebind { // convert an MMMallocAllocator<void> to an MMMallocAllocator <_Other> typedef MMMallocAllocator<_Other> other; }; MMMallocAllocator() _THROW0() { // construct default MMMallocAllocator (do nothing) } MMMallocAllocator(const MMMallocAllocator<_Ty>&) _THROW0() { // construct by copying (do nothing) } template<class _Other> MMMallocAllocator(const MMMallocAllocator<_Other>&) _THROW0() { // construct from related MMMallocAllocator (do nothing) } template<class _Other> MMMallocAllocator<_Ty>& operator=(const MMMallocAllocator<_Other>&) { // assign from a related MMMallocAllocator (do nothing) return (*this); } };
26.849057
120
0.734598
[ "object" ]
b080264ed3adf3900a37f0070e9bfddc0e3caec1
129,997
c
C
lib/zstd/compress.c
jainsakshi2395/linux
7ccb860232bb83fb60cd6bcf5aaf0c008d903acb
[ "Linux-OpenIB" ]
5
2020-07-08T01:35:16.000Z
2021-04-12T16:35:29.000Z
kernel/lib/zstd/compress.c
SFIP/SFIP
e428a425d2d0e287f23d49f3dd583617ebd2e4a3
[ "Zlib" ]
1
2021-01-27T01:29:47.000Z
2021-01-27T01:29:47.000Z
kernel/lib/zstd/compress.c
SFIP/SFIP
e428a425d2d0e287f23d49f3dd583617ebd2e4a3
[ "Zlib" ]
null
null
null
/** * Copyright (c) 2016-present, Yann Collet, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of https://github.com/facebook/zstd. * An additional grant of patent rights can be found in the PATENTS file in the * same directory. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as published by the * Free Software Foundation. This program is dual-licensed; you may select * either version 2 of the GNU General Public License ("GPL") or BSD license * ("BSD"). */ /*-************************************* * Dependencies ***************************************/ #include "fse.h" #include "huf.h" #include "mem.h" #include "zstd_internal.h" /* includes zstd.h */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/string.h> /* memset */ /*-************************************* * Constants ***************************************/ static const U32 g_searchStrength = 8; /* control skip over incompressible data */ #define HASH_READ_SIZE 8 typedef enum { ZSTDcs_created = 0, ZSTDcs_init, ZSTDcs_ongoing, ZSTDcs_ending } ZSTD_compressionStage_e; /*-************************************* * Helper functions ***************************************/ size_t ZSTD_compressBound(size_t srcSize) { return FSE_compressBound(srcSize) + 12; } /*-************************************* * Sequence storage ***************************************/ static void ZSTD_resetSeqStore(seqStore_t *ssPtr) { ssPtr->lit = ssPtr->litStart; ssPtr->sequences = ssPtr->sequencesStart; ssPtr->longLengthID = 0; } /*-************************************* * Context memory management ***************************************/ struct ZSTD_CCtx_s { const BYTE *nextSrc; /* next block here to continue on curr prefix */ const BYTE *base; /* All regular indexes relative to this position */ const BYTE *dictBase; /* extDict indexes relative to this position */ U32 dictLimit; /* below that point, need extDict */ U32 lowLimit; /* below that point, no more data */ U32 nextToUpdate; /* index from which to continue dictionary update */ U32 nextToUpdate3; /* index from which to continue dictionary update */ U32 hashLog3; /* dispatch table : larger == faster, more memory */ U32 loadedDictEnd; /* index of end of dictionary */ U32 forceWindow; /* force back-references to respect limit of 1<<wLog, even for dictionary */ U32 forceRawDict; /* Force loading dictionary in "content-only" mode (no header analysis) */ ZSTD_compressionStage_e stage; U32 rep[ZSTD_REP_NUM]; U32 repToConfirm[ZSTD_REP_NUM]; U32 dictID; ZSTD_parameters params; void *workSpace; size_t workSpaceSize; size_t blockSize; U64 frameContentSize; struct xxh64_state xxhState; ZSTD_customMem customMem; seqStore_t seqStore; /* sequences storage ptrs */ U32 *hashTable; U32 *hashTable3; U32 *chainTable; HUF_CElt *hufTable; U32 flagStaticTables; HUF_repeat flagStaticHufTable; FSE_CTable offcodeCTable[FSE_CTABLE_SIZE_U32(OffFSELog, MaxOff)]; FSE_CTable matchlengthCTable[FSE_CTABLE_SIZE_U32(MLFSELog, MaxML)]; FSE_CTable litlengthCTable[FSE_CTABLE_SIZE_U32(LLFSELog, MaxLL)]; unsigned tmpCounters[HUF_COMPRESS_WORKSPACE_SIZE_U32]; }; size_t ZSTD_CCtxWorkspaceBound(ZSTD_compressionParameters cParams) { size_t const blockSize = MIN(ZSTD_BLOCKSIZE_ABSOLUTEMAX, (size_t)1 << cParams.windowLog); U32 const divider = (cParams.searchLength == 3) ? 3 : 4; size_t const maxNbSeq = blockSize / divider; size_t const tokenSpace = blockSize + 11 * maxNbSeq; size_t const chainSize = (cParams.strategy == ZSTD_fast) ? 0 : (1 << cParams.chainLog); size_t const hSize = ((size_t)1) << cParams.hashLog; U32 const hashLog3 = (cParams.searchLength > 3) ? 0 : MIN(ZSTD_HASHLOG3_MAX, cParams.windowLog); size_t const h3Size = ((size_t)1) << hashLog3; size_t const tableSpace = (chainSize + hSize + h3Size) * sizeof(U32); size_t const optSpace = ((MaxML + 1) + (MaxLL + 1) + (MaxOff + 1) + (1 << Litbits)) * sizeof(U32) + (ZSTD_OPT_NUM + 1) * (sizeof(ZSTD_match_t) + sizeof(ZSTD_optimal_t)); size_t const workspaceSize = tableSpace + (256 * sizeof(U32)) /* huffTable */ + tokenSpace + (((cParams.strategy == ZSTD_btopt) || (cParams.strategy == ZSTD_btopt2)) ? optSpace : 0); return ZSTD_ALIGN(sizeof(ZSTD_stack)) + ZSTD_ALIGN(sizeof(ZSTD_CCtx)) + ZSTD_ALIGN(workspaceSize); } static ZSTD_CCtx *ZSTD_createCCtx_advanced(ZSTD_customMem customMem) { ZSTD_CCtx *cctx; if (!customMem.customAlloc || !customMem.customFree) return NULL; cctx = (ZSTD_CCtx *)ZSTD_malloc(sizeof(ZSTD_CCtx), customMem); if (!cctx) return NULL; memset(cctx, 0, sizeof(ZSTD_CCtx)); cctx->customMem = customMem; return cctx; } ZSTD_CCtx *ZSTD_initCCtx(void *workspace, size_t workspaceSize) { ZSTD_customMem const stackMem = ZSTD_initStack(workspace, workspaceSize); ZSTD_CCtx *cctx = ZSTD_createCCtx_advanced(stackMem); if (cctx) { cctx->workSpace = ZSTD_stackAllocAll(cctx->customMem.opaque, &cctx->workSpaceSize); } return cctx; } size_t ZSTD_freeCCtx(ZSTD_CCtx *cctx) { if (cctx == NULL) return 0; /* support free on NULL */ ZSTD_free(cctx->workSpace, cctx->customMem); ZSTD_free(cctx, cctx->customMem); return 0; /* reserved as a potential error code in the future */ } const seqStore_t *ZSTD_getSeqStore(const ZSTD_CCtx *ctx) /* hidden interface */ { return &(ctx->seqStore); } static ZSTD_parameters ZSTD_getParamsFromCCtx(const ZSTD_CCtx *cctx) { return cctx->params; } /** ZSTD_checkParams() : ensure param values remain within authorized range. @return : 0, or an error code if one value is beyond authorized range */ size_t ZSTD_checkCParams(ZSTD_compressionParameters cParams) { #define CLAMPCHECK(val, min, max) \ { \ if ((val < min) | (val > max)) \ return ERROR(compressionParameter_unsupported); \ } CLAMPCHECK(cParams.windowLog, ZSTD_WINDOWLOG_MIN, ZSTD_WINDOWLOG_MAX); CLAMPCHECK(cParams.chainLog, ZSTD_CHAINLOG_MIN, ZSTD_CHAINLOG_MAX); CLAMPCHECK(cParams.hashLog, ZSTD_HASHLOG_MIN, ZSTD_HASHLOG_MAX); CLAMPCHECK(cParams.searchLog, ZSTD_SEARCHLOG_MIN, ZSTD_SEARCHLOG_MAX); CLAMPCHECK(cParams.searchLength, ZSTD_SEARCHLENGTH_MIN, ZSTD_SEARCHLENGTH_MAX); CLAMPCHECK(cParams.targetLength, ZSTD_TARGETLENGTH_MIN, ZSTD_TARGETLENGTH_MAX); if ((U32)(cParams.strategy) > (U32)ZSTD_btopt2) return ERROR(compressionParameter_unsupported); return 0; } /** ZSTD_cycleLog() : * condition for correct operation : hashLog > 1 */ static U32 ZSTD_cycleLog(U32 hashLog, ZSTD_strategy strat) { U32 const btScale = ((U32)strat >= (U32)ZSTD_btlazy2); return hashLog - btScale; } /** ZSTD_adjustCParams() : optimize `cPar` for a given input (`srcSize` and `dictSize`). mostly downsizing to reduce memory consumption and initialization. Both `srcSize` and `dictSize` are optional (use 0 if unknown), but if both are 0, no optimization can be done. Note : cPar is considered validated at this stage. Use ZSTD_checkParams() to ensure that. */ ZSTD_compressionParameters ZSTD_adjustCParams(ZSTD_compressionParameters cPar, unsigned long long srcSize, size_t dictSize) { if (srcSize + dictSize == 0) return cPar; /* no size information available : no adjustment */ /* resize params, to use less memory when necessary */ { U32 const minSrcSize = (srcSize == 0) ? 500 : 0; U64 const rSize = srcSize + dictSize + minSrcSize; if (rSize < ((U64)1 << ZSTD_WINDOWLOG_MAX)) { U32 const srcLog = MAX(ZSTD_HASHLOG_MIN, ZSTD_highbit32((U32)(rSize)-1) + 1); if (cPar.windowLog > srcLog) cPar.windowLog = srcLog; } } if (cPar.hashLog > cPar.windowLog) cPar.hashLog = cPar.windowLog; { U32 const cycleLog = ZSTD_cycleLog(cPar.chainLog, cPar.strategy); if (cycleLog > cPar.windowLog) cPar.chainLog -= (cycleLog - cPar.windowLog); } if (cPar.windowLog < ZSTD_WINDOWLOG_ABSOLUTEMIN) cPar.windowLog = ZSTD_WINDOWLOG_ABSOLUTEMIN; /* required for frame header */ return cPar; } static U32 ZSTD_equivalentParams(ZSTD_parameters param1, ZSTD_parameters param2) { return (param1.cParams.hashLog == param2.cParams.hashLog) & (param1.cParams.chainLog == param2.cParams.chainLog) & (param1.cParams.strategy == param2.cParams.strategy) & ((param1.cParams.searchLength == 3) == (param2.cParams.searchLength == 3)); } /*! ZSTD_continueCCtx() : reuse CCtx without reset (note : requires no dictionary) */ static size_t ZSTD_continueCCtx(ZSTD_CCtx *cctx, ZSTD_parameters params, U64 frameContentSize) { U32 const end = (U32)(cctx->nextSrc - cctx->base); cctx->params = params; cctx->frameContentSize = frameContentSize; cctx->lowLimit = end; cctx->dictLimit = end; cctx->nextToUpdate = end + 1; cctx->stage = ZSTDcs_init; cctx->dictID = 0; cctx->loadedDictEnd = 0; { int i; for (i = 0; i < ZSTD_REP_NUM; i++) cctx->rep[i] = repStartValue[i]; } cctx->seqStore.litLengthSum = 0; /* force reset of btopt stats */ xxh64_reset(&cctx->xxhState, 0); return 0; } typedef enum { ZSTDcrp_continue, ZSTDcrp_noMemset, ZSTDcrp_fullReset } ZSTD_compResetPolicy_e; /*! ZSTD_resetCCtx_advanced() : note : `params` must be validated */ static size_t ZSTD_resetCCtx_advanced(ZSTD_CCtx *zc, ZSTD_parameters params, U64 frameContentSize, ZSTD_compResetPolicy_e const crp) { if (crp == ZSTDcrp_continue) if (ZSTD_equivalentParams(params, zc->params)) { zc->flagStaticTables = 0; zc->flagStaticHufTable = HUF_repeat_none; return ZSTD_continueCCtx(zc, params, frameContentSize); } { size_t const blockSize = MIN(ZSTD_BLOCKSIZE_ABSOLUTEMAX, (size_t)1 << params.cParams.windowLog); U32 const divider = (params.cParams.searchLength == 3) ? 3 : 4; size_t const maxNbSeq = blockSize / divider; size_t const tokenSpace = blockSize + 11 * maxNbSeq; size_t const chainSize = (params.cParams.strategy == ZSTD_fast) ? 0 : (1 << params.cParams.chainLog); size_t const hSize = ((size_t)1) << params.cParams.hashLog; U32 const hashLog3 = (params.cParams.searchLength > 3) ? 0 : MIN(ZSTD_HASHLOG3_MAX, params.cParams.windowLog); size_t const h3Size = ((size_t)1) << hashLog3; size_t const tableSpace = (chainSize + hSize + h3Size) * sizeof(U32); void *ptr; /* Check if workSpace is large enough, alloc a new one if needed */ { size_t const optSpace = ((MaxML + 1) + (MaxLL + 1) + (MaxOff + 1) + (1 << Litbits)) * sizeof(U32) + (ZSTD_OPT_NUM + 1) * (sizeof(ZSTD_match_t) + sizeof(ZSTD_optimal_t)); size_t const neededSpace = tableSpace + (256 * sizeof(U32)) /* huffTable */ + tokenSpace + (((params.cParams.strategy == ZSTD_btopt) || (params.cParams.strategy == ZSTD_btopt2)) ? optSpace : 0); if (zc->workSpaceSize < neededSpace) { ZSTD_free(zc->workSpace, zc->customMem); zc->workSpace = ZSTD_malloc(neededSpace, zc->customMem); if (zc->workSpace == NULL) return ERROR(memory_allocation); zc->workSpaceSize = neededSpace; } } if (crp != ZSTDcrp_noMemset) memset(zc->workSpace, 0, tableSpace); /* reset tables only */ xxh64_reset(&zc->xxhState, 0); zc->hashLog3 = hashLog3; zc->hashTable = (U32 *)(zc->workSpace); zc->chainTable = zc->hashTable + hSize; zc->hashTable3 = zc->chainTable + chainSize; ptr = zc->hashTable3 + h3Size; zc->hufTable = (HUF_CElt *)ptr; zc->flagStaticTables = 0; zc->flagStaticHufTable = HUF_repeat_none; ptr = ((U32 *)ptr) + 256; /* note : HUF_CElt* is incomplete type, size is simulated using U32 */ zc->nextToUpdate = 1; zc->nextSrc = NULL; zc->base = NULL; zc->dictBase = NULL; zc->dictLimit = 0; zc->lowLimit = 0; zc->params = params; zc->blockSize = blockSize; zc->frameContentSize = frameContentSize; { int i; for (i = 0; i < ZSTD_REP_NUM; i++) zc->rep[i] = repStartValue[i]; } if ((params.cParams.strategy == ZSTD_btopt) || (params.cParams.strategy == ZSTD_btopt2)) { zc->seqStore.litFreq = (U32 *)ptr; zc->seqStore.litLengthFreq = zc->seqStore.litFreq + (1 << Litbits); zc->seqStore.matchLengthFreq = zc->seqStore.litLengthFreq + (MaxLL + 1); zc->seqStore.offCodeFreq = zc->seqStore.matchLengthFreq + (MaxML + 1); ptr = zc->seqStore.offCodeFreq + (MaxOff + 1); zc->seqStore.matchTable = (ZSTD_match_t *)ptr; ptr = zc->seqStore.matchTable + ZSTD_OPT_NUM + 1; zc->seqStore.priceTable = (ZSTD_optimal_t *)ptr; ptr = zc->seqStore.priceTable + ZSTD_OPT_NUM + 1; zc->seqStore.litLengthSum = 0; } zc->seqStore.sequencesStart = (seqDef *)ptr; ptr = zc->seqStore.sequencesStart + maxNbSeq; zc->seqStore.llCode = (BYTE *)ptr; zc->seqStore.mlCode = zc->seqStore.llCode + maxNbSeq; zc->seqStore.ofCode = zc->seqStore.mlCode + maxNbSeq; zc->seqStore.litStart = zc->seqStore.ofCode + maxNbSeq; zc->stage = ZSTDcs_init; zc->dictID = 0; zc->loadedDictEnd = 0; return 0; } } /* ZSTD_invalidateRepCodes() : * ensures next compression will not use repcodes from previous block. * Note : only works with regular variant; * do not use with extDict variant ! */ void ZSTD_invalidateRepCodes(ZSTD_CCtx *cctx) { int i; for (i = 0; i < ZSTD_REP_NUM; i++) cctx->rep[i] = 0; } /*! ZSTD_copyCCtx() : * Duplicate an existing context `srcCCtx` into another one `dstCCtx`. * Only works during stage ZSTDcs_init (i.e. after creation, but before first call to ZSTD_compressContinue()). * @return : 0, or an error code */ size_t ZSTD_copyCCtx(ZSTD_CCtx *dstCCtx, const ZSTD_CCtx *srcCCtx, unsigned long long pledgedSrcSize) { if (srcCCtx->stage != ZSTDcs_init) return ERROR(stage_wrong); memcpy(&dstCCtx->customMem, &srcCCtx->customMem, sizeof(ZSTD_customMem)); { ZSTD_parameters params = srcCCtx->params; params.fParams.contentSizeFlag = (pledgedSrcSize > 0); ZSTD_resetCCtx_advanced(dstCCtx, params, pledgedSrcSize, ZSTDcrp_noMemset); } /* copy tables */ { size_t const chainSize = (srcCCtx->params.cParams.strategy == ZSTD_fast) ? 0 : (1 << srcCCtx->params.cParams.chainLog); size_t const hSize = ((size_t)1) << srcCCtx->params.cParams.hashLog; size_t const h3Size = (size_t)1 << srcCCtx->hashLog3; size_t const tableSpace = (chainSize + hSize + h3Size) * sizeof(U32); memcpy(dstCCtx->workSpace, srcCCtx->workSpace, tableSpace); } /* copy dictionary offsets */ dstCCtx->nextToUpdate = srcCCtx->nextToUpdate; dstCCtx->nextToUpdate3 = srcCCtx->nextToUpdate3; dstCCtx->nextSrc = srcCCtx->nextSrc; dstCCtx->base = srcCCtx->base; dstCCtx->dictBase = srcCCtx->dictBase; dstCCtx->dictLimit = srcCCtx->dictLimit; dstCCtx->lowLimit = srcCCtx->lowLimit; dstCCtx->loadedDictEnd = srcCCtx->loadedDictEnd; dstCCtx->dictID = srcCCtx->dictID; /* copy entropy tables */ dstCCtx->flagStaticTables = srcCCtx->flagStaticTables; dstCCtx->flagStaticHufTable = srcCCtx->flagStaticHufTable; if (srcCCtx->flagStaticTables) { memcpy(dstCCtx->litlengthCTable, srcCCtx->litlengthCTable, sizeof(dstCCtx->litlengthCTable)); memcpy(dstCCtx->matchlengthCTable, srcCCtx->matchlengthCTable, sizeof(dstCCtx->matchlengthCTable)); memcpy(dstCCtx->offcodeCTable, srcCCtx->offcodeCTable, sizeof(dstCCtx->offcodeCTable)); } if (srcCCtx->flagStaticHufTable) { memcpy(dstCCtx->hufTable, srcCCtx->hufTable, 256 * 4); } return 0; } /*! ZSTD_reduceTable() : * reduce table indexes by `reducerValue` */ static void ZSTD_reduceTable(U32 *const table, U32 const size, U32 const reducerValue) { U32 u; for (u = 0; u < size; u++) { if (table[u] < reducerValue) table[u] = 0; else table[u] -= reducerValue; } } /*! ZSTD_reduceIndex() : * rescale all indexes to avoid future overflow (indexes are U32) */ static void ZSTD_reduceIndex(ZSTD_CCtx *zc, const U32 reducerValue) { { U32 const hSize = 1 << zc->params.cParams.hashLog; ZSTD_reduceTable(zc->hashTable, hSize, reducerValue); } { U32 const chainSize = (zc->params.cParams.strategy == ZSTD_fast) ? 0 : (1 << zc->params.cParams.chainLog); ZSTD_reduceTable(zc->chainTable, chainSize, reducerValue); } { U32 const h3Size = (zc->hashLog3) ? 1 << zc->hashLog3 : 0; ZSTD_reduceTable(zc->hashTable3, h3Size, reducerValue); } } /*-******************************************************* * Block entropic compression *********************************************************/ /* See doc/zstd_compression_format.md for detailed format description */ size_t ZSTD_noCompressBlock(void *dst, size_t dstCapacity, const void *src, size_t srcSize) { if (srcSize + ZSTD_blockHeaderSize > dstCapacity) return ERROR(dstSize_tooSmall); memcpy((BYTE *)dst + ZSTD_blockHeaderSize, src, srcSize); ZSTD_writeLE24(dst, (U32)(srcSize << 2) + (U32)bt_raw); return ZSTD_blockHeaderSize + srcSize; } static size_t ZSTD_noCompressLiterals(void *dst, size_t dstCapacity, const void *src, size_t srcSize) { BYTE *const ostart = (BYTE * const)dst; U32 const flSize = 1 + (srcSize > 31) + (srcSize > 4095); if (srcSize + flSize > dstCapacity) return ERROR(dstSize_tooSmall); switch (flSize) { case 1: /* 2 - 1 - 5 */ ostart[0] = (BYTE)((U32)set_basic + (srcSize << 3)); break; case 2: /* 2 - 2 - 12 */ ZSTD_writeLE16(ostart, (U16)((U32)set_basic + (1 << 2) + (srcSize << 4))); break; default: /*note : should not be necessary : flSize is within {1,2,3} */ case 3: /* 2 - 2 - 20 */ ZSTD_writeLE32(ostart, (U32)((U32)set_basic + (3 << 2) + (srcSize << 4))); break; } memcpy(ostart + flSize, src, srcSize); return srcSize + flSize; } static size_t ZSTD_compressRleLiteralsBlock(void *dst, size_t dstCapacity, const void *src, size_t srcSize) { BYTE *const ostart = (BYTE * const)dst; U32 const flSize = 1 + (srcSize > 31) + (srcSize > 4095); (void)dstCapacity; /* dstCapacity already guaranteed to be >=4, hence large enough */ switch (flSize) { case 1: /* 2 - 1 - 5 */ ostart[0] = (BYTE)((U32)set_rle + (srcSize << 3)); break; case 2: /* 2 - 2 - 12 */ ZSTD_writeLE16(ostart, (U16)((U32)set_rle + (1 << 2) + (srcSize << 4))); break; default: /*note : should not be necessary : flSize is necessarily within {1,2,3} */ case 3: /* 2 - 2 - 20 */ ZSTD_writeLE32(ostart, (U32)((U32)set_rle + (3 << 2) + (srcSize << 4))); break; } ostart[flSize] = *(const BYTE *)src; return flSize + 1; } static size_t ZSTD_minGain(size_t srcSize) { return (srcSize >> 6) + 2; } static size_t ZSTD_compressLiterals(ZSTD_CCtx *zc, void *dst, size_t dstCapacity, const void *src, size_t srcSize) { size_t const minGain = ZSTD_minGain(srcSize); size_t const lhSize = 3 + (srcSize >= 1 KB) + (srcSize >= 16 KB); BYTE *const ostart = (BYTE *)dst; U32 singleStream = srcSize < 256; symbolEncodingType_e hType = set_compressed; size_t cLitSize; /* small ? don't even attempt compression (speed opt) */ #define LITERAL_NOENTROPY 63 { size_t const minLitSize = zc->flagStaticHufTable == HUF_repeat_valid ? 6 : LITERAL_NOENTROPY; if (srcSize <= minLitSize) return ZSTD_noCompressLiterals(dst, dstCapacity, src, srcSize); } if (dstCapacity < lhSize + 1) return ERROR(dstSize_tooSmall); /* not enough space for compression */ { HUF_repeat repeat = zc->flagStaticHufTable; int const preferRepeat = zc->params.cParams.strategy < ZSTD_lazy ? srcSize <= 1024 : 0; if (repeat == HUF_repeat_valid && lhSize == 3) singleStream = 1; cLitSize = singleStream ? HUF_compress1X_repeat(ostart + lhSize, dstCapacity - lhSize, src, srcSize, 255, 11, zc->tmpCounters, sizeof(zc->tmpCounters), zc->hufTable, &repeat, preferRepeat) : HUF_compress4X_repeat(ostart + lhSize, dstCapacity - lhSize, src, srcSize, 255, 11, zc->tmpCounters, sizeof(zc->tmpCounters), zc->hufTable, &repeat, preferRepeat); if (repeat != HUF_repeat_none) { hType = set_repeat; } /* reused the existing table */ else { zc->flagStaticHufTable = HUF_repeat_check; } /* now have a table to reuse */ } if ((cLitSize == 0) | (cLitSize >= srcSize - minGain)) { zc->flagStaticHufTable = HUF_repeat_none; return ZSTD_noCompressLiterals(dst, dstCapacity, src, srcSize); } if (cLitSize == 1) { zc->flagStaticHufTable = HUF_repeat_none; return ZSTD_compressRleLiteralsBlock(dst, dstCapacity, src, srcSize); } /* Build header */ switch (lhSize) { case 3: /* 2 - 2 - 10 - 10 */ { U32 const lhc = hType + ((!singleStream) << 2) + ((U32)srcSize << 4) + ((U32)cLitSize << 14); ZSTD_writeLE24(ostart, lhc); break; } case 4: /* 2 - 2 - 14 - 14 */ { U32 const lhc = hType + (2 << 2) + ((U32)srcSize << 4) + ((U32)cLitSize << 18); ZSTD_writeLE32(ostart, lhc); break; } default: /* should not be necessary, lhSize is only {3,4,5} */ case 5: /* 2 - 2 - 18 - 18 */ { U32 const lhc = hType + (3 << 2) + ((U32)srcSize << 4) + ((U32)cLitSize << 22); ZSTD_writeLE32(ostart, lhc); ostart[4] = (BYTE)(cLitSize >> 10); break; } } return lhSize + cLitSize; } static const BYTE LL_Code[64] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24}; static const BYTE ML_Code[128] = {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, 32, 32, 33, 33, 34, 34, 35, 35, 36, 36, 36, 36, 37, 37, 37, 37, 38, 38, 38, 38, 38, 38, 38, 38, 39, 39, 39, 39, 39, 39, 39, 39, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42}; void ZSTD_seqToCodes(const seqStore_t *seqStorePtr) { BYTE const LL_deltaCode = 19; BYTE const ML_deltaCode = 36; const seqDef *const sequences = seqStorePtr->sequencesStart; BYTE *const llCodeTable = seqStorePtr->llCode; BYTE *const ofCodeTable = seqStorePtr->ofCode; BYTE *const mlCodeTable = seqStorePtr->mlCode; U32 const nbSeq = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart); U32 u; for (u = 0; u < nbSeq; u++) { U32 const llv = sequences[u].litLength; U32 const mlv = sequences[u].matchLength; llCodeTable[u] = (llv > 63) ? (BYTE)ZSTD_highbit32(llv) + LL_deltaCode : LL_Code[llv]; ofCodeTable[u] = (BYTE)ZSTD_highbit32(sequences[u].offset); mlCodeTable[u] = (mlv > 127) ? (BYTE)ZSTD_highbit32(mlv) + ML_deltaCode : ML_Code[mlv]; } if (seqStorePtr->longLengthID == 1) llCodeTable[seqStorePtr->longLengthPos] = MaxLL; if (seqStorePtr->longLengthID == 2) mlCodeTable[seqStorePtr->longLengthPos] = MaxML; } ZSTD_STATIC size_t ZSTD_compressSequences_internal(ZSTD_CCtx *zc, void *dst, size_t dstCapacity) { const int longOffsets = zc->params.cParams.windowLog > STREAM_ACCUMULATOR_MIN; const seqStore_t *seqStorePtr = &(zc->seqStore); FSE_CTable *CTable_LitLength = zc->litlengthCTable; FSE_CTable *CTable_OffsetBits = zc->offcodeCTable; FSE_CTable *CTable_MatchLength = zc->matchlengthCTable; U32 LLtype, Offtype, MLtype; /* compressed, raw or rle */ const seqDef *const sequences = seqStorePtr->sequencesStart; const BYTE *const ofCodeTable = seqStorePtr->ofCode; const BYTE *const llCodeTable = seqStorePtr->llCode; const BYTE *const mlCodeTable = seqStorePtr->mlCode; BYTE *const ostart = (BYTE *)dst; BYTE *const oend = ostart + dstCapacity; BYTE *op = ostart; size_t const nbSeq = seqStorePtr->sequences - seqStorePtr->sequencesStart; BYTE *seqHead; U32 *count; S16 *norm; U32 *workspace; size_t workspaceSize = sizeof(zc->tmpCounters); { size_t spaceUsed32 = 0; count = (U32 *)zc->tmpCounters + spaceUsed32; spaceUsed32 += MaxSeq + 1; norm = (S16 *)((U32 *)zc->tmpCounters + spaceUsed32); spaceUsed32 += ALIGN(sizeof(S16) * (MaxSeq + 1), sizeof(U32)) >> 2; workspace = (U32 *)zc->tmpCounters + spaceUsed32; workspaceSize -= (spaceUsed32 << 2); } /* Compress literals */ { const BYTE *const literals = seqStorePtr->litStart; size_t const litSize = seqStorePtr->lit - literals; size_t const cSize = ZSTD_compressLiterals(zc, op, dstCapacity, literals, litSize); if (ZSTD_isError(cSize)) return cSize; op += cSize; } /* Sequences Header */ if ((oend - op) < 3 /*max nbSeq Size*/ + 1 /*seqHead */) return ERROR(dstSize_tooSmall); if (nbSeq < 0x7F) *op++ = (BYTE)nbSeq; else if (nbSeq < LONGNBSEQ) op[0] = (BYTE)((nbSeq >> 8) + 0x80), op[1] = (BYTE)nbSeq, op += 2; else op[0] = 0xFF, ZSTD_writeLE16(op + 1, (U16)(nbSeq - LONGNBSEQ)), op += 3; if (nbSeq == 0) return op - ostart; /* seqHead : flags for FSE encoding type */ seqHead = op++; #define MIN_SEQ_FOR_DYNAMIC_FSE 64 #define MAX_SEQ_FOR_STATIC_FSE 1000 /* convert length/distances into codes */ ZSTD_seqToCodes(seqStorePtr); /* CTable for Literal Lengths */ { U32 max = MaxLL; size_t const mostFrequent = FSE_countFast_wksp(count, &max, llCodeTable, nbSeq, workspace); if ((mostFrequent == nbSeq) && (nbSeq > 2)) { *op++ = llCodeTable[0]; FSE_buildCTable_rle(CTable_LitLength, (BYTE)max); LLtype = set_rle; } else if ((zc->flagStaticTables) && (nbSeq < MAX_SEQ_FOR_STATIC_FSE)) { LLtype = set_repeat; } else if ((nbSeq < MIN_SEQ_FOR_DYNAMIC_FSE) || (mostFrequent < (nbSeq >> (LL_defaultNormLog - 1)))) { FSE_buildCTable_wksp(CTable_LitLength, LL_defaultNorm, MaxLL, LL_defaultNormLog, workspace, workspaceSize); LLtype = set_basic; } else { size_t nbSeq_1 = nbSeq; const U32 tableLog = FSE_optimalTableLog(LLFSELog, nbSeq, max); if (count[llCodeTable[nbSeq - 1]] > 1) { count[llCodeTable[nbSeq - 1]]--; nbSeq_1--; } FSE_normalizeCount(norm, tableLog, count, nbSeq_1, max); { size_t const NCountSize = FSE_writeNCount(op, oend - op, norm, max, tableLog); /* overflow protected */ if (FSE_isError(NCountSize)) return NCountSize; op += NCountSize; } FSE_buildCTable_wksp(CTable_LitLength, norm, max, tableLog, workspace, workspaceSize); LLtype = set_compressed; } } /* CTable for Offsets */ { U32 max = MaxOff; size_t const mostFrequent = FSE_countFast_wksp(count, &max, ofCodeTable, nbSeq, workspace); if ((mostFrequent == nbSeq) && (nbSeq > 2)) { *op++ = ofCodeTable[0]; FSE_buildCTable_rle(CTable_OffsetBits, (BYTE)max); Offtype = set_rle; } else if ((zc->flagStaticTables) && (nbSeq < MAX_SEQ_FOR_STATIC_FSE)) { Offtype = set_repeat; } else if ((nbSeq < MIN_SEQ_FOR_DYNAMIC_FSE) || (mostFrequent < (nbSeq >> (OF_defaultNormLog - 1)))) { FSE_buildCTable_wksp(CTable_OffsetBits, OF_defaultNorm, MaxOff, OF_defaultNormLog, workspace, workspaceSize); Offtype = set_basic; } else { size_t nbSeq_1 = nbSeq; const U32 tableLog = FSE_optimalTableLog(OffFSELog, nbSeq, max); if (count[ofCodeTable[nbSeq - 1]] > 1) { count[ofCodeTable[nbSeq - 1]]--; nbSeq_1--; } FSE_normalizeCount(norm, tableLog, count, nbSeq_1, max); { size_t const NCountSize = FSE_writeNCount(op, oend - op, norm, max, tableLog); /* overflow protected */ if (FSE_isError(NCountSize)) return NCountSize; op += NCountSize; } FSE_buildCTable_wksp(CTable_OffsetBits, norm, max, tableLog, workspace, workspaceSize); Offtype = set_compressed; } } /* CTable for MatchLengths */ { U32 max = MaxML; size_t const mostFrequent = FSE_countFast_wksp(count, &max, mlCodeTable, nbSeq, workspace); if ((mostFrequent == nbSeq) && (nbSeq > 2)) { *op++ = *mlCodeTable; FSE_buildCTable_rle(CTable_MatchLength, (BYTE)max); MLtype = set_rle; } else if ((zc->flagStaticTables) && (nbSeq < MAX_SEQ_FOR_STATIC_FSE)) { MLtype = set_repeat; } else if ((nbSeq < MIN_SEQ_FOR_DYNAMIC_FSE) || (mostFrequent < (nbSeq >> (ML_defaultNormLog - 1)))) { FSE_buildCTable_wksp(CTable_MatchLength, ML_defaultNorm, MaxML, ML_defaultNormLog, workspace, workspaceSize); MLtype = set_basic; } else { size_t nbSeq_1 = nbSeq; const U32 tableLog = FSE_optimalTableLog(MLFSELog, nbSeq, max); if (count[mlCodeTable[nbSeq - 1]] > 1) { count[mlCodeTable[nbSeq - 1]]--; nbSeq_1--; } FSE_normalizeCount(norm, tableLog, count, nbSeq_1, max); { size_t const NCountSize = FSE_writeNCount(op, oend - op, norm, max, tableLog); /* overflow protected */ if (FSE_isError(NCountSize)) return NCountSize; op += NCountSize; } FSE_buildCTable_wksp(CTable_MatchLength, norm, max, tableLog, workspace, workspaceSize); MLtype = set_compressed; } } *seqHead = (BYTE)((LLtype << 6) + (Offtype << 4) + (MLtype << 2)); zc->flagStaticTables = 0; /* Encoding Sequences */ { BIT_CStream_t blockStream; FSE_CState_t stateMatchLength; FSE_CState_t stateOffsetBits; FSE_CState_t stateLitLength; CHECK_E(BIT_initCStream(&blockStream, op, oend - op), dstSize_tooSmall); /* not enough space remaining */ /* first symbols */ FSE_initCState2(&stateMatchLength, CTable_MatchLength, mlCodeTable[nbSeq - 1]); FSE_initCState2(&stateOffsetBits, CTable_OffsetBits, ofCodeTable[nbSeq - 1]); FSE_initCState2(&stateLitLength, CTable_LitLength, llCodeTable[nbSeq - 1]); BIT_addBits(&blockStream, sequences[nbSeq - 1].litLength, LL_bits[llCodeTable[nbSeq - 1]]); if (ZSTD_32bits()) BIT_flushBits(&blockStream); BIT_addBits(&blockStream, sequences[nbSeq - 1].matchLength, ML_bits[mlCodeTable[nbSeq - 1]]); if (ZSTD_32bits()) BIT_flushBits(&blockStream); if (longOffsets) { U32 const ofBits = ofCodeTable[nbSeq - 1]; int const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN - 1); if (extraBits) { BIT_addBits(&blockStream, sequences[nbSeq - 1].offset, extraBits); BIT_flushBits(&blockStream); } BIT_addBits(&blockStream, sequences[nbSeq - 1].offset >> extraBits, ofBits - extraBits); } else { BIT_addBits(&blockStream, sequences[nbSeq - 1].offset, ofCodeTable[nbSeq - 1]); } BIT_flushBits(&blockStream); { size_t n; for (n = nbSeq - 2; n < nbSeq; n--) { /* intentional underflow */ BYTE const llCode = llCodeTable[n]; BYTE const ofCode = ofCodeTable[n]; BYTE const mlCode = mlCodeTable[n]; U32 const llBits = LL_bits[llCode]; U32 const ofBits = ofCode; /* 32b*/ /* 64b*/ U32 const mlBits = ML_bits[mlCode]; /* (7)*/ /* (7)*/ FSE_encodeSymbol(&blockStream, &stateOffsetBits, ofCode); /* 15 */ /* 15 */ FSE_encodeSymbol(&blockStream, &stateMatchLength, mlCode); /* 24 */ /* 24 */ if (ZSTD_32bits()) BIT_flushBits(&blockStream); /* (7)*/ FSE_encodeSymbol(&blockStream, &stateLitLength, llCode); /* 16 */ /* 33 */ if (ZSTD_32bits() || (ofBits + mlBits + llBits >= 64 - 7 - (LLFSELog + MLFSELog + OffFSELog))) BIT_flushBits(&blockStream); /* (7)*/ BIT_addBits(&blockStream, sequences[n].litLength, llBits); if (ZSTD_32bits() && ((llBits + mlBits) > 24)) BIT_flushBits(&blockStream); BIT_addBits(&blockStream, sequences[n].matchLength, mlBits); if (ZSTD_32bits()) BIT_flushBits(&blockStream); /* (7)*/ if (longOffsets) { int const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN - 1); if (extraBits) { BIT_addBits(&blockStream, sequences[n].offset, extraBits); BIT_flushBits(&blockStream); /* (7)*/ } BIT_addBits(&blockStream, sequences[n].offset >> extraBits, ofBits - extraBits); /* 31 */ } else { BIT_addBits(&blockStream, sequences[n].offset, ofBits); /* 31 */ } BIT_flushBits(&blockStream); /* (7)*/ } } FSE_flushCState(&blockStream, &stateMatchLength); FSE_flushCState(&blockStream, &stateOffsetBits); FSE_flushCState(&blockStream, &stateLitLength); { size_t const streamSize = BIT_closeCStream(&blockStream); if (streamSize == 0) return ERROR(dstSize_tooSmall); /* not enough space */ op += streamSize; } } return op - ostart; } ZSTD_STATIC size_t ZSTD_compressSequences(ZSTD_CCtx *zc, void *dst, size_t dstCapacity, size_t srcSize) { size_t const cSize = ZSTD_compressSequences_internal(zc, dst, dstCapacity); size_t const minGain = ZSTD_minGain(srcSize); size_t const maxCSize = srcSize - minGain; /* If the srcSize <= dstCapacity, then there is enough space to write a * raw uncompressed block. Since we ran out of space, the block must not * be compressible, so fall back to a raw uncompressed block. */ int const uncompressibleError = cSize == ERROR(dstSize_tooSmall) && srcSize <= dstCapacity; int i; if (ZSTD_isError(cSize) && !uncompressibleError) return cSize; if (cSize >= maxCSize || uncompressibleError) { zc->flagStaticHufTable = HUF_repeat_none; return 0; } /* confirm repcodes */ for (i = 0; i < ZSTD_REP_NUM; i++) zc->rep[i] = zc->repToConfirm[i]; return cSize; } /*! ZSTD_storeSeq() : Store a sequence (literal length, literals, offset code and match length code) into seqStore_t. `offsetCode` : distance to match, or 0 == repCode. `matchCode` : matchLength - MINMATCH */ ZSTD_STATIC void ZSTD_storeSeq(seqStore_t *seqStorePtr, size_t litLength, const void *literals, U32 offsetCode, size_t matchCode) { /* copy Literals */ ZSTD_wildcopy(seqStorePtr->lit, literals, litLength); seqStorePtr->lit += litLength; /* literal Length */ if (litLength > 0xFFFF) { seqStorePtr->longLengthID = 1; seqStorePtr->longLengthPos = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart); } seqStorePtr->sequences[0].litLength = (U16)litLength; /* match offset */ seqStorePtr->sequences[0].offset = offsetCode + 1; /* match Length */ if (matchCode > 0xFFFF) { seqStorePtr->longLengthID = 2; seqStorePtr->longLengthPos = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart); } seqStorePtr->sequences[0].matchLength = (U16)matchCode; seqStorePtr->sequences++; } /*-************************************* * Match length counter ***************************************/ static unsigned ZSTD_NbCommonBytes(register size_t val) { if (ZSTD_isLittleEndian()) { if (ZSTD_64bits()) { return (__builtin_ctzll((U64)val) >> 3); } else { /* 32 bits */ return (__builtin_ctz((U32)val) >> 3); } } else { /* Big Endian CPU */ if (ZSTD_64bits()) { return (__builtin_clzll(val) >> 3); } else { /* 32 bits */ return (__builtin_clz((U32)val) >> 3); } } } static size_t ZSTD_count(const BYTE *pIn, const BYTE *pMatch, const BYTE *const pInLimit) { const BYTE *const pStart = pIn; const BYTE *const pInLoopLimit = pInLimit - (sizeof(size_t) - 1); while (pIn < pInLoopLimit) { size_t const diff = ZSTD_readST(pMatch) ^ ZSTD_readST(pIn); if (!diff) { pIn += sizeof(size_t); pMatch += sizeof(size_t); continue; } pIn += ZSTD_NbCommonBytes(diff); return (size_t)(pIn - pStart); } if (ZSTD_64bits()) if ((pIn < (pInLimit - 3)) && (ZSTD_read32(pMatch) == ZSTD_read32(pIn))) { pIn += 4; pMatch += 4; } if ((pIn < (pInLimit - 1)) && (ZSTD_read16(pMatch) == ZSTD_read16(pIn))) { pIn += 2; pMatch += 2; } if ((pIn < pInLimit) && (*pMatch == *pIn)) pIn++; return (size_t)(pIn - pStart); } /** ZSTD_count_2segments() : * can count match length with `ip` & `match` in 2 different segments. * convention : on reaching mEnd, match count continue starting from iStart */ static size_t ZSTD_count_2segments(const BYTE *ip, const BYTE *match, const BYTE *iEnd, const BYTE *mEnd, const BYTE *iStart) { const BYTE *const vEnd = MIN(ip + (mEnd - match), iEnd); size_t const matchLength = ZSTD_count(ip, match, vEnd); if (match + matchLength != mEnd) return matchLength; return matchLength + ZSTD_count(ip + matchLength, iStart, iEnd); } /*-************************************* * Hashes ***************************************/ static const U32 prime3bytes = 506832829U; static U32 ZSTD_hash3(U32 u, U32 h) { return ((u << (32 - 24)) * prime3bytes) >> (32 - h); } ZSTD_STATIC size_t ZSTD_hash3Ptr(const void *ptr, U32 h) { return ZSTD_hash3(ZSTD_readLE32(ptr), h); } /* only in zstd_opt.h */ static const U32 prime4bytes = 2654435761U; static U32 ZSTD_hash4(U32 u, U32 h) { return (u * prime4bytes) >> (32 - h); } static size_t ZSTD_hash4Ptr(const void *ptr, U32 h) { return ZSTD_hash4(ZSTD_read32(ptr), h); } static const U64 prime5bytes = 889523592379ULL; static size_t ZSTD_hash5(U64 u, U32 h) { return (size_t)(((u << (64 - 40)) * prime5bytes) >> (64 - h)); } static size_t ZSTD_hash5Ptr(const void *p, U32 h) { return ZSTD_hash5(ZSTD_readLE64(p), h); } static const U64 prime6bytes = 227718039650203ULL; static size_t ZSTD_hash6(U64 u, U32 h) { return (size_t)(((u << (64 - 48)) * prime6bytes) >> (64 - h)); } static size_t ZSTD_hash6Ptr(const void *p, U32 h) { return ZSTD_hash6(ZSTD_readLE64(p), h); } static const U64 prime7bytes = 58295818150454627ULL; static size_t ZSTD_hash7(U64 u, U32 h) { return (size_t)(((u << (64 - 56)) * prime7bytes) >> (64 - h)); } static size_t ZSTD_hash7Ptr(const void *p, U32 h) { return ZSTD_hash7(ZSTD_readLE64(p), h); } static const U64 prime8bytes = 0xCF1BBCDCB7A56463ULL; static size_t ZSTD_hash8(U64 u, U32 h) { return (size_t)(((u)*prime8bytes) >> (64 - h)); } static size_t ZSTD_hash8Ptr(const void *p, U32 h) { return ZSTD_hash8(ZSTD_readLE64(p), h); } static size_t ZSTD_hashPtr(const void *p, U32 hBits, U32 mls) { switch (mls) { // case 3: return ZSTD_hash3Ptr(p, hBits); default: case 4: return ZSTD_hash4Ptr(p, hBits); case 5: return ZSTD_hash5Ptr(p, hBits); case 6: return ZSTD_hash6Ptr(p, hBits); case 7: return ZSTD_hash7Ptr(p, hBits); case 8: return ZSTD_hash8Ptr(p, hBits); } } /*-************************************* * Fast Scan ***************************************/ static void ZSTD_fillHashTable(ZSTD_CCtx *zc, const void *end, const U32 mls) { U32 *const hashTable = zc->hashTable; U32 const hBits = zc->params.cParams.hashLog; const BYTE *const base = zc->base; const BYTE *ip = base + zc->nextToUpdate; const BYTE *const iend = ((const BYTE *)end) - HASH_READ_SIZE; const size_t fastHashFillStep = 3; while (ip <= iend) { hashTable[ZSTD_hashPtr(ip, hBits, mls)] = (U32)(ip - base); ip += fastHashFillStep; } } FORCE_INLINE void ZSTD_compressBlock_fast_generic(ZSTD_CCtx *cctx, const void *src, size_t srcSize, const U32 mls) { U32 *const hashTable = cctx->hashTable; U32 const hBits = cctx->params.cParams.hashLog; seqStore_t *seqStorePtr = &(cctx->seqStore); const BYTE *const base = cctx->base; const BYTE *const istart = (const BYTE *)src; const BYTE *ip = istart; const BYTE *anchor = istart; const U32 lowestIndex = cctx->dictLimit; const BYTE *const lowest = base + lowestIndex; const BYTE *const iend = istart + srcSize; const BYTE *const ilimit = iend - HASH_READ_SIZE; U32 offset_1 = cctx->rep[0], offset_2 = cctx->rep[1]; U32 offsetSaved = 0; /* init */ ip += (ip == lowest); { U32 const maxRep = (U32)(ip - lowest); if (offset_2 > maxRep) offsetSaved = offset_2, offset_2 = 0; if (offset_1 > maxRep) offsetSaved = offset_1, offset_1 = 0; } /* Main Search Loop */ while (ip < ilimit) { /* < instead of <=, because repcode check at (ip+1) */ size_t mLength; size_t const h = ZSTD_hashPtr(ip, hBits, mls); U32 const curr = (U32)(ip - base); U32 const matchIndex = hashTable[h]; const BYTE *match = base + matchIndex; hashTable[h] = curr; /* update hash table */ if ((offset_1 > 0) & (ZSTD_read32(ip + 1 - offset_1) == ZSTD_read32(ip + 1))) { mLength = ZSTD_count(ip + 1 + 4, ip + 1 + 4 - offset_1, iend) + 4; ip++; ZSTD_storeSeq(seqStorePtr, ip - anchor, anchor, 0, mLength - MINMATCH); } else { U32 offset; if ((matchIndex <= lowestIndex) || (ZSTD_read32(match) != ZSTD_read32(ip))) { ip += ((ip - anchor) >> g_searchStrength) + 1; continue; } mLength = ZSTD_count(ip + 4, match + 4, iend) + 4; offset = (U32)(ip - match); while (((ip > anchor) & (match > lowest)) && (ip[-1] == match[-1])) { ip--; match--; mLength++; } /* catch up */ offset_2 = offset_1; offset_1 = offset; ZSTD_storeSeq(seqStorePtr, ip - anchor, anchor, offset + ZSTD_REP_MOVE, mLength - MINMATCH); } /* match found */ ip += mLength; anchor = ip; if (ip <= ilimit) { /* Fill Table */ hashTable[ZSTD_hashPtr(base + curr + 2, hBits, mls)] = curr + 2; /* here because curr+2 could be > iend-8 */ hashTable[ZSTD_hashPtr(ip - 2, hBits, mls)] = (U32)(ip - 2 - base); /* check immediate repcode */ while ((ip <= ilimit) && ((offset_2 > 0) & (ZSTD_read32(ip) == ZSTD_read32(ip - offset_2)))) { /* store sequence */ size_t const rLength = ZSTD_count(ip + 4, ip + 4 - offset_2, iend) + 4; { U32 const tmpOff = offset_2; offset_2 = offset_1; offset_1 = tmpOff; } /* swap offset_2 <=> offset_1 */ hashTable[ZSTD_hashPtr(ip, hBits, mls)] = (U32)(ip - base); ZSTD_storeSeq(seqStorePtr, 0, anchor, 0, rLength - MINMATCH); ip += rLength; anchor = ip; continue; /* faster when present ... (?) */ } } } /* save reps for next block */ cctx->repToConfirm[0] = offset_1 ? offset_1 : offsetSaved; cctx->repToConfirm[1] = offset_2 ? offset_2 : offsetSaved; /* Last Literals */ { size_t const lastLLSize = iend - anchor; memcpy(seqStorePtr->lit, anchor, lastLLSize); seqStorePtr->lit += lastLLSize; } } static void ZSTD_compressBlock_fast(ZSTD_CCtx *ctx, const void *src, size_t srcSize) { const U32 mls = ctx->params.cParams.searchLength; switch (mls) { default: /* includes case 3 */ case 4: ZSTD_compressBlock_fast_generic(ctx, src, srcSize, 4); return; case 5: ZSTD_compressBlock_fast_generic(ctx, src, srcSize, 5); return; case 6: ZSTD_compressBlock_fast_generic(ctx, src, srcSize, 6); return; case 7: ZSTD_compressBlock_fast_generic(ctx, src, srcSize, 7); return; } } static void ZSTD_compressBlock_fast_extDict_generic(ZSTD_CCtx *ctx, const void *src, size_t srcSize, const U32 mls) { U32 *hashTable = ctx->hashTable; const U32 hBits = ctx->params.cParams.hashLog; seqStore_t *seqStorePtr = &(ctx->seqStore); const BYTE *const base = ctx->base; const BYTE *const dictBase = ctx->dictBase; const BYTE *const istart = (const BYTE *)src; const BYTE *ip = istart; const BYTE *anchor = istart; const U32 lowestIndex = ctx->lowLimit; const BYTE *const dictStart = dictBase + lowestIndex; const U32 dictLimit = ctx->dictLimit; const BYTE *const lowPrefixPtr = base + dictLimit; const BYTE *const dictEnd = dictBase + dictLimit; const BYTE *const iend = istart + srcSize; const BYTE *const ilimit = iend - 8; U32 offset_1 = ctx->rep[0], offset_2 = ctx->rep[1]; /* Search Loop */ while (ip < ilimit) { /* < instead of <=, because (ip+1) */ const size_t h = ZSTD_hashPtr(ip, hBits, mls); const U32 matchIndex = hashTable[h]; const BYTE *matchBase = matchIndex < dictLimit ? dictBase : base; const BYTE *match = matchBase + matchIndex; const U32 curr = (U32)(ip - base); const U32 repIndex = curr + 1 - offset_1; /* offset_1 expected <= curr +1 */ const BYTE *repBase = repIndex < dictLimit ? dictBase : base; const BYTE *repMatch = repBase + repIndex; size_t mLength; hashTable[h] = curr; /* update hash table */ if ((((U32)((dictLimit - 1) - repIndex) >= 3) /* intentional underflow */ & (repIndex > lowestIndex)) && (ZSTD_read32(repMatch) == ZSTD_read32(ip + 1))) { const BYTE *repMatchEnd = repIndex < dictLimit ? dictEnd : iend; mLength = ZSTD_count_2segments(ip + 1 + EQUAL_READ32, repMatch + EQUAL_READ32, iend, repMatchEnd, lowPrefixPtr) + EQUAL_READ32; ip++; ZSTD_storeSeq(seqStorePtr, ip - anchor, anchor, 0, mLength - MINMATCH); } else { if ((matchIndex < lowestIndex) || (ZSTD_read32(match) != ZSTD_read32(ip))) { ip += ((ip - anchor) >> g_searchStrength) + 1; continue; } { const BYTE *matchEnd = matchIndex < dictLimit ? dictEnd : iend; const BYTE *lowMatchPtr = matchIndex < dictLimit ? dictStart : lowPrefixPtr; U32 offset; mLength = ZSTD_count_2segments(ip + EQUAL_READ32, match + EQUAL_READ32, iend, matchEnd, lowPrefixPtr) + EQUAL_READ32; while (((ip > anchor) & (match > lowMatchPtr)) && (ip[-1] == match[-1])) { ip--; match--; mLength++; } /* catch up */ offset = curr - matchIndex; offset_2 = offset_1; offset_1 = offset; ZSTD_storeSeq(seqStorePtr, ip - anchor, anchor, offset + ZSTD_REP_MOVE, mLength - MINMATCH); } } /* found a match : store it */ ip += mLength; anchor = ip; if (ip <= ilimit) { /* Fill Table */ hashTable[ZSTD_hashPtr(base + curr + 2, hBits, mls)] = curr + 2; hashTable[ZSTD_hashPtr(ip - 2, hBits, mls)] = (U32)(ip - 2 - base); /* check immediate repcode */ while (ip <= ilimit) { U32 const curr2 = (U32)(ip - base); U32 const repIndex2 = curr2 - offset_2; const BYTE *repMatch2 = repIndex2 < dictLimit ? dictBase + repIndex2 : base + repIndex2; if ((((U32)((dictLimit - 1) - repIndex2) >= 3) & (repIndex2 > lowestIndex)) /* intentional overflow */ && (ZSTD_read32(repMatch2) == ZSTD_read32(ip))) { const BYTE *const repEnd2 = repIndex2 < dictLimit ? dictEnd : iend; size_t repLength2 = ZSTD_count_2segments(ip + EQUAL_READ32, repMatch2 + EQUAL_READ32, iend, repEnd2, lowPrefixPtr) + EQUAL_READ32; U32 tmpOffset = offset_2; offset_2 = offset_1; offset_1 = tmpOffset; /* swap offset_2 <=> offset_1 */ ZSTD_storeSeq(seqStorePtr, 0, anchor, 0, repLength2 - MINMATCH); hashTable[ZSTD_hashPtr(ip, hBits, mls)] = curr2; ip += repLength2; anchor = ip; continue; } break; } } } /* save reps for next block */ ctx->repToConfirm[0] = offset_1; ctx->repToConfirm[1] = offset_2; /* Last Literals */ { size_t const lastLLSize = iend - anchor; memcpy(seqStorePtr->lit, anchor, lastLLSize); seqStorePtr->lit += lastLLSize; } } static void ZSTD_compressBlock_fast_extDict(ZSTD_CCtx *ctx, const void *src, size_t srcSize) { U32 const mls = ctx->params.cParams.searchLength; switch (mls) { default: /* includes case 3 */ case 4: ZSTD_compressBlock_fast_extDict_generic(ctx, src, srcSize, 4); return; case 5: ZSTD_compressBlock_fast_extDict_generic(ctx, src, srcSize, 5); return; case 6: ZSTD_compressBlock_fast_extDict_generic(ctx, src, srcSize, 6); return; case 7: ZSTD_compressBlock_fast_extDict_generic(ctx, src, srcSize, 7); return; } } /*-************************************* * Double Fast ***************************************/ static void ZSTD_fillDoubleHashTable(ZSTD_CCtx *cctx, const void *end, const U32 mls) { U32 *const hashLarge = cctx->hashTable; U32 const hBitsL = cctx->params.cParams.hashLog; U32 *const hashSmall = cctx->chainTable; U32 const hBitsS = cctx->params.cParams.chainLog; const BYTE *const base = cctx->base; const BYTE *ip = base + cctx->nextToUpdate; const BYTE *const iend = ((const BYTE *)end) - HASH_READ_SIZE; const size_t fastHashFillStep = 3; while (ip <= iend) { hashSmall[ZSTD_hashPtr(ip, hBitsS, mls)] = (U32)(ip - base); hashLarge[ZSTD_hashPtr(ip, hBitsL, 8)] = (U32)(ip - base); ip += fastHashFillStep; } } FORCE_INLINE void ZSTD_compressBlock_doubleFast_generic(ZSTD_CCtx *cctx, const void *src, size_t srcSize, const U32 mls) { U32 *const hashLong = cctx->hashTable; const U32 hBitsL = cctx->params.cParams.hashLog; U32 *const hashSmall = cctx->chainTable; const U32 hBitsS = cctx->params.cParams.chainLog; seqStore_t *seqStorePtr = &(cctx->seqStore); const BYTE *const base = cctx->base; const BYTE *const istart = (const BYTE *)src; const BYTE *ip = istart; const BYTE *anchor = istart; const U32 lowestIndex = cctx->dictLimit; const BYTE *const lowest = base + lowestIndex; const BYTE *const iend = istart + srcSize; const BYTE *const ilimit = iend - HASH_READ_SIZE; U32 offset_1 = cctx->rep[0], offset_2 = cctx->rep[1]; U32 offsetSaved = 0; /* init */ ip += (ip == lowest); { U32 const maxRep = (U32)(ip - lowest); if (offset_2 > maxRep) offsetSaved = offset_2, offset_2 = 0; if (offset_1 > maxRep) offsetSaved = offset_1, offset_1 = 0; } /* Main Search Loop */ while (ip < ilimit) { /* < instead of <=, because repcode check at (ip+1) */ size_t mLength; size_t const h2 = ZSTD_hashPtr(ip, hBitsL, 8); size_t const h = ZSTD_hashPtr(ip, hBitsS, mls); U32 const curr = (U32)(ip - base); U32 const matchIndexL = hashLong[h2]; U32 const matchIndexS = hashSmall[h]; const BYTE *matchLong = base + matchIndexL; const BYTE *match = base + matchIndexS; hashLong[h2] = hashSmall[h] = curr; /* update hash tables */ if ((offset_1 > 0) & (ZSTD_read32(ip + 1 - offset_1) == ZSTD_read32(ip + 1))) { /* note : by construction, offset_1 <= curr */ mLength = ZSTD_count(ip + 1 + 4, ip + 1 + 4 - offset_1, iend) + 4; ip++; ZSTD_storeSeq(seqStorePtr, ip - anchor, anchor, 0, mLength - MINMATCH); } else { U32 offset; if ((matchIndexL > lowestIndex) && (ZSTD_read64(matchLong) == ZSTD_read64(ip))) { mLength = ZSTD_count(ip + 8, matchLong + 8, iend) + 8; offset = (U32)(ip - matchLong); while (((ip > anchor) & (matchLong > lowest)) && (ip[-1] == matchLong[-1])) { ip--; matchLong--; mLength++; } /* catch up */ } else if ((matchIndexS > lowestIndex) && (ZSTD_read32(match) == ZSTD_read32(ip))) { size_t const h3 = ZSTD_hashPtr(ip + 1, hBitsL, 8); U32 const matchIndex3 = hashLong[h3]; const BYTE *match3 = base + matchIndex3; hashLong[h3] = curr + 1; if ((matchIndex3 > lowestIndex) && (ZSTD_read64(match3) == ZSTD_read64(ip + 1))) { mLength = ZSTD_count(ip + 9, match3 + 8, iend) + 8; ip++; offset = (U32)(ip - match3); while (((ip > anchor) & (match3 > lowest)) && (ip[-1] == match3[-1])) { ip--; match3--; mLength++; } /* catch up */ } else { mLength = ZSTD_count(ip + 4, match + 4, iend) + 4; offset = (U32)(ip - match); while (((ip > anchor) & (match > lowest)) && (ip[-1] == match[-1])) { ip--; match--; mLength++; } /* catch up */ } } else { ip += ((ip - anchor) >> g_searchStrength) + 1; continue; } offset_2 = offset_1; offset_1 = offset; ZSTD_storeSeq(seqStorePtr, ip - anchor, anchor, offset + ZSTD_REP_MOVE, mLength - MINMATCH); } /* match found */ ip += mLength; anchor = ip; if (ip <= ilimit) { /* Fill Table */ hashLong[ZSTD_hashPtr(base + curr + 2, hBitsL, 8)] = hashSmall[ZSTD_hashPtr(base + curr + 2, hBitsS, mls)] = curr + 2; /* here because curr+2 could be > iend-8 */ hashLong[ZSTD_hashPtr(ip - 2, hBitsL, 8)] = hashSmall[ZSTD_hashPtr(ip - 2, hBitsS, mls)] = (U32)(ip - 2 - base); /* check immediate repcode */ while ((ip <= ilimit) && ((offset_2 > 0) & (ZSTD_read32(ip) == ZSTD_read32(ip - offset_2)))) { /* store sequence */ size_t const rLength = ZSTD_count(ip + 4, ip + 4 - offset_2, iend) + 4; { U32 const tmpOff = offset_2; offset_2 = offset_1; offset_1 = tmpOff; } /* swap offset_2 <=> offset_1 */ hashSmall[ZSTD_hashPtr(ip, hBitsS, mls)] = (U32)(ip - base); hashLong[ZSTD_hashPtr(ip, hBitsL, 8)] = (U32)(ip - base); ZSTD_storeSeq(seqStorePtr, 0, anchor, 0, rLength - MINMATCH); ip += rLength; anchor = ip; continue; /* faster when present ... (?) */ } } } /* save reps for next block */ cctx->repToConfirm[0] = offset_1 ? offset_1 : offsetSaved; cctx->repToConfirm[1] = offset_2 ? offset_2 : offsetSaved; /* Last Literals */ { size_t const lastLLSize = iend - anchor; memcpy(seqStorePtr->lit, anchor, lastLLSize); seqStorePtr->lit += lastLLSize; } } static void ZSTD_compressBlock_doubleFast(ZSTD_CCtx *ctx, const void *src, size_t srcSize) { const U32 mls = ctx->params.cParams.searchLength; switch (mls) { default: /* includes case 3 */ case 4: ZSTD_compressBlock_doubleFast_generic(ctx, src, srcSize, 4); return; case 5: ZSTD_compressBlock_doubleFast_generic(ctx, src, srcSize, 5); return; case 6: ZSTD_compressBlock_doubleFast_generic(ctx, src, srcSize, 6); return; case 7: ZSTD_compressBlock_doubleFast_generic(ctx, src, srcSize, 7); return; } } static void ZSTD_compressBlock_doubleFast_extDict_generic(ZSTD_CCtx *ctx, const void *src, size_t srcSize, const U32 mls) { U32 *const hashLong = ctx->hashTable; U32 const hBitsL = ctx->params.cParams.hashLog; U32 *const hashSmall = ctx->chainTable; U32 const hBitsS = ctx->params.cParams.chainLog; seqStore_t *seqStorePtr = &(ctx->seqStore); const BYTE *const base = ctx->base; const BYTE *const dictBase = ctx->dictBase; const BYTE *const istart = (const BYTE *)src; const BYTE *ip = istart; const BYTE *anchor = istart; const U32 lowestIndex = ctx->lowLimit; const BYTE *const dictStart = dictBase + lowestIndex; const U32 dictLimit = ctx->dictLimit; const BYTE *const lowPrefixPtr = base + dictLimit; const BYTE *const dictEnd = dictBase + dictLimit; const BYTE *const iend = istart + srcSize; const BYTE *const ilimit = iend - 8; U32 offset_1 = ctx->rep[0], offset_2 = ctx->rep[1]; /* Search Loop */ while (ip < ilimit) { /* < instead of <=, because (ip+1) */ const size_t hSmall = ZSTD_hashPtr(ip, hBitsS, mls); const U32 matchIndex = hashSmall[hSmall]; const BYTE *matchBase = matchIndex < dictLimit ? dictBase : base; const BYTE *match = matchBase + matchIndex; const size_t hLong = ZSTD_hashPtr(ip, hBitsL, 8); const U32 matchLongIndex = hashLong[hLong]; const BYTE *matchLongBase = matchLongIndex < dictLimit ? dictBase : base; const BYTE *matchLong = matchLongBase + matchLongIndex; const U32 curr = (U32)(ip - base); const U32 repIndex = curr + 1 - offset_1; /* offset_1 expected <= curr +1 */ const BYTE *repBase = repIndex < dictLimit ? dictBase : base; const BYTE *repMatch = repBase + repIndex; size_t mLength; hashSmall[hSmall] = hashLong[hLong] = curr; /* update hash table */ if ((((U32)((dictLimit - 1) - repIndex) >= 3) /* intentional underflow */ & (repIndex > lowestIndex)) && (ZSTD_read32(repMatch) == ZSTD_read32(ip + 1))) { const BYTE *repMatchEnd = repIndex < dictLimit ? dictEnd : iend; mLength = ZSTD_count_2segments(ip + 1 + 4, repMatch + 4, iend, repMatchEnd, lowPrefixPtr) + 4; ip++; ZSTD_storeSeq(seqStorePtr, ip - anchor, anchor, 0, mLength - MINMATCH); } else { if ((matchLongIndex > lowestIndex) && (ZSTD_read64(matchLong) == ZSTD_read64(ip))) { const BYTE *matchEnd = matchLongIndex < dictLimit ? dictEnd : iend; const BYTE *lowMatchPtr = matchLongIndex < dictLimit ? dictStart : lowPrefixPtr; U32 offset; mLength = ZSTD_count_2segments(ip + 8, matchLong + 8, iend, matchEnd, lowPrefixPtr) + 8; offset = curr - matchLongIndex; while (((ip > anchor) & (matchLong > lowMatchPtr)) && (ip[-1] == matchLong[-1])) { ip--; matchLong--; mLength++; } /* catch up */ offset_2 = offset_1; offset_1 = offset; ZSTD_storeSeq(seqStorePtr, ip - anchor, anchor, offset + ZSTD_REP_MOVE, mLength - MINMATCH); } else if ((matchIndex > lowestIndex) && (ZSTD_read32(match) == ZSTD_read32(ip))) { size_t const h3 = ZSTD_hashPtr(ip + 1, hBitsL, 8); U32 const matchIndex3 = hashLong[h3]; const BYTE *const match3Base = matchIndex3 < dictLimit ? dictBase : base; const BYTE *match3 = match3Base + matchIndex3; U32 offset; hashLong[h3] = curr + 1; if ((matchIndex3 > lowestIndex) && (ZSTD_read64(match3) == ZSTD_read64(ip + 1))) { const BYTE *matchEnd = matchIndex3 < dictLimit ? dictEnd : iend; const BYTE *lowMatchPtr = matchIndex3 < dictLimit ? dictStart : lowPrefixPtr; mLength = ZSTD_count_2segments(ip + 9, match3 + 8, iend, matchEnd, lowPrefixPtr) + 8; ip++; offset = curr + 1 - matchIndex3; while (((ip > anchor) & (match3 > lowMatchPtr)) && (ip[-1] == match3[-1])) { ip--; match3--; mLength++; } /* catch up */ } else { const BYTE *matchEnd = matchIndex < dictLimit ? dictEnd : iend; const BYTE *lowMatchPtr = matchIndex < dictLimit ? dictStart : lowPrefixPtr; mLength = ZSTD_count_2segments(ip + 4, match + 4, iend, matchEnd, lowPrefixPtr) + 4; offset = curr - matchIndex; while (((ip > anchor) & (match > lowMatchPtr)) && (ip[-1] == match[-1])) { ip--; match--; mLength++; } /* catch up */ } offset_2 = offset_1; offset_1 = offset; ZSTD_storeSeq(seqStorePtr, ip - anchor, anchor, offset + ZSTD_REP_MOVE, mLength - MINMATCH); } else { ip += ((ip - anchor) >> g_searchStrength) + 1; continue; } } /* found a match : store it */ ip += mLength; anchor = ip; if (ip <= ilimit) { /* Fill Table */ hashSmall[ZSTD_hashPtr(base + curr + 2, hBitsS, mls)] = curr + 2; hashLong[ZSTD_hashPtr(base + curr + 2, hBitsL, 8)] = curr + 2; hashSmall[ZSTD_hashPtr(ip - 2, hBitsS, mls)] = (U32)(ip - 2 - base); hashLong[ZSTD_hashPtr(ip - 2, hBitsL, 8)] = (U32)(ip - 2 - base); /* check immediate repcode */ while (ip <= ilimit) { U32 const curr2 = (U32)(ip - base); U32 const repIndex2 = curr2 - offset_2; const BYTE *repMatch2 = repIndex2 < dictLimit ? dictBase + repIndex2 : base + repIndex2; if ((((U32)((dictLimit - 1) - repIndex2) >= 3) & (repIndex2 > lowestIndex)) /* intentional overflow */ && (ZSTD_read32(repMatch2) == ZSTD_read32(ip))) { const BYTE *const repEnd2 = repIndex2 < dictLimit ? dictEnd : iend; size_t const repLength2 = ZSTD_count_2segments(ip + EQUAL_READ32, repMatch2 + EQUAL_READ32, iend, repEnd2, lowPrefixPtr) + EQUAL_READ32; U32 tmpOffset = offset_2; offset_2 = offset_1; offset_1 = tmpOffset; /* swap offset_2 <=> offset_1 */ ZSTD_storeSeq(seqStorePtr, 0, anchor, 0, repLength2 - MINMATCH); hashSmall[ZSTD_hashPtr(ip, hBitsS, mls)] = curr2; hashLong[ZSTD_hashPtr(ip, hBitsL, 8)] = curr2; ip += repLength2; anchor = ip; continue; } break; } } } /* save reps for next block */ ctx->repToConfirm[0] = offset_1; ctx->repToConfirm[1] = offset_2; /* Last Literals */ { size_t const lastLLSize = iend - anchor; memcpy(seqStorePtr->lit, anchor, lastLLSize); seqStorePtr->lit += lastLLSize; } } static void ZSTD_compressBlock_doubleFast_extDict(ZSTD_CCtx *ctx, const void *src, size_t srcSize) { U32 const mls = ctx->params.cParams.searchLength; switch (mls) { default: /* includes case 3 */ case 4: ZSTD_compressBlock_doubleFast_extDict_generic(ctx, src, srcSize, 4); return; case 5: ZSTD_compressBlock_doubleFast_extDict_generic(ctx, src, srcSize, 5); return; case 6: ZSTD_compressBlock_doubleFast_extDict_generic(ctx, src, srcSize, 6); return; case 7: ZSTD_compressBlock_doubleFast_extDict_generic(ctx, src, srcSize, 7); return; } } /*-************************************* * Binary Tree search ***************************************/ /** ZSTD_insertBt1() : add one or multiple positions to tree. * ip : assumed <= iend-8 . * @return : nb of positions added */ static U32 ZSTD_insertBt1(ZSTD_CCtx *zc, const BYTE *const ip, const U32 mls, const BYTE *const iend, U32 nbCompares, U32 extDict) { U32 *const hashTable = zc->hashTable; U32 const hashLog = zc->params.cParams.hashLog; size_t const h = ZSTD_hashPtr(ip, hashLog, mls); U32 *const bt = zc->chainTable; U32 const btLog = zc->params.cParams.chainLog - 1; U32 const btMask = (1 << btLog) - 1; U32 matchIndex = hashTable[h]; size_t commonLengthSmaller = 0, commonLengthLarger = 0; const BYTE *const base = zc->base; const BYTE *const dictBase = zc->dictBase; const U32 dictLimit = zc->dictLimit; const BYTE *const dictEnd = dictBase + dictLimit; const BYTE *const prefixStart = base + dictLimit; const BYTE *match; const U32 curr = (U32)(ip - base); const U32 btLow = btMask >= curr ? 0 : curr - btMask; U32 *smallerPtr = bt + 2 * (curr & btMask); U32 *largerPtr = smallerPtr + 1; U32 dummy32; /* to be nullified at the end */ U32 const windowLow = zc->lowLimit; U32 matchEndIdx = curr + 8; size_t bestLength = 8; hashTable[h] = curr; /* Update Hash Table */ while (nbCompares-- && (matchIndex > windowLow)) { U32 *const nextPtr = bt + 2 * (matchIndex & btMask); size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger); /* guaranteed minimum nb of common bytes */ if ((!extDict) || (matchIndex + matchLength >= dictLimit)) { match = base + matchIndex; if (match[matchLength] == ip[matchLength]) matchLength += ZSTD_count(ip + matchLength + 1, match + matchLength + 1, iend) + 1; } else { match = dictBase + matchIndex; matchLength += ZSTD_count_2segments(ip + matchLength, match + matchLength, iend, dictEnd, prefixStart); if (matchIndex + matchLength >= dictLimit) match = base + matchIndex; /* to prepare for next usage of match[matchLength] */ } if (matchLength > bestLength) { bestLength = matchLength; if (matchLength > matchEndIdx - matchIndex) matchEndIdx = matchIndex + (U32)matchLength; } if (ip + matchLength == iend) /* equal : no way to know if inf or sup */ break; /* drop , to guarantee consistency ; miss a bit of compression, but other solutions can corrupt the tree */ if (match[matchLength] < ip[matchLength]) { /* necessarily within correct buffer */ /* match is smaller than curr */ *smallerPtr = matchIndex; /* update smaller idx */ commonLengthSmaller = matchLength; /* all smaller will now have at least this guaranteed common length */ if (matchIndex <= btLow) { smallerPtr = &dummy32; break; } /* beyond tree size, stop the search */ smallerPtr = nextPtr + 1; /* new "smaller" => larger of match */ matchIndex = nextPtr[1]; /* new matchIndex larger than previous (closer to curr) */ } else { /* match is larger than curr */ *largerPtr = matchIndex; commonLengthLarger = matchLength; if (matchIndex <= btLow) { largerPtr = &dummy32; break; } /* beyond tree size, stop the search */ largerPtr = nextPtr; matchIndex = nextPtr[0]; } } *smallerPtr = *largerPtr = 0; if (bestLength > 384) return MIN(192, (U32)(bestLength - 384)); /* speed optimization */ if (matchEndIdx > curr + 8) return matchEndIdx - curr - 8; return 1; } static size_t ZSTD_insertBtAndFindBestMatch(ZSTD_CCtx *zc, const BYTE *const ip, const BYTE *const iend, size_t *offsetPtr, U32 nbCompares, const U32 mls, U32 extDict) { U32 *const hashTable = zc->hashTable; U32 const hashLog = zc->params.cParams.hashLog; size_t const h = ZSTD_hashPtr(ip, hashLog, mls); U32 *const bt = zc->chainTable; U32 const btLog = zc->params.cParams.chainLog - 1; U32 const btMask = (1 << btLog) - 1; U32 matchIndex = hashTable[h]; size_t commonLengthSmaller = 0, commonLengthLarger = 0; const BYTE *const base = zc->base; const BYTE *const dictBase = zc->dictBase; const U32 dictLimit = zc->dictLimit; const BYTE *const dictEnd = dictBase + dictLimit; const BYTE *const prefixStart = base + dictLimit; const U32 curr = (U32)(ip - base); const U32 btLow = btMask >= curr ? 0 : curr - btMask; const U32 windowLow = zc->lowLimit; U32 *smallerPtr = bt + 2 * (curr & btMask); U32 *largerPtr = bt + 2 * (curr & btMask) + 1; U32 matchEndIdx = curr + 8; U32 dummy32; /* to be nullified at the end */ size_t bestLength = 0; hashTable[h] = curr; /* Update Hash Table */ while (nbCompares-- && (matchIndex > windowLow)) { U32 *const nextPtr = bt + 2 * (matchIndex & btMask); size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger); /* guaranteed minimum nb of common bytes */ const BYTE *match; if ((!extDict) || (matchIndex + matchLength >= dictLimit)) { match = base + matchIndex; if (match[matchLength] == ip[matchLength]) matchLength += ZSTD_count(ip + matchLength + 1, match + matchLength + 1, iend) + 1; } else { match = dictBase + matchIndex; matchLength += ZSTD_count_2segments(ip + matchLength, match + matchLength, iend, dictEnd, prefixStart); if (matchIndex + matchLength >= dictLimit) match = base + matchIndex; /* to prepare for next usage of match[matchLength] */ } if (matchLength > bestLength) { if (matchLength > matchEndIdx - matchIndex) matchEndIdx = matchIndex + (U32)matchLength; if ((4 * (int)(matchLength - bestLength)) > (int)(ZSTD_highbit32(curr - matchIndex + 1) - ZSTD_highbit32((U32)offsetPtr[0] + 1))) bestLength = matchLength, *offsetPtr = ZSTD_REP_MOVE + curr - matchIndex; if (ip + matchLength == iend) /* equal : no way to know if inf or sup */ break; /* drop, to guarantee consistency (miss a little bit of compression) */ } if (match[matchLength] < ip[matchLength]) { /* match is smaller than curr */ *smallerPtr = matchIndex; /* update smaller idx */ commonLengthSmaller = matchLength; /* all smaller will now have at least this guaranteed common length */ if (matchIndex <= btLow) { smallerPtr = &dummy32; break; } /* beyond tree size, stop the search */ smallerPtr = nextPtr + 1; /* new "smaller" => larger of match */ matchIndex = nextPtr[1]; /* new matchIndex larger than previous (closer to curr) */ } else { /* match is larger than curr */ *largerPtr = matchIndex; commonLengthLarger = matchLength; if (matchIndex <= btLow) { largerPtr = &dummy32; break; } /* beyond tree size, stop the search */ largerPtr = nextPtr; matchIndex = nextPtr[0]; } } *smallerPtr = *largerPtr = 0; zc->nextToUpdate = (matchEndIdx > curr + 8) ? matchEndIdx - 8 : curr + 1; return bestLength; } static void ZSTD_updateTree(ZSTD_CCtx *zc, const BYTE *const ip, const BYTE *const iend, const U32 nbCompares, const U32 mls) { const BYTE *const base = zc->base; const U32 target = (U32)(ip - base); U32 idx = zc->nextToUpdate; while (idx < target) idx += ZSTD_insertBt1(zc, base + idx, mls, iend, nbCompares, 0); } /** ZSTD_BtFindBestMatch() : Tree updater, providing best match */ static size_t ZSTD_BtFindBestMatch(ZSTD_CCtx *zc, const BYTE *const ip, const BYTE *const iLimit, size_t *offsetPtr, const U32 maxNbAttempts, const U32 mls) { if (ip < zc->base + zc->nextToUpdate) return 0; /* skipped area */ ZSTD_updateTree(zc, ip, iLimit, maxNbAttempts, mls); return ZSTD_insertBtAndFindBestMatch(zc, ip, iLimit, offsetPtr, maxNbAttempts, mls, 0); } static size_t ZSTD_BtFindBestMatch_selectMLS(ZSTD_CCtx *zc, /* Index table will be updated */ const BYTE *ip, const BYTE *const iLimit, size_t *offsetPtr, const U32 maxNbAttempts, const U32 matchLengthSearch) { switch (matchLengthSearch) { default: /* includes case 3 */ case 4: return ZSTD_BtFindBestMatch(zc, ip, iLimit, offsetPtr, maxNbAttempts, 4); case 5: return ZSTD_BtFindBestMatch(zc, ip, iLimit, offsetPtr, maxNbAttempts, 5); case 7: case 6: return ZSTD_BtFindBestMatch(zc, ip, iLimit, offsetPtr, maxNbAttempts, 6); } } static void ZSTD_updateTree_extDict(ZSTD_CCtx *zc, const BYTE *const ip, const BYTE *const iend, const U32 nbCompares, const U32 mls) { const BYTE *const base = zc->base; const U32 target = (U32)(ip - base); U32 idx = zc->nextToUpdate; while (idx < target) idx += ZSTD_insertBt1(zc, base + idx, mls, iend, nbCompares, 1); } /** Tree updater, providing best match */ static size_t ZSTD_BtFindBestMatch_extDict(ZSTD_CCtx *zc, const BYTE *const ip, const BYTE *const iLimit, size_t *offsetPtr, const U32 maxNbAttempts, const U32 mls) { if (ip < zc->base + zc->nextToUpdate) return 0; /* skipped area */ ZSTD_updateTree_extDict(zc, ip, iLimit, maxNbAttempts, mls); return ZSTD_insertBtAndFindBestMatch(zc, ip, iLimit, offsetPtr, maxNbAttempts, mls, 1); } static size_t ZSTD_BtFindBestMatch_selectMLS_extDict(ZSTD_CCtx *zc, /* Index table will be updated */ const BYTE *ip, const BYTE *const iLimit, size_t *offsetPtr, const U32 maxNbAttempts, const U32 matchLengthSearch) { switch (matchLengthSearch) { default: /* includes case 3 */ case 4: return ZSTD_BtFindBestMatch_extDict(zc, ip, iLimit, offsetPtr, maxNbAttempts, 4); case 5: return ZSTD_BtFindBestMatch_extDict(zc, ip, iLimit, offsetPtr, maxNbAttempts, 5); case 7: case 6: return ZSTD_BtFindBestMatch_extDict(zc, ip, iLimit, offsetPtr, maxNbAttempts, 6); } } /* ********************************* * Hash Chain ***********************************/ #define NEXT_IN_CHAIN(d, mask) chainTable[(d)&mask] /* Update chains up to ip (excluded) Assumption : always within prefix (i.e. not within extDict) */ FORCE_INLINE U32 ZSTD_insertAndFindFirstIndex(ZSTD_CCtx *zc, const BYTE *ip, U32 mls) { U32 *const hashTable = zc->hashTable; const U32 hashLog = zc->params.cParams.hashLog; U32 *const chainTable = zc->chainTable; const U32 chainMask = (1 << zc->params.cParams.chainLog) - 1; const BYTE *const base = zc->base; const U32 target = (U32)(ip - base); U32 idx = zc->nextToUpdate; while (idx < target) { /* catch up */ size_t const h = ZSTD_hashPtr(base + idx, hashLog, mls); NEXT_IN_CHAIN(idx, chainMask) = hashTable[h]; hashTable[h] = idx; idx++; } zc->nextToUpdate = target; return hashTable[ZSTD_hashPtr(ip, hashLog, mls)]; } /* inlining is important to hardwire a hot branch (template emulation) */ FORCE_INLINE size_t ZSTD_HcFindBestMatch_generic(ZSTD_CCtx *zc, /* Index table will be updated */ const BYTE *const ip, const BYTE *const iLimit, size_t *offsetPtr, const U32 maxNbAttempts, const U32 mls, const U32 extDict) { U32 *const chainTable = zc->chainTable; const U32 chainSize = (1 << zc->params.cParams.chainLog); const U32 chainMask = chainSize - 1; const BYTE *const base = zc->base; const BYTE *const dictBase = zc->dictBase; const U32 dictLimit = zc->dictLimit; const BYTE *const prefixStart = base + dictLimit; const BYTE *const dictEnd = dictBase + dictLimit; const U32 lowLimit = zc->lowLimit; const U32 curr = (U32)(ip - base); const U32 minChain = curr > chainSize ? curr - chainSize : 0; int nbAttempts = maxNbAttempts; size_t ml = EQUAL_READ32 - 1; /* HC4 match finder */ U32 matchIndex = ZSTD_insertAndFindFirstIndex(zc, ip, mls); for (; (matchIndex > lowLimit) & (nbAttempts > 0); nbAttempts--) { const BYTE *match; size_t currMl = 0; if ((!extDict) || matchIndex >= dictLimit) { match = base + matchIndex; if (match[ml] == ip[ml]) /* potentially better */ currMl = ZSTD_count(ip, match, iLimit); } else { match = dictBase + matchIndex; if (ZSTD_read32(match) == ZSTD_read32(ip)) /* assumption : matchIndex <= dictLimit-4 (by table construction) */ currMl = ZSTD_count_2segments(ip + EQUAL_READ32, match + EQUAL_READ32, iLimit, dictEnd, prefixStart) + EQUAL_READ32; } /* save best solution */ if (currMl > ml) { ml = currMl; *offsetPtr = curr - matchIndex + ZSTD_REP_MOVE; if (ip + currMl == iLimit) break; /* best possible, and avoid read overflow*/ } if (matchIndex <= minChain) break; matchIndex = NEXT_IN_CHAIN(matchIndex, chainMask); } return ml; } FORCE_INLINE size_t ZSTD_HcFindBestMatch_selectMLS(ZSTD_CCtx *zc, const BYTE *ip, const BYTE *const iLimit, size_t *offsetPtr, const U32 maxNbAttempts, const U32 matchLengthSearch) { switch (matchLengthSearch) { default: /* includes case 3 */ case 4: return ZSTD_HcFindBestMatch_generic(zc, ip, iLimit, offsetPtr, maxNbAttempts, 4, 0); case 5: return ZSTD_HcFindBestMatch_generic(zc, ip, iLimit, offsetPtr, maxNbAttempts, 5, 0); case 7: case 6: return ZSTD_HcFindBestMatch_generic(zc, ip, iLimit, offsetPtr, maxNbAttempts, 6, 0); } } FORCE_INLINE size_t ZSTD_HcFindBestMatch_extDict_selectMLS(ZSTD_CCtx *zc, const BYTE *ip, const BYTE *const iLimit, size_t *offsetPtr, const U32 maxNbAttempts, const U32 matchLengthSearch) { switch (matchLengthSearch) { default: /* includes case 3 */ case 4: return ZSTD_HcFindBestMatch_generic(zc, ip, iLimit, offsetPtr, maxNbAttempts, 4, 1); case 5: return ZSTD_HcFindBestMatch_generic(zc, ip, iLimit, offsetPtr, maxNbAttempts, 5, 1); case 7: case 6: return ZSTD_HcFindBestMatch_generic(zc, ip, iLimit, offsetPtr, maxNbAttempts, 6, 1); } } /* ******************************* * Common parser - lazy strategy *********************************/ FORCE_INLINE void ZSTD_compressBlock_lazy_generic(ZSTD_CCtx *ctx, const void *src, size_t srcSize, const U32 searchMethod, const U32 depth) { seqStore_t *seqStorePtr = &(ctx->seqStore); const BYTE *const istart = (const BYTE *)src; const BYTE *ip = istart; const BYTE *anchor = istart; const BYTE *const iend = istart + srcSize; const BYTE *const ilimit = iend - 8; const BYTE *const base = ctx->base + ctx->dictLimit; U32 const maxSearches = 1 << ctx->params.cParams.searchLog; U32 const mls = ctx->params.cParams.searchLength; typedef size_t (*searchMax_f)(ZSTD_CCtx * zc, const BYTE *ip, const BYTE *iLimit, size_t *offsetPtr, U32 maxNbAttempts, U32 matchLengthSearch); searchMax_f const searchMax = searchMethod ? ZSTD_BtFindBestMatch_selectMLS : ZSTD_HcFindBestMatch_selectMLS; U32 offset_1 = ctx->rep[0], offset_2 = ctx->rep[1], savedOffset = 0; /* init */ ip += (ip == base); ctx->nextToUpdate3 = ctx->nextToUpdate; { U32 const maxRep = (U32)(ip - base); if (offset_2 > maxRep) savedOffset = offset_2, offset_2 = 0; if (offset_1 > maxRep) savedOffset = offset_1, offset_1 = 0; } /* Match Loop */ while (ip < ilimit) { size_t matchLength = 0; size_t offset = 0; const BYTE *start = ip + 1; /* check repCode */ if ((offset_1 > 0) & (ZSTD_read32(ip + 1) == ZSTD_read32(ip + 1 - offset_1))) { /* repcode : we take it */ matchLength = ZSTD_count(ip + 1 + EQUAL_READ32, ip + 1 + EQUAL_READ32 - offset_1, iend) + EQUAL_READ32; if (depth == 0) goto _storeSequence; } /* first search (depth 0) */ { size_t offsetFound = 99999999; size_t const ml2 = searchMax(ctx, ip, iend, &offsetFound, maxSearches, mls); if (ml2 > matchLength) matchLength = ml2, start = ip, offset = offsetFound; } if (matchLength < EQUAL_READ32) { ip += ((ip - anchor) >> g_searchStrength) + 1; /* jump faster over incompressible sections */ continue; } /* let's try to find a better solution */ if (depth >= 1) while (ip < ilimit) { ip++; if ((offset) && ((offset_1 > 0) & (ZSTD_read32(ip) == ZSTD_read32(ip - offset_1)))) { size_t const mlRep = ZSTD_count(ip + EQUAL_READ32, ip + EQUAL_READ32 - offset_1, iend) + EQUAL_READ32; int const gain2 = (int)(mlRep * 3); int const gain1 = (int)(matchLength * 3 - ZSTD_highbit32((U32)offset + 1) + 1); if ((mlRep >= EQUAL_READ32) && (gain2 > gain1)) matchLength = mlRep, offset = 0, start = ip; } { size_t offset2 = 99999999; size_t const ml2 = searchMax(ctx, ip, iend, &offset2, maxSearches, mls); int const gain2 = (int)(ml2 * 4 - ZSTD_highbit32((U32)offset2 + 1)); /* raw approx */ int const gain1 = (int)(matchLength * 4 - ZSTD_highbit32((U32)offset + 1) + 4); if ((ml2 >= EQUAL_READ32) && (gain2 > gain1)) { matchLength = ml2, offset = offset2, start = ip; continue; /* search a better one */ } } /* let's find an even better one */ if ((depth == 2) && (ip < ilimit)) { ip++; if ((offset) && ((offset_1 > 0) & (ZSTD_read32(ip) == ZSTD_read32(ip - offset_1)))) { size_t const ml2 = ZSTD_count(ip + EQUAL_READ32, ip + EQUAL_READ32 - offset_1, iend) + EQUAL_READ32; int const gain2 = (int)(ml2 * 4); int const gain1 = (int)(matchLength * 4 - ZSTD_highbit32((U32)offset + 1) + 1); if ((ml2 >= EQUAL_READ32) && (gain2 > gain1)) matchLength = ml2, offset = 0, start = ip; } { size_t offset2 = 99999999; size_t const ml2 = searchMax(ctx, ip, iend, &offset2, maxSearches, mls); int const gain2 = (int)(ml2 * 4 - ZSTD_highbit32((U32)offset2 + 1)); /* raw approx */ int const gain1 = (int)(matchLength * 4 - ZSTD_highbit32((U32)offset + 1) + 7); if ((ml2 >= EQUAL_READ32) && (gain2 > gain1)) { matchLength = ml2, offset = offset2, start = ip; continue; } } } break; /* nothing found : store previous solution */ } /* NOTE: * start[-offset+ZSTD_REP_MOVE-1] is undefined behavior. * (-offset+ZSTD_REP_MOVE-1) is unsigned, and is added to start, which * overflows the pointer, which is undefined behavior. */ /* catch up */ if (offset) { while ((start > anchor) && (start > base + offset - ZSTD_REP_MOVE) && (start[-1] == (start-offset+ZSTD_REP_MOVE)[-1])) /* only search for offset within prefix */ { start--; matchLength++; } offset_2 = offset_1; offset_1 = (U32)(offset - ZSTD_REP_MOVE); } /* store sequence */ _storeSequence: { size_t const litLength = start - anchor; ZSTD_storeSeq(seqStorePtr, litLength, anchor, (U32)offset, matchLength - MINMATCH); anchor = ip = start + matchLength; } /* check immediate repcode */ while ((ip <= ilimit) && ((offset_2 > 0) & (ZSTD_read32(ip) == ZSTD_read32(ip - offset_2)))) { /* store sequence */ matchLength = ZSTD_count(ip + EQUAL_READ32, ip + EQUAL_READ32 - offset_2, iend) + EQUAL_READ32; offset = offset_2; offset_2 = offset_1; offset_1 = (U32)offset; /* swap repcodes */ ZSTD_storeSeq(seqStorePtr, 0, anchor, 0, matchLength - MINMATCH); ip += matchLength; anchor = ip; continue; /* faster when present ... (?) */ } } /* Save reps for next block */ ctx->repToConfirm[0] = offset_1 ? offset_1 : savedOffset; ctx->repToConfirm[1] = offset_2 ? offset_2 : savedOffset; /* Last Literals */ { size_t const lastLLSize = iend - anchor; memcpy(seqStorePtr->lit, anchor, lastLLSize); seqStorePtr->lit += lastLLSize; } } static void ZSTD_compressBlock_btlazy2(ZSTD_CCtx *ctx, const void *src, size_t srcSize) { ZSTD_compressBlock_lazy_generic(ctx, src, srcSize, 1, 2); } static void ZSTD_compressBlock_lazy2(ZSTD_CCtx *ctx, const void *src, size_t srcSize) { ZSTD_compressBlock_lazy_generic(ctx, src, srcSize, 0, 2); } static void ZSTD_compressBlock_lazy(ZSTD_CCtx *ctx, const void *src, size_t srcSize) { ZSTD_compressBlock_lazy_generic(ctx, src, srcSize, 0, 1); } static void ZSTD_compressBlock_greedy(ZSTD_CCtx *ctx, const void *src, size_t srcSize) { ZSTD_compressBlock_lazy_generic(ctx, src, srcSize, 0, 0); } FORCE_INLINE void ZSTD_compressBlock_lazy_extDict_generic(ZSTD_CCtx *ctx, const void *src, size_t srcSize, const U32 searchMethod, const U32 depth) { seqStore_t *seqStorePtr = &(ctx->seqStore); const BYTE *const istart = (const BYTE *)src; const BYTE *ip = istart; const BYTE *anchor = istart; const BYTE *const iend = istart + srcSize; const BYTE *const ilimit = iend - 8; const BYTE *const base = ctx->base; const U32 dictLimit = ctx->dictLimit; const U32 lowestIndex = ctx->lowLimit; const BYTE *const prefixStart = base + dictLimit; const BYTE *const dictBase = ctx->dictBase; const BYTE *const dictEnd = dictBase + dictLimit; const BYTE *const dictStart = dictBase + ctx->lowLimit; const U32 maxSearches = 1 << ctx->params.cParams.searchLog; const U32 mls = ctx->params.cParams.searchLength; typedef size_t (*searchMax_f)(ZSTD_CCtx * zc, const BYTE *ip, const BYTE *iLimit, size_t *offsetPtr, U32 maxNbAttempts, U32 matchLengthSearch); searchMax_f searchMax = searchMethod ? ZSTD_BtFindBestMatch_selectMLS_extDict : ZSTD_HcFindBestMatch_extDict_selectMLS; U32 offset_1 = ctx->rep[0], offset_2 = ctx->rep[1]; /* init */ ctx->nextToUpdate3 = ctx->nextToUpdate; ip += (ip == prefixStart); /* Match Loop */ while (ip < ilimit) { size_t matchLength = 0; size_t offset = 0; const BYTE *start = ip + 1; U32 curr = (U32)(ip - base); /* check repCode */ { const U32 repIndex = (U32)(curr + 1 - offset_1); const BYTE *const repBase = repIndex < dictLimit ? dictBase : base; const BYTE *const repMatch = repBase + repIndex; if (((U32)((dictLimit - 1) - repIndex) >= 3) & (repIndex > lowestIndex)) /* intentional overflow */ if (ZSTD_read32(ip + 1) == ZSTD_read32(repMatch)) { /* repcode detected we should take it */ const BYTE *const repEnd = repIndex < dictLimit ? dictEnd : iend; matchLength = ZSTD_count_2segments(ip + 1 + EQUAL_READ32, repMatch + EQUAL_READ32, iend, repEnd, prefixStart) + EQUAL_READ32; if (depth == 0) goto _storeSequence; } } /* first search (depth 0) */ { size_t offsetFound = 99999999; size_t const ml2 = searchMax(ctx, ip, iend, &offsetFound, maxSearches, mls); if (ml2 > matchLength) matchLength = ml2, start = ip, offset = offsetFound; } if (matchLength < EQUAL_READ32) { ip += ((ip - anchor) >> g_searchStrength) + 1; /* jump faster over incompressible sections */ continue; } /* let's try to find a better solution */ if (depth >= 1) while (ip < ilimit) { ip++; curr++; /* check repCode */ if (offset) { const U32 repIndex = (U32)(curr - offset_1); const BYTE *const repBase = repIndex < dictLimit ? dictBase : base; const BYTE *const repMatch = repBase + repIndex; if (((U32)((dictLimit - 1) - repIndex) >= 3) & (repIndex > lowestIndex)) /* intentional overflow */ if (ZSTD_read32(ip) == ZSTD_read32(repMatch)) { /* repcode detected */ const BYTE *const repEnd = repIndex < dictLimit ? dictEnd : iend; size_t const repLength = ZSTD_count_2segments(ip + EQUAL_READ32, repMatch + EQUAL_READ32, iend, repEnd, prefixStart) + EQUAL_READ32; int const gain2 = (int)(repLength * 3); int const gain1 = (int)(matchLength * 3 - ZSTD_highbit32((U32)offset + 1) + 1); if ((repLength >= EQUAL_READ32) && (gain2 > gain1)) matchLength = repLength, offset = 0, start = ip; } } /* search match, depth 1 */ { size_t offset2 = 99999999; size_t const ml2 = searchMax(ctx, ip, iend, &offset2, maxSearches, mls); int const gain2 = (int)(ml2 * 4 - ZSTD_highbit32((U32)offset2 + 1)); /* raw approx */ int const gain1 = (int)(matchLength * 4 - ZSTD_highbit32((U32)offset + 1) + 4); if ((ml2 >= EQUAL_READ32) && (gain2 > gain1)) { matchLength = ml2, offset = offset2, start = ip; continue; /* search a better one */ } } /* let's find an even better one */ if ((depth == 2) && (ip < ilimit)) { ip++; curr++; /* check repCode */ if (offset) { const U32 repIndex = (U32)(curr - offset_1); const BYTE *const repBase = repIndex < dictLimit ? dictBase : base; const BYTE *const repMatch = repBase + repIndex; if (((U32)((dictLimit - 1) - repIndex) >= 3) & (repIndex > lowestIndex)) /* intentional overflow */ if (ZSTD_read32(ip) == ZSTD_read32(repMatch)) { /* repcode detected */ const BYTE *const repEnd = repIndex < dictLimit ? dictEnd : iend; size_t repLength = ZSTD_count_2segments(ip + EQUAL_READ32, repMatch + EQUAL_READ32, iend, repEnd, prefixStart) + EQUAL_READ32; int gain2 = (int)(repLength * 4); int gain1 = (int)(matchLength * 4 - ZSTD_highbit32((U32)offset + 1) + 1); if ((repLength >= EQUAL_READ32) && (gain2 > gain1)) matchLength = repLength, offset = 0, start = ip; } } /* search match, depth 2 */ { size_t offset2 = 99999999; size_t const ml2 = searchMax(ctx, ip, iend, &offset2, maxSearches, mls); int const gain2 = (int)(ml2 * 4 - ZSTD_highbit32((U32)offset2 + 1)); /* raw approx */ int const gain1 = (int)(matchLength * 4 - ZSTD_highbit32((U32)offset + 1) + 7); if ((ml2 >= EQUAL_READ32) && (gain2 > gain1)) { matchLength = ml2, offset = offset2, start = ip; continue; } } } break; /* nothing found : store previous solution */ } /* catch up */ if (offset) { U32 const matchIndex = (U32)((start - base) - (offset - ZSTD_REP_MOVE)); const BYTE *match = (matchIndex < dictLimit) ? dictBase + matchIndex : base + matchIndex; const BYTE *const mStart = (matchIndex < dictLimit) ? dictStart : prefixStart; while ((start > anchor) && (match > mStart) && (start[-1] == match[-1])) { start--; match--; matchLength++; } /* catch up */ offset_2 = offset_1; offset_1 = (U32)(offset - ZSTD_REP_MOVE); } /* store sequence */ _storeSequence : { size_t const litLength = start - anchor; ZSTD_storeSeq(seqStorePtr, litLength, anchor, (U32)offset, matchLength - MINMATCH); anchor = ip = start + matchLength; } /* check immediate repcode */ while (ip <= ilimit) { const U32 repIndex = (U32)((ip - base) - offset_2); const BYTE *const repBase = repIndex < dictLimit ? dictBase : base; const BYTE *const repMatch = repBase + repIndex; if (((U32)((dictLimit - 1) - repIndex) >= 3) & (repIndex > lowestIndex)) /* intentional overflow */ if (ZSTD_read32(ip) == ZSTD_read32(repMatch)) { /* repcode detected we should take it */ const BYTE *const repEnd = repIndex < dictLimit ? dictEnd : iend; matchLength = ZSTD_count_2segments(ip + EQUAL_READ32, repMatch + EQUAL_READ32, iend, repEnd, prefixStart) + EQUAL_READ32; offset = offset_2; offset_2 = offset_1; offset_1 = (U32)offset; /* swap offset history */ ZSTD_storeSeq(seqStorePtr, 0, anchor, 0, matchLength - MINMATCH); ip += matchLength; anchor = ip; continue; /* faster when present ... (?) */ } break; } } /* Save reps for next block */ ctx->repToConfirm[0] = offset_1; ctx->repToConfirm[1] = offset_2; /* Last Literals */ { size_t const lastLLSize = iend - anchor; memcpy(seqStorePtr->lit, anchor, lastLLSize); seqStorePtr->lit += lastLLSize; } } void ZSTD_compressBlock_greedy_extDict(ZSTD_CCtx *ctx, const void *src, size_t srcSize) { ZSTD_compressBlock_lazy_extDict_generic(ctx, src, srcSize, 0, 0); } static void ZSTD_compressBlock_lazy_extDict(ZSTD_CCtx *ctx, const void *src, size_t srcSize) { ZSTD_compressBlock_lazy_extDict_generic(ctx, src, srcSize, 0, 1); } static void ZSTD_compressBlock_lazy2_extDict(ZSTD_CCtx *ctx, const void *src, size_t srcSize) { ZSTD_compressBlock_lazy_extDict_generic(ctx, src, srcSize, 0, 2); } static void ZSTD_compressBlock_btlazy2_extDict(ZSTD_CCtx *ctx, const void *src, size_t srcSize) { ZSTD_compressBlock_lazy_extDict_generic(ctx, src, srcSize, 1, 2); } /* The optimal parser */ #include "zstd_opt.h" static void ZSTD_compressBlock_btopt(ZSTD_CCtx *ctx, const void *src, size_t srcSize) { #ifdef ZSTD_OPT_H_91842398743 ZSTD_compressBlock_opt_generic(ctx, src, srcSize, 0); #else (void)ctx; (void)src; (void)srcSize; return; #endif } static void ZSTD_compressBlock_btopt2(ZSTD_CCtx *ctx, const void *src, size_t srcSize) { #ifdef ZSTD_OPT_H_91842398743 ZSTD_compressBlock_opt_generic(ctx, src, srcSize, 1); #else (void)ctx; (void)src; (void)srcSize; return; #endif } static void ZSTD_compressBlock_btopt_extDict(ZSTD_CCtx *ctx, const void *src, size_t srcSize) { #ifdef ZSTD_OPT_H_91842398743 ZSTD_compressBlock_opt_extDict_generic(ctx, src, srcSize, 0); #else (void)ctx; (void)src; (void)srcSize; return; #endif } static void ZSTD_compressBlock_btopt2_extDict(ZSTD_CCtx *ctx, const void *src, size_t srcSize) { #ifdef ZSTD_OPT_H_91842398743 ZSTD_compressBlock_opt_extDict_generic(ctx, src, srcSize, 1); #else (void)ctx; (void)src; (void)srcSize; return; #endif } typedef void (*ZSTD_blockCompressor)(ZSTD_CCtx *ctx, const void *src, size_t srcSize); static ZSTD_blockCompressor ZSTD_selectBlockCompressor(ZSTD_strategy strat, int extDict) { static const ZSTD_blockCompressor blockCompressor[2][8] = { {ZSTD_compressBlock_fast, ZSTD_compressBlock_doubleFast, ZSTD_compressBlock_greedy, ZSTD_compressBlock_lazy, ZSTD_compressBlock_lazy2, ZSTD_compressBlock_btlazy2, ZSTD_compressBlock_btopt, ZSTD_compressBlock_btopt2}, {ZSTD_compressBlock_fast_extDict, ZSTD_compressBlock_doubleFast_extDict, ZSTD_compressBlock_greedy_extDict, ZSTD_compressBlock_lazy_extDict, ZSTD_compressBlock_lazy2_extDict, ZSTD_compressBlock_btlazy2_extDict, ZSTD_compressBlock_btopt_extDict, ZSTD_compressBlock_btopt2_extDict}}; return blockCompressor[extDict][(U32)strat]; } static size_t ZSTD_compressBlock_internal(ZSTD_CCtx *zc, void *dst, size_t dstCapacity, const void *src, size_t srcSize) { ZSTD_blockCompressor const blockCompressor = ZSTD_selectBlockCompressor(zc->params.cParams.strategy, zc->lowLimit < zc->dictLimit); const BYTE *const base = zc->base; const BYTE *const istart = (const BYTE *)src; const U32 curr = (U32)(istart - base); if (srcSize < MIN_CBLOCK_SIZE + ZSTD_blockHeaderSize + 1) return 0; /* don't even attempt compression below a certain srcSize */ ZSTD_resetSeqStore(&(zc->seqStore)); if (curr > zc->nextToUpdate + 384) zc->nextToUpdate = curr - MIN(192, (U32)(curr - zc->nextToUpdate - 384)); /* update tree not updated after finding very long rep matches */ blockCompressor(zc, src, srcSize); return ZSTD_compressSequences(zc, dst, dstCapacity, srcSize); } /*! ZSTD_compress_generic() : * Compress a chunk of data into one or multiple blocks. * All blocks will be terminated, all input will be consumed. * Function will issue an error if there is not enough `dstCapacity` to hold the compressed content. * Frame is supposed already started (header already produced) * @return : compressed size, or an error code */ static size_t ZSTD_compress_generic(ZSTD_CCtx *cctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize, U32 lastFrameChunk) { size_t blockSize = cctx->blockSize; size_t remaining = srcSize; const BYTE *ip = (const BYTE *)src; BYTE *const ostart = (BYTE *)dst; BYTE *op = ostart; U32 const maxDist = 1 << cctx->params.cParams.windowLog; if (cctx->params.fParams.checksumFlag && srcSize) xxh64_update(&cctx->xxhState, src, srcSize); while (remaining) { U32 const lastBlock = lastFrameChunk & (blockSize >= remaining); size_t cSize; if (dstCapacity < ZSTD_blockHeaderSize + MIN_CBLOCK_SIZE) return ERROR(dstSize_tooSmall); /* not enough space to store compressed block */ if (remaining < blockSize) blockSize = remaining; /* preemptive overflow correction */ if (cctx->lowLimit > (3U << 29)) { U32 const cycleMask = (1 << ZSTD_cycleLog(cctx->params.cParams.hashLog, cctx->params.cParams.strategy)) - 1; U32 const curr = (U32)(ip - cctx->base); U32 const newCurr = (curr & cycleMask) + (1 << cctx->params.cParams.windowLog); U32 const correction = curr - newCurr; ZSTD_STATIC_ASSERT(ZSTD_WINDOWLOG_MAX_64 <= 30); ZSTD_reduceIndex(cctx, correction); cctx->base += correction; cctx->dictBase += correction; cctx->lowLimit -= correction; cctx->dictLimit -= correction; if (cctx->nextToUpdate < correction) cctx->nextToUpdate = 0; else cctx->nextToUpdate -= correction; } if ((U32)(ip + blockSize - cctx->base) > cctx->loadedDictEnd + maxDist) { /* enforce maxDist */ U32 const newLowLimit = (U32)(ip + blockSize - cctx->base) - maxDist; if (cctx->lowLimit < newLowLimit) cctx->lowLimit = newLowLimit; if (cctx->dictLimit < cctx->lowLimit) cctx->dictLimit = cctx->lowLimit; } cSize = ZSTD_compressBlock_internal(cctx, op + ZSTD_blockHeaderSize, dstCapacity - ZSTD_blockHeaderSize, ip, blockSize); if (ZSTD_isError(cSize)) return cSize; if (cSize == 0) { /* block is not compressible */ U32 const cBlockHeader24 = lastBlock + (((U32)bt_raw) << 1) + (U32)(blockSize << 3); if (blockSize + ZSTD_blockHeaderSize > dstCapacity) return ERROR(dstSize_tooSmall); ZSTD_writeLE32(op, cBlockHeader24); /* no pb, 4th byte will be overwritten */ memcpy(op + ZSTD_blockHeaderSize, ip, blockSize); cSize = ZSTD_blockHeaderSize + blockSize; } else { U32 const cBlockHeader24 = lastBlock + (((U32)bt_compressed) << 1) + (U32)(cSize << 3); ZSTD_writeLE24(op, cBlockHeader24); cSize += ZSTD_blockHeaderSize; } remaining -= blockSize; dstCapacity -= cSize; ip += blockSize; op += cSize; } if (lastFrameChunk && (op > ostart)) cctx->stage = ZSTDcs_ending; return op - ostart; } static size_t ZSTD_writeFrameHeader(void *dst, size_t dstCapacity, ZSTD_parameters params, U64 pledgedSrcSize, U32 dictID) { BYTE *const op = (BYTE *)dst; U32 const dictIDSizeCode = (dictID > 0) + (dictID >= 256) + (dictID >= 65536); /* 0-3 */ U32 const checksumFlag = params.fParams.checksumFlag > 0; U32 const windowSize = 1U << params.cParams.windowLog; U32 const singleSegment = params.fParams.contentSizeFlag && (windowSize >= pledgedSrcSize); BYTE const windowLogByte = (BYTE)((params.cParams.windowLog - ZSTD_WINDOWLOG_ABSOLUTEMIN) << 3); U32 const fcsCode = params.fParams.contentSizeFlag ? (pledgedSrcSize >= 256) + (pledgedSrcSize >= 65536 + 256) + (pledgedSrcSize >= 0xFFFFFFFFU) : 0; /* 0-3 */ BYTE const frameHeaderDecriptionByte = (BYTE)(dictIDSizeCode + (checksumFlag << 2) + (singleSegment << 5) + (fcsCode << 6)); size_t pos; if (dstCapacity < ZSTD_frameHeaderSize_max) return ERROR(dstSize_tooSmall); ZSTD_writeLE32(dst, ZSTD_MAGICNUMBER); op[4] = frameHeaderDecriptionByte; pos = 5; if (!singleSegment) op[pos++] = windowLogByte; switch (dictIDSizeCode) { default: /* impossible */ case 0: break; case 1: op[pos] = (BYTE)(dictID); pos++; break; case 2: ZSTD_writeLE16(op + pos, (U16)dictID); pos += 2; break; case 3: ZSTD_writeLE32(op + pos, dictID); pos += 4; break; } switch (fcsCode) { default: /* impossible */ case 0: if (singleSegment) op[pos++] = (BYTE)(pledgedSrcSize); break; case 1: ZSTD_writeLE16(op + pos, (U16)(pledgedSrcSize - 256)); pos += 2; break; case 2: ZSTD_writeLE32(op + pos, (U32)(pledgedSrcSize)); pos += 4; break; case 3: ZSTD_writeLE64(op + pos, (U64)(pledgedSrcSize)); pos += 8; break; } return pos; } static size_t ZSTD_compressContinue_internal(ZSTD_CCtx *cctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize, U32 frame, U32 lastFrameChunk) { const BYTE *const ip = (const BYTE *)src; size_t fhSize = 0; if (cctx->stage == ZSTDcs_created) return ERROR(stage_wrong); /* missing init (ZSTD_compressBegin) */ if (frame && (cctx->stage == ZSTDcs_init)) { fhSize = ZSTD_writeFrameHeader(dst, dstCapacity, cctx->params, cctx->frameContentSize, cctx->dictID); if (ZSTD_isError(fhSize)) return fhSize; dstCapacity -= fhSize; dst = (char *)dst + fhSize; cctx->stage = ZSTDcs_ongoing; } /* Check if blocks follow each other */ if (src != cctx->nextSrc) { /* not contiguous */ ptrdiff_t const delta = cctx->nextSrc - ip; cctx->lowLimit = cctx->dictLimit; cctx->dictLimit = (U32)(cctx->nextSrc - cctx->base); cctx->dictBase = cctx->base; cctx->base -= delta; cctx->nextToUpdate = cctx->dictLimit; if (cctx->dictLimit - cctx->lowLimit < HASH_READ_SIZE) cctx->lowLimit = cctx->dictLimit; /* too small extDict */ } /* if input and dictionary overlap : reduce dictionary (area presumed modified by input) */ if ((ip + srcSize > cctx->dictBase + cctx->lowLimit) & (ip < cctx->dictBase + cctx->dictLimit)) { ptrdiff_t const highInputIdx = (ip + srcSize) - cctx->dictBase; U32 const lowLimitMax = (highInputIdx > (ptrdiff_t)cctx->dictLimit) ? cctx->dictLimit : (U32)highInputIdx; cctx->lowLimit = lowLimitMax; } cctx->nextSrc = ip + srcSize; if (srcSize) { size_t const cSize = frame ? ZSTD_compress_generic(cctx, dst, dstCapacity, src, srcSize, lastFrameChunk) : ZSTD_compressBlock_internal(cctx, dst, dstCapacity, src, srcSize); if (ZSTD_isError(cSize)) return cSize; return cSize + fhSize; } else return fhSize; } size_t ZSTD_compressContinue(ZSTD_CCtx *cctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize) { return ZSTD_compressContinue_internal(cctx, dst, dstCapacity, src, srcSize, 1, 0); } size_t ZSTD_getBlockSizeMax(ZSTD_CCtx *cctx) { return MIN(ZSTD_BLOCKSIZE_ABSOLUTEMAX, 1 << cctx->params.cParams.windowLog); } size_t ZSTD_compressBlock(ZSTD_CCtx *cctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize) { size_t const blockSizeMax = ZSTD_getBlockSizeMax(cctx); if (srcSize > blockSizeMax) return ERROR(srcSize_wrong); return ZSTD_compressContinue_internal(cctx, dst, dstCapacity, src, srcSize, 0, 0); } /*! ZSTD_loadDictionaryContent() : * @return : 0, or an error code */ static size_t ZSTD_loadDictionaryContent(ZSTD_CCtx *zc, const void *src, size_t srcSize) { const BYTE *const ip = (const BYTE *)src; const BYTE *const iend = ip + srcSize; /* input becomes curr prefix */ zc->lowLimit = zc->dictLimit; zc->dictLimit = (U32)(zc->nextSrc - zc->base); zc->dictBase = zc->base; zc->base += ip - zc->nextSrc; zc->nextToUpdate = zc->dictLimit; zc->loadedDictEnd = zc->forceWindow ? 0 : (U32)(iend - zc->base); zc->nextSrc = iend; if (srcSize <= HASH_READ_SIZE) return 0; switch (zc->params.cParams.strategy) { case ZSTD_fast: ZSTD_fillHashTable(zc, iend, zc->params.cParams.searchLength); break; case ZSTD_dfast: ZSTD_fillDoubleHashTable(zc, iend, zc->params.cParams.searchLength); break; case ZSTD_greedy: case ZSTD_lazy: case ZSTD_lazy2: if (srcSize >= HASH_READ_SIZE) ZSTD_insertAndFindFirstIndex(zc, iend - HASH_READ_SIZE, zc->params.cParams.searchLength); break; case ZSTD_btlazy2: case ZSTD_btopt: case ZSTD_btopt2: if (srcSize >= HASH_READ_SIZE) ZSTD_updateTree(zc, iend - HASH_READ_SIZE, iend, 1 << zc->params.cParams.searchLog, zc->params.cParams.searchLength); break; default: return ERROR(GENERIC); /* strategy doesn't exist; impossible */ } zc->nextToUpdate = (U32)(iend - zc->base); return 0; } /* Dictionaries that assign zero probability to symbols that show up causes problems when FSE encoding. Refuse dictionaries that assign zero probability to symbols that we may encounter during compression. NOTE: This behavior is not standard and could be improved in the future. */ static size_t ZSTD_checkDictNCount(short *normalizedCounter, unsigned dictMaxSymbolValue, unsigned maxSymbolValue) { U32 s; if (dictMaxSymbolValue < maxSymbolValue) return ERROR(dictionary_corrupted); for (s = 0; s <= maxSymbolValue; ++s) { if (normalizedCounter[s] == 0) return ERROR(dictionary_corrupted); } return 0; } /* Dictionary format : * See : * https://github.com/facebook/zstd/blob/master/doc/zstd_compression_format.md#dictionary-format */ /*! ZSTD_loadZstdDictionary() : * @return : 0, or an error code * assumptions : magic number supposed already checked * dictSize supposed > 8 */ static size_t ZSTD_loadZstdDictionary(ZSTD_CCtx *cctx, const void *dict, size_t dictSize) { const BYTE *dictPtr = (const BYTE *)dict; const BYTE *const dictEnd = dictPtr + dictSize; short offcodeNCount[MaxOff + 1]; unsigned offcodeMaxValue = MaxOff; dictPtr += 4; /* skip magic number */ cctx->dictID = cctx->params.fParams.noDictIDFlag ? 0 : ZSTD_readLE32(dictPtr); dictPtr += 4; { size_t const hufHeaderSize = HUF_readCTable_wksp(cctx->hufTable, 255, dictPtr, dictEnd - dictPtr, cctx->tmpCounters, sizeof(cctx->tmpCounters)); if (HUF_isError(hufHeaderSize)) return ERROR(dictionary_corrupted); dictPtr += hufHeaderSize; } { unsigned offcodeLog; size_t const offcodeHeaderSize = FSE_readNCount(offcodeNCount, &offcodeMaxValue, &offcodeLog, dictPtr, dictEnd - dictPtr); if (FSE_isError(offcodeHeaderSize)) return ERROR(dictionary_corrupted); if (offcodeLog > OffFSELog) return ERROR(dictionary_corrupted); /* Defer checking offcodeMaxValue because we need to know the size of the dictionary content */ CHECK_E(FSE_buildCTable_wksp(cctx->offcodeCTable, offcodeNCount, offcodeMaxValue, offcodeLog, cctx->tmpCounters, sizeof(cctx->tmpCounters)), dictionary_corrupted); dictPtr += offcodeHeaderSize; } { short matchlengthNCount[MaxML + 1]; unsigned matchlengthMaxValue = MaxML, matchlengthLog; size_t const matchlengthHeaderSize = FSE_readNCount(matchlengthNCount, &matchlengthMaxValue, &matchlengthLog, dictPtr, dictEnd - dictPtr); if (FSE_isError(matchlengthHeaderSize)) return ERROR(dictionary_corrupted); if (matchlengthLog > MLFSELog) return ERROR(dictionary_corrupted); /* Every match length code must have non-zero probability */ CHECK_F(ZSTD_checkDictNCount(matchlengthNCount, matchlengthMaxValue, MaxML)); CHECK_E( FSE_buildCTable_wksp(cctx->matchlengthCTable, matchlengthNCount, matchlengthMaxValue, matchlengthLog, cctx->tmpCounters, sizeof(cctx->tmpCounters)), dictionary_corrupted); dictPtr += matchlengthHeaderSize; } { short litlengthNCount[MaxLL + 1]; unsigned litlengthMaxValue = MaxLL, litlengthLog; size_t const litlengthHeaderSize = FSE_readNCount(litlengthNCount, &litlengthMaxValue, &litlengthLog, dictPtr, dictEnd - dictPtr); if (FSE_isError(litlengthHeaderSize)) return ERROR(dictionary_corrupted); if (litlengthLog > LLFSELog) return ERROR(dictionary_corrupted); /* Every literal length code must have non-zero probability */ CHECK_F(ZSTD_checkDictNCount(litlengthNCount, litlengthMaxValue, MaxLL)); CHECK_E(FSE_buildCTable_wksp(cctx->litlengthCTable, litlengthNCount, litlengthMaxValue, litlengthLog, cctx->tmpCounters, sizeof(cctx->tmpCounters)), dictionary_corrupted); dictPtr += litlengthHeaderSize; } if (dictPtr + 12 > dictEnd) return ERROR(dictionary_corrupted); cctx->rep[0] = ZSTD_readLE32(dictPtr + 0); cctx->rep[1] = ZSTD_readLE32(dictPtr + 4); cctx->rep[2] = ZSTD_readLE32(dictPtr + 8); dictPtr += 12; { size_t const dictContentSize = (size_t)(dictEnd - dictPtr); U32 offcodeMax = MaxOff; if (dictContentSize <= ((U32)-1) - 128 KB) { U32 const maxOffset = (U32)dictContentSize + 128 KB; /* The maximum offset that must be supported */ offcodeMax = ZSTD_highbit32(maxOffset); /* Calculate minimum offset code required to represent maxOffset */ } /* All offset values <= dictContentSize + 128 KB must be representable */ CHECK_F(ZSTD_checkDictNCount(offcodeNCount, offcodeMaxValue, MIN(offcodeMax, MaxOff))); /* All repCodes must be <= dictContentSize and != 0*/ { U32 u; for (u = 0; u < 3; u++) { if (cctx->rep[u] == 0) return ERROR(dictionary_corrupted); if (cctx->rep[u] > dictContentSize) return ERROR(dictionary_corrupted); } } cctx->flagStaticTables = 1; cctx->flagStaticHufTable = HUF_repeat_valid; return ZSTD_loadDictionaryContent(cctx, dictPtr, dictContentSize); } } /** ZSTD_compress_insertDictionary() : * @return : 0, or an error code */ static size_t ZSTD_compress_insertDictionary(ZSTD_CCtx *cctx, const void *dict, size_t dictSize) { if ((dict == NULL) || (dictSize <= 8)) return 0; /* dict as pure content */ if ((ZSTD_readLE32(dict) != ZSTD_DICT_MAGIC) || (cctx->forceRawDict)) return ZSTD_loadDictionaryContent(cctx, dict, dictSize); /* dict as zstd dictionary */ return ZSTD_loadZstdDictionary(cctx, dict, dictSize); } /*! ZSTD_compressBegin_internal() : * @return : 0, or an error code */ static size_t ZSTD_compressBegin_internal(ZSTD_CCtx *cctx, const void *dict, size_t dictSize, ZSTD_parameters params, U64 pledgedSrcSize) { ZSTD_compResetPolicy_e const crp = dictSize ? ZSTDcrp_fullReset : ZSTDcrp_continue; CHECK_F(ZSTD_resetCCtx_advanced(cctx, params, pledgedSrcSize, crp)); return ZSTD_compress_insertDictionary(cctx, dict, dictSize); } /*! ZSTD_compressBegin_advanced() : * @return : 0, or an error code */ size_t ZSTD_compressBegin_advanced(ZSTD_CCtx *cctx, const void *dict, size_t dictSize, ZSTD_parameters params, unsigned long long pledgedSrcSize) { /* compression parameters verification and optimization */ CHECK_F(ZSTD_checkCParams(params.cParams)); return ZSTD_compressBegin_internal(cctx, dict, dictSize, params, pledgedSrcSize); } size_t ZSTD_compressBegin_usingDict(ZSTD_CCtx *cctx, const void *dict, size_t dictSize, int compressionLevel) { ZSTD_parameters const params = ZSTD_getParams(compressionLevel, 0, dictSize); return ZSTD_compressBegin_internal(cctx, dict, dictSize, params, 0); } size_t ZSTD_compressBegin(ZSTD_CCtx *cctx, int compressionLevel) { return ZSTD_compressBegin_usingDict(cctx, NULL, 0, compressionLevel); } /*! ZSTD_writeEpilogue() : * Ends a frame. * @return : nb of bytes written into dst (or an error code) */ static size_t ZSTD_writeEpilogue(ZSTD_CCtx *cctx, void *dst, size_t dstCapacity) { BYTE *const ostart = (BYTE *)dst; BYTE *op = ostart; size_t fhSize = 0; if (cctx->stage == ZSTDcs_created) return ERROR(stage_wrong); /* init missing */ /* special case : empty frame */ if (cctx->stage == ZSTDcs_init) { fhSize = ZSTD_writeFrameHeader(dst, dstCapacity, cctx->params, 0, 0); if (ZSTD_isError(fhSize)) return fhSize; dstCapacity -= fhSize; op += fhSize; cctx->stage = ZSTDcs_ongoing; } if (cctx->stage != ZSTDcs_ending) { /* write one last empty block, make it the "last" block */ U32 const cBlockHeader24 = 1 /* last block */ + (((U32)bt_raw) << 1) + 0; if (dstCapacity < 4) return ERROR(dstSize_tooSmall); ZSTD_writeLE32(op, cBlockHeader24); op += ZSTD_blockHeaderSize; dstCapacity -= ZSTD_blockHeaderSize; } if (cctx->params.fParams.checksumFlag) { U32 const checksum = (U32)xxh64_digest(&cctx->xxhState); if (dstCapacity < 4) return ERROR(dstSize_tooSmall); ZSTD_writeLE32(op, checksum); op += 4; } cctx->stage = ZSTDcs_created; /* return to "created but no init" status */ return op - ostart; } size_t ZSTD_compressEnd(ZSTD_CCtx *cctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize) { size_t endResult; size_t const cSize = ZSTD_compressContinue_internal(cctx, dst, dstCapacity, src, srcSize, 1, 1); if (ZSTD_isError(cSize)) return cSize; endResult = ZSTD_writeEpilogue(cctx, (char *)dst + cSize, dstCapacity - cSize); if (ZSTD_isError(endResult)) return endResult; return cSize + endResult; } static size_t ZSTD_compress_internal(ZSTD_CCtx *cctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize, const void *dict, size_t dictSize, ZSTD_parameters params) { CHECK_F(ZSTD_compressBegin_internal(cctx, dict, dictSize, params, srcSize)); return ZSTD_compressEnd(cctx, dst, dstCapacity, src, srcSize); } size_t ZSTD_compress_usingDict(ZSTD_CCtx *ctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize, const void *dict, size_t dictSize, ZSTD_parameters params) { return ZSTD_compress_internal(ctx, dst, dstCapacity, src, srcSize, dict, dictSize, params); } size_t ZSTD_compressCCtx(ZSTD_CCtx *ctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize, ZSTD_parameters params) { return ZSTD_compress_internal(ctx, dst, dstCapacity, src, srcSize, NULL, 0, params); } /* ===== Dictionary API ===== */ struct ZSTD_CDict_s { void *dictBuffer; const void *dictContent; size_t dictContentSize; ZSTD_CCtx *refContext; }; /* typedef'd tp ZSTD_CDict within "zstd.h" */ size_t ZSTD_CDictWorkspaceBound(ZSTD_compressionParameters cParams) { return ZSTD_CCtxWorkspaceBound(cParams) + ZSTD_ALIGN(sizeof(ZSTD_CDict)); } static ZSTD_CDict *ZSTD_createCDict_advanced(const void *dictBuffer, size_t dictSize, unsigned byReference, ZSTD_parameters params, ZSTD_customMem customMem) { if (!customMem.customAlloc || !customMem.customFree) return NULL; { ZSTD_CDict *const cdict = (ZSTD_CDict *)ZSTD_malloc(sizeof(ZSTD_CDict), customMem); ZSTD_CCtx *const cctx = ZSTD_createCCtx_advanced(customMem); if (!cdict || !cctx) { ZSTD_free(cdict, customMem); ZSTD_freeCCtx(cctx); return NULL; } if ((byReference) || (!dictBuffer) || (!dictSize)) { cdict->dictBuffer = NULL; cdict->dictContent = dictBuffer; } else { void *const internalBuffer = ZSTD_malloc(dictSize, customMem); if (!internalBuffer) { ZSTD_free(cctx, customMem); ZSTD_free(cdict, customMem); return NULL; } memcpy(internalBuffer, dictBuffer, dictSize); cdict->dictBuffer = internalBuffer; cdict->dictContent = internalBuffer; } { size_t const errorCode = ZSTD_compressBegin_advanced(cctx, cdict->dictContent, dictSize, params, 0); if (ZSTD_isError(errorCode)) { ZSTD_free(cdict->dictBuffer, customMem); ZSTD_free(cdict, customMem); ZSTD_freeCCtx(cctx); return NULL; } } cdict->refContext = cctx; cdict->dictContentSize = dictSize; return cdict; } } ZSTD_CDict *ZSTD_initCDict(const void *dict, size_t dictSize, ZSTD_parameters params, void *workspace, size_t workspaceSize) { ZSTD_customMem const stackMem = ZSTD_initStack(workspace, workspaceSize); return ZSTD_createCDict_advanced(dict, dictSize, 1, params, stackMem); } size_t ZSTD_freeCDict(ZSTD_CDict *cdict) { if (cdict == NULL) return 0; /* support free on NULL */ { ZSTD_customMem const cMem = cdict->refContext->customMem; ZSTD_freeCCtx(cdict->refContext); ZSTD_free(cdict->dictBuffer, cMem); ZSTD_free(cdict, cMem); return 0; } } static ZSTD_parameters ZSTD_getParamsFromCDict(const ZSTD_CDict *cdict) { return ZSTD_getParamsFromCCtx(cdict->refContext); } size_t ZSTD_compressBegin_usingCDict(ZSTD_CCtx *cctx, const ZSTD_CDict *cdict, unsigned long long pledgedSrcSize) { if (cdict->dictContentSize) CHECK_F(ZSTD_copyCCtx(cctx, cdict->refContext, pledgedSrcSize)) else { ZSTD_parameters params = cdict->refContext->params; params.fParams.contentSizeFlag = (pledgedSrcSize > 0); CHECK_F(ZSTD_compressBegin_advanced(cctx, NULL, 0, params, pledgedSrcSize)); } return 0; } /*! ZSTD_compress_usingCDict() : * Compression using a digested Dictionary. * Faster startup than ZSTD_compress_usingDict(), recommended when same dictionary is used multiple times. * Note that compression level is decided during dictionary creation */ size_t ZSTD_compress_usingCDict(ZSTD_CCtx *cctx, void *dst, size_t dstCapacity, const void *src, size_t srcSize, const ZSTD_CDict *cdict) { CHECK_F(ZSTD_compressBegin_usingCDict(cctx, cdict, srcSize)); if (cdict->refContext->params.fParams.contentSizeFlag == 1) { cctx->params.fParams.contentSizeFlag = 1; cctx->frameContentSize = srcSize; } else { cctx->params.fParams.contentSizeFlag = 0; } return ZSTD_compressEnd(cctx, dst, dstCapacity, src, srcSize); } /* ****************************************************************** * Streaming ********************************************************************/ typedef enum { zcss_init, zcss_load, zcss_flush, zcss_final } ZSTD_cStreamStage; struct ZSTD_CStream_s { ZSTD_CCtx *cctx; ZSTD_CDict *cdictLocal; const ZSTD_CDict *cdict; char *inBuff; size_t inBuffSize; size_t inToCompress; size_t inBuffPos; size_t inBuffTarget; size_t blockSize; char *outBuff; size_t outBuffSize; size_t outBuffContentSize; size_t outBuffFlushedSize; ZSTD_cStreamStage stage; U32 checksum; U32 frameEnded; U64 pledgedSrcSize; U64 inputProcessed; ZSTD_parameters params; ZSTD_customMem customMem; }; /* typedef'd to ZSTD_CStream within "zstd.h" */ size_t ZSTD_CStreamWorkspaceBound(ZSTD_compressionParameters cParams) { size_t const inBuffSize = (size_t)1 << cParams.windowLog; size_t const blockSize = MIN(ZSTD_BLOCKSIZE_ABSOLUTEMAX, inBuffSize); size_t const outBuffSize = ZSTD_compressBound(blockSize) + 1; return ZSTD_CCtxWorkspaceBound(cParams) + ZSTD_ALIGN(sizeof(ZSTD_CStream)) + ZSTD_ALIGN(inBuffSize) + ZSTD_ALIGN(outBuffSize); } ZSTD_CStream *ZSTD_createCStream_advanced(ZSTD_customMem customMem) { ZSTD_CStream *zcs; if (!customMem.customAlloc || !customMem.customFree) return NULL; zcs = (ZSTD_CStream *)ZSTD_malloc(sizeof(ZSTD_CStream), customMem); if (zcs == NULL) return NULL; memset(zcs, 0, sizeof(ZSTD_CStream)); memcpy(&zcs->customMem, &customMem, sizeof(ZSTD_customMem)); zcs->cctx = ZSTD_createCCtx_advanced(customMem); if (zcs->cctx == NULL) { ZSTD_freeCStream(zcs); return NULL; } return zcs; } size_t ZSTD_freeCStream(ZSTD_CStream *zcs) { if (zcs == NULL) return 0; /* support free on NULL */ { ZSTD_customMem const cMem = zcs->customMem; ZSTD_freeCCtx(zcs->cctx); zcs->cctx = NULL; ZSTD_freeCDict(zcs->cdictLocal); zcs->cdictLocal = NULL; ZSTD_free(zcs->inBuff, cMem); zcs->inBuff = NULL; ZSTD_free(zcs->outBuff, cMem); zcs->outBuff = NULL; ZSTD_free(zcs, cMem); return 0; } } /*====== Initialization ======*/ size_t ZSTD_CStreamInSize(void) { return ZSTD_BLOCKSIZE_ABSOLUTEMAX; } size_t ZSTD_CStreamOutSize(void) { return ZSTD_compressBound(ZSTD_BLOCKSIZE_ABSOLUTEMAX) + ZSTD_blockHeaderSize + 4 /* 32-bits hash */; } static size_t ZSTD_resetCStream_internal(ZSTD_CStream *zcs, unsigned long long pledgedSrcSize) { if (zcs->inBuffSize == 0) return ERROR(stage_wrong); /* zcs has not been init at least once => can't reset */ if (zcs->cdict) CHECK_F(ZSTD_compressBegin_usingCDict(zcs->cctx, zcs->cdict, pledgedSrcSize)) else CHECK_F(ZSTD_compressBegin_advanced(zcs->cctx, NULL, 0, zcs->params, pledgedSrcSize)); zcs->inToCompress = 0; zcs->inBuffPos = 0; zcs->inBuffTarget = zcs->blockSize; zcs->outBuffContentSize = zcs->outBuffFlushedSize = 0; zcs->stage = zcss_load; zcs->frameEnded = 0; zcs->pledgedSrcSize = pledgedSrcSize; zcs->inputProcessed = 0; return 0; /* ready to go */ } size_t ZSTD_resetCStream(ZSTD_CStream *zcs, unsigned long long pledgedSrcSize) { zcs->params.fParams.contentSizeFlag = (pledgedSrcSize > 0); return ZSTD_resetCStream_internal(zcs, pledgedSrcSize); } static size_t ZSTD_initCStream_advanced(ZSTD_CStream *zcs, const void *dict, size_t dictSize, ZSTD_parameters params, unsigned long long pledgedSrcSize) { /* allocate buffers */ { size_t const neededInBuffSize = (size_t)1 << params.cParams.windowLog; if (zcs->inBuffSize < neededInBuffSize) { zcs->inBuffSize = neededInBuffSize; ZSTD_free(zcs->inBuff, zcs->customMem); zcs->inBuff = (char *)ZSTD_malloc(neededInBuffSize, zcs->customMem); if (zcs->inBuff == NULL) return ERROR(memory_allocation); } zcs->blockSize = MIN(ZSTD_BLOCKSIZE_ABSOLUTEMAX, neededInBuffSize); } if (zcs->outBuffSize < ZSTD_compressBound(zcs->blockSize) + 1) { zcs->outBuffSize = ZSTD_compressBound(zcs->blockSize) + 1; ZSTD_free(zcs->outBuff, zcs->customMem); zcs->outBuff = (char *)ZSTD_malloc(zcs->outBuffSize, zcs->customMem); if (zcs->outBuff == NULL) return ERROR(memory_allocation); } if (dict && dictSize >= 8) { ZSTD_freeCDict(zcs->cdictLocal); zcs->cdictLocal = ZSTD_createCDict_advanced(dict, dictSize, 0, params, zcs->customMem); if (zcs->cdictLocal == NULL) return ERROR(memory_allocation); zcs->cdict = zcs->cdictLocal; } else zcs->cdict = NULL; zcs->checksum = params.fParams.checksumFlag > 0; zcs->params = params; return ZSTD_resetCStream_internal(zcs, pledgedSrcSize); } ZSTD_CStream *ZSTD_initCStream(ZSTD_parameters params, unsigned long long pledgedSrcSize, void *workspace, size_t workspaceSize) { ZSTD_customMem const stackMem = ZSTD_initStack(workspace, workspaceSize); ZSTD_CStream *const zcs = ZSTD_createCStream_advanced(stackMem); if (zcs) { size_t const code = ZSTD_initCStream_advanced(zcs, NULL, 0, params, pledgedSrcSize); if (ZSTD_isError(code)) { return NULL; } } return zcs; } ZSTD_CStream *ZSTD_initCStream_usingCDict(const ZSTD_CDict *cdict, unsigned long long pledgedSrcSize, void *workspace, size_t workspaceSize) { ZSTD_parameters const params = ZSTD_getParamsFromCDict(cdict); ZSTD_CStream *const zcs = ZSTD_initCStream(params, pledgedSrcSize, workspace, workspaceSize); if (zcs) { zcs->cdict = cdict; if (ZSTD_isError(ZSTD_resetCStream_internal(zcs, pledgedSrcSize))) { return NULL; } } return zcs; } /*====== Compression ======*/ typedef enum { zsf_gather, zsf_flush, zsf_end } ZSTD_flush_e; ZSTD_STATIC size_t ZSTD_limitCopy(void *dst, size_t dstCapacity, const void *src, size_t srcSize) { size_t const length = MIN(dstCapacity, srcSize); memcpy(dst, src, length); return length; } static size_t ZSTD_compressStream_generic(ZSTD_CStream *zcs, void *dst, size_t *dstCapacityPtr, const void *src, size_t *srcSizePtr, ZSTD_flush_e const flush) { U32 someMoreWork = 1; const char *const istart = (const char *)src; const char *const iend = istart + *srcSizePtr; const char *ip = istart; char *const ostart = (char *)dst; char *const oend = ostart + *dstCapacityPtr; char *op = ostart; while (someMoreWork) { switch (zcs->stage) { case zcss_init: return ERROR(init_missing); /* call ZBUFF_compressInit() first ! */ case zcss_load: /* complete inBuffer */ { size_t const toLoad = zcs->inBuffTarget - zcs->inBuffPos; size_t const loaded = ZSTD_limitCopy(zcs->inBuff + zcs->inBuffPos, toLoad, ip, iend - ip); zcs->inBuffPos += loaded; ip += loaded; if ((zcs->inBuffPos == zcs->inToCompress) || (!flush && (toLoad != loaded))) { someMoreWork = 0; break; /* not enough input to get a full block : stop there, wait for more */ } } /* compress curr block (note : this stage cannot be stopped in the middle) */ { void *cDst; size_t cSize; size_t const iSize = zcs->inBuffPos - zcs->inToCompress; size_t oSize = oend - op; if (oSize >= ZSTD_compressBound(iSize)) cDst = op; /* compress directly into output buffer (avoid flush stage) */ else cDst = zcs->outBuff, oSize = zcs->outBuffSize; cSize = (flush == zsf_end) ? ZSTD_compressEnd(zcs->cctx, cDst, oSize, zcs->inBuff + zcs->inToCompress, iSize) : ZSTD_compressContinue(zcs->cctx, cDst, oSize, zcs->inBuff + zcs->inToCompress, iSize); if (ZSTD_isError(cSize)) return cSize; if (flush == zsf_end) zcs->frameEnded = 1; /* prepare next block */ zcs->inBuffTarget = zcs->inBuffPos + zcs->blockSize; if (zcs->inBuffTarget > zcs->inBuffSize) zcs->inBuffPos = 0, zcs->inBuffTarget = zcs->blockSize; /* note : inBuffSize >= blockSize */ zcs->inToCompress = zcs->inBuffPos; if (cDst == op) { op += cSize; break; } /* no need to flush */ zcs->outBuffContentSize = cSize; zcs->outBuffFlushedSize = 0; zcs->stage = zcss_flush; /* pass-through to flush stage */ } fallthrough; case zcss_flush: { size_t const toFlush = zcs->outBuffContentSize - zcs->outBuffFlushedSize; size_t const flushed = ZSTD_limitCopy(op, oend - op, zcs->outBuff + zcs->outBuffFlushedSize, toFlush); op += flushed; zcs->outBuffFlushedSize += flushed; if (toFlush != flushed) { someMoreWork = 0; break; } /* dst too small to store flushed data : stop there */ zcs->outBuffContentSize = zcs->outBuffFlushedSize = 0; zcs->stage = zcss_load; break; } case zcss_final: someMoreWork = 0; /* do nothing */ break; default: return ERROR(GENERIC); /* impossible */ } } *srcSizePtr = ip - istart; *dstCapacityPtr = op - ostart; zcs->inputProcessed += *srcSizePtr; if (zcs->frameEnded) return 0; { size_t hintInSize = zcs->inBuffTarget - zcs->inBuffPos; if (hintInSize == 0) hintInSize = zcs->blockSize; return hintInSize; } } size_t ZSTD_compressStream(ZSTD_CStream *zcs, ZSTD_outBuffer *output, ZSTD_inBuffer *input) { size_t sizeRead = input->size - input->pos; size_t sizeWritten = output->size - output->pos; size_t const result = ZSTD_compressStream_generic(zcs, (char *)(output->dst) + output->pos, &sizeWritten, (const char *)(input->src) + input->pos, &sizeRead, zsf_gather); input->pos += sizeRead; output->pos += sizeWritten; return result; } /*====== Finalize ======*/ /*! ZSTD_flushStream() : * @return : amount of data remaining to flush */ size_t ZSTD_flushStream(ZSTD_CStream *zcs, ZSTD_outBuffer *output) { size_t srcSize = 0; size_t sizeWritten = output->size - output->pos; size_t const result = ZSTD_compressStream_generic(zcs, (char *)(output->dst) + output->pos, &sizeWritten, &srcSize, &srcSize, /* use a valid src address instead of NULL */ zsf_flush); output->pos += sizeWritten; if (ZSTD_isError(result)) return result; return zcs->outBuffContentSize - zcs->outBuffFlushedSize; /* remaining to flush */ } size_t ZSTD_endStream(ZSTD_CStream *zcs, ZSTD_outBuffer *output) { BYTE *const ostart = (BYTE *)(output->dst) + output->pos; BYTE *const oend = (BYTE *)(output->dst) + output->size; BYTE *op = ostart; if ((zcs->pledgedSrcSize) && (zcs->inputProcessed != zcs->pledgedSrcSize)) return ERROR(srcSize_wrong); /* pledgedSrcSize not respected */ if (zcs->stage != zcss_final) { /* flush whatever remains */ size_t srcSize = 0; size_t sizeWritten = output->size - output->pos; size_t const notEnded = ZSTD_compressStream_generic(zcs, ostart, &sizeWritten, &srcSize, &srcSize, zsf_end); /* use a valid src address instead of NULL */ size_t const remainingToFlush = zcs->outBuffContentSize - zcs->outBuffFlushedSize; op += sizeWritten; if (remainingToFlush) { output->pos += sizeWritten; return remainingToFlush + ZSTD_BLOCKHEADERSIZE /* final empty block */ + (zcs->checksum * 4); } /* create epilogue */ zcs->stage = zcss_final; zcs->outBuffContentSize = !notEnded ? 0 : ZSTD_compressEnd(zcs->cctx, zcs->outBuff, zcs->outBuffSize, NULL, 0); /* write epilogue, including final empty block, into outBuff */ } /* flush epilogue */ { size_t const toFlush = zcs->outBuffContentSize - zcs->outBuffFlushedSize; size_t const flushed = ZSTD_limitCopy(op, oend - op, zcs->outBuff + zcs->outBuffFlushedSize, toFlush); op += flushed; zcs->outBuffFlushedSize += flushed; output->pos += op - ostart; if (toFlush == flushed) zcs->stage = zcss_init; /* end reached */ return toFlush - flushed; } } /*-===== Pre-defined compression levels =====-*/ #define ZSTD_DEFAULT_CLEVEL 1 #define ZSTD_MAX_CLEVEL 22 int ZSTD_maxCLevel(void) { return ZSTD_MAX_CLEVEL; } static const ZSTD_compressionParameters ZSTD_defaultCParameters[4][ZSTD_MAX_CLEVEL + 1] = { { /* "default" */ /* W, C, H, S, L, TL, strat */ {18, 12, 12, 1, 7, 16, ZSTD_fast}, /* level 0 - never used */ {19, 13, 14, 1, 7, 16, ZSTD_fast}, /* level 1 */ {19, 15, 16, 1, 6, 16, ZSTD_fast}, /* level 2 */ {20, 16, 17, 1, 5, 16, ZSTD_dfast}, /* level 3.*/ {20, 18, 18, 1, 5, 16, ZSTD_dfast}, /* level 4.*/ {20, 15, 18, 3, 5, 16, ZSTD_greedy}, /* level 5 */ {21, 16, 19, 2, 5, 16, ZSTD_lazy}, /* level 6 */ {21, 17, 20, 3, 5, 16, ZSTD_lazy}, /* level 7 */ {21, 18, 20, 3, 5, 16, ZSTD_lazy2}, /* level 8 */ {21, 20, 20, 3, 5, 16, ZSTD_lazy2}, /* level 9 */ {21, 19, 21, 4, 5, 16, ZSTD_lazy2}, /* level 10 */ {22, 20, 22, 4, 5, 16, ZSTD_lazy2}, /* level 11 */ {22, 20, 22, 5, 5, 16, ZSTD_lazy2}, /* level 12 */ {22, 21, 22, 5, 5, 16, ZSTD_lazy2}, /* level 13 */ {22, 21, 22, 6, 5, 16, ZSTD_lazy2}, /* level 14 */ {22, 21, 21, 5, 5, 16, ZSTD_btlazy2}, /* level 15 */ {23, 22, 22, 5, 5, 16, ZSTD_btlazy2}, /* level 16 */ {23, 21, 22, 4, 5, 24, ZSTD_btopt}, /* level 17 */ {23, 23, 22, 6, 5, 32, ZSTD_btopt}, /* level 18 */ {23, 23, 22, 6, 3, 48, ZSTD_btopt}, /* level 19 */ {25, 25, 23, 7, 3, 64, ZSTD_btopt2}, /* level 20 */ {26, 26, 23, 7, 3, 256, ZSTD_btopt2}, /* level 21 */ {27, 27, 25, 9, 3, 512, ZSTD_btopt2}, /* level 22 */ }, { /* for srcSize <= 256 KB */ /* W, C, H, S, L, T, strat */ {0, 0, 0, 0, 0, 0, ZSTD_fast}, /* level 0 - not used */ {18, 13, 14, 1, 6, 8, ZSTD_fast}, /* level 1 */ {18, 14, 13, 1, 5, 8, ZSTD_dfast}, /* level 2 */ {18, 16, 15, 1, 5, 8, ZSTD_dfast}, /* level 3 */ {18, 15, 17, 1, 5, 8, ZSTD_greedy}, /* level 4.*/ {18, 16, 17, 4, 5, 8, ZSTD_greedy}, /* level 5.*/ {18, 16, 17, 3, 5, 8, ZSTD_lazy}, /* level 6.*/ {18, 17, 17, 4, 4, 8, ZSTD_lazy}, /* level 7 */ {18, 17, 17, 4, 4, 8, ZSTD_lazy2}, /* level 8 */ {18, 17, 17, 5, 4, 8, ZSTD_lazy2}, /* level 9 */ {18, 17, 17, 6, 4, 8, ZSTD_lazy2}, /* level 10 */ {18, 18, 17, 6, 4, 8, ZSTD_lazy2}, /* level 11.*/ {18, 18, 17, 7, 4, 8, ZSTD_lazy2}, /* level 12.*/ {18, 19, 17, 6, 4, 8, ZSTD_btlazy2}, /* level 13 */ {18, 18, 18, 4, 4, 16, ZSTD_btopt}, /* level 14.*/ {18, 18, 18, 4, 3, 16, ZSTD_btopt}, /* level 15.*/ {18, 19, 18, 6, 3, 32, ZSTD_btopt}, /* level 16.*/ {18, 19, 18, 8, 3, 64, ZSTD_btopt}, /* level 17.*/ {18, 19, 18, 9, 3, 128, ZSTD_btopt}, /* level 18.*/ {18, 19, 18, 10, 3, 256, ZSTD_btopt}, /* level 19.*/ {18, 19, 18, 11, 3, 512, ZSTD_btopt2}, /* level 20.*/ {18, 19, 18, 12, 3, 512, ZSTD_btopt2}, /* level 21.*/ {18, 19, 18, 13, 3, 512, ZSTD_btopt2}, /* level 22.*/ }, { /* for srcSize <= 128 KB */ /* W, C, H, S, L, T, strat */ {17, 12, 12, 1, 7, 8, ZSTD_fast}, /* level 0 - not used */ {17, 12, 13, 1, 6, 8, ZSTD_fast}, /* level 1 */ {17, 13, 16, 1, 5, 8, ZSTD_fast}, /* level 2 */ {17, 16, 16, 2, 5, 8, ZSTD_dfast}, /* level 3 */ {17, 13, 15, 3, 4, 8, ZSTD_greedy}, /* level 4 */ {17, 15, 17, 4, 4, 8, ZSTD_greedy}, /* level 5 */ {17, 16, 17, 3, 4, 8, ZSTD_lazy}, /* level 6 */ {17, 15, 17, 4, 4, 8, ZSTD_lazy2}, /* level 7 */ {17, 17, 17, 4, 4, 8, ZSTD_lazy2}, /* level 8 */ {17, 17, 17, 5, 4, 8, ZSTD_lazy2}, /* level 9 */ {17, 17, 17, 6, 4, 8, ZSTD_lazy2}, /* level 10 */ {17, 17, 17, 7, 4, 8, ZSTD_lazy2}, /* level 11 */ {17, 17, 17, 8, 4, 8, ZSTD_lazy2}, /* level 12 */ {17, 18, 17, 6, 4, 8, ZSTD_btlazy2}, /* level 13.*/ {17, 17, 17, 7, 3, 8, ZSTD_btopt}, /* level 14.*/ {17, 17, 17, 7, 3, 16, ZSTD_btopt}, /* level 15.*/ {17, 18, 17, 7, 3, 32, ZSTD_btopt}, /* level 16.*/ {17, 18, 17, 7, 3, 64, ZSTD_btopt}, /* level 17.*/ {17, 18, 17, 7, 3, 256, ZSTD_btopt}, /* level 18.*/ {17, 18, 17, 8, 3, 256, ZSTD_btopt}, /* level 19.*/ {17, 18, 17, 9, 3, 256, ZSTD_btopt2}, /* level 20.*/ {17, 18, 17, 10, 3, 256, ZSTD_btopt2}, /* level 21.*/ {17, 18, 17, 11, 3, 512, ZSTD_btopt2}, /* level 22.*/ }, { /* for srcSize <= 16 KB */ /* W, C, H, S, L, T, strat */ {14, 12, 12, 1, 7, 6, ZSTD_fast}, /* level 0 - not used */ {14, 14, 14, 1, 6, 6, ZSTD_fast}, /* level 1 */ {14, 14, 14, 1, 4, 6, ZSTD_fast}, /* level 2 */ {14, 14, 14, 1, 4, 6, ZSTD_dfast}, /* level 3.*/ {14, 14, 14, 4, 4, 6, ZSTD_greedy}, /* level 4.*/ {14, 14, 14, 3, 4, 6, ZSTD_lazy}, /* level 5.*/ {14, 14, 14, 4, 4, 6, ZSTD_lazy2}, /* level 6 */ {14, 14, 14, 5, 4, 6, ZSTD_lazy2}, /* level 7 */ {14, 14, 14, 6, 4, 6, ZSTD_lazy2}, /* level 8.*/ {14, 15, 14, 6, 4, 6, ZSTD_btlazy2}, /* level 9.*/ {14, 15, 14, 3, 3, 6, ZSTD_btopt}, /* level 10.*/ {14, 15, 14, 6, 3, 8, ZSTD_btopt}, /* level 11.*/ {14, 15, 14, 6, 3, 16, ZSTD_btopt}, /* level 12.*/ {14, 15, 14, 6, 3, 24, ZSTD_btopt}, /* level 13.*/ {14, 15, 15, 6, 3, 48, ZSTD_btopt}, /* level 14.*/ {14, 15, 15, 6, 3, 64, ZSTD_btopt}, /* level 15.*/ {14, 15, 15, 6, 3, 96, ZSTD_btopt}, /* level 16.*/ {14, 15, 15, 6, 3, 128, ZSTD_btopt}, /* level 17.*/ {14, 15, 15, 6, 3, 256, ZSTD_btopt}, /* level 18.*/ {14, 15, 15, 7, 3, 256, ZSTD_btopt}, /* level 19.*/ {14, 15, 15, 8, 3, 256, ZSTD_btopt2}, /* level 20.*/ {14, 15, 15, 9, 3, 256, ZSTD_btopt2}, /* level 21.*/ {14, 15, 15, 10, 3, 256, ZSTD_btopt2}, /* level 22.*/ }, }; /*! ZSTD_getCParams() : * @return ZSTD_compressionParameters structure for a selected compression level, `srcSize` and `dictSize`. * Size values are optional, provide 0 if not known or unused */ ZSTD_compressionParameters ZSTD_getCParams(int compressionLevel, unsigned long long srcSize, size_t dictSize) { ZSTD_compressionParameters cp; size_t const addedSize = srcSize ? 0 : 500; U64 const rSize = srcSize + dictSize ? srcSize + dictSize + addedSize : (U64)-1; U32 const tableID = (rSize <= 256 KB) + (rSize <= 128 KB) + (rSize <= 16 KB); /* intentional underflow for srcSizeHint == 0 */ if (compressionLevel <= 0) compressionLevel = ZSTD_DEFAULT_CLEVEL; /* 0 == default; no negative compressionLevel yet */ if (compressionLevel > ZSTD_MAX_CLEVEL) compressionLevel = ZSTD_MAX_CLEVEL; cp = ZSTD_defaultCParameters[tableID][compressionLevel]; if (ZSTD_32bits()) { /* auto-correction, for 32-bits mode */ if (cp.windowLog > ZSTD_WINDOWLOG_MAX) cp.windowLog = ZSTD_WINDOWLOG_MAX; if (cp.chainLog > ZSTD_CHAINLOG_MAX) cp.chainLog = ZSTD_CHAINLOG_MAX; if (cp.hashLog > ZSTD_HASHLOG_MAX) cp.hashLog = ZSTD_HASHLOG_MAX; } cp = ZSTD_adjustCParams(cp, srcSize, dictSize); return cp; } /*! ZSTD_getParams() : * same as ZSTD_getCParams(), but @return a `ZSTD_parameters` object (instead of `ZSTD_compressionParameters`). * All fields of `ZSTD_frameParameters` are set to default (0) */ ZSTD_parameters ZSTD_getParams(int compressionLevel, unsigned long long srcSize, size_t dictSize) { ZSTD_parameters params; ZSTD_compressionParameters const cParams = ZSTD_getCParams(compressionLevel, srcSize, dictSize); memset(&params, 0, sizeof(params)); params.cParams = cParams; return params; } EXPORT_SYMBOL(ZSTD_maxCLevel); EXPORT_SYMBOL(ZSTD_compressBound); EXPORT_SYMBOL(ZSTD_CCtxWorkspaceBound); EXPORT_SYMBOL(ZSTD_initCCtx); EXPORT_SYMBOL(ZSTD_compressCCtx); EXPORT_SYMBOL(ZSTD_compress_usingDict); EXPORT_SYMBOL(ZSTD_CDictWorkspaceBound); EXPORT_SYMBOL(ZSTD_initCDict); EXPORT_SYMBOL(ZSTD_compress_usingCDict); EXPORT_SYMBOL(ZSTD_CStreamWorkspaceBound); EXPORT_SYMBOL(ZSTD_initCStream); EXPORT_SYMBOL(ZSTD_initCStream_usingCDict); EXPORT_SYMBOL(ZSTD_resetCStream); EXPORT_SYMBOL(ZSTD_compressStream); EXPORT_SYMBOL(ZSTD_flushStream); EXPORT_SYMBOL(ZSTD_endStream); EXPORT_SYMBOL(ZSTD_CStreamInSize); EXPORT_SYMBOL(ZSTD_CStreamOutSize); EXPORT_SYMBOL(ZSTD_getCParams); EXPORT_SYMBOL(ZSTD_getParams); EXPORT_SYMBOL(ZSTD_checkCParams); EXPORT_SYMBOL(ZSTD_adjustCParams); EXPORT_SYMBOL(ZSTD_compressBegin); EXPORT_SYMBOL(ZSTD_compressBegin_usingDict); EXPORT_SYMBOL(ZSTD_compressBegin_advanced); EXPORT_SYMBOL(ZSTD_copyCCtx); EXPORT_SYMBOL(ZSTD_compressBegin_usingCDict); EXPORT_SYMBOL(ZSTD_compressContinue); EXPORT_SYMBOL(ZSTD_compressEnd); EXPORT_SYMBOL(ZSTD_getBlockSizeMax); EXPORT_SYMBOL(ZSTD_compressBlock); MODULE_LICENSE("Dual BSD/GPL"); MODULE_DESCRIPTION("Zstd Compressor");
37.291165
159
0.676762
[ "object" ]
b08e4ebe0532e3b71bcacfcf9fb69975ff1eae09
3,392
h
C
include/nuttx/eeprom/i2c_xx24xx.h
ccxtechnologies/nuttx
c9f175eea81cfa4b76c005e80ccc90bf8cf9bb18
[ "Apache-2.0" ]
null
null
null
include/nuttx/eeprom/i2c_xx24xx.h
ccxtechnologies/nuttx
c9f175eea81cfa4b76c005e80ccc90bf8cf9bb18
[ "Apache-2.0" ]
51
2021-06-30T20:08:24.000Z
2021-09-15T15:07:01.000Z
include/nuttx/eeprom/i2c_xx24xx.h
ccxtechnologies/nuttx
c9f175eea81cfa4b76c005e80ccc90bf8cf9bb18
[ "Apache-2.0" ]
null
null
null
/**************************************************************************** * include/nuttx/eeprom/i2c_xx24xx.h * * 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. * ****************************************************************************/ #ifndef __INCLUDE_NUTTX_EEPROM_I2C_XX24XX_H #define __INCLUDE_NUTTX_EEPROM_I2C_XX24XX_H /**************************************************************************** * Public Types ****************************************************************************/ /* DO NOT CHANGE ORDER, IT MATCHES CODE IN drivers/eeprom/i2c_xx24xx.c */ enum eeprom_24xx_e { /* Microchip geometries */ EEPROM_24XX00, EEPROM_24XX01, EEPROM_24XX02, EEPROM_24XX04, EEPROM_24XX08, EEPROM_24XX16, EEPROM_24XX32, EEPROM_24XX64, EEPROM_24XX128, EEPROM_24XX256, EEPROM_24XX512, EEPROM_24XX1025, EEPROM_24XX1026, EEPROM_24CM02, /* Atmel geometries - none... */ /* STM geometries */ EEPROM_M24C01, EEPROM_M24C02, EEPROM_M24M02, /* Aliases (devices similar to previously defined ones) */ EEPROM_AT24C01 = EEPROM_24XX01, EEPROM_AT24C02 = EEPROM_24XX02, EEPROM_AT24C04 = EEPROM_24XX04, EEPROM_AT24C08 = EEPROM_24XX08, EEPROM_AT24C16 = EEPROM_24XX16, EEPROM_AT24C32 = EEPROM_24XX32, EEPROM_AT24C64 = EEPROM_24XX64, EEPROM_AT24C128 = EEPROM_24XX128, EEPROM_AT24C256 = EEPROM_24XX256, EEPROM_AT24C512 = EEPROM_24XX512, EEPROM_AT24C1024 = EEPROM_24XX1026, EEPROM_AT24CM02 = EEPROM_24CM02, EEPROM_M24C04 = EEPROM_24XX04, EEPROM_M24C08 = EEPROM_24XX08, EEPROM_M24C16 = EEPROM_24XX16, EEPROM_M24C32 = EEPROM_24XX32, EEPROM_M24C64 = EEPROM_24XX64, EEPROM_M24128 = EEPROM_24XX128, EEPROM_M24256 = EEPROM_24XX256, EEPROM_M24512 = EEPROM_24XX512, EEPROM_M24M01 = EEPROM_24XX1026, }; /**************************************************************************** * Public Function Prototypes ****************************************************************************/ /**************************************************************************** * Name: ee24xx_initialize * * Description: Bind a EEPROM driver to an I2C bus. The user MUST provide * a description of the device geometry, since it is not possible to read * this information from the device (contrary to the SPI flash devices). * ****************************************************************************/ struct i2c_master_s; int ee24xx_initialize(FAR struct i2c_master_s *bus, uint8_t devaddr, FAR const char *devname, int devtype, int readonly); #endif /* __INCLUDE__NUTTX_EEPROM_I2C_XX24XX_H */
33.584158
78
0.609965
[ "geometry" ]
b0917c8c762370a8e084f4194afe8b39234fd2d3
2,359
h
C
src/providers/CIM_DiskDrive/CIM_DiskDrive_Provider.h
LegalizeAdulthood/cimple
5ec70784f2ee3e455a2258f82b07c0dacccb4093
[ "MIT" ]
4
2015-12-16T06:43:14.000Z
2020-01-24T06:05:47.000Z
src/providers/CIM_DiskDrive/CIM_DiskDrive_Provider.h
LegalizeAdulthood/cimple
5ec70784f2ee3e455a2258f82b07c0dacccb4093
[ "MIT" ]
null
null
null
src/providers/CIM_DiskDrive/CIM_DiskDrive_Provider.h
LegalizeAdulthood/cimple
5ec70784f2ee3e455a2258f82b07c0dacccb4093
[ "MIT" ]
null
null
null
#ifndef _CIM_DiskDrive_Provider_h #define _CIM_DiskDrive_Provider_h #include <cimple/cimple.h> #include "CIM_DiskDrive.h" CIMPLE_NAMESPACE_BEGIN class CIM_DiskDrive_Provider { public: typedef CIM_DiskDrive Class; CIM_DiskDrive_Provider(); ~CIM_DiskDrive_Provider(); Load_Status load(); Unload_Status unload(); Get_Instance_Status get_instance( const CIM_DiskDrive* model, CIM_DiskDrive*& instance); Enum_Instances_Status enum_instances( const CIM_DiskDrive* model, Enum_Instances_Handler<CIM_DiskDrive>* handler); Create_Instance_Status create_instance( CIM_DiskDrive* instance); Delete_Instance_Status delete_instance( const CIM_DiskDrive* instance); Modify_Instance_Status modify_instance( const CIM_DiskDrive* model, const CIM_DiskDrive* instance); Invoke_Method_Status RequestStateChange( const CIM_DiskDrive* self, const Property<uint16>& RequestedState, CIM_ConcreteJob*& Job, const Property<Datetime>& TimeoutPeriod, Property<uint32>& return_value); Invoke_Method_Status SetPowerState( const CIM_DiskDrive* self, const Property<uint16>& PowerState, const Property<Datetime>& Time, Property<uint32>& return_value); Invoke_Method_Status Reset( const CIM_DiskDrive* self, Property<uint32>& return_value); Invoke_Method_Status EnableDevice( const CIM_DiskDrive* self, const Property<boolean>& Enabled, Property<uint32>& return_value); Invoke_Method_Status OnlineDevice( const CIM_DiskDrive* self, const Property<boolean>& Online, Property<uint32>& return_value); Invoke_Method_Status QuiesceDevice( const CIM_DiskDrive* self, const Property<boolean>& Quiesce, Property<uint32>& return_value); Invoke_Method_Status SaveProperties( const CIM_DiskDrive* self, Property<uint32>& return_value); Invoke_Method_Status RestoreProperties( const CIM_DiskDrive* self, Property<uint32>& return_value); Invoke_Method_Status LockMedia( const CIM_DiskDrive* self, const Property<boolean>& Lock, Property<uint32>& return_value); }; CIMPLE_NAMESPACE_END #endif /* _CIM_DiskDrive_Provider_h */
26.211111
56
0.704112
[ "model" ]
b09b74fd85f560adcdfc01fca962f2b33472eea8
2,597
h
C
Sources/Core/Manager/RenderpassManager.h
vgabi94/Lava-Engine
ab5b89d7379b2d0f7398fb2f4dae5b14baa7fd19
[ "MIT" ]
null
null
null
Sources/Core/Manager/RenderpassManager.h
vgabi94/Lava-Engine
ab5b89d7379b2d0f7398fb2f4dae5b14baa7fd19
[ "MIT" ]
null
null
null
Sources/Core/Manager/RenderpassManager.h
vgabi94/Lava-Engine
ab5b89d7379b2d0f7398fb2f4dae5b14baa7fd19
[ "MIT" ]
null
null
null
#pragma once #include <Common\Constants.h> #include <RenderPass\RenderPass.h> #include <string> #include <unordered_map> #define GRenderpassManager Engine::g_RenderpassManager #define RP Engine::RPConst namespace Engine { // Render pass constant names namespace RPConst { static constexpr const char* FRAME = "framePass"; static constexpr const char* SKY = "skyPass"; static constexpr const char* PRENV = "prenvPass"; static constexpr const char* BRDF = "brdfPass"; static constexpr const char* UI = "uiPass"; } class RenderpassManager { static constexpr uint32_t RENDERPASS_CAPACITY = 2; public: void Init(); void PostShaderLoadInit(); void PostSwapchainInit(); void Destroy(); template<typename T> T* AddPass(const std::string& name) { THROW_IF(mPassMap.find(name) != mPassMap.end(), "RenderPass already added: {0}", name.c_str()); RenderPass* pass = T::Allocate(); pass->Init(); mPass.push_back(pass); mPassMap[name] = pass; return static_cast<T*>(pass); } template<typename T> T* AddPassTask(uint32_t& index, const std::string& name) { RenderPass* pass = T::Allocate(); pass->Init(); if (mPostShader) pass->PostShaderLoadInit(); index = mPassTask.size(); mPassTask.push_back(pass); mPassMap[name] = pass; return static_cast<T*>(pass); } template<typename T = RenderPass> T* GetPassTaskAt(uint32_t index) const { return reinterpret_cast<T*>(mPassTask[index]); } template<typename T = RenderPass> T* GetPassAt(uint32_t index) const { return reinterpret_cast<T*>(mPass[index]); } template<typename T = RenderPass> T* GetPass(const std::string& name) { THROW_IF(mPassMap.find(name) == mPassMap.end(), "RenderPass {0} is does not exist", name.c_str()); return reinterpret_cast<T*>(mPassMap[name]); } vk::Fence GetFenceAt(uint32_t index) const { return mFence[index]; } void InitPasses(); void SetupPasses(); void RenderPasses(vk::Semaphore& waitSem, vk::PipelineStageFlags waitStage, vk::Semaphore& signalSem); private: void CreateFences(); void DestroyFences(); std::vector<RenderPass*> mPass; // These are task passes which are not totally controlled by these manager. // They can be used for example to generate stuff on the gpu. std::vector<RenderPass*> mPassTask; std::unordered_map<std::string, RenderPass*> mPassMap; std::vector<vk::Fence> mFence; bool mPostShader; }; extern RenderpassManager g_RenderpassManager; }
28.538462
104
0.67578
[ "render", "vector" ]
b09cdbbb524131921c079de4f2216af0237a2145
5,832
h
C
iPhoneOS14.0.sdk/System/Library/Frameworks/CoreData.framework/Headers/NSPersistentStoreResult.h
quiprr/sdks-1
f6735879039f4aea29a75a896b5386dfcc2ddacb
[ "MIT" ]
1
2021-01-16T08:49:06.000Z
2021-01-16T08:49:06.000Z
iPhoneOS14.0.sdk/System/Library/Frameworks/CoreData.framework/Headers/NSPersistentStoreResult.h
quiprr/sdks-1
f6735879039f4aea29a75a896b5386dfcc2ddacb
[ "MIT" ]
null
null
null
iPhoneOS14.0.sdk/System/Library/Frameworks/CoreData.framework/Headers/NSPersistentStoreResult.h
quiprr/sdks-1
f6735879039f4aea29a75a896b5386dfcc2ddacb
[ "MIT" ]
1
2021-01-28T13:52:20.000Z
2021-01-28T13:52:20.000Z
/* NSPersistentStoreResult.h Core Data Copyright (c) 2014-2020, Apple Inc. All rights reserved. */ #import <Foundation/NSArray.h> #import <CoreData/NSFetchRequest.h> NS_ASSUME_NONNULL_BEGIN @class NSError; @class NSProgress; @class NSManagedObjectContext; @class NSFetchRequest; @class NSPersistentStoreAsynchronousResult; @class NSAsynchronousFetchResult; @class NSAsynchronousFetchRequest; typedef NS_ENUM(NSUInteger, NSBatchInsertRequestResultType) { NSBatchInsertRequestResultTypeStatusOnly = 0x0, // Return a status boolean NSBatchInsertRequestResultTypeObjectIDs = 0x1, // Return the object IDs of the rows that were inserted/updated NSBatchInsertRequestResultTypeCount = 0x2 // Return the number of rows that were inserted/updated } API_AVAILABLE(macosx(10.15),ios(13.0),tvos(13.0),watchos(6.0)); typedef NS_ENUM(NSUInteger, NSBatchUpdateRequestResultType) { NSStatusOnlyResultType = 0x0, // Return a status boolean NSUpdatedObjectIDsResultType = 0x1, // Return the object IDs of the rows that were updated NSUpdatedObjectsCountResultType = 0x2 // Return the number of rows that were updated } API_AVAILABLE(macosx(10.10), ios(8.0)); typedef NS_ENUM(NSUInteger, NSBatchDeleteRequestResultType) { NSBatchDeleteResultTypeStatusOnly = 0x0, // Return a status boolean NSBatchDeleteResultTypeObjectIDs = 0x1, // Return the object IDs of the rows that were deleted NSBatchDeleteResultTypeCount = 0x2, // Return the number of rows that were deleted } API_AVAILABLE(macosx(10.11), ios(9.0)); typedef NS_ENUM(NSInteger, NSPersistentHistoryResultType) { NSPersistentHistoryResultTypeStatusOnly = 0x0, // Return a status boolean NSPersistentHistoryResultTypeObjectIDs = 0x1, // Return the object IDs of the changes objects NSPersistentHistoryResultTypeCount = 0x2, // Return the number of transactions NSPersistentHistoryResultTypeTransactionsOnly = 0x3, // Return NSPersistentHistoryTransaction objects NSPersistentHistoryResultTypeChangesOnly = 0x4, // Return NSPersistentHistoryChange objects NSPersistentHistoryResultTypeTransactionsAndChanges = 0x5, // Return NSPersistentHistoryTransaction objects with related NSPersistentHistoryChange objects } API_AVAILABLE(macosx(10.13),ios(11.0),tvos(11.0),watchos(4.0)); // Used to wrap the result of whatever is returned by the persistent store coordinator when // -[NSManagedObjectContext executeRequest:error:] is called API_AVAILABLE(macosx(10.10),ios(8.0)) @interface NSPersistentStoreResult : NSObject @end API_AVAILABLE(macosx(10.10),ios(8.0)) @interface NSPersistentStoreAsynchronousResult : NSPersistentStoreResult { } @property (strong, readonly) NSManagedObjectContext* managedObjectContext; @property (nullable, strong, readonly) NSError* operationError; @property (nullable, strong, readonly) NSProgress* progress; - (void)cancel; @end API_AVAILABLE(macosx(10.10),ios(8.0)) @interface NSAsynchronousFetchResult<ResultType:id<NSFetchRequestResult>> : NSPersistentStoreAsynchronousResult { } @property (strong, readonly) NSAsynchronousFetchRequest<ResultType> * fetchRequest; @property (nullable, strong, readonly) NSArray<ResultType> * finalResult; @end // The result returned when executing an NSBatchInsertRequest API_AVAILABLE(macosx(10.15),ios(13.0),tvos(13.0),watchos(6.0)) @interface NSBatchInsertResult : NSPersistentStoreResult { } // Return the result. See NSBatchInsertRequestResultType for options @property (nullable, strong, readonly) id result; @property (readonly) NSBatchInsertRequestResultType resultType; @end // The result returned when executing an NSBatchUpdateRequest API_AVAILABLE(macosx(10.10),ios(8.0)) @interface NSBatchUpdateResult : NSPersistentStoreResult { } // Return the result. See NSBatchUpdateRequestResultType for options @property (nullable, strong, readonly) id result; @property (readonly) NSBatchUpdateRequestResultType resultType; @end // The result returned when executing an NSBatchDeleteRequest API_AVAILABLE(macosx(10.11),ios(9.0)) @interface NSBatchDeleteResult : NSPersistentStoreResult { } // Return the result. See NSBatchDeleteRequestResultType for options @property (nullable, strong, readonly) id result; @property (readonly) NSBatchDeleteRequestResultType resultType; @end // The result returned when executing an NSPersistentHistoryChangeRequest API_AVAILABLE(macosx(10.13),ios(11.0),tvos(11.0),watchos(4.0)) @interface NSPersistentHistoryResult : NSPersistentStoreResult { } // Return the result. See NSPersistentHistoryResultType for options @property (nullable, strong, readonly) id result; @property (readonly) NSPersistentHistoryResultType resultType; @end typedef NS_ENUM(NSInteger, NSPersistentCloudKitContainerEventResultType) { NSPersistentCloudKitContainerEventResultTypeEvents = 0, //the result is an NSArray<NSPersistentCloudKitContainerEvent *> NSPersistentCloudKitContainerEventResultTypeCountEvents //the result is an NSArray<NSNumber *> indicating the count of events matching the request } API_AVAILABLE(macosx(10.16),ios(14.0),tvos(14.0),watchos(7.0)) NS_SWIFT_NAME(NSPersistentCloudKitContainerEventResult.ResultType); // The result returned when executing an NSPersistentCloudKitContainerEventRequest API_AVAILABLE(macosx(10.16),ios(14.0),tvos(14.0),watchos(7.0)) @interface NSPersistentCloudKitContainerEventResult : NSPersistentStoreResult // Return the result. See NSPersistentCloudKitContainerEventResultType for options @property (nullable, strong, readonly) id result; @property (readonly) NSPersistentCloudKitContainerEventResultType resultType; - (instancetype)init NS_UNAVAILABLE; + (instancetype)new NS_UNAVAILABLE; @end NS_ASSUME_NONNULL_END
41.070423
159
0.789952
[ "object" ]
b0a15ce68defdeba9814236877c2ab5ee75d3815
3,468
h
C
image2gb.h
DaSalba/Image2GB
1b3b4c441eb209b044f6ce82675e88fe64f8bb87
[ "MIT" ]
1
2020-06-17T10:53:06.000Z
2020-06-17T10:53:06.000Z
image2gb.h
DaSalba/Image2GB
1b3b4c441eb209b044f6ce82675e88fe64f8bb87
[ "MIT" ]
null
null
null
image2gb.h
DaSalba/Image2GB
1b3b4c441eb209b044f6ce82675e88fe64f8bb87
[ "MIT" ]
null
null
null
/** * @file image2gb.h * @brief GIMP plugin to export an image to Game Boy data (C code, for use with GBDK). (header) */ #ifndef IMAGE2GB_H_INCLUDED #define IMAGE2GB_H_INCLUDED // Ignore warnings in external libraries (GIMP, GTK...). #pragma GCC system_header #include <libgimp/gimp.h> #include <libgimp/gimpui.h> #include <ctype.h> // DEFINITIONS ///////////////////////////////////////////////////////////////// #define IMAGE2GB_BINARY_NAME "image2gb" /**< Name of the output binary. */ #define IMAGE2GB_PROCEDURE_MENU "Image2GB-menu" /**< Name of the procedure registered as menu entry. */ #define IMAGE2GB_PROCEDURE_SAVE "Image2GB-export" /**< Name of the procedure registered as save handler. */ #define IMAGE2GB_DESCRIPTION_SHORT "Export image to Game Boy data" #define IMAGE2GB_DESCRIPTION_LONG "Exports an indexed 4-color image to Game Boy data (C code, for use with GBDK)." #define IMAGE2GB_AUTHOR "DaSalba" #define IMAGE2GB_COPYRIGHT "Copyright (c) 2020 DaSalba" #define IMAGE2GB_DATE "2020" #define IMAGE2GB_MENU_NAME "Game Boy (GBDK)" /**< Entry that will appear in the menus and "Export as" dialog. */ #define IMAGE2GB_IMAGE_TYPES "INDEXED" /**< What type of images the plugin supports (RGB, GRAY, INDEXED...). */ #define IMAGE2GB_MENU_PATH "<Image>/Tools" /**< Category, and menu path the plugin will appear in. */ #define IMAGE2GB_ASSOCIATED_MIME_TYPE "text/plain" /**< MIME file type that will be associated with this plugin. */ #define IMAGE2GB_ASSOCIATED_EXTENSION "gbdk" /**< File extension that will be associated with this plugin. */ #define IMAGE2GB_ASSET_NAME_MAX_LENGTH 32 /**< Max characters of the asset name used for the C variable identifier. */ #define IMAGE2GB_PARASITE "gbdk-export-options" /**< Cookie to store export parameters between invocations (persistent data). */ /** Object that stores this plugin's export parameters. */ typedef struct PluginExportOptions { gchar name[IMAGE2GB_ASSET_NAME_MAX_LENGTH]; /**< Base name of the image asset to export. */ gchar folder[PATH_MAX]; /**< Full path of the directory to save to. */ gint bank; /**< ROM bank to store the image data in. */ } PluginExportOptions; // FUNCTIONS /////////////////////////////////////////////////////////////////// /** Returns information about this plugin whenever it is loaded or changes. */ static void image2gb_query(void); /** Called when the plugin is run, it does the job. */ static void image2gb_run(const gchar* Sname, gint InumParams, const GimpParam* Gparams, gint* InumReturnVals, GimpParam** GreturnVals); /** Checks the validity of the image for being exported to Game Boy. Returns * TRUE if it is valid, FALSE otherwise. */ static gboolean image2gb_check_image(gint32 IimageID); /** Opens a dialog window to let the user set the export parameters. Returns * the program status. */ static GimpPDBStatusType image2gb_show_dialog(void); /** Callback function for the GTK dialog window ("Export" or "Cancel" clicked). */ static void image2gb_dialog_response(GtkWidget* Wwidget, gint IresponseID, gpointer Pdata); /** Tries to load existing export parameters from the parasite. Returns TRUE if * success, FALSE otherwise. */ static gboolean image2gb_load_parameters(gint32 IimageID); /** Saves the current export parameters using a parasite. */ static void image2gb_save_parameters(gint32 IimageID); #endif // IMAGE2GB_H_INCLUDED
39.862069
128
0.710208
[ "object" ]
b0ac31011c7e9707134ea746326478f22ea300af
1,528
h
C
include/s2s/TexturePacker.h
xzrunner/s2serializer
0c3f48a042f0f359d48d6ab79e8ab9c0aceb2906
[ "MIT" ]
null
null
null
include/s2s/TexturePacker.h
xzrunner/s2serializer
0c3f48a042f0f359d48d6ab79e8ab9c0aceb2906
[ "MIT" ]
null
null
null
include/s2s/TexturePacker.h
xzrunner/s2serializer
0c3f48a042f0f359d48d6ab79e8ab9c0aceb2906
[ "MIT" ]
null
null
null
#pragma once #include <rapidjson/document.h> #include <string> #include <vector> #include <map> #include <memory> namespace s2s { class TexturePacker { public: TexturePacker(const std::string& src_dir); void AddTexture(const std::string& filepath); bool Query(const std::string& filepath, float& xmin, float& xmax, float& ymin, float& ymax, float& offx, float& offy) const; private: struct Region { int x, y; int w, h; void Load(const rapidjson::Value& val); }; struct FrameSrcData { std::string filename; Region frame; bool rotated; bool trimmed; Region sprite_source_size; int src_width, src_height; void Load(const rapidjson::Value& val, const std::string& src_dir); }; struct Texture; struct FrameDstData { // 0 3 // 1 2 float tex_coords[8]; float offset[2]; void Load(const FrameSrcData& src, const Texture& tex); }; struct Frame { FrameSrcData src; FrameDstData dst; int tex_idx; void Load(const rapidjson::Value& val, const std::string& src_dir, const Texture& tex); }; struct Texture { const std::string filepath; int idx; int width, height; std::string format; std::map<std::string, Frame> frames; bool is_easydb; Texture(const std::string& filepath) : filepath(filepath) {} void Load(const rapidjson::Value& val, const std::string& src_dir); const Frame* Query(const std::string& filepath) const; }; private: std::string m_src_dir; std::vector<std::unique_ptr<Texture>> m_textures; }; // TexturePacker }
15.591837
89
0.687827
[ "vector" ]
b0ad89c3aa30c5e72ad1c843b70272dd2234f707
623
h
C
ShipEditor/Source/Editor/object.h
Hopson97/Faster-Than-Wind
17bfc8fc1798b4dc5e6e285de8064255c9eedd3e
[ "MIT" ]
3
2016-12-11T01:39:17.000Z
2018-11-24T20:49:48.000Z
ShipEditor/Source/Editor/object.h
Hopson97/Faster-Than-Wind
17bfc8fc1798b4dc5e6e285de8064255c9eedd3e
[ "MIT" ]
null
null
null
ShipEditor/Source/Editor/object.h
Hopson97/Faster-Than-Wind
17bfc8fc1798b4dc5e6e285de8064255c9eedd3e
[ "MIT" ]
null
null
null
#ifndef OBJECT_H #define OBJECT_H #include <SFML/Graphics.hpp> #include <iostream> class Object { public: Object (const sf::Texture& ghostTexture); virtual void draw (sf::RenderWindow& window); void setPos (const sf::Vector2f pos); sf::Vector2f getPos () const; sf::Sprite getSprite () const; void setColour (const sf::Color& c); void setTextureRect (const sf::IntRect& ); protected: sf::Sprite mSprite; }; #endif // OBJECT_H
23.074074
74
0.505618
[ "object" ]
b0adfe7018e4a48d0474fb870cfead81183ff27c
4,294
h
C
src/environments/Environment.h
litlpoet/beliefbox
6b303e49017f8054f43c6c840686fcc632205e4e
[ "OLDAP-2.3" ]
null
null
null
src/environments/Environment.h
litlpoet/beliefbox
6b303e49017f8054f43c6c840686fcc632205e4e
[ "OLDAP-2.3" ]
null
null
null
src/environments/Environment.h
litlpoet/beliefbox
6b303e49017f8054f43c6c840686fcc632205e4e
[ "OLDAP-2.3" ]
null
null
null
// -*- Mode: c++ -*- // copyright (c) 2008 by Christos Dimitrakakis <christos.dimitrakakis@gmail.com> // $Revision$ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef SRC_ENVIRONMENTS_ENVIRONMENT_H_ #define SRC_ENVIRONMENTS_ENVIRONMENT_H_ #include <cstdlib> #include "MDP.h" #include "Vector.h" /** \defgroup EnvironmentGroup Environments */ /** \ingroup EnvironmentGroup */ /*@{*/ /// Template for environments template <typename S, typename A> class Environment { protected: S state; ///< The current state real reward; ///< The current reward bool endsim; ///< Absorbing state uint n_states; ///< The state dimension uint n_actions; ///< The action dimension S state_lower_bound; ///< lower bound on the states S state_upper_bound; ///< upper bound on the states public: Environment() : n_states(1), n_actions(1) { state_lower_bound = 0; state_upper_bound = 0; reward = 0.0; endsim = false; } Environment(int n_states_, int n_actions_) : n_states(n_states_), n_actions(n_actions_) { state_lower_bound = 0; state_upper_bound = n_states; reward = 0.0; endsim = false; } virtual ~Environment() {} /// put the environment in its "natural: state virtual void Reset() { Serror("Not implemented\n"); exit(-1); } /// returns true if the action succeeds, false if it does not. /// /// The usual of false is that the environment is in a terminal /// absorbing state. virtual bool Act(const A& action) { Serror("Not implemented\n"); exit(-1); return false; } /// Return a full MDP model of the environment. This may not be /// possible for some environments. The MDP is required to be /// freed by the user! virtual MDP<S, A>* getMDP() const { return NULL; } virtual const char* Name() const { return "Undefined environment name"; } // --- The following functions are not supposed to be overwritten.. -- // /// returns a (reference to) the current state const S& getState() const { return state; } /// sets the current state void setState(const S& s_next) { state = s_next; } /// returns the current reward real getReward() const { return reward; } /// indicates if the current state is absorbing or not bool getEndsim() const { return endsim; } void setEndsim(const bool& esim_) { endsim = esim_; } /// returns the number of state dimensions uint getNStates() const { return n_states; } uint getNActions() const { return n_actions; } /// Set the overall randomness of the environment virtual void setRandomness(real randomness) {} const S& StateUpperBound() const { return state_upper_bound; } const S& StateLowerBound() const { return state_lower_bound; } virtual real getTransitionProbability(const S& state, const A& action, const S& next_state) const { Serror("Should be implemented\n"); exit(-1); return 1.0; } virtual real getExpectedReward(const S& state, const A& action) const { Serror("Should be implemented\n"); exit(-1); return 0.0; } }; /// Default type for discrete environments typedef Environment<int, int> DiscreteEnvironment; /// Default type for continuous state environments typedef Environment<Vector, int> ContinuousStateEnvironment; /// Default type for continuous environments typedef Environment<Vector, Vector> ContinuousEnvironment; /// Template for environment generators template <typename S, typename A> class EnvironmentGenerator { public: virtual Environment<S, A>* Generate(bool random = true) = 0; virtual ~EnvironmentGenerator() {} }; /*@}*/ #endif // SRC_ENVIRONMENTS_ENVIRONMENT_H_
30.671429
80
0.624825
[ "vector", "model" ]
b0b0b557462d7eeef5c6a298a77640ce27bb2ea3
78,636
h
C
include/muu/matrix.h
marzer/muu
7045e28d159d978ca56a68e13921e456869e7430
[ "MIT" ]
8
2020-10-09T06:50:26.000Z
2022-02-07T21:08:34.000Z
include/muu/matrix.h
marzer/muu
7045e28d159d978ca56a68e13921e456869e7430
[ "MIT" ]
null
null
null
include/muu/matrix.h
marzer/muu
7045e28d159d978ca56a68e13921e456869e7430
[ "MIT" ]
null
null
null
// This file is a part of muu 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/muu/blob/master/LICENSE for the full license text. // SPDX-License-Identifier: MIT #pragma once /// \file /// \brief Contains the definition of muu::matrix. #include "vector.h" #include "quaternion.h" MUU_DISABLE_WARNINGS; #include <tuple> MUU_ENABLE_WARNINGS; #include "impl/header_start.h" MUU_FORCE_NDEBUG_OPTIMIZATIONS; MUU_DISABLE_SHADOW_WARNINGS; MUU_DISABLE_SUGGEST_WARNINGS; MUU_DISABLE_ARITHMETIC_WARNINGS; MUU_PRAGMA_MSVC(float_control(except, off)) MUU_PRAGMA_MSVC(float_control(precise, off)) //====================================================================================================================== // IMPLEMENTATION DETAILS #if 1 /// \cond namespace muu::impl { struct columnwise_init_tag {}; struct columnwise_copy_tag {}; struct row_major_tuple_tag {}; template <typename Scalar, size_t Rows, size_t Columns> struct MUU_TRIVIAL_ABI matrix_ { vector<Scalar, Rows> m[Columns]; matrix_() noexcept = default; private: #if MUU_MSVC template <size_t Index> MUU_NODISCARD MUU_ALWAYS_INLINE MUU_ATTR(const) static constexpr vector<Scalar, Rows> fill_column_initializer_msvc(Scalar fill) noexcept { return vector<Scalar, Rows>{ fill }; } #endif public: #if MUU_MSVC // internal compiler error: // https://developercommunity2.visualstudio.com/t/C-Internal-Compiler-Error-in-constexpr/1264044 template <size_t... ColumnIndices> explicit constexpr matrix_(value_fill_tag, std::index_sequence<ColumnIndices...>, Scalar fill) noexcept : m{ fill_column_initializer_msvc<ColumnIndices>(fill)... } { static_assert(sizeof...(ColumnIndices) <= Columns); } #else template <size_t... ColumnIndices> explicit constexpr matrix_(value_fill_tag, std::index_sequence<ColumnIndices...>, Scalar fill) noexcept : m{ (MUU_UNUSED(ColumnIndices), vector<Scalar, Rows>{ fill })... } { static_assert(sizeof...(ColumnIndices) <= Columns); } #endif template <typename... T> explicit constexpr matrix_(columnwise_init_tag, T... cols) noexcept // : m{ cols... } { static_assert(sizeof...(T) <= Columns); } template <typename T, size_t... ColumnIndices> explicit constexpr matrix_(columnwise_copy_tag, std::index_sequence<ColumnIndices...>, const T& cols) noexcept : m{ vector<Scalar, Rows>{ cols[ColumnIndices] }... } { static_assert(sizeof...(ColumnIndices) <= Columns); } private: template <size_t Index, typename T> MUU_NODISCARD MUU_ALWAYS_INLINE MUU_ATTR(pure) static constexpr decltype(auto) get_tuple_value_or_zero(const T& tpl) noexcept { if constexpr (Index < tuple_size<T>) { return get_from_tuple_like<Index>(tpl); } else { MUU_UNUSED(tpl); return Scalar{}; } } template <size_t Column, typename T, size_t... RowIndices> MUU_NODISCARD MUU_ATTR(pure) MUU_ATTR(flatten) static constexpr vector<Scalar, Rows> column_from_row_major_tuple(const T& tpl, std::index_sequence<RowIndices...>) noexcept { static_assert(sizeof...(RowIndices) == Rows); return vector<Scalar, Rows>{ static_cast<Scalar>( get_tuple_value_or_zero<Column + (Columns * RowIndices)>(tpl))... }; } public: template <typename T, size_t... ColumnIndices> explicit constexpr matrix_(const T& tpl, std::index_sequence<ColumnIndices...>) noexcept : m{ column_from_row_major_tuple<ColumnIndices>(tpl, std::make_index_sequence<Rows>{})... } { static_assert(tuple_size<T> <= Rows * Columns); static_assert(sizeof...(ColumnIndices) == Columns); } template <typename T> explicit constexpr matrix_(row_major_tuple_tag, const T& tpl) noexcept : matrix_{ tpl, std::make_index_sequence<Columns>{} } { static_assert(tuple_size<T> <= Rows * Columns); } // row-major scalar constructor optimizations for some common cases // 2x2 MUU_LEGACY_REQUIRES((R == 2 && C == 2), size_t R = Rows, size_t C = Columns) constexpr matrix_(Scalar v00, Scalar v01, Scalar v10 = Scalar{}, Scalar v11 = Scalar{}) noexcept : m{ { v00, v10 }, { v01, v11 } } {} // 3x3 MUU_LEGACY_REQUIRES((R == 3 && C == 3), size_t R = Rows, size_t C = Columns) constexpr matrix_(Scalar v00, Scalar v01, Scalar v02 = Scalar{}, Scalar v10 = Scalar{}, Scalar v11 = Scalar{}, Scalar v12 = Scalar{}, Scalar v20 = Scalar{}, Scalar v21 = Scalar{}, Scalar v22 = Scalar{}) noexcept // : m{ { v00, v10, v20 }, { v01, v11, v21 }, { v02, v12, v22 } } {} // 3x4 MUU_LEGACY_REQUIRES((R == 3 && C == 4), size_t R = Rows, size_t C = Columns) constexpr matrix_(Scalar v00, Scalar v01, Scalar v02 = Scalar{}, Scalar v03 = Scalar{}, Scalar v10 = Scalar{}, Scalar v11 = Scalar{}, Scalar v12 = Scalar{}, Scalar v13 = Scalar{}, Scalar v20 = Scalar{}, Scalar v21 = Scalar{}, Scalar v22 = Scalar{}, Scalar v23 = Scalar{}) noexcept // : m{ { v00, v10, v20 }, { v01, v11, v21 }, { v02, v12, v22 }, { v03, v13, v23 } } {} // 4x4 MUU_LEGACY_REQUIRES((R == 4 && C == 4), size_t R = Rows, size_t C = Columns) constexpr matrix_(Scalar v00, Scalar v01, Scalar v02 = Scalar{}, Scalar v03 = Scalar{}, Scalar v10 = Scalar{}, Scalar v11 = Scalar{}, Scalar v12 = Scalar{}, Scalar v13 = Scalar{}, Scalar v20 = Scalar{}, Scalar v21 = Scalar{}, Scalar v22 = Scalar{}, Scalar v23 = Scalar{}, Scalar v30 = Scalar{}, Scalar v31 = Scalar{}, Scalar v32 = Scalar{}, Scalar v33 = Scalar{}) noexcept // : m{ { v00, v10, v20, v30 }, { v01, v11, v21, v31 }, { v02, v12, v22, v32 }, { v03, v13, v23, v33 } } {} }; template <typename Scalar, size_t Rows, size_t Columns> inline constexpr bool is_hva<matrix_<Scalar, Rows, Columns>> = can_be_hva_of<Scalar, matrix_<Scalar, Rows, Columns>>; template <typename Scalar, size_t Rows, size_t Columns> inline constexpr bool is_hva<matrix<Scalar, Rows, Columns>> = is_hva<matrix_<Scalar, Rows, Columns>>; template <typename Scalar, size_t Rows, size_t Columns> struct vectorcall_param_<matrix<Scalar, Rows, Columns>> { using type = std::conditional_t<pass_vectorcall_by_value<matrix_<Scalar, Rows, Columns>>, matrix<Scalar, Rows, Columns>, const matrix<Scalar, Rows, Columns>&>; }; template <size_t Rows, size_t Columns> inline constexpr bool is_common_matrix = false; template <> inline constexpr bool is_common_matrix<2, 2> = true; template <> inline constexpr bool is_common_matrix<3, 3> = true; template <> inline constexpr bool is_common_matrix<3, 4> = true; template <> inline constexpr bool is_common_matrix<4, 4> = true; #define MAT_GET(r, c) static_cast<type>(m.m[c].template get<r>()) template <size_t Row0 = 0, size_t Row1 = 1, size_t Col0 = 0, size_t Col1 = 1, typename T> MUU_NODISCARD MUU_ATTR(pure) static constexpr promote_if_small_float<typename T::determinant_type> raw_determinant_2x2(const T& m) noexcept { MUU_FMA_BLOCK; using type = promote_if_small_float<typename T::determinant_type>; return MAT_GET(Row0, Col0) * MAT_GET(Row1, Col1) - MAT_GET(Row0, Col1) * MAT_GET(Row1, Col0); } template <size_t Row0 = 0, size_t Row1 = 1, size_t Row2 = 2, size_t Col0 = 0, size_t Col1 = 1, size_t Col2 = 2, typename T> MUU_NODISCARD MUU_ATTR(pure) static constexpr promote_if_small_float<typename T::determinant_type> raw_determinant_3x3(const T& m) noexcept { MUU_FMA_BLOCK; using type = promote_if_small_float<typename T::determinant_type>; return MAT_GET(Row0, Col0) * raw_determinant_2x2<Row1, Row2, Col1, Col2>(m) - MAT_GET(Row0, Col1) * raw_determinant_2x2<Row1, Row2, Col0, Col2>(m) + MAT_GET(Row0, Col2) * raw_determinant_2x2<Row1, Row2, Col0, Col1>(m); } template <size_t Row0 = 0, size_t Row1 = 1, size_t Row2 = 2, size_t Row3 = 3, size_t Col0 = 0, size_t Col1 = 1, size_t Col2 = 2, size_t Col3 = 3, typename T> MUU_NODISCARD MUU_ATTR(pure) static constexpr promote_if_small_float<typename T::determinant_type> raw_determinant_4x4(const T& m) noexcept { MUU_FMA_BLOCK; using type = promote_if_small_float<typename T::determinant_type>; return MAT_GET(Row0, Col0) * raw_determinant_3x3<Row1, Row2, Row3, Col1, Col2, Col3>(m) - MAT_GET(Row0, Col1) * raw_determinant_3x3<Row1, Row2, Row3, Col0, Col2, Col3>(m) + MAT_GET(Row0, Col2) * raw_determinant_3x3<Row1, Row2, Row3, Col0, Col1, Col3>(m) - MAT_GET(Row0, Col3) * raw_determinant_3x3<Row1, Row2, Row3, Col0, Col1, Col2>(m); } #undef MAT_GET } namespace muu { template <typename From, typename Scalar, size_t Rows, size_t Columns> inline constexpr bool allow_implicit_bit_cast<From, impl::matrix_<Scalar, Rows, Columns>> = allow_implicit_bit_cast<From, matrix<Scalar, Rows, Columns>>; } #define SPECIALIZED_IF(cond) , bool = (cond) /// \endcond #ifndef SPECIALIZED_IF #define SPECIALIZED_IF(cond) #endif #endif //=============================================================================================================== //====================================================================================================================== // MATRIX CLASS #if 1 namespace muu { /// \brief A matrix. /// \ingroup math /// /// \tparam Scalar The matrix's scalar component type. /// \tparam Rows The number of rows in the matrix. /// \tparam Columns The number of columns in the matrix. template <typename Scalar, size_t Rows, size_t Columns> struct MUU_TRIVIAL_ABI matrix // MUU_HIDDEN_BASE(impl::matrix_<Scalar, Rows, Columns>) { static_assert(!std::is_reference_v<Scalar>, "Matrix scalar type cannot be a reference"); static_assert(!is_cv<Scalar>, "Matrix scalar type cannot be const- or volatile-qualified"); static_assert(std::is_trivially_constructible_v<Scalar> // && std::is_trivially_copyable_v<Scalar> // && std::is_trivially_destructible_v<Scalar>, "Matrix scalar type must be trivially constructible, copyable and destructible"); static_assert(Rows >= 1, "Matrices must have at least one row"); static_assert(Columns >= 1, "Matrices must have at least one column"); /// \brief The number of rows in the matrix. static constexpr size_t rows = Rows; /// \brief The number of columns in the matrix. static constexpr size_t columns = Columns; /// \brief The type of each scalar component stored in this matrix. using scalar_type = Scalar; /// \brief The type of one row of this matrix. using row_type = vector<scalar_type, columns>; /// \brief The type of one column of this matrix. using column_type = vector<scalar_type, rows>; /// \brief Compile-time constants for this matrix. using constants = muu::constants<matrix>; /// \brief The scalar type used for determinants. Always signed. using determinant_type = std:: conditional_t<is_integral<scalar_type>, impl::highest_ranked<make_signed<scalar_type>, int>, scalar_type>; /// \brief The matrix type returned by inversion operations. Always floating-point. using inverse_type = matrix<std::conditional_t<is_integral<scalar_type>, double, scalar_type>, Rows, Columns>; private: template <typename S, size_t R, size_t C> friend struct matrix; using base = impl::matrix_<Scalar, Rows, Columns>; static_assert(sizeof(base) == (sizeof(scalar_type) * Rows * Columns), "Matrices should not have padding"); using intermediate_float = promote_if_small_float<typename inverse_type::scalar_type>; static_assert(is_floating_point<typename inverse_type::scalar_type>); static_assert(is_floating_point<intermediate_float>); using scalar_constants = muu::constants<scalar_type>; public: #ifdef DOXYGEN /// \brief The values in the matrix (stored column-major). column_type m[columns]; #endif // DOXYGEN #if 1 // constructors --------------------------------------------------------------------------------------------- /// \brief Default constructor. Values are not initialized. MUU_NODISCARD_CTOR matrix() noexcept = default; /// \brief Copy constructor. MUU_NODISCARD_CTOR constexpr matrix(const matrix&) noexcept = default; /// \brief Copy-assigment operator. constexpr matrix& operator=(const matrix&) noexcept = default; /// \brief Constructs a matrix with all scalar components set to the same value. /// /// \details \cpp /// std::cout << matrix<int, 3, 3>{ 1 } << "\n"; /// \ecpp /// /// \out /// { 1, 1, 1, /// 1, 1, 1, /// 1, 1, 1 } /// \eout /// /// \param fill The value used to initialize each of the matrix's scalar components. MUU_NODISCARD_CTOR explicit constexpr matrix(scalar_type fill) noexcept : base{ impl::value_fill_tag{}, std::make_index_sequence<Columns>{}, fill } {} /// \brief Constructs a matrix from (row-major-ordered) scalars. /// /// \details \cpp /// // explicitly-sized matrices: /// std::cout << matrix<int, 2, 3>{ 1, 2, 3, 4, 5, 6 } << "\n\n"; /// /// // 2x2, 3x3, 3x4 and 4x4 matrices can be deduced automatically from 4, 9 12 and 16 inputs (respectively): /// std::cout << matrix{ 1, 2, 3, 4 } << "\n\n"; /// std::cout << matrix{ 1, 2, 3, 4, 5, 6, 7, 8, 9 } << "\n\n"; /// std::cout << matrix{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 } << "\n\n"; /// std::cout << matrix{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 } << "\n\n"; /// \ecpp /// /// \out /// { 1, 2, 3, /// 4, 5, 6 } /// /// { 1, 2, /// 3, 4 } /// /// { 1, 2, 3, /// 4, 5, 6, /// 7, 8, 9 } /// /// { 1, 2, 3, 4, /// 5, 6, 7, 8, /// 9, 10, 11, 12 } /// /// { 1, 2, 3, 4, /// 5, 6, 7, 8, /// 9, 10, 11, 12, /// 13, 14, 15, 16 } /// \eout /// /// Any scalar components not covered by the constructor's parameters are initialized to zero. /// /// \tparam T Types convertible to #scalar_type. /// \param v0 Initial value for the matrix's first scalar component. /// \param v1 Initial value for the matrix's second scalar component. /// \param vals Initial values for the matrix's remaining scalar components. MUU_CONSTRAINED_TEMPLATE((!impl::is_common_matrix<Rows, Columns> // && (Rows * Columns) >= sizeof...(T) + 2 && all_convertible_to<scalar_type, scalar_type, T...>), typename... T) MUU_NODISCARD_CTOR constexpr matrix(scalar_type v0, scalar_type v1, const T&... vals) noexcept : base{ impl::row_major_tuple_tag{}, std::tuple<scalar_type, scalar_type, const T&...>{ v0, v1, vals... } } {} #ifndef DOXYGEN // row-major scalar constructor optimizations for some common cases // 2x2 MUU_LEGACY_REQUIRES((R == 2 && C == 2), size_t R = Rows, size_t C = Columns) MUU_NODISCARD_CTOR constexpr matrix(scalar_type v00, scalar_type v01, scalar_type v10 = scalar_type{}, scalar_type v11 = scalar_type{}) noexcept // : base{ v00, v01, v10, v11 } {} // 3x3 MUU_LEGACY_REQUIRES((R == 3 && C == 3), size_t R = Rows, size_t C = Columns) MUU_NODISCARD_CTOR constexpr matrix(scalar_type v00, scalar_type v01, scalar_type v02 = scalar_type{}, scalar_type v10 = scalar_type{}, scalar_type v11 = scalar_type{}, scalar_type v12 = scalar_type{}, scalar_type v20 = scalar_type{}, scalar_type v21 = scalar_type{}, scalar_type v22 = scalar_type{}) noexcept // : base{ v00, v01, v02, v10, v11, v12, v20, v21, v22 } {} // 3x4 MUU_LEGACY_REQUIRES((R == 3 && C == 4), size_t R = Rows, size_t C = Columns) MUU_NODISCARD_CTOR constexpr matrix(scalar_type v00, scalar_type v01, scalar_type v02 = scalar_type{}, scalar_type v03 = scalar_type{}, scalar_type v10 = scalar_type{}, scalar_type v11 = scalar_type{}, scalar_type v12 = scalar_type{}, scalar_type v13 = scalar_type{}, scalar_type v20 = scalar_type{}, scalar_type v21 = scalar_type{}, scalar_type v22 = scalar_type{}, scalar_type v23 = scalar_type{}) noexcept // : base{ v00, v01, v02, v03, v10, v11, v12, v13, v20, v21, v22, v23 } {} // 4x4 MUU_LEGACY_REQUIRES((R == 4 && C == 4), size_t R = Rows, size_t C = Columns) MUU_NODISCARD_CTOR constexpr matrix(scalar_type v00, scalar_type v01, scalar_type v02 = scalar_type{}, scalar_type v03 = scalar_type{}, scalar_type v10 = scalar_type{}, scalar_type v11 = scalar_type{}, scalar_type v12 = scalar_type{}, scalar_type v13 = scalar_type{}, scalar_type v20 = scalar_type{}, scalar_type v21 = scalar_type{}, scalar_type v22 = scalar_type{}, scalar_type v23 = scalar_type{}, scalar_type v30 = scalar_type{}, scalar_type v31 = scalar_type{}, scalar_type v32 = scalar_type{}, scalar_type v33 = scalar_type{}) noexcept // : base{ v00, v01, v02, v03, v10, v11, v12, v13, v20, v21, v22, v23, v30, v31, v32, v33 } {} #endif /// \brief Enlarging/truncating/converting constructor. /// \details Copies source matrix's scalar components, casting if necessary: /// \cpp /// matrix<int, 3, 3> m33 = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; /// std::cout << m33 << "\n\n"; /// /// matrix<int, 2, 2> m22 = { m33 }; /// std::cout << m22 << "\n\n"; /// /// matrix<int, 4, 4> m44 = { m33 }; /// std::cout << m44 << "\n\n"; /// \ecpp /// /// \out /// { 1, 2, 3, /// 4, 5, 6, /// 7, 8, 9 } /// /// { 1, 2, /// 4, 5 } /// /// { 1, 2, 3, 0, /// 4, 5, 6, 0, /// 7, 8, 9, 0, /// 0, 0, 0, 0 } /// \eout /// /// Any scalar components not covered by the constructor's parameters are initialized to zero. /// /// \tparam S Source matrix's #scalar_type. /// \tparam R Source matrix's row count. /// \tparam C Source matrix's column count. /// \param mat Source matrix. template <typename S, size_t R, size_t C> MUU_NODISCARD_CTOR explicit constexpr matrix(const matrix<S, R, C>& mat) noexcept : base{ impl::columnwise_copy_tag{}, std::make_index_sequence<(C < Columns ? C : Columns)>{}, mat.m } {} /// \brief Constructs a matrix from an implicitly bit-castable type. /// /// \tparam T A bit-castable type. /// /// \see muu::allow_implicit_bit_cast MUU_CONSTRAINED_TEMPLATE((allow_implicit_bit_cast<T, matrix> && !impl::is_matrix_<T>), typename T) MUU_NODISCARD_CTOR /*implicit*/ constexpr matrix(const T& blittable) noexcept // : base{ muu::bit_cast<base>(blittable) } { static_assert(sizeof(T) == sizeof(base), "Bit-castable types must be the same size as the matrix"); static_assert(std::is_trivially_copyable_v<T>, "Bit-castable types must be trivially-copyable"); } private: template <typename... T> MUU_NODISCARD_CTOR constexpr matrix(impl::columnwise_init_tag, T... cols) noexcept // : base{ impl::columnwise_init_tag{}, cols... } {} public: #endif // constructors #if 1 // scalar component accessors ------------------------------------------------------------------------------- private: template <size_t R, size_t C, typename T> MUU_NODISCARD MUU_ALWAYS_INLINE MUU_ATTR(pure) MUU_ATTR(flatten) static constexpr auto& do_get(T& mat) noexcept { static_assert(R < Rows, "Row index out of range"); static_assert(C < Columns, "Column index out of range"); return mat.m[C].template get<R>(); } template <typename T> MUU_NODISCARD MUU_ATTR(pure) static constexpr auto& do_lookup_operator(T& mat, size_t r, size_t c) noexcept { MUU_ASSUME(r < Rows); MUU_ASSUME(c < Columns); return mat.m[c][r]; } public: /// \brief Gets a reference to the scalar component at a specific row and column. /// /// \tparam R The row of the scalar component to retrieve. /// \tparam C The column of the scalar component to retrieve. /// /// \return A reference to the selected scalar component. template <size_t R, size_t C> MUU_NODISCARD MUU_ALWAYS_INLINE MUU_ATTR(pure) MUU_ATTR(flatten) constexpr const scalar_type& get() const noexcept { return do_get<R, C>(*this); } /// \brief Gets a reference to the scalar component at a specific row and column. /// /// \tparam R The row of the scalar component to retrieve. /// \tparam C The column of the scalar component to retrieve. /// /// \return A reference to the selected scalar component. template <size_t R, size_t C> MUU_NODISCARD MUU_ALWAYS_INLINE MUU_ATTR(pure) MUU_ATTR(flatten) constexpr scalar_type& get() noexcept { return do_get<R, C>(*this); } /// \brief Gets a reference to the scalar component at a specific row and column. /// /// \param r The row of the scalar component to retrieve. /// \param c The column of the scalar component to retrieve. /// /// \return A reference to the selected scalar component. MUU_NODISCARD MUU_ATTR(pure) constexpr const scalar_type& operator()(size_t r, size_t c) const noexcept { return do_lookup_operator(*this, r, c); } /// \brief Gets a reference to the scalar component at a specific row and column. /// /// \param r The row of the scalar component to retrieve. /// \param c The column of the scalar component to retrieve. /// /// \return A reference to the selected scalar component. MUU_NODISCARD MUU_ATTR(pure) constexpr scalar_type& operator()(size_t r, size_t c) noexcept { return do_lookup_operator(*this, r, c); } /// \brief Returns a pointer to the first scalar component in the matrix. MUU_NODISCARD MUU_ALWAYS_INLINE MUU_ATTR(pure) MUU_ATTR(flatten) constexpr const scalar_type* data() const noexcept { return &do_get<0, 0>(*this); } /// \brief Returns a pointer to the first scalar component in the matrix. MUU_NODISCARD MUU_ALWAYS_INLINE MUU_ATTR(pure) MUU_ATTR(flatten) constexpr scalar_type* data() noexcept { return &do_get<0, 0>(*this); } #endif // scalar component accessors #if 1 // equality ------------------------------------------------------------------------------------------------- /// \brief Returns true if two matrices are exactly equal. /// /// \remarks This is an exact check; /// use #approx_equal() if you want an epsilon-based "near-enough" check. MUU_CONSTRAINED_TEMPLATE((!MUU_HAS_VECTORCALL || impl::pass_vectorcall_by_reference<matrix, matrix<T, Rows, Columns>>), typename T) MUU_NODISCARD MUU_ATTR(pure) friend constexpr bool operator==(const matrix& lhs, const matrix<T, rows, columns>& rhs) noexcept { for (size_t i = 0; i < columns; i++) if (lhs.m[i] != rhs.m[i]) return false; return true; } #if MUU_HAS_VECTORCALL MUU_CONSTRAINED_TEMPLATE((impl::pass_vectorcall_by_value<matrix, matrix<T, Rows, Columns>>), typename T) MUU_NODISCARD MUU_ATTR(const) friend constexpr bool MUU_VECTORCALL operator==(matrix lhs, matrix<T, rows, columns> rhs) noexcept { for (size_t i = 0; i < columns; i++) if (lhs.m[i] != rhs.m[i]) return false; return true; } #endif // MUU_HAS_VECTORCALL /// \brief Returns true if two matrices are not exactly equal. /// /// \remarks This is an exact check; /// use #approx_equal() if you want an epsilon-based "near-enough" check. MUU_CONSTRAINED_TEMPLATE((!MUU_HAS_VECTORCALL || impl::pass_vectorcall_by_reference<matrix, matrix<T, Rows, Columns>>), typename T) MUU_NODISCARD MUU_ATTR(pure) friend constexpr bool operator!=(const matrix& lhs, const matrix<T, rows, columns>& rhs) noexcept { return !(lhs == rhs); } #if MUU_HAS_VECTORCALL MUU_CONSTRAINED_TEMPLATE((impl::pass_vectorcall_by_value<matrix, matrix<T, Rows, Columns>>), typename T) MUU_NODISCARD MUU_ATTR(const) friend constexpr bool operator!=(matrix lhs, matrix<T, rows, columns> rhs) noexcept { return !(lhs == rhs); } #endif // MUU_HAS_VECTORCALL /// \brief Returns true if all the scalar components of a matrix are exactly zero. /// /// \remarks This is an exact check; /// use #approx_zero() if you want an epsilon-based "near-enough" check. MUU_NODISCARD MUU_ATTR(pure) static constexpr bool MUU_VECTORCALL zero(MUU_VC_PARAM(matrix) m) noexcept { for (size_t i = 0; i < columns; i++) if (!column_type::zero(m.m[i])) return false; return true; } /// \brief Returns true if all the scalar components of the matrix are exactly zero. /// /// \remarks This is an exact check; /// use #approx_zero() if you want an epsilon-based "near-enough" check. MUU_NODISCARD MUU_ATTR(pure) constexpr bool zero() const noexcept { return zero(*this); } /// \brief Returns true if any of the scalar components of a matrix are infinity or NaN. MUU_NODISCARD MUU_ATTR(pure) static constexpr bool MUU_VECTORCALL infinity_or_nan(MUU_VC_PARAM(matrix) m) noexcept { if constexpr (is_floating_point<scalar_type>) { for (size_t i = 0; i < columns; i++) if (column_type::infinity_or_nan(m.m[i])) return true; return false; } else { MUU_UNUSED(m); return false; } } /// \brief Returns true if any of the scalar components of the matrix are infinity or NaN. MUU_NODISCARD MUU_ATTR(pure) constexpr bool infinity_or_nan() const noexcept { if constexpr (is_floating_point<scalar_type>) return infinity_or_nan(*this); else return false; } #endif // equality #if 1 // approx_equal --------------------------------------------------------------------------------------------- /// \brief Returns true if two matrices are approximately equal. /// /// \availability This function is only available when at least one of #scalar_type /// and `T` is a floating-point type. MUU_CONSTRAINED_TEMPLATE((any_floating_point<Scalar, T> // && (!MUU_HAS_VECTORCALL || impl::pass_vectorcall_by_reference<matrix, matrix<T, Rows, Columns>>)), typename T) MUU_NODISCARD MUU_ATTR(pure) static constexpr bool MUU_VECTORCALL approx_equal( const matrix& m1, const matrix<T, rows, columns>& m2, epsilon_type<scalar_type, T> epsilon = default_epsilon<scalar_type, T>) noexcept { for (size_t i = 0; i < columns; i++) if (!column_type::approx_equal(m1.m[i], m2.m[i], epsilon)) return false; return true; } #if MUU_HAS_VECTORCALL MUU_CONSTRAINED_TEMPLATE((any_floating_point<Scalar, T> // && impl::pass_vectorcall_by_value<matrix, matrix<T, Rows, Columns>>), typename T) MUU_NODISCARD MUU_ATTR(const) static constexpr bool MUU_VECTORCALL approx_equal( matrix m1, matrix<T, rows, columns> m2, epsilon_type<scalar_type, T> epsilon = default_epsilon<scalar_type, T>) noexcept { for (size_t i = 0; i < columns; i++) if (!column_type::approx_equal(m1.m[i], m2.m[i], epsilon)) return false; return true; } #endif // MUU_HAS_VECTORCALL /// \brief Returns true if the matrix is approximately equal to another. /// /// \availability This function is only available when at least one of #scalar_type /// and `T` is a floating-point type. MUU_CONSTRAINED_TEMPLATE((any_floating_point<Scalar, T> // && (!MUU_HAS_VECTORCALL || impl::pass_vectorcall_by_reference<matrix<T, Rows, Columns>>)), typename T) MUU_NODISCARD MUU_ATTR(pure) constexpr bool MUU_VECTORCALL approx_equal( const matrix<T, rows, columns>& m, epsilon_type<scalar_type, T> epsilon = default_epsilon<scalar_type, T>) const noexcept { return approx_equal(*this, m, epsilon); } #if MUU_HAS_VECTORCALL MUU_CONSTRAINED_TEMPLATE((any_floating_point<Scalar, T> // && impl::pass_vectorcall_by_value<matrix<T, Rows, Columns>>), typename T) MUU_NODISCARD MUU_ATTR(const) constexpr bool MUU_VECTORCALL approx_equal( matrix<T, rows, columns> m, epsilon_type<scalar_type, T> epsilon = default_epsilon<scalar_type, T>) const noexcept { return approx_equal(*this, m, epsilon); } #endif // MUU_HAS_VECTORCALL /// \brief Returns true if all the scalar components in a matrix are approximately equal to zero. /// /// \availability This function is only available when #scalar_type is a floating-point type. MUU_LEGACY_REQUIRES(is_floating_point<T>, typename T = Scalar) MUU_NODISCARD MUU_ATTR(pure) static constexpr bool MUU_VECTORCALL approx_zero(MUU_VC_PARAM(matrix) m, scalar_type epsilon = default_epsilon<scalar_type>) noexcept { for (size_t i = 0; i < columns; i++) if (!column_type::approx_zero(m.m[i], epsilon)) return false; return true; } /// \brief Returns true if all the scalar components in the matrix are approximately equal to zero. /// /// \availability This function is only available when #scalar_type is a floating-point type. MUU_LEGACY_REQUIRES(is_floating_point<T>, typename T = Scalar) MUU_NODISCARD MUU_ATTR(pure) constexpr bool MUU_VECTORCALL approx_zero(scalar_type epsilon = default_epsilon<scalar_type>) const noexcept { return approx_zero(*this, epsilon); } #endif // approx_equal #if 1 // addition ------------------------------------------------------------------------------------------------- /// \brief Returns the componentwise addition of two matrices. MUU_NODISCARD MUU_ATTR(pure) friend constexpr matrix MUU_VECTORCALL operator+(MUU_VC_PARAM(matrix) lhs, MUU_VC_PARAM(matrix) rhs) noexcept { matrix out{ lhs }; for (size_t i = 0; i < columns; i++) out.m[i] += rhs.m[i]; return out; } /// \brief Componentwise adds another matrix to this one. constexpr matrix& MUU_VECTORCALL operator+=(MUU_VC_PARAM(matrix) rhs) noexcept { for (size_t i = 0; i < columns; i++) base::m[i] += rhs.m[i]; return *this; } /// \brief Returns a componentwise copy of a matrix. MUU_NODISCARD MUU_ATTR(pure) constexpr matrix operator+() const noexcept { return *this; } #endif // addition #if 1 // subtraction // ------------------------------------------------------------------------------------------------- /// \brief Returns the componentwise subtraction of two matrices. MUU_NODISCARD MUU_ATTR(pure) friend constexpr matrix MUU_VECTORCALL operator-(MUU_VC_PARAM(matrix) lhs, MUU_VC_PARAM(matrix) rhs) noexcept { matrix out{ lhs }; for (size_t i = 0; i < columns; i++) out.m[i] -= rhs.m[i]; return out; } /// \brief Componentwise subtracts another matrix from this one. constexpr matrix& MUU_VECTORCALL operator-=(MUU_VC_PARAM(matrix) rhs) noexcept { for (size_t i = 0; i < columns; i++) base::m[i] -= rhs.m[i]; return *this; } /// \brief Returns a componentwise negation of a matrix. MUU_LEGACY_REQUIRES(is_signed<T>, typename T = Scalar) MUU_NODISCARD MUU_ATTR(pure) constexpr matrix operator-() const noexcept { matrix out{ *this }; for (size_t i = 0; i < columns; i++) out.m[i] = -out.m[i]; return out; } #endif // subtraction #if 1 // multiplication ------------------------------------------------------------------------------------------- /// \brief Multiplies two matrices. /// /// \tparam C The number of columns in the RHS matrix. /// \param lhs The LHS matrix. /// \param rhs The RHS matrix. /// /// \return The result of `lhs * rhs`. template <size_t C> MUU_NODISCARD MUU_ATTR(pure) friend constexpr matrix<scalar_type, rows, C> MUU_VECTORCALL operator*( MUU_VC_PARAM(matrix) lhs, const matrix<scalar_type, columns, C>& rhs) noexcept { using result_type = matrix<scalar_type, Rows, C>; using type = impl::highest_ranked< typename column_type::product_type, std::conditional_t<is_floating_point<scalar_type>, intermediate_float, scalar_type>>; #define MULT_DOT(row, col, idx) \ static_cast<type>(lhs.m[idx].template get<row>()) * static_cast<type>(rhs.m[col].template get<idx>()) // common square cases are manually unrolled if constexpr (Rows == 2 && Columns == 2 && C == 2) { MUU_FMA_BLOCK; return result_type{ impl::columnwise_init_tag{}, column_type{ static_cast<scalar_type>(MULT_DOT(0, 0, 0) + MULT_DOT(0, 0, 1)), static_cast<scalar_type>(MULT_DOT(1, 0, 0) + MULT_DOT(1, 0, 1)) }, column_type{ static_cast<scalar_type>(MULT_DOT(0, 1, 0) + MULT_DOT(0, 1, 1)), static_cast<scalar_type>(MULT_DOT(1, 1, 0) + MULT_DOT(1, 1, 1)) } }; } else if constexpr (Rows == 3 && Columns == 3 && C == 3) { MUU_FMA_BLOCK; return result_type{ impl::columnwise_init_tag{}, column_type{ static_cast<scalar_type>(MULT_DOT(0, 0, 0) + MULT_DOT(0, 0, 1) + MULT_DOT(0, 0, 2)), static_cast<scalar_type>(MULT_DOT(1, 0, 0) + MULT_DOT(1, 0, 1) + MULT_DOT(1, 0, 2)), static_cast<scalar_type>(MULT_DOT(2, 0, 0) + MULT_DOT(2, 0, 1) + MULT_DOT(2, 0, 2)) }, column_type{ static_cast<scalar_type>(MULT_DOT(0, 1, 0) + MULT_DOT(0, 1, 1) + MULT_DOT(0, 1, 2)), static_cast<scalar_type>(MULT_DOT(1, 1, 0) + MULT_DOT(1, 1, 1) + MULT_DOT(1, 1, 2)), static_cast<scalar_type>(MULT_DOT(2, 1, 0) + MULT_DOT(2, 1, 1) + MULT_DOT(2, 1, 2)) }, column_type{ static_cast<scalar_type>(MULT_DOT(0, 2, 0) + MULT_DOT(0, 2, 1) + MULT_DOT(0, 2, 2)), static_cast<scalar_type>(MULT_DOT(1, 2, 0) + MULT_DOT(1, 2, 1) + MULT_DOT(1, 2, 2)), static_cast<scalar_type>(MULT_DOT(2, 2, 0) + MULT_DOT(2, 2, 1) + MULT_DOT(2, 2, 2)) } }; } else if constexpr (Rows == 4 && Columns == 4 && C == 4) { MUU_FMA_BLOCK; return result_type{ impl::columnwise_init_tag{}, column_type{ static_cast<scalar_type>(MULT_DOT(0, 0, 0) + MULT_DOT(0, 0, 1) + MULT_DOT(0, 0, 2) + MULT_DOT(0, 0, 3)), static_cast<scalar_type>(MULT_DOT(1, 0, 0) + MULT_DOT(1, 0, 1) + MULT_DOT(1, 0, 2) + MULT_DOT(1, 0, 3)), static_cast<scalar_type>(MULT_DOT(2, 0, 0) + MULT_DOT(2, 0, 1) + MULT_DOT(2, 0, 2) + MULT_DOT(2, 0, 3)), static_cast<scalar_type>(MULT_DOT(3, 0, 0) + MULT_DOT(3, 0, 1) + MULT_DOT(3, 0, 2) + MULT_DOT(3, 0, 3)) }, column_type{ static_cast<scalar_type>(MULT_DOT(0, 1, 0) + MULT_DOT(0, 1, 1) + MULT_DOT(0, 1, 2) + MULT_DOT(0, 1, 3)), static_cast<scalar_type>(MULT_DOT(1, 1, 0) + MULT_DOT(1, 1, 1) + MULT_DOT(1, 1, 2) + MULT_DOT(1, 1, 3)), static_cast<scalar_type>(MULT_DOT(2, 1, 0) + MULT_DOT(2, 1, 1) + MULT_DOT(2, 1, 2) + MULT_DOT(2, 1, 3)), static_cast<scalar_type>(MULT_DOT(3, 1, 0) + MULT_DOT(3, 1, 1) + MULT_DOT(3, 1, 2) + MULT_DOT(3, 1, 3)) }, column_type{ static_cast<scalar_type>(MULT_DOT(0, 2, 0) + MULT_DOT(0, 2, 1) + MULT_DOT(0, 2, 2) + MULT_DOT(0, 2, 3)), static_cast<scalar_type>(MULT_DOT(1, 2, 0) + MULT_DOT(1, 2, 1) + MULT_DOT(1, 2, 2) + MULT_DOT(1, 2, 3)), static_cast<scalar_type>(MULT_DOT(2, 2, 0) + MULT_DOT(2, 2, 1) + MULT_DOT(2, 2, 2) + MULT_DOT(2, 2, 3)), static_cast<scalar_type>(MULT_DOT(3, 2, 0) + MULT_DOT(3, 2, 1) + MULT_DOT(3, 2, 2) + MULT_DOT(3, 2, 3)) }, column_type{ static_cast<scalar_type>(MULT_DOT(0, 3, 0) + MULT_DOT(0, 3, 1) + MULT_DOT(0, 3, 2) + MULT_DOT(0, 3, 3)), static_cast<scalar_type>(MULT_DOT(1, 3, 0) + MULT_DOT(1, 3, 1) + MULT_DOT(1, 3, 2) + MULT_DOT(1, 3, 3)), static_cast<scalar_type>(MULT_DOT(2, 3, 0) + MULT_DOT(2, 3, 1) + MULT_DOT(2, 3, 2) + MULT_DOT(2, 3, 3)), static_cast<scalar_type>(MULT_DOT(3, 3, 0) + MULT_DOT(3, 3, 1) + MULT_DOT(3, 3, 2) + MULT_DOT(3, 3, 3)) } }; } else { result_type out; for (size_t out_r = 0; out_r < Rows; out_r++) { for (size_t out_c = 0; out_c < C; out_c++) { MUU_FMA_BLOCK; auto val = static_cast<type>(lhs(out_r, 0)) * static_cast<type>(rhs(0, out_c)); for (size_t r = 1; r < Columns; r++) val += static_cast<type>(lhs(out_r, r)) * static_cast<type>(rhs(r, out_c)); out(out_r, out_c) = static_cast<scalar_type>(val); } } return out; } #undef MULT_DOT } /// \brief Multiplies this matrix with another and assigns the result. /// /// \availability This function is only available when the matrix is square. MUU_LEGACY_REQUIRES(R == C, size_t R = Rows, size_t C = Columns) constexpr matrix& MUU_VECTORCALL operator*=(MUU_VC_PARAM(matrix) rhs) noexcept { return *this = *this * rhs; } /// \brief Multiplies a matrix and a column vector. /// /// \param lhs The LHS matrix. /// \param rhs The RHS column vector. /// /// \return The result of `lhs * rhs`. MUU_NODISCARD MUU_ATTR(pure) friend constexpr column_type MUU_VECTORCALL operator*(MUU_VC_PARAM(matrix) lhs, MUU_VC_PARAM(vector<scalar_type, columns>) rhs) noexcept { using type = impl::highest_ranked< typename column_type::product_type, std::conditional_t<is_floating_point<scalar_type>, intermediate_float, scalar_type>>; #define MULT_COL(row, col, vec_elem) \ static_cast<type>(lhs.m[col].template get<row>()) * static_cast<type>(rhs.vec_elem) // common square cases are manually unrolled if constexpr (Rows == 2 && Columns == 2) { MUU_FMA_BLOCK; return column_type{ static_cast<scalar_type>(MULT_COL(0, 0, x) + MULT_COL(0, 1, y)), static_cast<scalar_type>(MULT_COL(1, 0, x) + MULT_COL(1, 1, y)) }; } else if constexpr (Rows == 3 && Columns == 3) { MUU_FMA_BLOCK; return column_type{ static_cast<scalar_type>(MULT_COL(0, 0, x) + MULT_COL(0, 1, y) + MULT_COL(0, 2, z)), static_cast<scalar_type>(MULT_COL(1, 0, x) + MULT_COL(1, 1, y) + MULT_COL(1, 2, z)), static_cast<scalar_type>(MULT_COL(2, 0, x) + MULT_COL(2, 1, y) + MULT_COL(2, 2, z)) }; } else if constexpr (Rows == 4 && Columns == 4) { MUU_FMA_BLOCK; return column_type{ static_cast<scalar_type>(MULT_COL(0, 0, x) + MULT_COL(0, 1, y) + MULT_COL(0, 2, z) + MULT_COL(0, 3, w)), static_cast<scalar_type>(MULT_COL(1, 0, x) + MULT_COL(1, 1, y) + MULT_COL(1, 2, z) + MULT_COL(1, 3, w)), static_cast<scalar_type>(MULT_COL(2, 0, x) + MULT_COL(2, 1, y) + MULT_COL(2, 2, z) + MULT_COL(2, 3, w)), static_cast<scalar_type>(MULT_COL(3, 0, x) + MULT_COL(3, 1, y) + MULT_COL(3, 2, z) + MULT_COL(3, 3, w)) }; } else { column_type out; for (size_t out_r = 0; out_r < Rows; out_r++) { MUU_FMA_BLOCK; auto val = static_cast<type>(lhs(out_r, 0)) * static_cast<type>(rhs.template get<0>()); for (size_t c = 1; c < Columns; c++) val += static_cast<type>(lhs(out_r, c)) * static_cast<type>(rhs[c]); out[out_r] = static_cast<scalar_type>(val); } return out; } #undef MULT_COL } /// \brief Multiplies a row vector and a matrix. /// /// \param lhs The LHS row vector. /// \param rhs The RHS matrix. /// /// \return The result of `lhs * rhs`. MUU_NODISCARD MUU_ATTR(pure) friend constexpr row_type MUU_VECTORCALL operator*(MUU_VC_PARAM(vector<scalar_type, rows>) lhs, MUU_VC_PARAM(matrix) rhs) noexcept { using type = impl::highest_ranked< typename column_type::product_type, std::conditional_t<is_floating_point<scalar_type>, intermediate_float, scalar_type>>; #define MULT_ROW(row, col, vec_elem) \ static_cast<type>(lhs.vec_elem) * static_cast<type>(rhs.template get<row, col>()) // unroll the common square cases if constexpr (Rows == 2 && Columns == 2) { MUU_FMA_BLOCK; return row_type{ static_cast<scalar_type>(MULT_ROW(0, 0, x) + MULT_ROW(1, 0, y)), static_cast<scalar_type>(MULT_ROW(0, 1, x) + MULT_ROW(1, 1, y)) }; } else if constexpr (Rows == 3 && Columns == 3) { MUU_FMA_BLOCK; return row_type{ static_cast<scalar_type>(MULT_ROW(0, 0, x) + MULT_ROW(1, 0, y) + MULT_ROW(2, 0, z)), static_cast<scalar_type>(MULT_ROW(0, 1, x) + MULT_ROW(1, 1, y) + MULT_ROW(2, 1, z)), static_cast<scalar_type>(MULT_ROW(0, 2, x) + MULT_ROW(1, 2, y) + MULT_ROW(2, 2, z)) }; } else if constexpr (Rows == 4 && Columns == 4) { MUU_FMA_BLOCK; return row_type{ static_cast<scalar_type>(MULT_ROW(0, 0, x) + MULT_ROW(1, 0, y) + MULT_ROW(2, 0, z) + MULT_ROW(3, 0, w)), static_cast<scalar_type>(MULT_ROW(0, 1, x) + MULT_ROW(1, 1, y) + MULT_ROW(2, 1, z) + MULT_ROW(3, 1, w)), static_cast<scalar_type>(MULT_ROW(0, 2, x) + MULT_ROW(1, 2, y) + MULT_ROW(2, 2, z) + MULT_ROW(3, 2, w)), static_cast<scalar_type>(MULT_ROW(0, 3, x) + MULT_ROW(1, 3, y) + MULT_ROW(2, 3, z) + MULT_ROW(3, 3, w)) }; } else { row_type out; for (size_t out_col = 0; out_col < Columns; out_col++) { MUU_FMA_BLOCK; auto val = static_cast<type>(lhs.template get<0>()) * static_cast<type>(rhs(0, out_col)); for (size_t r = 1; r < Rows; r++) val += static_cast<type>(lhs[r]) * static_cast<type>(rhs(r, out_col)); out[out_col] = static_cast<scalar_type>(val); } return out; } #undef MULT_ROW } /// \brief Returns the componentwise multiplication of a matrix and a scalar. MUU_NODISCARD MUU_ATTR(pure) friend constexpr matrix MUU_VECTORCALL operator*(MUU_VC_PARAM(matrix) lhs, scalar_type rhs) noexcept { matrix out{ lhs }; out *= rhs; return out; } /// \brief Returns the componentwise multiplication of a matrix and a scalar. MUU_NODISCARD MUU_ATTR(pure) friend constexpr matrix MUU_VECTORCALL operator*(scalar_type lhs, MUU_VC_PARAM(matrix) rhs) noexcept { return rhs * lhs; } /// \brief Componentwise multiplies this matrix by a scalar. constexpr matrix& MUU_VECTORCALL operator*=(scalar_type rhs) noexcept { using type = impl::highest_ranked< typename column_type::product_type, std::conditional_t<is_floating_point<scalar_type>, intermediate_float, scalar_type>>; if constexpr (std::is_same_v<type, scalar_type>) { for (auto& col : base::m) col.raw_multiply_assign_scalar(rhs); } else { const auto rhs_ = static_cast<type>(rhs); for (auto& col : base::m) col.raw_multiply_assign_scalar(rhs_); } return *this; } #endif // multiplication #if 1 // division ------------------------------------------------------------------------------------------------- /// \brief Returns the componentwise multiplication of a matrix by a scalar. MUU_NODISCARD MUU_ATTR(pure) friend constexpr matrix MUU_VECTORCALL operator/(MUU_VC_PARAM(matrix) lhs, scalar_type rhs) noexcept { matrix out{ lhs }; out /= rhs; return out; } /// \brief Componentwise multiplies this matrix by a scalar. constexpr matrix& MUU_VECTORCALL operator/=(scalar_type rhs) noexcept { using type = impl::highest_ranked< typename column_type::product_type, std::conditional_t<is_floating_point<scalar_type>, intermediate_float, scalar_type>>; if constexpr (is_floating_point<type>) { const auto rhs_ = type{ 1 } / static_cast<type>(rhs); for (auto& col : base::m) col.raw_multiply_assign_scalar(rhs_); } else if constexpr (std::is_same_v<type, scalar_type>) { for (auto& col : base::m) col.raw_divide_assign_scalar(rhs); } else { const auto rhs_ = static_cast<type>(rhs); for (auto& col : base::m) col.raw_divide_assign_scalar(rhs_); } return *this; } #endif // division #if 1 // transposition -------------------------------------------------------------------------------------------- /// \brief Returns a transposed copy of a matrix. MUU_NODISCARD MUU_ATTR(pure) static constexpr matrix<scalar_type, columns, rows> MUU_VECTORCALL transpose(MUU_VC_PARAM(matrix) m) noexcept { using result_type = matrix<scalar_type, columns, rows>; using result_column = vector<scalar_type, columns>; #define MAT_GET(r, c) m.m[c].template get<r>() // common square cases are manually unrolled if constexpr (Rows == 2 && Columns == 2) { return result_type{ impl::columnwise_init_tag{}, result_column{ MAT_GET(0, 0), MAT_GET(0, 1) }, result_column{ MAT_GET(1, 0), MAT_GET(1, 1) }, }; } else if constexpr (Rows == 3 && Columns == 3) { return result_type{ impl::columnwise_init_tag{}, result_column{ MAT_GET(0, 0), MAT_GET(0, 1), MAT_GET(0, 2) }, result_column{ MAT_GET(1, 0), MAT_GET(1, 1), MAT_GET(1, 2) }, result_column{ MAT_GET(2, 0), MAT_GET(2, 1), MAT_GET(2, 2) }, }; } else if constexpr (Rows == 4 && Columns == 4) { return result_type{ impl::columnwise_init_tag{}, result_column{ MAT_GET(0, 0), MAT_GET(0, 1), MAT_GET(0, 2), MAT_GET(0, 3) }, result_column{ MAT_GET(1, 0), MAT_GET(1, 1), MAT_GET(1, 2), MAT_GET(1, 3) }, result_column{ MAT_GET(2, 0), MAT_GET(2, 1), MAT_GET(2, 2), MAT_GET(2, 3) }, result_column{ MAT_GET(3, 0), MAT_GET(3, 1), MAT_GET(3, 2), MAT_GET(3, 3) }, }; } else { result_type out; for (size_t c = 0; c < Columns; c++) { auto& col = m.m[c]; for (size_t r = 0; r < Rows; r++) out.m[r][c] = col[r]; } return out; } #undef MAT_GET } /// \brief Transposes the matrix (in-place). /// /// \availability This function is only available when the matrix is square. MUU_LEGACY_REQUIRES(R == C, size_t R = Rows, size_t C = Columns) constexpr matrix& transpose() noexcept { return *this = transpose(*this); } #endif // transposition #if 1 // inverse & determinant ------------------------------------------------------------------------------------ /// \brief Calculates the determinant of a matrix. /// /// \availability This function is only available when the matrix is square /// and has at most 4 rows and columns. MUU_LEGACY_REQUIRES(R == C && C <= 4, size_t R = Rows, size_t C = Columns) MUU_NODISCARD MUU_ATTR(pure) static constexpr determinant_type MUU_VECTORCALL determinant(MUU_VC_PARAM(matrix) m) noexcept { if constexpr (Columns == 1) return static_cast<determinant_type>(m.m[0].x); if constexpr (Columns == 2) return static_cast<determinant_type>(impl::raw_determinant_2x2(m)); if constexpr (Columns == 3) return static_cast<determinant_type>(impl::raw_determinant_3x3(m)); if constexpr (Columns == 4) return static_cast<determinant_type>(impl::raw_determinant_4x4(m)); } /// \brief Calculates the determinant of a matrix. /// /// \availability This function is only available when the matrix is square /// and has at most 4 rows and columns. MUU_LEGACY_REQUIRES(R == C && C <= 4, size_t R = Rows, size_t C = Columns) MUU_NODISCARD MUU_ATTR(pure) constexpr determinant_type determinant() noexcept { return determinant(*this); } /// \brief Returns the inverse of a matrix. /// /// \availability This function is only available when the matrix is square /// and has at most 4 rows and columns. MUU_LEGACY_REQUIRES(R == C && C <= 4, size_t R = Rows, size_t C = Columns) MUU_NODISCARD MUU_ATTR(pure) static constexpr inverse_type MUU_VECTORCALL invert(MUU_VC_PARAM(matrix) m) noexcept { #define MAT_GET(r, c) static_cast<intermediate_float>(m.m[c].template get<r>()) using result_scalar = typename inverse_type::scalar_type; using result_column = typename inverse_type::column_type; if constexpr (Columns == 1) { return inverse_type{ impl::columnwise_init_tag{}, result_column{ static_cast<result_scalar>( intermediate_float{ 1 } / static_cast<intermediate_float>(m.m[0].x)) } }; } if constexpr (Columns == 2) { MUU_FMA_BLOCK; const auto det = intermediate_float{ 1 } / static_cast<intermediate_float>(impl::raw_determinant_2x2(m)); return inverse_type{ impl::columnwise_init_tag{}, result_column{ static_cast<result_scalar>(det * MAT_GET(1, 1)), static_cast<result_scalar>(det * -MAT_GET(1, 0)) }, result_column{ static_cast<result_scalar>(det * -MAT_GET(0, 1)), static_cast<result_scalar>(det * MAT_GET(0, 0)) } }; } if constexpr (Columns == 3) { MUU_FMA_BLOCK; const auto det = intermediate_float{ 1 } / static_cast<intermediate_float>(impl::raw_determinant_3x3(m)); return inverse_type{ impl::columnwise_init_tag{}, result_column{ static_cast<result_scalar>( det * (MAT_GET(1, 1) * MAT_GET(2, 2) - MAT_GET(1, 2) * MAT_GET(2, 1))), static_cast<result_scalar>( det * -(MAT_GET(1, 0) * MAT_GET(2, 2) - MAT_GET(1, 2) * MAT_GET(2, 0))), static_cast<result_scalar>( det * (MAT_GET(1, 0) * MAT_GET(2, 1) - MAT_GET(1, 1) * MAT_GET(2, 0))) }, result_column{ static_cast<result_scalar>( det * -(MAT_GET(0, 1) * MAT_GET(2, 2) - MAT_GET(0, 2) * MAT_GET(2, 1))), static_cast<result_scalar>( det * (MAT_GET(0, 0) * MAT_GET(2, 2) - MAT_GET(0, 2) * MAT_GET(2, 0))), static_cast<result_scalar>( det * -(MAT_GET(0, 0) * MAT_GET(2, 1) - MAT_GET(0, 1) * MAT_GET(2, 0))) }, result_column{ static_cast<result_scalar>( det * (MAT_GET(0, 1) * MAT_GET(1, 2) - MAT_GET(0, 2) * MAT_GET(1, 1))), static_cast<result_scalar>( det * -(MAT_GET(0, 0) * MAT_GET(1, 2) - MAT_GET(0, 2) * MAT_GET(1, 0))), static_cast<result_scalar>( det * (MAT_GET(0, 0) * MAT_GET(1, 1) - MAT_GET(0, 1) * MAT_GET(1, 0))) } }; } if constexpr (Columns == 4) { // generated using https://github.com/willnode/N-Matrix-Programmer MUU_FMA_BLOCK; const auto A2323 = MAT_GET(2, 2) * MAT_GET(3, 3) - MAT_GET(2, 3) * MAT_GET(3, 2); const auto A1323 = MAT_GET(2, 1) * MAT_GET(3, 3) - MAT_GET(2, 3) * MAT_GET(3, 1); const auto A1223 = MAT_GET(2, 1) * MAT_GET(3, 2) - MAT_GET(2, 2) * MAT_GET(3, 1); const auto A0323 = MAT_GET(2, 0) * MAT_GET(3, 3) - MAT_GET(2, 3) * MAT_GET(3, 0); const auto A0223 = MAT_GET(2, 0) * MAT_GET(3, 2) - MAT_GET(2, 2) * MAT_GET(3, 0); const auto A0123 = MAT_GET(2, 0) * MAT_GET(3, 1) - MAT_GET(2, 1) * MAT_GET(3, 0); const auto A2313 = MAT_GET(1, 2) * MAT_GET(3, 3) - MAT_GET(1, 3) * MAT_GET(3, 2); const auto A1313 = MAT_GET(1, 1) * MAT_GET(3, 3) - MAT_GET(1, 3) * MAT_GET(3, 1); const auto A1213 = MAT_GET(1, 1) * MAT_GET(3, 2) - MAT_GET(1, 2) * MAT_GET(3, 1); const auto A2312 = MAT_GET(1, 2) * MAT_GET(2, 3) - MAT_GET(1, 3) * MAT_GET(2, 2); const auto A1312 = MAT_GET(1, 1) * MAT_GET(2, 3) - MAT_GET(1, 3) * MAT_GET(2, 1); const auto A1212 = MAT_GET(1, 1) * MAT_GET(2, 2) - MAT_GET(1, 2) * MAT_GET(2, 1); const auto A0313 = MAT_GET(1, 0) * MAT_GET(3, 3) - MAT_GET(1, 3) * MAT_GET(3, 0); const auto A0213 = MAT_GET(1, 0) * MAT_GET(3, 2) - MAT_GET(1, 2) * MAT_GET(3, 0); const auto A0312 = MAT_GET(1, 0) * MAT_GET(2, 3) - MAT_GET(1, 3) * MAT_GET(2, 0); const auto A0212 = MAT_GET(1, 0) * MAT_GET(2, 2) - MAT_GET(1, 2) * MAT_GET(2, 0); const auto A0113 = MAT_GET(1, 0) * MAT_GET(3, 1) - MAT_GET(1, 1) * MAT_GET(3, 0); const auto A0112 = MAT_GET(1, 0) * MAT_GET(2, 1) - MAT_GET(1, 1) * MAT_GET(2, 0); const auto det = intermediate_float{ 1 } / (MAT_GET(0, 0) * (MAT_GET(1, 1) * A2323 - MAT_GET(1, 2) * A1323 + MAT_GET(1, 3) * A1223) - MAT_GET(0, 1) * (MAT_GET(1, 0) * A2323 - MAT_GET(1, 2) * A0323 + MAT_GET(1, 3) * A0223) + MAT_GET(0, 2) * (MAT_GET(1, 0) * A1323 - MAT_GET(1, 1) * A0323 + MAT_GET(1, 3) * A0123) - MAT_GET(0, 3) * (MAT_GET(1, 0) * A1223 - MAT_GET(1, 1) * A0223 + MAT_GET(1, 2) * A0123)); return inverse_type{ impl::columnwise_init_tag{}, result_column{ // static_cast<result_scalar>( det * (MAT_GET(1, 1) * A2323 - MAT_GET(1, 2) * A1323 + MAT_GET(1, 3) * A1223)), static_cast<result_scalar>( det * -(MAT_GET(1, 0) * A2323 - MAT_GET(1, 2) * A0323 + MAT_GET(1, 3) * A0223)), static_cast<result_scalar>( det * (MAT_GET(1, 0) * A1323 - MAT_GET(1, 1) * A0323 + MAT_GET(1, 3) * A0123)), static_cast<result_scalar>( det * -(MAT_GET(1, 0) * A1223 - MAT_GET(1, 1) * A0223 + MAT_GET(1, 2) * A0123)) }, result_column{ // static_cast<result_scalar>( det * -(MAT_GET(0, 1) * A2323 - MAT_GET(0, 2) * A1323 + MAT_GET(0, 3) * A1223)), static_cast<result_scalar>( det * (MAT_GET(0, 0) * A2323 - MAT_GET(0, 2) * A0323 + MAT_GET(0, 3) * A0223)), static_cast<result_scalar>( det * -(MAT_GET(0, 0) * A1323 - MAT_GET(0, 1) * A0323 + MAT_GET(0, 3) * A0123)), static_cast<result_scalar>( det * (MAT_GET(0, 0) * A1223 - MAT_GET(0, 1) * A0223 + MAT_GET(0, 2) * A0123)) }, result_column{ // static_cast<result_scalar>( det * (MAT_GET(0, 1) * A2313 - MAT_GET(0, 2) * A1313 + MAT_GET(0, 3) * A1213)), static_cast<result_scalar>( det * -(MAT_GET(0, 0) * A2313 - MAT_GET(0, 2) * A0313 + MAT_GET(0, 3) * A0213)), static_cast<result_scalar>( det * (MAT_GET(0, 0) * A1313 - MAT_GET(0, 1) * A0313 + MAT_GET(0, 3) * A0113)), static_cast<result_scalar>( det * -(MAT_GET(0, 0) * A1213 - MAT_GET(0, 1) * A0213 + MAT_GET(0, 2) * A0113)) }, result_column{ // static_cast<result_scalar>( det * -(MAT_GET(0, 1) * A2312 - MAT_GET(0, 2) * A1312 + MAT_GET(0, 3) * A1212)), static_cast<result_scalar>( det * (MAT_GET(0, 0) * A2312 - MAT_GET(0, 2) * A0312 + MAT_GET(0, 3) * A0212)), static_cast<result_scalar>( det * -(MAT_GET(0, 0) * A1312 - MAT_GET(0, 1) * A0312 + MAT_GET(0, 3) * A0112)), static_cast<result_scalar>( det * (MAT_GET(0, 0) * A1212 - MAT_GET(0, 1) * A0212 + MAT_GET(0, 2) * A0112)) } }; } #undef MAT_GET } /// \brief Inverts the matrix (in-place). /// /// \availability This function is only available when the matrix is square, /// has at most 4 rows and columns, and has a floating-point #scalar_type. MUU_LEGACY_REQUIRES((R == C && C <= 4 && is_floating_point<Scalar>), size_t R = Rows, size_t C = Columns) constexpr matrix& invert() noexcept { return *this = invert(*this); } #endif // inverse & determinant #if 1 // orthonormalize ------------------------------------------------------------------------------------------- private: template <size_t Depth = Rows> static constexpr intermediate_float MUU_VECTORCALL column_dot(MUU_VC_PARAM(column_type) c1, MUU_VC_PARAM(column_type) c2) noexcept { static_assert(Depth > 0); static_assert(Depth <= Rows); using type = intermediate_float; if constexpr (Depth == Rows) return column_type::template raw_dot<type>(c1, c2); else { MUU_FMA_BLOCK; // avoid operator[] for vectors <= 4 elems (potentially slower and/or not-constexpr safe) type dot = static_cast<type>(c1.template get<0>()) * static_cast<type>(c2.template get<0>()); if constexpr (Depth > 1) dot += static_cast<type>(c1.template get<1>()) * static_cast<type>(c2.template get<1>()); if constexpr (Depth > 2) dot += static_cast<type>(c1.template get<2>()) * static_cast<type>(c2.template get<2>()); if constexpr (Depth > 3) dot += static_cast<type>(c1.template get<3>()) * static_cast<type>(c2.template get<3>()); if constexpr (Depth > 4) { for (size_t i = 4; i < Depth; i++) dot += static_cast<type>(c1[i]) * static_cast<type>(c2[i]); } return dot; } } template <size_t Depth = Rows> static constexpr void column_normalize(column_type& c) noexcept { static_assert(Depth > 0); static_assert(Depth <= Rows); if constexpr (Depth == Rows) c.normalize(); else { MUU_FMA_BLOCK; using type = intermediate_float; const type inv_len = type{ 1 } / muu::sqrt(column_dot<Depth>(c, c)); // avoid operator[] for vectors <= 4 elems (potentially slower and/or not-constexpr safe) c.template get<0>() = static_cast<scalar_type>(static_cast<type>(c.template get<0>()) * inv_len); if constexpr (Depth > 1) c.template get<1>() = static_cast<scalar_type>(static_cast<type>(c.template get<1>()) * inv_len); if constexpr (Depth > 2) c.template get<2>() = static_cast<scalar_type>(static_cast<type>(c.template get<2>()) * inv_len); if constexpr (Depth > 3) c.template get<3>() = static_cast<scalar_type>(static_cast<type>(c.template get<3>()) * inv_len); if constexpr (Depth > 4) { for (size_t i = 4; i < Depth; i++) c[i] = static_cast<scalar_type>(static_cast<type>(c[i]) * inv_len); } } } public: /// \brief Orthonormalizes the 3x3 part of a rotation or transformation matrix. /// /// \availability This function is only available when the matrix has 3 or 4 rows and columns /// and has a floating-point #scalar_type. /// /// \see [Orthonormal basis](https://en.wikipedia.org/wiki/Orthonormal_basis) MUU_LEGACY_REQUIRES((is_floating_point<T> && (Rows == 3 || Rows == 4) && (Columns == 3 || Columns == 4)), typename T = Scalar) static constexpr matrix MUU_VECTORCALL orthonormalize(MUU_VC_PARAM(matrix) m) noexcept { // 'modified' gram-schmidt: // https://fgiesen.wordpress.com/2013/06/02/modified-gram-schmidt-orthogonalization/ matrix out{ m }; // x-axis column_normalize<3>(out.m[0]); constexpr auto subtract_dot_mult = [](auto& out_, auto& c1, auto& c2) noexcept { MUU_FMA_BLOCK; const auto dot = column_dot<3>(c1, c2); out_.template get<0>() -= dot * c2.template get<0>(); out_.template get<1>() -= dot * c2.template get<1>(); out_.template get<2>() -= dot * c2.template get<2>(); }; // y-axis subtract_dot_mult(out.m[1], m.m[1], out.m[0]); column_normalize<3>(out.m[1]); // z-axis subtract_dot_mult(out.m[2], m.m[2], out.m[0]); subtract_dot_mult(out.m[2], out.m[2], out.m[1]); column_normalize<3>(out.m[2]); return out; } /// \brief Orthonormalizes the 3x3 part of the matrix. /// /// \availability This function is only available when the matrix has 3 or 4 rows and columns /// and has a floating-point #scalar_type. /// /// \see [Orthonormal basis](https://en.wikipedia.org/wiki/Orthonormal_basis) MUU_LEGACY_REQUIRES((is_floating_point<T> && (Rows == 3 || Rows == 4) && (Columns == 3 || Columns == 4)), typename T = Scalar) constexpr matrix& orthonormalize() noexcept { return *this = orthonormalize(*this); } #endif // orthonormalize #if 1 // misc ----------------------------------------------------------------------------------------------------- /// \brief Writes a matrix out to a text stream. template <typename Char, typename Traits> friend std::basic_ostream<Char, Traits>& operator<<(std::basic_ostream<Char, Traits>& os, const matrix& m) { impl::print_matrix(os, &m.get<0, 0>(), Rows, Columns); return os; } #endif // misc }; /// \cond MUU_CONSTRAINED_TEMPLATE(is_arithmetic<T>, typename T) matrix(T)->matrix<std::remove_cv_t<T>, 1, 1>; MUU_CONSTRAINED_TEMPLATE((all_arithmetic<T1, T2, T3, T4>), typename T1, typename T2, typename T3, typename T4) matrix(T1, T2, T3, T4)->matrix<impl::highest_ranked<T1, T2, T3, T4>, 2, 2>; MUU_CONSTRAINED_TEMPLATE((all_arithmetic<T1, T2, T3, T4, T5, T6, T7, T8, T9>), typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9) matrix(T1, T2, T3, T4, T5, T6, T7, T8, T9)->matrix<impl::highest_ranked<T1, T2, T3, T4, T5, T6, T7, T8, T9>, 3, 3>; MUU_CONSTRAINED_TEMPLATE((all_arithmetic<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>), typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12) matrix(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12) ->matrix<impl::highest_ranked<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>, 3, 4>; MUU_CONSTRAINED_TEMPLATE((all_arithmetic<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16>), typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16) matrix(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16) ->matrix<impl::highest_ranked<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16>, 4, 4>; /// \endcond } #endif //=============================================================================================================== //====================================================================================================================== // CONSTANTS #if 1 MUU_PUSH_PRECISE_MATH; namespace muu { namespace impl { /// \cond template <template <typename, size_t, size_t> typename Matrix, typename Scalar, size_t Rows, size_t Columns> MUU_NODISCARD MUU_CONSTEVAL Matrix<Scalar, Rows, Columns> make_identity_matrix() noexcept { using scalars = constants<Scalar>; Matrix<Scalar, Rows, Columns> m{ scalars::zero }; m.template get<0, 0>() = scalars::one; if constexpr (Rows > 1 && Columns > 1) m.template get<1, 1>() = scalars::one; if constexpr (Rows > 2 && Columns > 2) m.template get<2, 2>() = scalars::one; if constexpr (Rows > 3 && Columns > 3) m.template get<3, 3>() = scalars::one; if constexpr (Rows > 4 && Columns > 4) { for (size_t i = 4; i < muu::min(Rows, Columns); i++) m(i, i) = scalars::one; } return m; } template <template <typename, size_t, size_t> typename Matrix, typename Scalar, size_t Rows, size_t Columns> MUU_NODISCARD MUU_CONSTEVAL Matrix<Scalar, Rows, Columns> make_rotation_matrix(Scalar xx, Scalar yx, Scalar zx, Scalar xy, Scalar yy, Scalar zy, Scalar xz, Scalar yz, Scalar zz) noexcept { auto m = make_identity_matrix<Matrix, Scalar, Rows, Columns>(); m.template get<0, 0>() = xx; m.template get<1, 0>() = xy; m.template get<2, 0>() = xz; m.template get<0, 1>() = yx; m.template get<1, 1>() = yy; m.template get<2, 1>() = yz; m.template get<0, 2>() = zx; m.template get<1, 2>() = zy; m.template get<2, 2>() = zz; return m; } template <typename Scalar, size_t Rows, size_t Columns> struct integer_limits<matrix<Scalar, Rows, Columns>> { using type = matrix<Scalar, Rows, Columns>; using scalars = integer_limits<Scalar>; static constexpr type lowest = type{ scalars::lowest }; static constexpr type highest = type{ scalars::highest }; }; template <typename Scalar, size_t Rows, size_t Columns> struct integer_positive_constants<matrix<Scalar, Rows, Columns>> { using type = matrix<Scalar, Rows, Columns>; using scalars = integer_positive_constants<Scalar>; static constexpr type zero = type{ scalars::zero }; static constexpr type one = type{ scalars::one }; static constexpr type two = type{ scalars::two }; static constexpr type three = type{ scalars::three }; static constexpr type four = type{ scalars::four }; static constexpr type five = type{ scalars::five }; static constexpr type six = type{ scalars::six }; static constexpr type seven = type{ scalars::seven }; static constexpr type eight = type{ scalars::eight }; static constexpr type nine = type{ scalars::nine }; static constexpr type ten = type{ scalars::ten }; static constexpr type one_hundred = type{ scalars::one_hundred }; }; template <typename Scalar, size_t Rows, size_t Columns> struct floating_point_traits<matrix<Scalar, Rows, Columns>> : floating_point_traits<Scalar> {}; template <typename Scalar, size_t Rows, size_t Columns> struct floating_point_special_constants<matrix<Scalar, Rows, Columns>> { using type = matrix<Scalar, Rows, Columns>; using scalars = floating_point_special_constants<Scalar>; static constexpr type nan = type{ scalars::nan }; static constexpr type signaling_nan = type{ scalars::signaling_nan }; static constexpr type infinity = type{ scalars::infinity }; static constexpr type negative_infinity = type{ scalars::negative_infinity }; static constexpr type negative_zero = type{ scalars::negative_zero }; }; template <typename Scalar, size_t Rows, size_t Columns> struct floating_point_named_constants<matrix<Scalar, Rows, Columns>> { using type = matrix<Scalar, Rows, Columns>; using scalars = floating_point_named_constants<Scalar>; static constexpr type one_over_two = type{ scalars::one_over_two }; static constexpr type two_over_three = type{ scalars::two_over_three }; static constexpr type two_over_five = type{ scalars::two_over_five }; static constexpr type sqrt_two = type{ scalars::sqrt_two }; static constexpr type one_over_sqrt_two = type{ scalars::one_over_sqrt_two }; static constexpr type one_over_three = type{ scalars::one_over_three }; static constexpr type three_over_two = type{ scalars::three_over_two }; static constexpr type three_over_four = type{ scalars::three_over_four }; static constexpr type three_over_five = type{ scalars::three_over_five }; static constexpr type sqrt_three = type{ scalars::sqrt_three }; static constexpr type one_over_sqrt_three = type{ scalars::one_over_sqrt_three }; static constexpr type pi = type{ scalars::pi }; static constexpr type one_over_pi = type{ scalars::one_over_pi }; static constexpr type pi_over_two = type{ scalars::pi_over_two }; static constexpr type pi_over_three = type{ scalars::pi_over_three }; static constexpr type pi_over_four = type{ scalars::pi_over_four }; static constexpr type pi_over_five = type{ scalars::pi_over_five }; static constexpr type pi_over_six = type{ scalars::pi_over_six }; static constexpr type pi_over_seven = type{ scalars::pi_over_seven }; static constexpr type pi_over_eight = type{ scalars::pi_over_eight }; static constexpr type sqrt_pi = type{ scalars::sqrt_pi }; static constexpr type one_over_sqrt_pi = type{ scalars::one_over_sqrt_pi }; static constexpr type two_pi = type{ scalars::two_pi }; static constexpr type sqrt_two_pi = type{ scalars::sqrt_two_pi }; static constexpr type one_over_sqrt_two_pi = type{ scalars::one_over_sqrt_two_pi }; static constexpr type one_over_three_pi = type{ scalars::one_over_three_pi }; static constexpr type three_pi_over_two = type{ scalars::three_pi_over_two }; static constexpr type three_pi_over_four = type{ scalars::three_pi_over_four }; static constexpr type three_pi_over_five = type{ scalars::three_pi_over_five }; static constexpr type e = type{ scalars::e }; static constexpr type one_over_e = type{ scalars::one_over_e }; static constexpr type e_over_two = type{ scalars::e_over_two }; static constexpr type e_over_three = type{ scalars::e_over_three }; static constexpr type e_over_four = type{ scalars::e_over_four }; static constexpr type e_over_five = type{ scalars::e_over_five }; static constexpr type e_over_six = type{ scalars::e_over_six }; static constexpr type sqrt_e = type{ scalars::sqrt_e }; static constexpr type one_over_sqrt_e = type{ scalars::one_over_sqrt_e }; static constexpr type phi = type{ scalars::phi }; static constexpr type one_over_phi = type{ scalars::one_over_phi }; static constexpr type phi_over_two = type{ scalars::phi_over_two }; static constexpr type phi_over_three = type{ scalars::phi_over_three }; static constexpr type phi_over_four = type{ scalars::phi_over_four }; static constexpr type phi_over_five = type{ scalars::phi_over_five }; static constexpr type phi_over_six = type{ scalars::phi_over_six }; static constexpr type sqrt_phi = type{ scalars::sqrt_phi }; static constexpr type one_over_sqrt_phi = type{ scalars::one_over_sqrt_phi }; static constexpr type degrees_to_radians = type{ scalars::degrees_to_radians }; static constexpr type radians_to_degrees = type{ scalars::radians_to_degrees }; }; template <typename Scalar, size_t Rows, size_t Columns, int = (is_floating_point<Scalar> ? 2 : (is_signed<Scalar> ? 1 : 0))> struct matrix_constants_base : unsigned_integral_constants<matrix<Scalar, Rows, Columns>> {}; template <typename Scalar, size_t Rows, size_t Columns> struct matrix_constants_base<Scalar, Rows, Columns, 1> : signed_integral_constants<matrix<Scalar, Rows, Columns>> {}; template <typename Scalar, size_t Rows, size_t Columns> struct matrix_constants_base<Scalar, Rows, Columns, 2> : floating_point_constants<matrix<Scalar, Rows, Columns>> {}; /// \endcond template <typename Scalar, size_t Rows, size_t Columns SPECIALIZED_IF(Rows >= 3 && Rows <= 4 && Columns >= 3 && Columns <= 4 && is_signed<Scalar>)> struct rotation_matrix_constants { using scalars = muu::constants<Scalar>; /// \name Rotations /// @{ /// \brief A matrix encoding a rotation 90 degrees to the right. static constexpr matrix<Scalar, Rows, Columns> right = make_rotation_matrix<matrix, Scalar, Rows, Columns>(scalars::zero, scalars::zero, -scalars::one, scalars::zero, scalars::one, scalars::zero, scalars::one, scalars::zero, scalars::zero); /// \brief A matrix encoding a rotation 90 degrees upward. static constexpr matrix<Scalar, Rows, Columns> up = make_rotation_matrix<matrix, Scalar, Rows, Columns>(scalars::one, scalars::zero, scalars::zero, scalars::zero, scalars::zero, -scalars::one, scalars::zero, scalars::one, scalars::zero); /// \brief A matrix encoding a rotation 180 degrees backward. static constexpr matrix<Scalar, Rows, Columns> backward = make_rotation_matrix<matrix, Scalar, Rows, Columns>(-scalars::one, scalars::zero, scalars::zero, scalars::zero, scalars::one, scalars::zero, scalars::zero, scalars::zero, -scalars::one); /// \brief A matrix encoding a rotation 90 degrees to the left. static constexpr matrix<Scalar, Rows, Columns> left = make_rotation_matrix<matrix, Scalar, Rows, Columns>(scalars::zero, scalars::zero, scalars::one, scalars::zero, scalars::one, scalars::zero, -scalars::one, scalars::zero, scalars::zero); /// \brief A matrix encoding a rotation 90 degrees downward. static constexpr matrix<Scalar, Rows, Columns> down = make_rotation_matrix<matrix, Scalar, Rows, Columns>(scalars::one, scalars::zero, scalars::zero, scalars::zero, scalars::zero, scalars::one, scalars::zero, -scalars::one, scalars::zero); /// @} }; /// \cond template <typename Scalar, size_t Rows, size_t Columns> struct rotation_matrix_constants<Scalar, Rows, Columns, false> {}; /// \endcond } #ifdef DOXYGEN #define MATRIX_CONSTANTS_BASES \ impl::rotation_matrix_constants<Scalar, Rows, Columns>, \ impl::integer_limits<matrix<Scalar, Rows, Columns>>, \ impl::integer_positive_constants<matrix<Scalar, Rows, Columns>>, \ impl::floating_point_traits<matrix<Scalar, Rows, Columns>>, \ impl::floating_point_special_constants<matrix<Scalar, Rows, Columns>>, \ impl::floating_point_named_constants<matrix<Scalar, Rows, Columns>> #else #define MATRIX_CONSTANTS_BASES \ impl::rotation_matrix_constants<Scalar, Rows, Columns>, impl::matrix_constants_base<Scalar, Rows, Columns> #endif /// \brief Matrix constants. /// /// \ingroup constants /// \see muu::matrix template <typename Scalar, size_t Rows, size_t Columns> struct constants<matrix<Scalar, Rows, Columns>> : MATRIX_CONSTANTS_BASES { /// \brief The identity matrix. static constexpr matrix<Scalar, Rows, Columns> identity = impl::make_identity_matrix<matrix, Scalar, Rows, Columns>(); }; #undef MATRIX_CONSTANTS_BASES } MUU_POP_PRECISE_MATH; #endif //=============================================================================================================== //====================================================================================================================== // FREE FUNCTIONS #if 1 namespace muu { /// \ingroup infinity_or_nan /// \relatesalso muu::matrix /// /// \brief Returns true if any of the scalar components of a matrix are infinity or NaN. template <typename S, size_t R, size_t C> MUU_NODISCARD MUU_ATTR(pure) constexpr bool infinity_or_nan(const matrix<S, R, C>& m) noexcept { if constexpr (is_floating_point<S>) return matrix<S, R, C>::infinity_or_nan(m); else { MUU_UNUSED(m); return false; } } /// \brief Returns true if two matrices are approximately equal. /// /// \ingroup approx_equal /// \relatesalso muu::matrix /// /// \availability This function is only available when at least one of `S` and `T` is a floating-point type. MUU_CONSTRAINED_TEMPLATE((any_floating_point<S, T>), typename S, typename T, size_t R, size_t C) MUU_NODISCARD MUU_ATTR(pure) constexpr bool MUU_VECTORCALL approx_equal(const matrix<S, R, C>& m1, const matrix<T, R, C>& m2, epsilon_type<S, T> epsilon = default_epsilon<S, T>) noexcept { return matrix<S, R, C>::approx_equal(m1, m2, epsilon); } /// \brief Returns true if all the scalar components of a matrix are approximately equal to zero. /// /// \ingroup approx_zero /// \relatesalso muu::matrix /// /// \availability This function is only available when `S` is a floating-point type. MUU_CONSTRAINED_TEMPLATE(is_floating_point<S>, typename S, size_t R, size_t C) MUU_NODISCARD MUU_ATTR(pure) constexpr bool MUU_VECTORCALL approx_zero(const matrix<S, R, C>& m, S epsilon = default_epsilon<S>) noexcept { return matrix<S, R, C>::approx_zero(m, epsilon); } /// \brief Returns a transposed copy of a matrix. /// /// \relatesalso muu::matrix template <typename S, size_t R, size_t C> MUU_NODISCARD MUU_ATTR(pure) constexpr matrix<S, C, R> transpose(const matrix<S, R, C>& m) noexcept { return matrix<S, R, C>::transpose(m); } /// \brief Calculates the determinant of a matrix. /// /// \relatesalso muu::matrix /// /// \availability This function is only available for square matrices with at most 4 rows and columns. MUU_CONSTRAINED_TEMPLATE( (R == C && R <= 4), typename S, size_t R, size_t C // MUU_HIDDEN_PARAM(typename determinant_type = typename matrix<S, R, C>::determinant_type)) MUU_NODISCARD MUU_ATTR(pure) constexpr determinant_type determinant(const matrix<S, R, C>& m) noexcept { return matrix<S, R, C>::determinant(m); } /// \brief Returns the inverse of a matrix. /// /// \relatesalso muu::matrix /// /// \availability This function is only available for square matrices with at most 4 rows and columns. MUU_CONSTRAINED_TEMPLATE((R == C && R <= 4), typename S, size_t R, size_t C // MUU_HIDDEN_PARAM(typename inverse_type = typename matrix<S, R, C>::inverse_type)) MUU_NODISCARD MUU_ATTR(pure) constexpr inverse_type invert(const matrix<S, R, C>& m) noexcept { return matrix<S, R, C>::invert(m); } /// \brief Returns a copy of a matrix with the 3x3 part orthonormalized. /// /// \relatesalso muu::matrix /// /// \availability This function is only available for matrices with 3 or 4 rows and columns /// and a floating-point scalar_type. /// /// \see [Orthonormal basis](https://en.wikipedia.org/wiki/Orthonormal_basis) MUU_CONSTRAINED_TEMPLATE(is_floating_point<S>, typename S, size_t R, size_t C) MUU_NODISCARD MUU_ATTR(pure) constexpr matrix<S, R, C> orthonormalize(const matrix<S, R, C>& m) noexcept { return matrix<S, R, C>::orthonormalize(m); } } #endif //=============================================================================================================== #undef SPECIALIZED_IF MUU_RESET_NDEBUG_OPTIMIZATIONS; #include "impl/header_end.h"
35.906849
120
0.619233
[ "vector" ]
b0b63a2709d94374367b84300a2f8b49085450ff
7,819
h
C
src/input/button.h
HolyBlackCat/prototyping
0938ad889db0bfcc3b683beaa92eac81bf05bc76
[ "Zlib" ]
null
null
null
src/input/button.h
HolyBlackCat/prototyping
0938ad889db0bfcc3b683beaa92eac81bf05bc76
[ "Zlib" ]
null
null
null
src/input/button.h
HolyBlackCat/prototyping
0938ad889db0bfcc3b683beaa92eac81bf05bc76
[ "Zlib" ]
null
null
null
#pragma once #include <functional> #include <string> #include "input/enum.h" #include "interface/window.h" namespace Input { class Button { Enum index = None; bool Assign(Enum begin, Enum end) { auto window = Interface::Window::Get(); uint64_t tick = window.Ticks(); for (auto i = begin; i < end; i = Enum(i+1)) { if (window.GetInputData(i).press == tick) { index = i; return true; } } return false; } public: Button() {} Button(Enum index) : index(index) {} [[nodiscard]] bool pressed () const {auto window = Interface::Window::Get(); return window.GetInputData(index).press == window.Ticks();} [[nodiscard]] bool released() const {auto window = Interface::Window::Get(); return window.GetInputData(index).release == window.Ticks();} [[nodiscard]] bool repeated() const {auto window = Interface::Window::Get(); return window.GetInputData(index).repeat == window.Ticks();} [[nodiscard]] bool down () const {return Interface::Window::Get().GetInputData(index).is_down;} [[nodiscard]] bool up () const {return !down();} // Returns true if the key is not null. // We use a function instead of `operator bool` because then it's too easy to forget `.pressed()` (and other similar functions) when referring to a button. [[nodiscard]] bool IsAssigned() const { return index != None; } [[nodiscard]] Enum Index() const { return index; } // Returns a button name which should hopefully be layout-dependent, but not input-language-dependent. [[nodiscard]] std::string Name() const { if (index == None) { return "None"; } else if (index >= BeginKeys && index < EndKeys) // Note that `BeginKeys == None`, so we check for `None` before this. { const char *ret; // From looking at the code, `SDL_GetKeyFromScancode` returns 0 on failure. if (SDL_Keycode keycode = SDL_GetKeyFromScancode(SDL_Scancode(index))) ret = SDL_GetKeyName(keycode); else ret = SDL_GetScancodeName(SDL_Scancode(index)); // It looks like the functions we call return an empty string rather than null on failure, but it's better to be safe. if (ret && *ret) return ret; else return "Unknown " + std::to_string(index); } else if (index >= BeginMouseButtons && index < EndMouseButtons) { switch (index) { case mouse_left: return "Left Mouse Button"; case mouse_middle: return "Middle Mouse Button"; case mouse_right: return "Right Mouse Button"; case mouse_x1: return "X1 Mouse Button"; case mouse_x2: return "X2 Mouse Button"; default: return "Mouse Button " + std::to_string(index - mouse_left + 1); } } else { switch (index) { case mouse_wheel_up: return "Mouse Wheel Up"; case mouse_wheel_down: return "Mouse Wheel Down"; case mouse_wheel_left: return "Mouse Wheel Left"; case mouse_wheel_right: return "Mouse Wheel Right"; default: return "Invalid " + std::to_string(index); } } } // If a key is currently pressed (not down), assigns its index to this button. // Returns false if nothing is pressed. bool AssignKey() { return Assign(BeginKeys, EndKeys); } // Same but for the mouse buttons. bool AssignMouseButton() { return Assign(BeginMouseButtons, EndMouseButtons); } // Same but for the mouse wheel. bool AssignMouseWheel() { return Assign(BeginMouseWheel, EndMouseWheel); } }; class ButtonList { std::vector<Button> buttons; mutable std::uint64_t cached_time = 0; mutable std::optional<bool> cached_pressed, cached_released, cached_repeated, cached_down; void UpdateCache() const { auto cur_time = Interface::Window::Get().Ticks(); if (cur_time == cached_time) return; cached_time = cur_time; cached_pressed.reset(); cached_released.reset(); cached_repeated.reset(); cached_down.reset(); } public: ButtonList() {} ButtonList(std::vector<Button> buttons) : buttons(buttons) {} [[nodiscard]] const std::vector<Button> &GetButtons() const {return buttons;} [[nodiscard]] std::vector<Button> &ModifyButtons() {cached_time = 0; return buttons;} [[nodiscard]] bool pressed() const { // Return true if at least one button is pressed, and none of them are down and not pressed at the same time. UpdateCache(); if (!cached_pressed) { cached_pressed = false; for (const Button &button : buttons) { bool button_pressed = button.pressed(); if (!button_pressed && button.down()) { *cached_pressed = false; break; } if (button_pressed) *cached_pressed = true; } } return *cached_pressed; } [[nodiscard]] bool released() const { // Return true if at least one button is released, and none of them are down. UpdateCache(); if (!cached_released) { cached_released = false; for (const Button &button : buttons) { bool button_released = button.released(); if (!button_released && !button.pressed() && button.down()) // This can't be just `button.down()` to properly handle regrabbing the (same or different) button on the same tick. { *cached_released = false; break; } if (button_released) *cached_released = true; } } return *cached_released; } [[nodiscard]] bool repeated() const { // Return true if any of the buttons is repeated. UpdateCache(); if (!cached_repeated) cached_repeated = std::any_of(buttons.begin(), buttons.end(), std::mem_fn(&Button::repeated)); return *cached_repeated; } [[nodiscard]] bool down() const { // Return true if any of the buttons is down. UpdateCache(); if (!cached_down) cached_down = std::any_of(buttons.begin(), buttons.end(), std::mem_fn(&Button::down)); return *cached_down; } [[nodiscard]] bool up() const { return !down(); } }; }
34.751111
196
0.494309
[ "vector" ]
b0b910ac593b3b585ca4438e80d5dfc33cd32f79
318
h
C
ShapeInterface/Inheritance/Reactangle.h
NathanKr/CPP
62f9c996af49e42d9f4e2ff1961a59fbb2b29d6d
[ "MIT" ]
null
null
null
ShapeInterface/Inheritance/Reactangle.h
NathanKr/CPP
62f9c996af49e42d9f4e2ff1961a59fbb2b29d6d
[ "MIT" ]
null
null
null
ShapeInterface/Inheritance/Reactangle.h
NathanKr/CPP
62f9c996af49e42d9f4e2ff1961a59fbb2b29d6d
[ "MIT" ]
null
null
null
#pragma once #include "Shape.h" class Reactangle : public Shape { public: Reactangle(); Reactangle(int width ,int height , int x , int y); ~Reactangle(); void SetWidth(int width); void SetHeight(int height); float GetArea() const; int GetWidth() const; int GetHeight() const; private: int width, height; };
16.736842
51
0.701258
[ "shape" ]
b0bf1341e060198509cc2d20715f5d9343fb47f5
36,109
h
C
iPhoneOS15.2.sdk/System/Library/Frameworks/AVFAudio.framework/Headers/AVAudioSessionTypes.h
bakedpotato191/sdks
7b5c8c299a8afcb6d68b356668b4949a946734d9
[ "MIT" ]
10
2019-04-09T19:28:16.000Z
2021-08-11T19:23:00.000Z
iPhoneOS15.0.sdk/System/Library/Frameworks/AVFAudio.framework/Headers/AVAudioSessionTypes.h
chrisharper22/sdks
9b2f79c4a48fd5ca9a602044e617231d639a3f57
[ "MIT" ]
null
null
null
iPhoneOS15.0.sdk/System/Library/Frameworks/AVFAudio.framework/Headers/AVAudioSessionTypes.h
chrisharper22/sdks
9b2f79c4a48fd5ca9a602044e617231d639a3f57
[ "MIT" ]
2
2020-03-01T17:12:05.000Z
2021-08-11T14:59:07.000Z
#if (defined(USE_AVFAUDIO_PUBLIC_HEADERS) && USE_AVFAUDIO_PUBLIC_HEADERS) || !__has_include(<AudioSession/AVAudioSessionTypes.h>) /*! @file AVAudioSessionTypes.h @framework AudioSession.framework @copyright (c) 2009-2020 Apple Inc. All rights reserved. */ #ifndef AudioSession_AVAudioSessionTypes_h #define AudioSession_AVAudioSessionTypes_h #import <CoreAudioTypes/CoreAudioTypes.h> #import <Foundation/Foundation.h> #import <os/base.h> #pragma mark -- constants for endpoint and port types -- /// A port describes a specific type of audio input or output device or connector. typedef NSString *AVAudioSessionPort NS_STRING_ENUM; /* input port types */ /// Line level input on a dock connector OS_EXPORT AVAudioSessionPort const AVAudioSessionPortLineIn API_AVAILABLE(ios(6.0), watchos(2.0), tvos(9.0)) API_UNAVAILABLE(macos); /// Built-in microphone on an iOS device OS_EXPORT AVAudioSessionPort const AVAudioSessionPortBuiltInMic API_AVAILABLE(ios(6.0), watchos(2.0), tvos(9.0)) API_UNAVAILABLE(macos); /// Microphone on a wired headset. Headset refers to an accessory that has headphone outputs paired with a /// microphone. OS_EXPORT AVAudioSessionPort const AVAudioSessionPortHeadsetMic API_AVAILABLE(ios(6.0), watchos(2.0), tvos(9.0)) API_UNAVAILABLE(macos); /* output port types */ /// Line level output on a dock connector OS_EXPORT AVAudioSessionPort const AVAudioSessionPortLineOut API_AVAILABLE(ios(6.0), watchos(2.0), tvos(9.0)) API_UNAVAILABLE(macos); /// Headphone or headset output OS_EXPORT AVAudioSessionPort const AVAudioSessionPortHeadphones API_AVAILABLE(ios(6.0), watchos(2.0), tvos(9.0)) API_UNAVAILABLE(macos); /// Output on a Bluetooth A2DP device OS_EXPORT AVAudioSessionPort const AVAudioSessionPortBluetoothA2DP API_AVAILABLE(ios(6.0), watchos(2.0), tvos(9.0)) API_UNAVAILABLE(macos); /// The speaker you hold to your ear when on a phone call OS_EXPORT AVAudioSessionPort const AVAudioSessionPortBuiltInReceiver API_AVAILABLE(ios(6.0), watchos(2.0), tvos(9.0)) API_UNAVAILABLE(macos); /// Built-in speaker on an iOS device OS_EXPORT AVAudioSessionPort const AVAudioSessionPortBuiltInSpeaker API_AVAILABLE(ios(6.0), watchos(2.0), tvos(9.0)) API_UNAVAILABLE(macos); /// Output via High-Definition Multimedia Interface OS_EXPORT AVAudioSessionPort const AVAudioSessionPortHDMI API_AVAILABLE(ios(6.0), watchos(2.0), tvos(9.0)) API_UNAVAILABLE(macos); /// Output on a remote Air Play device OS_EXPORT AVAudioSessionPort const AVAudioSessionPortAirPlay API_AVAILABLE(ios(6.0), watchos(2.0), tvos(9.0)) API_UNAVAILABLE(macos); /// Output on a Bluetooth Low Energy device OS_EXPORT AVAudioSessionPort const AVAudioSessionPortBluetoothLE API_AVAILABLE(ios(7.0), watchos(2.0), tvos(9.0)) API_UNAVAILABLE(macos); /* port types that refer to either input or output */ /// Input or output on a Bluetooth Hands-Free Profile device OS_EXPORT AVAudioSessionPort const AVAudioSessionPortBluetoothHFP API_AVAILABLE(ios(6.0), watchos(2.0), tvos(9.0)) API_UNAVAILABLE(macos); /// Input or output on a Universal Serial Bus device OS_EXPORT AVAudioSessionPort const AVAudioSessionPortUSBAudio API_AVAILABLE(ios(6.0), watchos(2.0), tvos(9.0)) API_UNAVAILABLE(macos); /// Input or output via Car Audio OS_EXPORT AVAudioSessionPort const AVAudioSessionPortCarAudio API_AVAILABLE(ios(7.0), watchos(2.0), tvos(9.0)) API_UNAVAILABLE(macos); /// Input or output that does not correspond to real audio hardware OS_EXPORT AVAudioSessionPort const AVAudioSessionPortVirtual API_AVAILABLE(ios(14.0), watchos(7.0), tvos(14.0)) API_UNAVAILABLE(macos); /// Input or output connected via the PCI (Peripheral Component Interconnect) bus OS_EXPORT AVAudioSessionPort const AVAudioSessionPortPCI API_AVAILABLE(ios(14.0), watchos(7.0), tvos(14.0)) API_UNAVAILABLE(macos); /// Input or output connected via FireWire OS_EXPORT AVAudioSessionPort const AVAudioSessionPortFireWire API_AVAILABLE(ios(14.0), watchos(7.0), tvos(14.0)) API_UNAVAILABLE(macos); /// Input or output connected via DisplayPort OS_EXPORT AVAudioSessionPort const AVAudioSessionPortDisplayPort API_AVAILABLE(ios(14.0), watchos(7.0), tvos(14.0)) API_UNAVAILABLE(macos); /// Input or output connected via AVB (Audio Video Bridging) OS_EXPORT AVAudioSessionPort const AVAudioSessionPortAVB API_AVAILABLE(ios(14.0), watchos(7.0), tvos(14.0)) API_UNAVAILABLE(macos); /// Input or output connected via Thunderbolt OS_EXPORT AVAudioSessionPort const AVAudioSessionPortThunderbolt API_AVAILABLE(ios(14.0), watchos(7.0), tvos(14.0)) API_UNAVAILABLE(macos); #pragma mark -- audio session categories -- /// A category defines a broad set of behaviors for a session. typedef NSString *AVAudioSessionCategory NS_STRING_ENUM; /*! Use this category for background sounds such as rain, car engine noise, etc. Mixes with other music. */ OS_EXPORT AVAudioSessionCategory const AVAudioSessionCategoryAmbient API_AVAILABLE(ios(3.0), watchos(2.0), tvos(9.0)) API_UNAVAILABLE(macos); /*! Use this category for background sounds. Other music will stop playing. */ OS_EXPORT AVAudioSessionCategory const AVAudioSessionCategorySoloAmbient API_AVAILABLE(ios(3.0), watchos(2.0), tvos(9.0)) API_UNAVAILABLE(macos); /*! Use this category for music tracks.*/ OS_EXPORT AVAudioSessionCategory const AVAudioSessionCategoryPlayback API_AVAILABLE(ios(3.0), watchos(2.0), tvos(9.0)) API_UNAVAILABLE(macos); /*! Use this category when recording audio. */ OS_EXPORT AVAudioSessionCategory const AVAudioSessionCategoryRecord API_AVAILABLE(ios(3.0), watchos(2.0), tvos(9.0)) API_UNAVAILABLE(macos); /*! Use this category when recording and playing back audio. */ OS_EXPORT AVAudioSessionCategory const AVAudioSessionCategoryPlayAndRecord API_AVAILABLE(ios(3.0), watchos(2.0), tvos(9.0)) API_UNAVAILABLE(macos); /*! Use this category when using a hardware codec or signal processor while not playing or recording audio. */ OS_EXPORT AVAudioSessionCategory const AVAudioSessionCategoryAudioProcessing API_DEPRECATED("No longer supported", ios(3.0, 10.0)) API_UNAVAILABLE(watchos, tvos) API_UNAVAILABLE(macos); /*! Use this category to customize the usage of available audio accessories and built-in audio hardware. For example, this category provides an application with the ability to use an available USB output and headphone output simultaneously for separate, distinct streams of audio data. Use of this category by an application requires a more detailed knowledge of, and interaction with, the capabilities of the available audio routes. May be used for input, output, or both. Note that not all output types and output combinations are eligible for multi-route. Input is limited to the last-in input port. Eligible inputs consist of the following: AVAudioSessionPortUSBAudio, AVAudioSessionPortHeadsetMic, and AVAudioSessionPortBuiltInMic. Eligible outputs consist of the following: AVAudioSessionPortUSBAudio, AVAudioSessionPortLineOut, AVAudioSessionPortHeadphones, AVAudioSessionPortHDMI, and AVAudioSessionPortBuiltInSpeaker. Note that AVAudioSessionPortBuiltInSpeaker is only allowed to be used when there are no other eligible outputs connected. */ OS_EXPORT AVAudioSessionCategory const AVAudioSessionCategoryMultiRoute API_AVAILABLE(ios(6.0), watchos(2.0), tvos(9.0)) API_UNAVAILABLE(macos); #pragma mark -- Values for the mode property -- /*! @brief Modes modify the audio category in order to introduce behavior that is tailored to the specific use of audio within an application. Available in iOS 5.0 and greater. */ typedef NSString *AVAudioSessionMode NS_STRING_ENUM; /*! The default mode */ OS_EXPORT AVAudioSessionMode const AVAudioSessionModeDefault API_AVAILABLE(ios(5.0), watchos(2.0), tvos(9.0)) API_UNAVAILABLE(macos); /*! Only valid with AVAudioSessionCategoryPlayAndRecord. Appropriate for Voice over IP (VoIP) applications. Reduces the number of allowable audio routes to be only those that are appropriate for VoIP applications and may engage appropriate system-supplied signal processing. Has the side effect of setting AVAudioSessionCategoryOptionAllowBluetooth */ OS_EXPORT AVAudioSessionMode const AVAudioSessionModeVoiceChat API_AVAILABLE(ios(5.0), watchos(2.0), tvos(9.0)) API_UNAVAILABLE(macos); /*! Set by Game Kit on behalf of an application that uses a GKVoiceChat object; valid only with the AVAudioSessionCategoryPlayAndRecord category. Do not set this mode directly. If you need similar behavior and are not using a GKVoiceChat object, use AVAudioSessionModeVoiceChat instead. */ OS_EXPORT AVAudioSessionMode const AVAudioSessionModeGameChat API_AVAILABLE(ios(5.0), watchos(2.0), tvos(9.0)) API_UNAVAILABLE(macos); /*! Only valid with AVAudioSessionCategoryPlayAndRecord or AVAudioSessionCategoryRecord. Modifies the audio routing options and may engage appropriate system-supplied signal processing. */ OS_EXPORT AVAudioSessionMode const AVAudioSessionModeVideoRecording API_AVAILABLE(ios(5.0), watchos(2.0), tvos(9.0)) API_UNAVAILABLE(macos); /*! Appropriate for applications that wish to minimize the effect of system-supplied signal processing for input and/or output audio signals. */ OS_EXPORT AVAudioSessionMode const AVAudioSessionModeMeasurement API_AVAILABLE(ios(5.0), watchos(2.0), tvos(9.0)) API_UNAVAILABLE(macos); /*! Engages appropriate output signal processing for movie playback scenarios. Currently only applied during playback over built-in speaker. */ OS_EXPORT AVAudioSessionMode const AVAudioSessionModeMoviePlayback API_AVAILABLE(ios(6.0), watchos(2.0), tvos(9.0)) API_UNAVAILABLE(macos); /*! Only valid with kAudioSessionCategory_PlayAndRecord. Reduces the number of allowable audio routes to be only those that are appropriate for video chat applications. May engage appropriate system-supplied signal processing. Has the side effect of setting AVAudioSessionCategoryOptionAllowBluetooth and AVAudioSessionCategoryOptionDefaultToSpeaker. */ OS_EXPORT AVAudioSessionMode const AVAudioSessionModeVideoChat API_AVAILABLE(ios(7.0), watchos(2.0), tvos(9.0)) API_UNAVAILABLE(macos); /*! Appropriate for applications which play spoken audio and wish to be paused (via audio session interruption) rather than ducked if another app (such as a navigation app) plays a spoken audio prompt. Examples of apps that would use this are podcast players and audio books. For more information, see the related category option AVAudioSessionCategoryOptionInterruptSpokenAudioAndMixWithOthers. */ OS_EXPORT AVAudioSessionMode const AVAudioSessionModeSpokenAudio API_AVAILABLE(ios(9.0), watchos(2.0), tvos(9.0)) API_UNAVAILABLE(macos); /*! Appropriate for applications which play audio using text to speech. Setting this mode allows for different routing behaviors when connected to certain audio devices such as CarPlay. An example of an app that would use this mode is a turn by turn navigation app that plays short prompts to the user. Typically, these same types of applications would also configure their session to use AVAudioSessionCategoryOptionDuckOthers and AVAudioSessionCategoryOptionInterruptSpokenAudioAndMixWithOthers */ OS_EXPORT AVAudioSessionMode const AVAudioSessionModeVoicePrompt API_AVAILABLE(ios(12.0), watchos(5.0), tvos(12.0)) API_UNAVAILABLE(macos); #pragma mark-- enumerations -- /*! @enum AVAudioSessionActivationOptions @brief For use with activateWithOptions:completionHandler: Reserved for future use. Added in watchOS 5.0. */ typedef NS_OPTIONS(NSUInteger, AVAudioSessionActivationOptions) { AVAudioSessionActivationOptionNone = 0 }; /// For use with overrideOutputAudioPort:error: typedef NS_ENUM(NSUInteger, AVAudioSessionPortOverride) { /// No override. Return audio routing to the default state for the current audio category. AVAudioSessionPortOverrideNone = 0, /// Route audio output to speaker. Use this override with AVAudioSessionCategoryPlayAndRecord, /// which by default routes the output to the receiver. AVAudioSessionPortOverrideSpeaker API_UNAVAILABLE(tvos, watchos, macos) = 'spkr' }; /// Values for AVAudioSessionRouteChangeReasonKey in AVAudioSessionRouteChangeNotification's /// userInfo dictionary typedef NS_ENUM(NSUInteger, AVAudioSessionRouteChangeReason) { /// The reason is unknown. AVAudioSessionRouteChangeReasonUnknown = 0, /// A new device became available (e.g. headphones have been plugged in). AVAudioSessionRouteChangeReasonNewDeviceAvailable = 1, /// The old device became unavailable (e.g. headphones have been unplugged). AVAudioSessionRouteChangeReasonOldDeviceUnavailable = 2, /// The audio category has changed (e.g. AVAudioSessionCategoryPlayback has been changed to /// AVAudioSessionCategoryPlayAndRecord). AVAudioSessionRouteChangeReasonCategoryChange = 3, /// The route has been overridden (e.g. category is AVAudioSessionCategoryPlayAndRecord and /// the output has been changed from the receiver, which is the default, to the speaker). AVAudioSessionRouteChangeReasonOverride = 4, /// The device woke from sleep. AVAudioSessionRouteChangeReasonWakeFromSleep = 6, /// Returned when there is no route for the current category (for instance, the category is /// AVAudioSessionCategoryRecord but no input device is available). AVAudioSessionRouteChangeReasonNoSuitableRouteForCategory = 7, /// Indicates that the set of input and/our output ports has not changed, but some aspect of /// their configuration has changed. For example, a port's selected data source has changed. /// (Introduced in iOS 7.0, watchOS 2.0, tvOS 9.0). AVAudioSessionRouteChangeReasonRouteConfigurationChange = 8 }; /*! @enum AVAudioSessionCategoryOptions @brief Customization of various aspects of a category's behavior. Use with setCategory:mode:options:error:. Applications must be prepared for changing category options to fail as behavior may change in future releases. If an application changes its category, it should reassert the options, since they are not sticky across category changes. Introduced in iOS 6.0 / watchOS 2.0 / tvOS 9.0. @var AVAudioSessionCategoryOptionMixWithOthers Controls whether other active audio apps will be interrupted or mixed with when your app's audio session goes active. Details depend on the category. AVAudioSessionCategoryPlayAndRecord or AVAudioSessionCategoryMultiRoute: MixWithOthers defaults to false, but can be set to true, allowing other applications to play in the background while your app has both audio input and output enabled. AVAudioSessionCategoryPlayback: MixWithOthers defaults to false, but can be set to true, allowing other applications to play in the background. Your app will still be able to play regardless of the setting of the ringer switch. Other categories: MixWithOthers defaults to false and cannot be changed. MixWithOthers is only valid with AVAudioSessionCategoryPlayAndRecord, AVAudioSessionCategoryPlayback, and AVAudioSessionCategoryMultiRoute. @var AVAudioSessionCategoryOptionDuckOthers Controls whether or not other active audio apps will be ducked when when your app's audio session goes active. An example of this is a workout app, which provides periodic updates to the user. It reduces the volume of any music currently being played while it provides its status. Defaults to off. Note that the other audio will be ducked for as long as the current session is active. You will need to deactivate your audio session when you want to restore full volume playback (un-duck) other sessions. Setting this option will also make your session mixable with others (AVAudioSessionCategoryOptionMixWithOthers will be set). DuckOthers is only valid with AVAudioSessionCategoryAmbient, AVAudioSessionCategoryPlayAndRecord, AVAudioSessionCategoryPlayback, and AVAudioSessionCategoryMultiRoute. @var AVAudioSessionCategoryOptionAllowBluetooth Allows an application to change the default behavior of some audio session categories with regard to whether Bluetooth Hands-Free Profile (HFP) devices are available for routing. The exact behavior depends on the category. AVAudioSessionCategoryPlayAndRecord: AllowBluetooth defaults to false, but can be set to true, allowing a paired bluetooth HFP device to appear as an available route for input, while playing through the category-appropriate output. AVAudioSessionCategoryRecord: AllowBluetooth defaults to false, but can be set to true, allowing a paired Bluetooth HFP device to appear as an available route for input Other categories: AllowBluetooth defaults to false and cannot be changed. Enabling Bluetooth for input in these categories is not allowed. @var AVAudioSessionCategoryOptionDefaultToSpeaker Allows an application to change the default behavior of some audio session categories with regard to the audio route. The exact behavior depends on the category. AVAudioSessionCategoryPlayAndRecord: DefaultToSpeaker will default to false, but can be set to true, routing to Speaker (instead of Receiver) when no other audio route is connected. Other categories: DefaultToSpeaker is always false and cannot be changed. @var AVAudioSessionCategoryOptionInterruptSpokenAudioAndMixWithOthers When a session with InterruptSpokenAudioAndMixWithOthers set goes active, then if there is another playing app whose session mode is AVAudioSessionModeSpokenAudio (for podcast playback in the background, for example), then the spoken-audio session will be interrupted. A good use of this is for a navigation app that provides prompts to its user: it pauses any spoken audio currently being played while it plays the prompt. InterruptSpokenAudioAndMixWithOthers defaults to off. Note that the other app's audio will be paused for as long as the current session is active. You will need to deactivate your audio session to allow the other session to resume playback. Setting this option will also make your category mixable with others (AVAudioSessionCategoryOptionMixWithOthers will be set). If you want other non-spoken audio apps to duck their audio when your app's session goes active, also set AVAudioSessionCategoryOptionDuckOthers. Only valid with AVAudioSessionCategoryPlayAndRecord, AVAudioSessionCategoryPlayback, and AVAudioSessionCategoryMultiRoute. Introduced in iOS 9.0 / watchOS 2.0 / tvOS 9.0. @var AVAudioSessionCategoryOptionAllowBluetoothA2DP Allows an application to change the default behavior of some audio session categories with regard to whether Bluetooth Advanced Audio Distribution Profile (A2DP) devices are available for routing. The exact behavior depends on the category. AVAudioSessionCategoryPlayAndRecord: AllowBluetoothA2DP defaults to false, but can be set to true, allowing a paired Bluetooth A2DP device to appear as an available route for output, while recording through the category-appropriate input. AVAudioSessionCategoryMultiRoute and AVAudioSessionCategoryRecord: AllowBluetoothA2DP is false, and cannot be set to true. Other categories: AllowBluetoothA2DP is always implicitly true and cannot be changed; Bluetooth A2DP ports are always supported in output-only categories. Setting both AVAudioSessionCategoryOptionAllowBluetooth and AVAudioSessionCategoryOptionAllowBluetoothA2DP is allowed. In cases where a single Bluetooth device supports both HFP and A2DP, the HFP ports will be given a higher priority for routing. For HFP and A2DP ports on separate hardware devices, the last-in wins rule applies. Introduced in iOS 10.0 / watchOS 3.0 / tvOS 10.0. @var AVAudioSessionCategoryOptionAllowAirPlay Allows an application to change the default behavior of some audio session categories with with regard to showing AirPlay devices as available routes. This option applies to various categories in the same way as AVAudioSessionCategoryOptionAllowBluetoothA2DP; see above for details. Only valid with AVAudioSessionCategoryPlayAndRecord. Introduced in iOS 10.0 / tvOS 10.0. @var AVAudioSessionCategoryOptionOverrideMutedMicrophoneInterruption Some devices include a privacy feature that mutes the built-in microphone at a hardware level under certain conditions e.g. when the Smart Folio of an iPad is closed. The default behavior is to interrupt the session using the built-in microphone when that microphone is muted in hardware. This option allows an application to opt out of the default behavior if it is using a category that supports both input and output, such as AVAudioSessionCategoryPlayAndRecord, and wants to allow its session to stay activated even when the microphone has been muted. The result would be that playback continues as normal, and microphone sample buffers would continue to be produced but all microphone samples would have a value of zero. This may be useful if an application knows that it wants to allow playback to continue and recording/monitoring a muted microphone will not lead to a poor user experience. Attempting to use this option with a session category that doesn't support the use of audio input will result in an error. Note that under the default policy, a session will be interrupted if it is running input at the time when the microphone is muted in hardware. Similarly, attempting to start input when the microphone is muted will fail. Note that this option has no relation to the recordPermission property, which indicates whether or not the user has granted permission to use microphone input. */ typedef NS_OPTIONS(NSUInteger, AVAudioSessionCategoryOptions) { AVAudioSessionCategoryOptionMixWithOthers = 0x1, AVAudioSessionCategoryOptionDuckOthers = 0x2, AVAudioSessionCategoryOptionAllowBluetooth API_UNAVAILABLE(tvos, watchos, macos) = 0x4, AVAudioSessionCategoryOptionDefaultToSpeaker API_UNAVAILABLE(tvos, watchos, macos) = 0x8, AVAudioSessionCategoryOptionInterruptSpokenAudioAndMixWithOthers API_AVAILABLE(ios(9.0), watchos(2.0), tvos(9.0)) API_UNAVAILABLE(macos) = 0x11, AVAudioSessionCategoryOptionAllowBluetoothA2DP API_AVAILABLE(ios(10.0), watchos(3.0), tvos(10.0)) API_UNAVAILABLE(macos) = 0x20, AVAudioSessionCategoryOptionAllowAirPlay API_AVAILABLE(ios(10.0), tvos(10.0)) API_UNAVAILABLE(watchos, macos) = 0x40, AVAudioSessionCategoryOptionOverrideMutedMicrophoneInterruption API_AVAILABLE(ios(14.5), watchos(7.3)) API_UNAVAILABLE(tvos, macos) = 0x80, }; /// Values for AVAudioSessionInterruptionTypeKey in AVAudioSessionInterruptionNotification's /// userInfo dictionary. typedef NS_ENUM(NSUInteger, AVAudioSessionInterruptionType) { AVAudioSessionInterruptionTypeBegan = 1, ///< the system has interrupted your audio session AVAudioSessionInterruptionTypeEnded = 0, ///< the interruption has ended }; /// Values for AVAudioSessionInterruptionOptionKey in AVAudioSessionInterruptionNotification's /// userInfo dictionary. typedef NS_OPTIONS(NSUInteger, AVAudioSessionInterruptionOptions) { /// Indicates that you should resume playback now that the interruption has ended. AVAudioSessionInterruptionOptionShouldResume = 1 }; /*! @enum AVAudioSessionInterruptionReason @brief Values for AVAudioSessionInterruptionReasonKey in AVAudioSessionInterruptionNotification's userInfo dictionary. @var AVAudioSessionInterruptionReasonDefault The audio session was interrupted because another session was activated. @var AVAudioSessionInterruptionReasonAppWasSuspended The audio session was interrupted due to the app being suspended by the operating sytem. Starting in iOS 10, the system will deactivate the audio session of most apps in response to the app process being suspended. When the app starts running again, it will receive the notification that its session has been deactivated by the system. Note that the notification is necessarily delayed in time, due to the fact that the application was suspended at the time the session was deactivated by the system and the notification can only be delivered once the app is running again. @var AVAudioSessionInterruptionReasonBuiltInMicMuted The audio session was interrupted due to the built-in mic being muted e.g. due to an iPad's Smart Folio being closed. */ typedef NS_ENUM(NSUInteger, AVAudioSessionInterruptionReason) { AVAudioSessionInterruptionReasonDefault = 0, AVAudioSessionInterruptionReasonAppWasSuspended = 1, AVAudioSessionInterruptionReasonBuiltInMicMuted = 2 } NS_SWIFT_NAME(AVAudioSession.InterruptionReason); /// options for use when calling setActive:withOptions:error: typedef NS_OPTIONS(NSUInteger, AVAudioSessionSetActiveOptions) { /// Notify an interrupted app that the interruption has ended and it may resume playback. Only /// valid on session deactivation. AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation = 1 }; /// Values for AVAudioSessionSilenceSecondaryAudioHintTypeKey in /// AVAudioSessionSilenceSecondaryAudioHintNotification's userInfo dictionary, to indicate whether /// optional secondary audio muting should begin or end. typedef NS_ENUM(NSUInteger, AVAudioSessionSilenceSecondaryAudioHintType) { /// Another application's primary audio has started. AVAudioSessionSilenceSecondaryAudioHintTypeBegin = 1, /// Another application's primary audio has stopped. AVAudioSessionSilenceSecondaryAudioHintTypeEnd = 0, }; /*! @enum AVAudioSessionIOType @brief Values to be used by setAggregatedIOPreference:error: method. Starting in iOS 10, applications that use AVCaptureSession on iPads and iPhones that support taking Live Photos, will have non-aggregated audio I/O unless the app opts out by setting its AVAudioSessionIOType to Aggregated. Non-aggregated audio I/O means that separate threads will be used to service audio I/O for input and output directions. Note that in cases where the I/O is not aggregated, the sample rate and IO buffer duration properties will map to the output audio device. In this scenario, the input and output audio hardware may be running at different sample rates and with different IO buffer durations. If your app requires input and output audio to be presented in the same realtime I/O callback, or requires that input and output audio have the same sample rate or IO buffer duration, or if your app requires the ability to set a preferred sample rate or IO buffer duration for audio input, set the AVAudioSessionIOType to Aggregated. Apps that don't use AVCaptureSession and use AVAudioSessionCategoryPlayAndRecord will continue to have aggregated audio I/O, as in previous versions of iOS. @var AVAudioSessionIOTypeNotSpecified The default value. If your app does not use AVCaptureSession or does not have any specific requirement for aggregating input and output audio in the same realtime I/O callback, use this value. Note that if your app does not use AVCaptureSession, it will get aggregated I/O when using AVAudioSessionCategoryPlayAndRecord. If your app does utilize AVCaptureSession, use of this value will allow AVCaptureSession to start recording without glitching already running output audio and will allow the system to utilize power-saving optimizations. @var AVAudioSessionIOTypeAggregated Use this value if your session uses AVAudioSessionCategoryPlayAndRecord and requires input and output audio to be presented in the same realtime I/O callback. For example, if your app will be using a RemoteIO with both input and output enabled. Note that your session's preference to use aggregated IO will not be honored if it specifies AVAudioSessionCategoryOptionMixWithOthers AND another app's audio session was already active with non-mixable, non-aggregated input/output. Added in iOS 10.0. Not applicable on watchos, tvos, macos. */ typedef NS_ENUM(NSUInteger, AVAudioSessionIOType) { AVAudioSessionIOTypeNotSpecified = 0, AVAudioSessionIOTypeAggregated = 1, }; /*! @enum AVAudioSessionRouteSharingPolicy @brief Starting in iOS 11, tvOS 11, and watchOS 5, the route sharing policy allows a session to specify that its output audio should be routed somewhere other than the default system output, when appropriate alternative routes are available. @var AVAudioSessionRouteSharingPolicyDefault Follow normal rules for routing audio output. @var AVAudioSessionRouteSharingPolicyLongFormAudio Route output to the shared long-form audio output. A session whose primary use case is as a music or podcast player may use this value to play to the same output as the built-in Music (iOS), Podcasts, or iTunes (macOS) applications. Typically applications that use this policy will also want sign up for remote control events as documented in “Event Handling Guide for UIKit Apps” and will want to utilize MediaPlayer framework’s MPNowPlayingInfoCenter class. All applications on the system that use the long-form audio route sharing policy will have their audio routed to the same location. Apps running on watchOS using this policy will also be able to play audio in the background, as long as an eligible audio route can be activated. Apps running on watchOS using this policy must use -activateWithOptions:completionHandler: instead of -setActive:withOptions:error: in order to ensure that the user will be given the opportunity to pick an appropriate audio route in cases where the system is unable to automatically pick the route. @var AVAudioSessionRouteSharingPolicyLongForm Deprecated. Replaced by AVAudioSessionRouteSharingPolicyLongFormAudio. @var AVAudioSessionRouteSharingPolicyIndependent Applications should not attempt to set this value directly. On iOS, this value will be set by the system in cases where route picker UI is used to direct video to a wireless route. @var AVAudioSessionRouteSharingPolicyLongFormVideo Route output to the shared long-form video output. A session whose primary use case is as a movie or other long-form video content player may use this value to play to the same output as other long-form video content applications such as the built-in TV (iOS) application. Applications that use this policy will also want to also set the AVInitialRouteSharingPolicy key in their Info.plist to "LongFormVideo". All applications on the system that use the long-form video route sharing policy will have their audio and video routed to the same location (e.g. AppleTV when an AirPlay route is selected). Video content not using this route sharing policy will remain local to the playback device even when long form video content is being routed to AirPlay. */ typedef NS_ENUM(NSUInteger, AVAudioSessionRouteSharingPolicy) { AVAudioSessionRouteSharingPolicyDefault = 0, AVAudioSessionRouteSharingPolicyLongFormAudio = 1, AVAudioSessionRouteSharingPolicyLongForm API_DEPRECATED_WITH_REPLACEMENT("AVAudioSessionRouteSharingPolicyLongFormAudio", ios(11.0, 13.0), watchos(4.0, 6.0), tvos(11.0, 13.0)) API_UNAVAILABLE(macos) = AVAudioSessionRouteSharingPolicyLongFormAudio, AVAudioSessionRouteSharingPolicyIndependent = 2, AVAudioSessionRouteSharingPolicyLongFormVideo API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(watchos, tvos, macos) = 3, }; /*! @enum AVAudioSessionPromptStyle @brief The prompt style is a hint to sessions that use AVAudioSessionModeVoicePrompt to modify the type of prompt they play in response to other audio activity on the system, such as Siri or phone calls. Sessions that issue voice prompts are encouraged to pay attention to changes in the prompt style and modify their prompts in response. Apple encourages the use of non-verbal prompts when the Short style is requested. @var AVAudioSessionPromptStyleNone Indicates that another session is actively using microphone input and would be negatively impacted by having prompts play at that time. For example if Siri is recognizing speech, having navigation or exercise prompts play, could interfere with its ability to accurately recognize the user’s speech. Client sessions should refrain from playing any prompts while the prompt style is None. @var AVAudioSessionPromptStyleShort Indicates one of three states: Siri is active but not recording, voicemail playback is active, or voice call is active. Short, non-verbal versions of prompts should be used. @var AVAudioSessionPromptStyleNormal Indicates that normal (long, verbal) versions of prompts may be used. */ typedef NS_ENUM(NSUInteger, AVAudioSessionPromptStyle) { AVAudioSessionPromptStyleNone = 'none', AVAudioSessionPromptStyleShort = 'shrt', AVAudioSessionPromptStyleNormal = 'nrml', }; /*! @enum AVAudioStereoOrientation @brief Constants indicating stereo input audio orientation, for use with built-in mic input data sources with a stereo polar pattern selected. @var AVAudioStereoOrientationNone Indicates that audio capture orientation is not applicable (on mono capture, for instance). @var AVAudioStereoOrientationPortrait Indicates that audio capture should be oriented vertically, Lightning connector on the bottom. @var AVAudioStereoOrientationPortraitUpsideDown Indicates that audio capture should be oriented vertically, Lightning connector on the top. @var AVAudioStereoOrientationLandscapeRight Indicates that audio capture should be oriented horizontally, Lightning connector on the right. @var AVAudioStereoOrientationLandscapeLeft Indicates that audio capture should be oriented horizontally, Lightning connector on the left. */ typedef NS_ENUM(NSInteger, AVAudioStereoOrientation) { AVAudioStereoOrientationNone = 0, AVAudioStereoOrientationPortrait = 1, AVAudioStereoOrientationPortraitUpsideDown = 2, AVAudioStereoOrientationLandscapeRight = 3, AVAudioStereoOrientationLandscapeLeft = 4, } NS_SWIFT_NAME(AVAudioSession.StereoOrientation); /*! @enum AVAudioSessionRecordPermission @brief These are the values returned by recordPermission. @var AVAudioSessionRecordPermissionUndetermined The user has not yet been asked for permission. @var AVAudioSessionRecordPermissionDenied The user has been asked and has denied permission. @var AVAudioSessionRecordPermissionGranted The user has been asked and has granted permission. Introduced: ios(8.0), watchos(4.0) */ typedef NS_ENUM(NSUInteger, AVAudioSessionRecordPermission) { AVAudioSessionRecordPermissionUndetermined = 'undt', AVAudioSessionRecordPermissionDenied = 'deny', AVAudioSessionRecordPermissionGranted = 'grnt' }; #endif // AudioSession_AVAudioSessionTypes_h #else #include <AudioSession/AVAudioSessionTypes.h> #endif
59.389803
251
0.776039
[ "object" ]
b0c0c4ddbd370d291857a79db8de3c37726f272c
709
h
C
source/app/SceneImporter.h
aviktorov/pbr-sandbox
66a71c741dac2d2dd46668a506d02de88f05e399
[ "MIT" ]
19
2020-02-11T19:57:41.000Z
2022-02-20T14:11:33.000Z
source/app/SceneImporter.h
aviktorov/pbr-sandbox
66a71c741dac2d2dd46668a506d02de88f05e399
[ "MIT" ]
null
null
null
source/app/SceneImporter.h
aviktorov/pbr-sandbox
66a71c741dac2d2dd46668a506d02de88f05e399
[ "MIT" ]
5
2019-11-05T17:38:33.000Z
2022-03-04T12:49:58.000Z
#pragma once #include <scapes/visual/Fwd.h> namespace game { class World; } namespace render::backend { class Driver; } class ApplicationResources; struct cgltf_mesh; struct aiMesh; /* */ class SceneImporter { public: SceneImporter(game::World *world, scapes::visual::API *visual_api); ~SceneImporter(); bool importCGLTF(const char *path, ApplicationResources *resources); bool importAssimp(const char *path, ApplicationResources *resources); void clear(); private: scapes::visual::MeshHandle import_cgltf_mesh(const cgltf_mesh *mesh); scapes::visual::MeshHandle import_assimp_mesh(const aiMesh *mesh); private: game::World *world {nullptr}; scapes::visual::API *visual_api {nullptr}; };
17.725
70
0.754584
[ "mesh", "render" ]
b8047a941c4303841ea11da91aa9ea217efbd9ba
921
c
C
src/lib/dev/mos3/mos3del.c
prepare/spice3f5
a0d8c69d43927b7ced9cb619e3faa3d56332566a
[ "BSD-4-Clause-UC" ]
4
2018-02-21T17:31:40.000Z
2022-03-03T01:43:32.000Z
src/lib/dev/mos3/mos3del.c
prepare/spice3f5
a0d8c69d43927b7ced9cb619e3faa3d56332566a
[ "BSD-4-Clause-UC" ]
null
null
null
src/lib/dev/mos3/mos3del.c
prepare/spice3f5
a0d8c69d43927b7ced9cb619e3faa3d56332566a
[ "BSD-4-Clause-UC" ]
2
2019-07-20T00:47:29.000Z
2020-01-06T19:18:21.000Z
/********** Copyright 1990 Regents of the University of California. All rights reserved. Author: 1985 Thomas L. Quarles **********/ /* */ #include "spice.h" #include <stdio.h> #include "util.h" #include "mos3defs.h" #include "sperror.h" #include "suffix.h" int MOS3delete(inModel,name,inst) GENmodel *inModel; IFuid name; GENinstance **inst; { MOS3model *model = (MOS3model *)inModel; MOS3instance **fast = (MOS3instance **)inst; MOS3instance **prev = NULL; MOS3instance *here; for( ; model ; model = model->MOS3nextModel) { prev = &(model->MOS3instances); for(here = *prev; here ; here = *prev) { if(here->MOS3name == name || (fast && here==*fast) ) { *prev= here->MOS3nextInstance; FREE(here); return(OK); } prev = &(here->MOS3nextInstance); } } return(E_NODEV); }
23.025
77
0.563518
[ "model" ]
b808a22ac4332693df444914b4bb8476f5875bc3
9,351
h
C
include/rw/_specialized.h
isabella232/stdcxx
b0b0cab391b7b1f2d17ef4342aeee6b792bde63c
[ "Apache-2.0" ]
53
2015-01-13T05:46:43.000Z
2022-02-24T23:46:04.000Z
include/rw/_specialized.h
apache/stdcxx
b0b0cab391b7b1f2d17ef4342aeee6b792bde63c
[ "Apache-2.0" ]
1
2021-11-04T12:35:39.000Z
2021-11-04T12:35:39.000Z
include/rw/_specialized.h
isabella232/stdcxx
b0b0cab391b7b1f2d17ef4342aeee6b792bde63c
[ "Apache-2.0" ]
33
2015-07-09T13:31:00.000Z
2021-11-04T12:12:20.000Z
// -*- C++ -*- /*************************************************************************** * * _specialized.h - definitions of specialized algorithms * * This is an internal header file used to implement the C++ Standard * Library. It should never be #included directly by a program. * * $Id$ * *************************************************************************** * * 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. * * Copyright 1994-2006 Rogue Wave Software. * *************************************************************************** * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * **************************************************************************/ #ifndef _RWSTD_RW_SPECIALIZED_H_INCLUDED #define _RWSTD_RW_SPECIALIZED_H_INCLUDED #ifndef _RWSTD_RW_NEW_H_INCLUDED # include <rw/_new.h> #endif // _RWSTD_RW_NEW_H_INCLUDED #ifndef _RWSTD_RW_ITERBASE_H_INCLUDED # include <rw/_iterbase.h> #endif // _RWSTD_RW_ITERBASE_H_INCLUDED _RWSTD_NAMESPACE (__rw) { #ifndef _RWSTD_NO_NONDEDUCED_CONTEXT # define _RWSTD_CONTAINER_SIZE_TYPE typename _Container::size_type #else # define _RWSTD_CONTAINER_SIZE_TYPE _RWSTD_SIZE_T #endif // _RWSTD_NO_NONDEDUCED_CONTEXT // returns a suggested new capacity for a container needing more space template <class _Container> inline _RWSTD_CONTAINER_SIZE_TYPE __rw_new_capacity (_RWSTD_CONTAINER_SIZE_TYPE __size, const _Container*) { typedef _RWSTD_CONTAINER_SIZE_TYPE _RWSizeT; const _RWSizeT __ratio = _RWSizeT ( (_RWSTD_NEW_CAPACITY_RATIO << 10) / _RWSTD_RATIO_DIVIDER); const _RWSizeT __cap = (__size >> 10) * __ratio + (((__size & 0x3ff) * __ratio) >> 10); return (__size += _RWSTD_MINIMUM_NEW_CAPACITY) > __cap ? __size : __cap; } #undef _RWSTD_CONTAINER_SIZE_TYPE #ifndef _RWSTD_NO_PART_SPEC_OVERLOAD template <class _TypeT, class _TypeU> inline void __rw_construct (_TypeT* __p, _TypeU& __val) { ::new (_RWSTD_STATIC_CAST (void*, __p)) _TypeT (__val); } template <class _TypeT, class _TypeU> inline void __rw_construct (volatile _TypeT* __p, _TypeU& __val) { // remove volatile before invoking operator new __rw_construct (_RWSTD_CONST_CAST (_TypeT*, __p), __val); } #else // #ifdef _RWSTD_NO_PART_SPEC_OVERLOAD template <class _TypeT, class _TypeU> inline void __rw_construct_impl (_TypeT* __p, _TypeU& __val) { ::new (_RWSTD_STATIC_CAST (void*, __p)) _TypeT (__val); } template <class _TypeT, class _TypeU> inline void __rw_construct (volatile _TypeT* __p, _TypeU& __val) { // remove volatile before invoking operator new __rw_construct_impl (_RWSTD_CONST_CAST (_TypeT*, __p), __val); } #endif // _RWSTD_NO_PART_SPEC_OVERLOAD template <class _TypeT> inline void __rw_destroy (_TypeT &__ref) { __ref.~_TypeT (); } template <class _ForwardIterator> inline void __rw_destroy (_ForwardIterator __first, _ForwardIterator __last) { for (; __first != __last; ++__first) __rw_destroy (*__first); } #ifndef _RWSTD_NO_PTR_VALUE_TEMPLATE_OVERLOAD // for compilers that don't optimize "empty" loops template <class _TypeT> inline void __rw_destroy (_TypeT**, _TypeT**) { } #endif // _RWSTD_NO_PTR_VALUE_TEMPLATE_OVERLOAD } // namespace __rw _RWSTD_NAMESPACE (std) { template <class _TypeT> class allocator; // 20.4.4.1 template <class _InputIterator, class _ForwardIterator> inline _ForwardIterator uninitialized_copy (_InputIterator __first, _InputIterator __last, _ForwardIterator __res) { const _ForwardIterator __start = __res; typedef typename iterator_traits<_ForwardIterator>::value_type _TypeT; _TRY { for (; __first != __last; ++__first, ++__res) { // avoid const-qualifying ptr to prevent an HP aCC 3 bug volatile void* /* const */ __ptr = _RWSTD_STATIC_CAST (volatile void*, &*__res); ::new (_RWSTD_CONST_CAST (void*, __ptr)) _TypeT (*__first); } } _CATCH (...) { _RW::__rw_destroy (__start, __res); _RETHROW; } return __res; } #ifdef _RWSTD_ALLOCATOR // extension template <class _InputIterator, class _ForwardIterator, class _Allocator> inline _ForwardIterator uninitialized_copy (_InputIterator __first, _InputIterator __last, _ForwardIterator __res, _Allocator &__alloc) { _ForwardIterator __start = __res; _TRY { for (; __first != __last; ++__first, ++__res) __alloc.construct (__alloc.address (*__res), *__first); } _CATCH (...) { for (; __start != __res; ++__start) __alloc.destroy (__alloc.address (*__start)); _RETHROW; } return __res; } #endif // _RWSTD_ALLOCATOR // 20.4.4.2 template <class _ForwardIterator, class _TypeT> inline void uninitialized_fill (_ForwardIterator __first, _ForwardIterator __last, const _TypeT& __x) { const _ForwardIterator __start = __first; _TRY { for (; __first != __last; ++__first) _RW::__rw_construct (&*__first, __x); } _CATCH (...) { _RW::__rw_destroy (__start, __first); _RETHROW; } } // 20.4.4.3 template <class _ForwardIterator, class _Size, class _TypeT> inline void uninitialized_fill_n (_ForwardIterator __first, _Size __n, const _TypeT& __x) { const _ForwardIterator __start = __first; _TRY { for (; __n; --__n, ++__first) _RW::__rw_construct (&*__first, __x); } _CATCH (...) { _RW::__rw_destroy (__start, __first); _RETHROW; } } #ifdef _RWSTD_ALLOCATOR // extension template <class _ForwardIter, class _Size, class _TypeT, class _Allocator> inline void uninitialized_fill_n (_ForwardIter __first, _Size __n, const _TypeT& __x, _Allocator& __alloc) { _ForwardIter __start = __first; _TRY { for (; __n; --__n, ++__first) __alloc.construct (__alloc.address (*__first), __x); } _CATCH (...) { for (; __start != __first; ++__start) __alloc.destroy (__alloc.address (*__start)); _RETHROW; } } #else // if !defined (_RWSTD_ALLOCATOR) template <class _Allocator, class _TypeT> class allocator_interface; // Specializations for non-standard allocators. When vector calls // uninitialized_{copy,fill_n} with non-standard allocator, a temporary // instance of allocator_interface is passed to these functions. Since // C++ forbids temporaries to be passed as non-const references, we // use these specializations to pass a const reference (and we can force // allocator_interface members construct & destroy to be const). template <class _InputIterator, class _ForwardIterator, class _Allocator, class _TypeT> inline _ForwardIterator uninitialized_copy (_InputIterator __first, _InputIterator __last, _ForwardIterator __res, allocator_interface<_Allocator, _TypeT> &__alloc) { _ForwardIterator __start = __res; _TRY { for (; __first != __last; ++__first, ++__res) __alloc.construct (__alloc.address (*__res), *__first); } _CATCH (...) { for (; __start != __res; ++__start) __alloc.destroy (__alloc.address (*__start)); _RETHROW; } return __res; } template <class _ForwardIter, class _Size, class _TypeT, class _Allocator, class _TypeU> inline void uninitialized_fill_n (_ForwardIter __first, _Size __n, const _TypeT& __x, allocator_interface<_Allocator, _TypeU> &__alloc) { _ForwardIter __start = __first; _TRY { for (; __n; --__n, ++__first) __alloc.construct (__alloc.address (*__first), __x); } _CATCH (...) { for (; __start != __first; ++__start) __alloc.destroy (__alloc.address (*__start)); _RETHROW; } } #endif // _RWSTD_ALLOCATOR } // namespace std #endif // _RWSTD_RW_SPECIALIZED_H_INCLUDED
27.913433
77
0.659716
[ "vector" ]
b8096cc6f82696e6a7bf67682ddd3ff5dd3b7b3f
1,249
h
C
algorithms/medium/1772. Sort Features by Popularity.h
MultivacX/letcode2020
f86289f8718237303918a7705ae31625a12b68f6
[ "MIT" ]
null
null
null
algorithms/medium/1772. Sort Features by Popularity.h
MultivacX/letcode2020
f86289f8718237303918a7705ae31625a12b68f6
[ "MIT" ]
null
null
null
algorithms/medium/1772. Sort Features by Popularity.h
MultivacX/letcode2020
f86289f8718237303918a7705ae31625a12b68f6
[ "MIT" ]
null
null
null
// 1772. Sort Features by Popularity // https://leetcode.com/problems/sort-features-by-popularity/ // Runtime: 632 ms, faster than 100.00% of C++ online submissions for Sort Features by Popularity. // Memory Usage: 75.5 MB, less than 100.00% of C++ online submissions for Sort Features by Popularity. class Solution { public: vector<string> sortFeatures(vector<string>& features, vector<string>& responses) { // feature: {-appearances, idx} unordered_map<string, vector<int>> m; for (int i = 0; i < features.size(); ++i) m.insert({features[i], vector<int>{0, i}}); for (int i = 0, j = 0; i < responses.size(); ++i) { unordered_set<string> visited; istringstream s(responses[i]); while (!s.eof()) { string r; s >> r; if (!visited.insert(r).second) continue; auto it = m.find(r); if (it == m.end()) continue; --it->second[0]; } } sort(begin(features), end(features), [&m](const string& l, const string& r){ return m[l][0] < m[r][0] || (m[l][0] == m[r][0] && m[l][1] < m[r][1]); }); return features; } };
39.03125
102
0.528423
[ "vector" ]
b80a34d3ca46d6b54fe3c654b3ad9ed141624fb6
1,462
c
C
1 SEMESTER/PROGRAMMING/Lab3/Var18/Lab3C/main.c
ZizitopU/KPI
8d97ea48c27fd1fdcb7eef666a1662aa38bbb594
[ "MIT" ]
null
null
null
1 SEMESTER/PROGRAMMING/Lab3/Var18/Lab3C/main.c
ZizitopU/KPI
8d97ea48c27fd1fdcb7eef666a1662aa38bbb594
[ "MIT" ]
null
null
null
1 SEMESTER/PROGRAMMING/Lab3/Var18/Lab3C/main.c
ZizitopU/KPI
8d97ea48c27fd1fdcb7eef666a1662aa38bbb594
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <math.h> #define n 9 void fill(int arr[n][n]){ for(int i = 0; i<n; i++){ for(int j = 0; j<n; j++){ arr[i][j] = 2.758*i*i - 1.5*j - abs(3.3 - i); } } } void printarr(int arr[n][n]){ for(int i = 0; i<n; i++){ for(int j = 0; j<n; j++){ printf("%3d ",arr[i][j]); } printf("\n"); } printf("===================\n"); } void printvector(int vector[n]){ for(int i = 0;i<n;i++){ printf("%3d ",vector[i]); } printf("\n===================\n"); } void makevektor(int arr[n][n], int vector[n]){ for(int j = 0; j < n; j++){ for(int i = 0; i < n; i++){ for(int k = 0; k < n-1; k++){ if(arr[k][j] < arr[k+1][j]){ int t = arr[k][j]; arr[k][j] = arr[k+1][j]; arr[k+1][j] = t; } } } } for(int i = 0;i<n;i++){ vector[i] = arr[n-1][i]; } } float g(int V[n]){ float s = 0; for(int i = 0;i<n;i++){ s+= sqrt(abs(abs(V[i]+1)-10)); } return s; } int main() { int A[n][n]; int V[n]; fill(A); printf("Вихiдна матриця:\n"); printarr(A); makevektor(A,V); printf("Перетворена матриця:\n"); printarr(A); printf("Вектор:\n"); printvector(V); float s = g(V); printf("G(x) = %f\n",s); return 0; }
17.614458
57
0.386457
[ "vector", "3d" ]
b80d135d80d7a494d75a46b897c1fdcb9940c617
459
h
C
Meduza/Include/ECS/EntityTypes.h
NWagter/Meduza
d1df99061381fa1c7665d09e275ddc0060a6ac8d
[ "MIT" ]
6
2020-10-17T10:50:13.000Z
2022-02-25T20:14:23.000Z
Meduza/Include/ECS/EntityTypes.h
NWagter/Meduza
d1df99061381fa1c7665d09e275ddc0060a6ac8d
[ "MIT" ]
null
null
null
Meduza/Include/ECS/EntityTypes.h
NWagter/Meduza
d1df99061381fa1c7665d09e275ddc0060a6ac8d
[ "MIT" ]
1
2020-05-06T12:02:47.000Z
2020-05-06T12:02:47.000Z
#pragma once using EntityID = uint64_t; using ComponentID = uint64_t; using SystemID = uint64_t; using EntityFilter = std::set<ComponentID>; enum class Components : uint16_t { Tag, Transform, Editor, Render, DebugRender, Camera, Scripting, Physics, Collider, ColliderTag, BoxCollider2D, BoxCollider3D, CircleCollider, SphereCollider, AgentComponent, NavSurfaceComponent, Game };
13.5
43
0.662309
[ "render", "transform" ]
b80d2fd7449096cf750ace4083d14ec48a33c2b5
1,434
h
C
vox.geometry/points_to_implicit3.h
yangfengzzz/DigitalVox3
c3277007d7cae90cf3f55930bf86119c93662493
[ "MIT" ]
28
2021-11-23T11:52:55.000Z
2022-03-04T01:48:52.000Z
vox.geometry/points_to_implicit3.h
yangfengzzz/DigitalVox3
c3277007d7cae90cf3f55930bf86119c93662493
[ "MIT" ]
null
null
null
vox.geometry/points_to_implicit3.h
yangfengzzz/DigitalVox3
c3277007d7cae90cf3f55930bf86119c93662493
[ "MIT" ]
3
2022-01-02T12:23:04.000Z
2022-01-07T04:21:26.000Z
// Copyright (c) 2018 Doyub Kim // // I am making my contributions/submissions to this project solely in my // personal capacity and am not conveying any rights to any intellectual // property of any third parties. #ifndef INCLUDE_JET_POINTS_TO_IMPLICIT3_H_ #define INCLUDE_JET_POINTS_TO_IMPLICIT3_H_ #include "array_view.h" #include "grids/scalar_grid.h" #include "matrix.h" namespace vox { namespace geometry { //! Abstract base class for 3-D points-to-implicit converters. class PointsToImplicit3 { public: //! Default constructor. PointsToImplicit3() = default; //! Default copy constructor. PointsToImplicit3(const PointsToImplicit3 &) = default; //! Default move constructor. PointsToImplicit3(PointsToImplicit3 &&) noexcept = default; //! Default virtual destructor. virtual ~PointsToImplicit3() = default; //! Default copy assignment operator. PointsToImplicit3 &operator=(const PointsToImplicit3 &) = default; //! Default move assignment operator. PointsToImplicit3 &operator=(PointsToImplicit3 &&) noexcept = default; //! Converts the given points to implicit surface scalar field. virtual void convert(const ConstArrayView1<Vector3D> &points, ScalarGrid3 *output) const = 0; }; //! Shared pointer for the PointsToImplicit3 type. using PointsToImplicit3Ptr = std::shared_ptr<PointsToImplicit3>; } // namespace vox } // namespace geometry #endif // INCLUDE_JET_POINTS_TO_IMPLICIT3_H_
29.265306
95
0.76569
[ "geometry" ]
b81c3f559c8100f4fc370d86d6077cfbfe798d20
2,810
h
C
AsyncCoreData/Classes/AsyncCoreData+Configration.h
fengwei6666/AsyncCoreData
28fdd5a31878bf15da53c945706f71fbbd74a2fb
[ "MIT" ]
null
null
null
AsyncCoreData/Classes/AsyncCoreData+Configration.h
fengwei6666/AsyncCoreData
28fdd5a31878bf15da53c945706f71fbbd74a2fb
[ "MIT" ]
null
null
null
AsyncCoreData/Classes/AsyncCoreData+Configration.h
fengwei6666/AsyncCoreData
28fdd5a31878bf15da53c945706f71fbbd74a2fb
[ "MIT" ]
null
null
null
// // AsyncCoreData+Configration.h // AsyncCoreData // // Created by 罗亮富 on 2019/1/15. // #import "AsyncCoreData.h" @protocol UniqueValueProtocol; typedef void(^T_ModelToManagedObjectBlock)(__kindof NSObject<UniqueValueProtocol> * __nonnull model, NSManagedObject * _Nonnull managedObject); typedef __kindof NSObject * _Nonnull (^T_ModelFromManagedObjectBlock)(__kindof NSObject<UniqueValueProtocol> * __nullable model, NSManagedObject * _Nonnull managedObject); @interface AsyncCoreData (Configration) /** 设置当前类的persistantStore,使用前,必须调用此方法来设置,子类的设置可以独立于父类,子类和父类设置互不影响,如果子类没有单独设置,则使用父类的persistantStore 举个栗子: 假如MyMessageManager 继承自 AsyncCoreData ```objc [AsyncCoreData setPersistantStore:url1 withModel:@"mymodel1" completion:^{}]; [MyMessageManager setPersistantStore:url2 withModel:@"mymodel2" completion:^{}]; ``` AsyncCoreData 对应为 存储在url1的,对应数据模型为mymodel1的数据库 MyMessageManager 对应为 存储在url2的,对应数据模型为mymodel2的数据库 如果不设置MyMessageManager的话,那么MyMessageManager默认使用AsyncCoreData的设置 */ +(void)setPersistantStore:(nullable NSURL *)persistantFileUrl withModel:(nonnull NSString *)modelName completion:(void(^ _Nonnull )(void))mainThreadBlock; + (void)setupPersistantStoreWithSQLiteURL:(nullable NSURL *)sqliteURl modelName:(nonnull NSString *)modelName; /** 数据库写入和读取时候,通过block来设定数据映射规则 举个栗子: 有个LAGProjectInfo的数据模型,它的数据将要写到数据库中保存,辣么它的值一定要和数据表有映射关系才能进行读写操作 1.写入映射 [AsyncCoreData setModelMapToDataBaseBlock:^(__kindof LAGProjectInfo<UniqueIDProtocol> * _Nonnull model, NSManagedObject * _Nonnull managedObject) { [managedObject setValue:model.identifier forKey:@"uniqueID"]; [managedObject setValue:model.author forKey:@"author_"]; [managedObject setValue:model.title forKey:@"title_"]; } forEntity:@"DBProject"]; //读取映射 [AsyncCoreData setModelFromDataBase:^__kindof NSObject * _Nonnull(__kindof LAGProjectInfo<UniqueIDProtocol> * _Nullable model, NSManagedObject * _Nonnull managedObject) { if(!model) //注意这里没有对象的话,要负责创建对象 model = [LAGProjectInfo new]; model.identifier = [managedObject valueForKey:@"uniqueID"]; model.author = [managedObject valueForKey:@"author_"]; model.title = [managedObject valueForKey:@"title_"]; return model; } forEntity:@"DBProject"]; */ +(void)setModelToDataBaseMapper:(nonnull T_ModelToManagedObjectBlock)mapper forEntity:(nonnull NSString *)entityName;//非线程安全 +(void)setModelFromDataBaseMapper:(nonnull T_ModelFromManagedObjectBlock)mapper forEntity:(nonnull NSString *)entityName; //非线程安全 +(nullable NSPersistentStoreCoordinator *)persistentStoreCoordinator; +(void)invalidatePersistantSotre;//一般不会用到,测试的时候用 +(NSManagedObjectContext *)newContext; //在当前线程创建一个新的context @end //只是实验性尝试,打开的话会造成所有操作都集中在一个线程,造成任务拥堵,不能很好地利用多线程资源。 #define BG_USE_SAME_RUNLOOP_ 0 //@available(macOS 10.2, iOS 10, *)
36.025641
175
0.794306
[ "model" ]
b81d35dad4a231630affe9e7fccfb74fde6522a3
1,754
h
C
code/src/temp/Particles.h
Emmie-He/fluid-simulation
2e45d045f5b9f7be0adfb6aad4a34df58c4fd38e
[ "MIT" ]
1
2019-08-30T05:52:40.000Z
2019-08-30T05:52:40.000Z
code/src/temp/Particles.h
YAQIMIAO/fluid-simulation
e26c496ebea7dec6075374b904d645a18a3ba335
[ "MIT" ]
null
null
null
code/src/temp/Particles.h
YAQIMIAO/fluid-simulation
e26c496ebea7dec6075374b904d645a18a3ba335
[ "MIT" ]
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: Particles.h * Author: swl * * Created on April 15, 2016, 12:16 PM */ #ifndef PARTICLES_H #define PARTICLES_H #include <glm/glm.hpp> #include <vector> #if defined(__APPLE_CC__) #include <GLFW/glfw3.h> #include <OpenGL/glu.h> #include <GLUT/glut.h> #else #include <GL/glut.h> #include <math.h> #endif #define IX(x, y, z) ((x) + (y) * N + (z) * N * N) class Particles { public: int size; float dt; float diff; float visc; float *s; float *density; float *Vx; float *Vy; float *Vz; float *Vx0; float *Vy0; float *Vz0; Particles(); Particles(int size, int diffusion, int viscosity, float dt); void render() const; void step(){} // simulate one frame void freeParticles(); void FluidCubeAddDensity(int x, int y, int z, float amount); void FluidCubeAddVelocity(int x, int y, int z, float amountX, float amountY, float amountZ); void set_bnd(int b, float *x, int N); void lin_solve(int b, float *x, float *x0, float a, float c, int iter, int N); void diffuse (int b, float *x, float *x0, float diff, float dt, int iter, int N); void project(float *velocX, float *velocY, float *velocZ, float *p, float *div, int iter, int N); void advect(int b, float *d, float *d0, float *velocX, float *velocY, float *velocZ, float dt, int N); void FluidCubeStep(); private: struct Particle { glm::dvec3 p; glm::dvec3 v; glm::dvec3 v_last; }; std::vector<Particle> particles; }; #endif /* PARTICLES_H */
20.395349
107
0.628278
[ "render", "vector" ]
b8211e48e94ebe6376f01cee3f65e54a8e18008d
6,486
c
C
e2studio_project_threadX/ra/fsp/src/rm_threadx_port/tx_initialize_low_level.c
micro-ROS/micro_ros_renesas_testbench
56a25d9e7340eb902b697f68261eb607b2bd0587
[ "Apache-2.0" ]
null
null
null
e2studio_project_threadX/ra/fsp/src/rm_threadx_port/tx_initialize_low_level.c
micro-ROS/micro_ros_renesas_testbench
56a25d9e7340eb902b697f68261eb607b2bd0587
[ "Apache-2.0" ]
24
2021-08-31T06:47:23.000Z
2022-03-23T07:25:48.000Z
e2studio_project_threadX/ra/fsp/src/rm_threadx_port/tx_initialize_low_level.c
micro-ROS/micro_ros_renesas_testbench
56a25d9e7340eb902b697f68261eb607b2bd0587
[ "Apache-2.0" ]
1
2022-03-18T13:59:23.000Z
2022-03-18T13:59:23.000Z
/**************************************************************************/ /* */ /* Copyright (c) Microsoft Corporation. All rights reserved. */ /* */ /* This software is licensed under the Microsoft Software License */ /* Terms for Microsoft Azure RTOS. Full text of the license can be */ /* found in the LICENSE file at https://aka.ms/AzureRTOS_EULA */ /* and in the root directory of this software. */ /* */ /**************************************************************************/ /**************************************************************************/ /**************************************************************************/ /** */ /** ThreadX Component */ /** */ /** Initialize */ /** */ /**************************************************************************/ /**************************************************************************/ #define TX_SOURCE_CODE /* Include necessary system files. */ #include "bsp_api.h" #include "tx_api.h" #include "tx_initialize.h" #include "tx_thread.h" #include "tx_timer.h" /* SysTick must not be higher priority (lower numerical value) than maximum * ThreadX interrupt priority. */ #if TX_PORT_CFG_SYSTICK_IPL < TX_PORT_MAX_IPL #undef TX_PORT_CFG_SYSTICK_IPL #define TX_PORT_CFG_SYSTICK_IPL TX_PORT_MAX_IPL #endif /* Define the location of the begining of the free RAM */ #if defined(__ARMCC_VERSION) /* AC6 compiler */ extern uint32_t Image$$RAM_END$$Limit; #define TX_FREE_MEMORY_START &Image$$RAM_END$$Limit #elif defined(__GNUC__) /* GCC compiler */ extern void * __RAM_segment_used_end__; #define TX_FREE_MEMORY_START (&__RAM_segment_used_end__) #elif defined(__ICCARM__) /* IAR compiler */ extern void * __tx_free_memory_start; #define TX_FREE_MEMORY_START (&__tx_free_memory_start) /* __tx_free_memory_start is placed at the end of RAM in fsp.icf. */ #pragma section="FREE_MEM" __root void * __tx_free_memory_start @"FREE_MEM"; #endif extern void * __Vectors[]; #define TX_VECTOR_TABLE __Vectors /**************************************************************************/ /* */ /* FUNCTION RELEASE */ /* */ /* _tx_initialize_low_level Cortex-M/CMSIS */ /* */ /* DESCRIPTION */ /* */ /* This function is responsible for any low-level processor */ /* initialization, including setting up interrupt vectors, setting */ /* up a periodic timer interrupt source, saving the system stack */ /* pointer for use in ISR processing later, and finding the first */ /* available RAM memory address for tx_application_define. */ /* */ /* INPUT */ /* */ /* None */ /* */ /* OUTPUT */ /* */ /* None */ /* */ /* CALLS */ /* */ /* None */ /* */ /* CALLED BY */ /* */ /* _tx_initialize_kernel_enter ThreadX entry function */ /* */ /**************************************************************************/ VOID _tx_initialize_low_level (VOID) { /* Ensure that interrupts are disabled. */ #ifdef TX_PORT_USE_BASEPRI __set_BASEPRI(TX_PORT_MAX_IPL << (8U - __NVIC_PRIO_BITS)); #else __disable_irq(); #endif /* Set base of available memory to end of non-initialized RAM area. */ _tx_initialize_unused_memory = TX_UCHAR_POINTER_ADD(TX_FREE_MEMORY_START, 4); /* Set system stack pointer from vector value. */ _tx_thread_system_stack_ptr = TX_VECTOR_TABLE[0]; #if defined(__ARM_ARCH_7EM__) || defined(__ARM_ARCH_8M_MAIN__) /* Enable the cycle count register. */ DWT->CTRL |= (uint32_t) DWT_CTRL_CYCCNTENA_Msk; #endif #ifndef TX_NO_TIMER /* Configure SysTick based on user configuration (100 Hz by default). */ SysTick_Config(SystemCoreClock / TX_TIMER_TICKS_PER_SECOND); NVIC_SetPriority(SysTick_IRQn, TX_PORT_CFG_SYSTICK_IPL); // Set User configured Priority for Systick Interrupt #endif /* Configure the handler priorities. */ NVIC_SetPriority(SVCall_IRQn, UINT8_MAX); // Note: SVC must be lowest priority, which is 0xFF NVIC_SetPriority(PendSV_IRQn, UINT8_MAX); // Note: PnSV must be lowest priority, which is 0xFF #ifdef TX_PORT_VENDOR_STACK_MONITOR_ENABLE /* Disable PSP monitoring */ R_MPU_SPMON->SP[1].CTL = 0; #endif }
49.51145
115
0.384675
[ "vector" ]
b823420755a5df56b27e19dc1a4c3ebea1d18eb6
11,117
h
C
judger/uoj_judger/include/uoj_run.h
renbaoshuo/uoj
bb7266bcfa09f3f167e739415d07383aeca8225a
[ "MIT" ]
null
null
null
judger/uoj_judger/include/uoj_run.h
renbaoshuo/uoj
bb7266bcfa09f3f167e739415d07383aeca8225a
[ "MIT" ]
null
null
null
judger/uoj_judger/include/uoj_run.h
renbaoshuo/uoj
bb7266bcfa09f3f167e739415d07383aeca8225a
[ "MIT" ]
null
null
null
#include <string> #include <vector> #include <map> #include <sstream> #include <fstream> #include <cstdarg> #include <filesystem> #include <exception> #include <stdexcept> #define UOJ_GCC "/usr/bin/gcc-10" #define UOJ_GPLUSPLUS "/usr/bin/g++-10" #define UOJ_PYTHON2_7 "/usr/bin/python2.7" #define UOJ_PYTHON3 "/usr/bin/python3.9" #define UOJ_FPC "/usr/bin/fpc" #define UOJ_JDK7 "jdk1.7.0_80" #define UOJ_JDK8 "jdk1.8.0_202" #define UOJ_OPEN_JDK11 "/usr/lib/jvm/java-11-openjdk-amd64" #define UOJ_OPEN_JDK14 "/usr/lib/jvm/java-14-openjdk-amd64" std::string escapeshellarg(int arg) { return std::to_string(arg); } std::string escapeshellarg(const std::string &arg) { std::string res = "'"; for (char c : arg) { if (c == '\'') { res += "'\\''"; } else { res += c; } } res += "'"; return res; } template <typename T> std::ostream& spaced_out(std::ostream &out, const T &arg) { return out << arg; } template <typename T, typename... Args> std::ostream& spaced_out(std::ostream &out, const T &arg, const Args& ...rest) { return spaced_out(out << arg << " ", rest...); } template <typename T> std::ostream& add_spaced_out(std::ostream &out, const T &arg) { return out << " " << arg; } template <typename T, typename... Args> std::ostream& add_spaced_out(std::ostream &out, const T &arg, const Args& ...rest) { return spaced_out(out << " " << arg, rest...); } template <typename... Args> int execute(const Args& ...args) { std::ostringstream sout; spaced_out(sout, args...); int status = system(sout.str().c_str()); if (status == -1 || !WIFEXITED(status)) { return -1; } return WEXITSTATUS(status); } int executef(const char *fmt, ...) { const int L = 1 << 10; char cmd[L]; va_list ap; va_start(ap, fmt); int res = vsnprintf(cmd, L, fmt, ap); if (res < 0 || res >= L) { return -1; } res = execute(cmd); va_end(ap); return res; } class cannot_determine_class_name_error : std::invalid_argument { public: explicit cannot_determine_class_name_error() : std::invalid_argument("cannot determine the class name!") {} }; std::string get_class_name_from_file(const std::string &fname) { std::ifstream fin(fname); if (!fin) { throw cannot_determine_class_name_error(); } std::string class_name; if (!(fin >> class_name)) { throw cannot_determine_class_name_error(); } if (class_name.length() > 100) { throw cannot_determine_class_name_error(); } for (char &c : class_name) { if (!isalnum(c) && c != '_') { throw cannot_determine_class_name_error(); } } return class_name; } bool put_class_name_to_file(const std::string &fname, const std::string &class_name) { std::ofstream fout(fname); if (!fout) { return false; } if (!(fout << class_name << std::endl)) { return false; } return true; } namespace runp { namespace fs = std::filesystem; fs::path run_path; struct limits_t { int time; int memory; int output; int real_time; int stack; limits_t() = default; limits_t(const int &_time, const int &_memory, const int &_output) : time(_time), memory(_memory), output(_output), real_time(-1), stack(-1) { } }; // result type enum RS_TYPE { RS_AC = 0, RS_WA = 1, RS_RE = 2, RS_MLE = 3, RS_TLE = 4, RS_OLE = 5, RS_DGS = 6, RS_JGF = 7 }; inline std::string rstype_str(RS_TYPE id) { switch (id) { case RS_AC: return "Accepted"; case RS_WA: return "Wrong Answer"; case RS_RE : return "Runtime Error"; case RS_MLE: return "Memory Limit Exceeded"; case RS_TLE: return "Time Limit Exceeded"; case RS_OLE: return "Output Limit Exceeded"; case RS_DGS: return "Dangerous Syscalls"; case RS_JGF: return "Judgment Failed"; default : return "Unknown Result"; } } struct result { static std::string result_file_name; RS_TYPE type; std::string extra; int ust, usm; int exit_code; result() = default; result(RS_TYPE type, std::string extra, int ust = -1, int usm = -1, int exit_code = -1) : type(type), extra(extra), ust(ust), usm(usm), exit_code(exit_code) { if (this->type != RS_AC) { this->ust = -1, this->usm = -1; } } static result failed_result() { result res; res.type = RS_JGF; res.ust = -1; res.usm = -1; return res; } static result from_file(const std::string &file_name) { result res; FILE *fres = fopen(file_name.c_str(), "r"); if (!fres) { return result::failed_result(); } int type; if (fscanf(fres, "%d %d %d %d\n", &type, &res.ust, &res.usm, &res.exit_code) != 4) { fclose(fres); return result::failed_result(); } res.type = (RS_TYPE)type; int L = 1 << 15; char buf[L]; while (!feof(fres)) { int c = fread(buf, 1, L, fres); res.extra.append(buf, c); if (ferror(fres)) { fclose(fres); return result::failed_result(); } } fclose(fres); return res; } [[noreturn]] void dump_and_exit() { FILE *f; if (result_file_name == "stdout") { f = stdout; } else if (result_file_name == "stderr") { f = stderr; } else { f = fopen(result_file_name.c_str(), "w"); } fprintf(f, "%d %d %d %d\n", this->type, this->ust, this->usm, this->exit_code); fprintf(f, "%s\n", this->extra.c_str()); if (f != stdout && f != stderr) { fclose(f); } exit(this->type == RS_JGF ? 1 : 0); } }; std::string result::result_file_name("stdout"); template <typename T1, typename T2> inline std::ostream& add_runp_arg(std::ostream &out, const std::pair<T1, std::vector<T2>> &arg) { for (const auto &t : arg.second) { out << " --" << arg.first << "=" << escapeshellarg(t); } return out; } template <typename T1, typename T2> inline std::ostream& add_runp_arg(std::ostream &out, const std::pair<T1, T2> &arg) { return out << " --" << arg.first << "=" << escapeshellarg(arg.second); } inline std::ostream& add_runp_arg(std::ostream &out, const std::vector<std::string> &arg) { for (const auto &t : arg) { out << " " << escapeshellarg(t); } return out; } inline std::ostream& add_runp_arg(std::ostream &out, const std::string &arg) { return out << " " << escapeshellarg(arg); } struct config { std::vector<std::string> readable_file_names; // other than stdin std::vector<std::string> writable_file_names; // other than stdout, stderr std::string result_file_name; std::string input_file_name; std::string output_file_name; std::string error_file_name; std::string type = "default"; std::string work_path; limits_t limits; std::string program_name; std::vector<std::string> rest_args; // full args (possbily with interpreter) std::vector<std::string> full_args; bool unsafe = false; bool allow_proc = false; bool need_show_trace_details = false; config(std::string program_name = "", const std::vector<std::string> &rest_args = {}) : program_name(program_name), rest_args(rest_args) { } config &set_type(const std::string &type) { this->type = type; return *this; } std::string get_cmd() const { std::ostringstream sout; sout << escapeshellarg(run_path / "run_program"); if (this->need_show_trace_details) { add_runp_arg(sout, "--show-trace-details"); } add_runp_arg(sout, std::make_pair("res", this->result_file_name)); add_runp_arg(sout, std::make_pair("in", this->input_file_name)); add_runp_arg(sout, std::make_pair("out", this->output_file_name)); add_runp_arg(sout, std::make_pair("err", this->error_file_name)); add_runp_arg(sout, std::make_pair("type", this->type)); // limits add_runp_arg(sout, std::make_pair("tl", this->limits.time)); add_runp_arg(sout, std::make_pair("ml", this->limits.memory)); add_runp_arg(sout, std::make_pair("ol", this->limits.output)); if (this->limits.real_time != -1) { add_runp_arg(sout, std::make_pair("rtl", this->limits.real_time)); } if (this->limits.stack != -1) { add_runp_arg(sout, std::make_pair("sl", this->limits.stack)); } if (this->unsafe) { add_runp_arg(sout, "--unsafe"); } if (this->allow_proc) { add_runp_arg(sout, "--allow-proc"); } if (!this->work_path.empty()) { add_runp_arg(sout, std::make_pair("work-path", this->work_path)); } add_runp_arg(sout, std::make_pair("add-readable", this->readable_file_names)); add_runp_arg(sout, std::make_pair("add-writable", this->writable_file_names)); add_runp_arg(sout, this->program_name); add_runp_arg(sout, this->rest_args); return sout.str(); } void gen_full_args() { // assume that current_path() == work_path full_args.clear(); full_args.push_back(program_name); full_args.insert(full_args.end(), rest_args.begin(),rest_args.end()); if (type == "java7" || type == "java8") { full_args[0] = get_class_name_from_file(fs::path(full_args[0]) / ".main_class_name"); std::string jdk; if (type == "java7") { jdk = UOJ_JDK7; } else { // if (type == "java8") { jdk = UOJ_JDK8; } full_args.insert(full_args.begin(), { fs::canonical(run_path / "runtime" / jdk / "bin" / "java"), "-Xmx2048m", "-Xss1024m", "-classpath", program_name }); } else if (type == "java11" || type == "java14") { full_args[0] = get_class_name_from_file(fs::path(full_args[0]) / ".main_class_name"); std::string jdk; if (type == "java11") { jdk = UOJ_OPEN_JDK11; } else { // if (type == "java14") { jdk = UOJ_OPEN_JDK14; } full_args.insert(full_args.begin(), { fs::canonical(fs::path(jdk) / "bin" / "java"), "-Xmx2048m", "-Xss1024m", "-classpath", program_name }); } else if (type == "python2.7") { full_args.insert(full_args.begin(), { UOJ_PYTHON2_7, "-E", "-s", "-B" }); } else if (type == "python3") { full_args.insert(full_args.begin(), { UOJ_PYTHON3, "-I", "-B" }); } } }; } namespace runp::interaction { struct pipe_config { int from, from_fd; int to, to_fd; std::string saving_file_name; pipe_config() = default; pipe_config(int _from, int _from_fd, int _to, int _to_fd, const std::string &_saving_file_name = "") : from(_from), from_fd(_from_fd), to(_to), to_fd(_to_fd), saving_file_name(_saving_file_name) {} pipe_config(const std::string &str) { if (sscanf(str.c_str(), "%d:%d-%d:%d", &from, &from_fd, &to, &to_fd) != 4) { throw std::invalid_argument("bad init str for pipe"); } } }; struct config { std::vector<std::string> cmds; std::vector<pipe_config> pipes; std::string get_cmd() const { std::ostringstream sout; sout << escapeshellarg(run_path / "run_interaction"); for (auto &cmd : cmds) { sout << " " << escapeshellarg(cmd); } for (auto &pipe : pipes) { sout << " " << "-p"; sout << " " << pipe.from << ":" << pipe.from_fd; sout << "-" << pipe.to << ":" << pipe.to_fd; if (!pipe.saving_file_name.empty()) { sout << " " << "-s"; sout << " " << escapeshellarg(pipe.saving_file_name); } } return sout.str(); } }; /* * @return interaction return value **/ int run(const config &ric) { return execute(ric.get_cmd().c_str()); } }
26.469048
102
0.629486
[ "vector" ]
b82a277cead793ad3731cdac7a6c153ef305198c
714
h
C
fast.h
seIncorp/DiskDataAndHelper
6165bfcd89ad7a082eb6526d6b2fcb4add6b858d
[ "MIT" ]
null
null
null
fast.h
seIncorp/DiskDataAndHelper
6165bfcd89ad7a082eb6526d6b2fcb4add6b858d
[ "MIT" ]
null
null
null
fast.h
seIncorp/DiskDataAndHelper
6165bfcd89ad7a082eb6526d6b2fcb4add6b858d
[ "MIT" ]
null
null
null
#pragma once #ifndef FAST_H #define FAST_H #include <iostream> #include <climits> #include <vector> #include <Windows.h> #include <string> #include <math.h> #include <functional> #include <cmath> #define E "\n" #define T "\t" /* iostream */ #define o std::cout #define i std::cin #define er std::cerr #define l std::clog #define e std::endl #define ee (o << e) #define hex std::hex #define string std::string #define Vi std::vector<int> #define Vd std::vector<double> #define Vl std::vector<long> #define Vc std::vector<char> #define Vs std::vector<string> #define Vi2D std::vector<std::vector<int>> #define BAon (o << std::boolalpha) #define BAoff (o << std::noboolalpha) #endif
14.571429
42
0.669468
[ "vector" ]
b82b5991278ad00e86b8190f6cf5efbe3548aa7b
381
h
C
includes/stats.h
EvannBerthou/RogueLikeCPP
7b4d52b13ef4fcb283fbdf5d9a7a327886358aff
[ "MIT" ]
null
null
null
includes/stats.h
EvannBerthou/RogueLikeCPP
7b4d52b13ef4fcb283fbdf5d9a7a327886358aff
[ "MIT" ]
null
null
null
includes/stats.h
EvannBerthou/RogueLikeCPP
7b4d52b13ef4fcb283fbdf5d9a7a327886358aff
[ "MIT" ]
null
null
null
#ifndef STATS_H #define STATS_H #include "camera.h" #include "textures.h" #include "fonts.h" #include "vec2.h" typedef struct { int health; int max_health; int base_strength; int base_magic; int strength = base_strength; int magic = base_magic; bool alive = true; void render(camera_t &camera, TTF_Font *font, vec2i offset); } stats_t; #endif
15.875
64
0.67979
[ "render" ]
b8309f7a4b68afd63887a394891800656c4a9caf
299
h
C
src/essence.game/packets/lobby/outgoing/friend/AppearOnline.h
Deluze/qpang-essence-emulator
943189161fd1fb8022221f24524a18244724edd6
[ "MIT" ]
15
2019-12-04T14:36:09.000Z
2021-06-11T12:00:04.000Z
src/essence.game/packets/lobby/outgoing/friend/AppearOnline.h
Deluze/qpang-essence-emulator
943189161fd1fb8022221f24524a18244724edd6
[ "MIT" ]
6
2019-12-24T11:28:01.000Z
2020-03-31T00:14:50.000Z
src/essence.game/packets/lobby/outgoing/friend/AppearOnline.h
Deluze/qpang-essence-emulator
943189161fd1fb8022221f24524a18244724edd6
[ "MIT" ]
21
2019-12-04T14:35:56.000Z
2022-02-14T20:59:31.000Z
#pragma once #include <vector> #include "packets/LobbyServerPacket.h" #include "packets/writers/FriendWriter.h" #include "qpang/player/friend/Friend.h" class AppearOnline : public LobbyServerPacket { public: AppearOnline(uint32_t playerId) : LobbyServerPacket(603) { writeInt(playerId); } };
18.6875
57
0.769231
[ "vector" ]
b830c0531c79f6dd0377b3dd5645892127013744
1,355
h
C
Graphics/include/SceneWriter.h
MarcoLotto/ScenaFramework
533e5149a1580080e41bfb37d5648023b6e39f6f
[ "MIT" ]
2
2019-01-21T20:47:29.000Z
2020-01-09T01:08:24.000Z
Graphics/include/SceneWriter.h
MarcoLotto/ScaenaFramework
533e5149a1580080e41bfb37d5648023b6e39f6f
[ "MIT" ]
null
null
null
Graphics/include/SceneWriter.h
MarcoLotto/ScaenaFramework
533e5149a1580080e41bfb37d5648023b6e39f6f
[ "MIT" ]
null
null
null
/********************************** * SCAENA FRAMEWORK * Author: Marco Andrés Lotto * License: MIT - 2016 **********************************/ #pragma once #include "Scene.h" #include "XmlTree.h" class SceneWriter{ private: static SceneWriter* instance; void parseObjets(XmlTreeNode* node, ObjectManager* objectManager); void parseLights(XmlTreeNode* node, LightingManager* lightingManager); void serializeVec2ToNode(glm::vec2 vector, XmlTreeNode* parent); void serializeVec3ToNode(glm::vec3 vector, XmlTreeNode* parent); void serializeTransformationsToNode(Object* object, XmlTreeNode* parentNode); void serializeToNode(string propertyName, glm::vec3 vector, XmlTreeNode* parent); void serializeToNode(string propertyName, glm::vec2 vector, XmlTreeNode* parent); void serializeToNode(string propertyName, float vector, XmlTreeNode* parent); void serializePointLight(SceneLight* light, XmlTreeNode* parent); void serializeDirectionalLight(SceneLight* light, XmlTreeNode* parent); void serializeSpotLight(SceneLight* light, XmlTreeNode* parent); void serializePointDifuseLight(SceneLight* light, XmlTreeNode* parent); void serializeShadow(SceneLight* light, XmlTreeNode* lightNode); public: static SceneWriter* getInstance(); XmlTree* sceneToXmlTree(Scene* scene); void writeSceneToFileSystem(string filename, Scene* scene); };
37.638889
82
0.756458
[ "object", "vector" ]
b835418ebeadc1e9d9d69d4635a60f8d0f881383
2,226
c
C
mytest.c
phraber/mdl
1415e9b7de814a20c857c7522fb2e45054177ae8
[ "MIT" ]
null
null
null
mytest.c
phraber/mdl
1415e9b7de814a20c857c7522fb2e45054177ae8
[ "MIT" ]
null
null
null
mytest.c
phraber/mdl
1415e9b7de814a20c857c7522fb2e45054177ae8
[ "MIT" ]
null
null
null
/* main.c -- * USAGE: * PURPOSE: Perform all possible (legitimate) first-order splits. * Each case has 6 (10?) different loci with 2 alleles at each. * a[j][l][i] is the jth allele at locus l for case i * At any split, we choose l = L and have a list of alleles ind[k]. * If a[j][L][i] = ind[k] for either j and any k, i belongs in * primary group. If not, i belongs in secondary group. * AUTHORS: Tom Kepler and Peter Hraber (11/30/2001) */ #define maxClass 2 #define VERBOSE 1 #define DEBUG 0 //double log2; #include <math.h> #include <stdio.h> // for printf #include <stdlib.h> // for qsort - used to Winsorize mean #include <string.h> // for memcpy //#include "patient.h" //#include "HLAAsup.h" //#include "HLABsup.h" //#include "mytest.h" #include "n379.h" #include "etc.h" // this must follow the data-file inclusion int main(int argc, char** argv) { extern int X[nObs][nCov]; extern double y[nObs]; // raw data int nClass = maxClass; double thresh; double Y[nObs]; // transformed data moments* g; int n[nClass]; transformData(y,Y,nObs,0.); /* use theta=0. for log-transform */ g = malloc(sizeof(moments)); /* should error trap here */ g->n = nObs; g = Moments(Y,g); printf(" g->mean=%f\t g->var=%f\tL=%f\n",g->mean,g->var, L0(g)); // use estimators adjusted to censor below value of thresh thresh=1.; g = WDMoments(Y,g,log2(thresh)); printf("g->Wmean=%f\tg->Dvar=%f\tL=%f\t(thresh=%f.)\n",g->mean,g->var,L0(g),thresh); thresh=300.; g = WDMoments(Y,g,log2(thresh)); printf("g->Wmean=%f\tg->Dvar=%f\tL=%f\t(thresh=%f.)\n",g->mean,g->var,L0(g),thresh); thresh=400.; g = WDMoments(Y,g,log2(thresh)); printf("g->Wmean=%f\tg->Dvar=%f\tL=%f\t(thresh=%f.)\n",g->mean,g->var,L0(g),thresh); thresh=500.; g = WDMoments(Y,g,log2(thresh)); printf("g->Wmean=%f\tg->Dvar=%f\tL=%f\t(thresh=%f.)\n",g->mean,g->var,L0(g),thresh); thresh=1000.; g = WDMoments(Y,g,log2(thresh)); printf("g->Wmean=%f\tg->Dvar=%f\tL=%f\t(thresh=%f.)\n",g->mean,g->var,L0(g),thresh); free(g); g=0; return(0); } /* MAIN */ /***************************************************************************/
29.68
86
0.586253
[ "transform" ]
b8357bc129d20f395b65412ccfffc33a2c3abdd6
3,830
h
C
Server/Servers/TrafficServer/include/TrafficIPC.h
wayfinder/Wayfinder-Server
a688546589f246ee12a8a167a568a9c4c4ef8151
[ "BSD-3-Clause" ]
4
2015-08-17T20:12:22.000Z
2020-05-30T19:53:26.000Z
Server/Servers/TrafficServer/include/TrafficIPC.h
wayfinder/Wayfinder-Server
a688546589f246ee12a8a167a568a9c4c4ef8151
[ "BSD-3-Clause" ]
null
null
null
Server/Servers/TrafficServer/include/TrafficIPC.h
wayfinder/Wayfinder-Server
a688546589f246ee12a8a167a568a9c4c4ef8151
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Vodafone Group Services Ltd 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 TRAFFIC_IPC_H #define TRAFFIC_IPC_H #include "config.h" #include "TrafficDataTypes.h" #include "MC2String.h" #include <vector> #include <map> class ParserThread; class PacketContainer; class RouteRequest; class MC2Coordinate; class DisturbanceElement; class IDPair_t; class TrafficSituation; /** * Interface for a traffic inter process communication (ipc) that communicates * traffic changes to a destination process/module. */ class TrafficIPC { public: /// Holds disturbances typedef std::vector< DisturbanceElement* > Disturbances; /** * Sends the change set to the Info module. * @param newElements Situations to be updated. * @param removedElements Situations to be removed. * @return true if the send was succesful. */ virtual bool sendChangeset( const Disturbances& newElements, const Disturbances& removedElements ) = 0; /** * Get all disturbances from a specific \c provider. * @param provider A unique provider ID. * @param disturbances Will contain all the disturbances from the \c provider * if the fetch was successful. * @return True if the fetch was successful. */ virtual bool getAllDisturbances( const MC2String& provider, Disturbances& disturbances ) = 0; /// A vector of PacketContainer pointers. typedef std::vector< PacketContainer* > PacketContainers; /** * Sends PacketContainer's and if successful it will contains the answers in * the PacketContainer's * @param pcs The PacketContainers. * @return true if the send was fuccesful. */ virtual bool sendPacketContainers( PacketContainers& pcs ) = 0; typedef uint32 RouteIndex; typedef std::pair< MC2Coordinate, RouteIndex > CoordPair; typedef std::map< IDPair_t, CoordPair > IDPairsToCoords; /** * Gets all the valid mapIDs, nodeIDs, coordinates and routeIndexes for a * TrafficSituation. * * @param traffSit The TrafficSituation. * @param idPairsToCoords The id pair to coords map for this situation. */ virtual void getMapIDsNodeIDsCoords( const TrafficSituation& traffSit, IDPairsToCoords& idPairsToCoords ) = 0; }; #endif // TRAFFIC_IPC_H
44.022989
755
0.734987
[ "vector" ]
b83591f5848a39c06eea7c7625ba08e44e4a9755
2,874
h
C
Userland/Services/WebContent/ClientConnection.h
xeons/serenity
68a542623f5dc08d29d2b4bc87f7817b6aac4022
[ "BSD-2-Clause" ]
null
null
null
Userland/Services/WebContent/ClientConnection.h
xeons/serenity
68a542623f5dc08d29d2b4bc87f7817b6aac4022
[ "BSD-2-Clause" ]
null
null
null
Userland/Services/WebContent/ClientConnection.h
xeons/serenity
68a542623f5dc08d29d2b4bc87f7817b6aac4022
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org> * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <AK/HashMap.h> #include <LibIPC/ClientConnection.h> #include <LibJS/Forward.h> #include <LibWeb/Cookie/ParsedCookie.h> #include <LibWeb/Forward.h> #include <WebContent/Forward.h> #include <WebContent/WebContentClientEndpoint.h> #include <WebContent/WebContentConsoleClient.h> #include <WebContent/WebContentServerEndpoint.h> namespace WebContent { class ClientConnection final : public IPC::ClientConnection<WebContentClientEndpoint, WebContentServerEndpoint> , public WebContentServerEndpoint { C_OBJECT(ClientConnection); public: explicit ClientConnection(NonnullRefPtr<Core::LocalSocket>, int client_id); ~ClientConnection() override; virtual void die() override; private: Web::Page& page(); const Web::Page& page() const; virtual void handle(const Messages::WebContentServer::Greet&) override; virtual void handle(const Messages::WebContentServer::UpdateSystemTheme&) override; virtual void handle(const Messages::WebContentServer::UpdateScreenRect&) override; virtual void handle(const Messages::WebContentServer::LoadURL&) override; virtual void handle(const Messages::WebContentServer::LoadHTML&) override; virtual void handle(const Messages::WebContentServer::Paint&) override; virtual void handle(const Messages::WebContentServer::SetViewportRect&) override; virtual void handle(const Messages::WebContentServer::MouseDown&) override; virtual void handle(const Messages::WebContentServer::MouseMove&) override; virtual void handle(const Messages::WebContentServer::MouseUp&) override; virtual void handle(const Messages::WebContentServer::MouseWheel&) override; virtual void handle(const Messages::WebContentServer::KeyDown&) override; virtual void handle(const Messages::WebContentServer::AddBackingStore&) override; virtual void handle(const Messages::WebContentServer::RemoveBackingStore&) override; virtual void handle(const Messages::WebContentServer::DebugRequest&) override; virtual void handle(const Messages::WebContentServer::GetSource&) override; virtual void handle(const Messages::WebContentServer::JSConsoleInitialize&) override; virtual void handle(const Messages::WebContentServer::JSConsoleInput&) override; void flush_pending_paint_requests(); NonnullOwnPtr<PageHost> m_page_host; struct PaintRequest { Gfx::IntRect content_rect; NonnullRefPtr<Gfx::Bitmap> bitmap; i32 bitmap_id { -1 }; }; Vector<PaintRequest> m_pending_paint_requests; RefPtr<Core::Timer> m_paint_flush_timer; HashMap<i32, NonnullRefPtr<Gfx::Bitmap>> m_backing_stores; WeakPtr<JS::Interpreter> m_interpreter; OwnPtr<WebContentConsoleClient> m_console_client; }; }
39.369863
89
0.767919
[ "vector" ]
b8437f1f6cbf18a95aec3c495824a236ddf3c199
2,568
c
C
src/main.c
mohamedLazyBob/M21_mini_project
30fcd28186262aa8d7a5b669c0a065bc3f3a3ba7
[ "MIT" ]
2
2020-07-23T10:02:23.000Z
2020-09-06T00:52:24.000Z
src/main.c
mohamedLazyBob/M21_mini_project
30fcd28186262aa8d7a5b669c0a065bc3f3a3ba7
[ "MIT" ]
null
null
null
src/main.c
mohamedLazyBob/M21_mini_project
30fcd28186262aa8d7a5b669c0a065bc3f3a3ba7
[ "MIT" ]
null
null
null
/******************************************************************************/ /* Mohamed zaboub */ /******************************************************************************/ #include "mini_project.h" /* ** *************************************************************************** ** This function is used to print all the principal menus. ** So that we have a standard menu shape. */ int print_this_menu(char buff[][50], int size) { int choice; int idx; choice = 0; do { printf(" %s", UL HORZ HORZ HORZ HORZ HORZ HORZ HORZ \ HORZ HORZ UR ENDL); printf(" %s %s %s\n", VERT, buff[0], VERT); printf(" %s", DL HORZ HORZ HORZ HORZ HORZ HORZ HORZ \ HORZ HORZ DR ENDL); idx = 1; printf(UL HORZ HORZ HORZ HORZ HORZ HORZ HORZ HORZ HORZ \ HORZ HORZ HORZ UR ENDL); printf("%-47s %28s\n", VERT, VERT); while (idx < size) printf("%s %s %s\n", VERT, buff[idx++], VERT); printf("%-47s %28s\n", VERT, VERT); printf(DL HORZ HORZ HORZ HORZ HORZ HORZ HORZ HORZ HORZ \ HORZ HORZ HORZ DR ENDL); printf("\t\t votre choix : "); scanf("%d", &choice); } while (choice < 0 || choice > size); return (choice); } /* ** **************************************************************************** ** reads one whole line from the input. ** then copys just the first buff_size characters to str. */ char *ft_read_buffer(char *str, int buff_size) { int linesize; char *buff; char *ret; size_t len; len = 0; linesize = 0; buff = NULL; do { linesize = getline(&buff, &len, stdin); } while (linesize == 1);// in case of a leftover newline/whitespace buff[linesize - 1] = 0; memset(str, 0, buff_size); strncpy(str, buff, buff_size - 1); if (buff) free(buff); return (ret); } /* ** **************************************************************************** ** the main. */ int main(void) { int choice; char buff[5][50] = {" Menu Principal ", "Location..............................1", "Gestion voitures......................2", "Gestion clients.......................3", "Quitter...............................4"}; do { system("clear"); choice = print_this_menu(buff, 5); if (choice == 1) ft_rental_management(); else if (choice == 2) ft_cars_management(); else if (choice == 3) ft_clients_management(); } while (choice >= 0 && choice < 4); return (0); } /* ** **************************************************************************** */
25.425743
80
0.445872
[ "shape" ]
b851fe6d35421aa31f129a653f9a104d8f0a3150
2,009
h
C
cpp/cpp_primer/chapter13/ex_13_55.h
KaiserLancelot/Cpp-Primer
a4791a6765f0b6c864e8881e6a5328e2a3d68974
[ "MIT" ]
2
2019-12-21T00:53:47.000Z
2020-01-01T10:36:30.000Z
cpp/cpp_primer/chapter13/ex_13_55.h
KaiserLancelot/Cpp-Primer
a4791a6765f0b6c864e8881e6a5328e2a3d68974
[ "MIT" ]
null
null
null
cpp/cpp_primer/chapter13/ex_13_55.h
KaiserLancelot/Cpp-Primer
a4791a6765f0b6c864e8881e6a5328e2a3d68974
[ "MIT" ]
null
null
null
// // Created by kaiser on 18-12-22. // #ifndef CPP_PRIMER_EX_13_55_H #define CPP_PRIMER_EX_13_55_H #include <initializer_list> #include <memory> #include <string> #include <vector> class StrBlobPtr; class ConstStrBlobPtr; class StrBlob { friend class StrBlobPtr; friend class ConstStrBlobPtr; public: using SizeType = std::vector<std::string>::size_type; StrBlob(); StrBlob(std::initializer_list<std::string> il); StrBlobPtr begin(); StrBlobPtr end(); ConstStrBlobPtr begin() const; ConstStrBlobPtr end() const; SizeType Size() const; bool Empty() const; void PushBack(const std::string& t); void PushBack(std::string&& t); void PopBack(); std::string& Front(); const std::string& Front() const; std::string& Back(); const std::string& Back() const; std::string& At(SizeType index); const std::string& At(SizeType index) const; private: void Check(SizeType i, const std::string& msg) const; std::shared_ptr<std::vector<std::string>> data_; }; class StrBlobPtr { public: using size_type = StrBlob::SizeType; StrBlobPtr() = default; explicit StrBlobPtr(StrBlob& a, size_type sz = 0); std::string& Deref() const; StrBlobPtr& Incr(); bool NotEqual(const StrBlobPtr& item) const; private: std::shared_ptr<std::vector<std::string>> Check(size_type i, const std::string& msg) const; std::weak_ptr<std::vector<std::string>> wptr_; size_type curr_{}; }; class ConstStrBlobPtr { public: using size_type = StrBlob::SizeType; ConstStrBlobPtr() = default; explicit ConstStrBlobPtr(const StrBlob& a, size_type sz = 0); std::string& Deref() const; ConstStrBlobPtr& Incr(); bool NotEqual(const ConstStrBlobPtr& item) const; private: std::shared_ptr<std::vector<std::string>> Check(size_type i, const std::string& msg) const; std::weak_ptr<std::vector<std::string>> wptr_; size_type curr_{}; }; #endif // CPP_PRIMER_EX_13_55_H
25.75641
80
0.674465
[ "vector" ]
b8566e9da4970858232d50443d690e8c0d798f74
1,116
h
C
client/include/chat_client.h
mpunkenhofer/BoostAsioChat
3229980f38de5892ad08bcaa5e66cf1ae70cc626
[ "MIT" ]
null
null
null
client/include/chat_client.h
mpunkenhofer/BoostAsioChat
3229980f38de5892ad08bcaa5e66cf1ae70cc626
[ "MIT" ]
null
null
null
client/include/chat_client.h
mpunkenhofer/BoostAsioChat
3229980f38de5892ad08bcaa5e66cf1ae70cc626
[ "MIT" ]
null
null
null
// // Created by necator on 8/4/17. // #ifndef BOOSTCHAT_CHAT_CLIENT_H #define BOOSTCHAT_CHAT_CLIENT_H #include <boost/asio.hpp> #include <deque> #include "chat_message.h" class chat_client; using chat_client_ptr = std::shared_ptr<chat_client>; class chat_client { public: chat_client(boost::asio::io_service &io_service, boost::asio::ip::tcp::resolver::iterator endpoint_iterator); bool connect(const std::string&); void write(chat_message &msg); void close(); private: boost::asio::io_service& io_service_; boost::asio::ip::tcp::socket socket_; boost::asio::io_service::strand write_strand_; std::deque<chat_message> write_msgs_; std::array<char, chat_message::header_length> inbound_header_; std::vector<char> inbound_data_; boost::asio::ip::tcp::resolver::iterator endpoint_; //void do_connect(boost::asio::ip::tcp::resolver::iterator e); void do_read_header(); void do_read_message(); void do_write(); void handle_message(chat_message); void print(chat_message); void error_handler(); }; #endif //BOOSTCHAT_CHAT_CLIENT_H
23.25
113
0.715054
[ "vector" ]
b85c33cc81220ef2a61ef1bdea423990f12380ee
2,329
h
C
WorkScript/Parser/Generated/WorkScriptLexer.h
jingjiajie/WorkScript
6b80932fcdbae0e915c37bac19d262025234074b
[ "MIT" ]
3
2018-07-23T10:59:00.000Z
2019-04-05T04:57:19.000Z
WorkScript/Parser/Generated/WorkScriptLexer.h
jingjiajie/WorkScript
6b80932fcdbae0e915c37bac19d262025234074b
[ "MIT" ]
null
null
null
WorkScript/Parser/Generated/WorkScriptLexer.h
jingjiajie/WorkScript
6b80932fcdbae0e915c37bac19d262025234074b
[ "MIT" ]
1
2019-06-28T05:57:47.000Z
2019-06-28T05:57:47.000Z
// Generated from WorkScript.g4 by ANTLR 4.7.1 #pragma once #include "antlr4-runtime.h" class WorkScriptLexer : public antlr4::Lexer { public: enum { ACCESS_LEVEL = 1, INCLUDE = 2, WHEN = 3, CONST = 4, VOLATILE = 5, EXTERN = 6, STATIC = 7, SHORT = 8, LONG = 9, SIGNED = 10, UNSIGNED = 11, BOOLEAN = 12, IDENTIFIER = 13, DOUBLE = 14, INTEGER = 15, STRING = 16, SEMICOLON = 17, POINT = 18, COMMA = 19, LEFT_PARENTHESE = 20, RIGHT_PARENTHESE = 21, LEFT_BRACE = 22, RIGHT_BRACE = 23, LEFT_BRACKET = 24, RIGHT_BRACKET = 25, DOUBLE_EQUAL = 26, EQUALS = 27, RIGHT_ARROW = 28, ASSIGN = 29, COLON = 30, PLUS = 31, MINUS = 32, STAR = 33, SLASH = 34, PERCENT = 35, HASH = 36, GREATER_THAN = 37, GREATER_THAN_EQUAL = 38, LESS_THAN = 39, LESS_THAN_EQUAL = 40, SINGLE_LINE_COMMENT = 41, MULTILINE_COMMENT = 42, APOSTROPHE = 43, NEWLINE = 44, WS = 45 }; WorkScriptLexer(antlr4::CharStream *input); ~WorkScriptLexer(); virtual std::string getGrammarFileName() const override; virtual const std::vector<std::string>& getRuleNames() const override; virtual const std::vector<std::string>& getChannelNames() const override; virtual const std::vector<std::string>& getModeNames() const override; virtual const std::vector<std::string>& getTokenNames() const override; // deprecated, use vocabulary instead virtual antlr4::dfa::Vocabulary& getVocabulary() const override; virtual const std::vector<uint16_t> getSerializedATN() const override; virtual const antlr4::atn::ATN& getATN() const override; private: static std::vector<antlr4::dfa::DFA> _decisionToDFA; static antlr4::atn::PredictionContextCache _sharedContextCache; static std::vector<std::string> _ruleNames; static std::vector<std::string> _tokenNames; static std::vector<std::string> _channelNames; static std::vector<std::string> _modeNames; static std::vector<std::string> _literalNames; static std::vector<std::string> _symbolicNames; static antlr4::dfa::Vocabulary _vocabulary; static antlr4::atn::ATN _atn; static std::vector<uint16_t> _serializedATN; // Individual action functions triggered by action() above. // Individual semantic predicate functions triggered by sempred() above. struct Initializer { Initializer(); }; static Initializer _init; };
35.287879
111
0.708459
[ "vector" ]
b85ce46a89844befeb155c8f6d6c2cc940b86bf9
4,493
h
C
src/ast.h
porglezomp/lens
c03db0bba086c7eb01badebc8e07f7d55873bbbc
[ "MIT" ]
null
null
null
src/ast.h
porglezomp/lens
c03db0bba086c7eb01badebc8e07f7d55873bbbc
[ "MIT" ]
null
null
null
src/ast.h
porglezomp/lens
c03db0bba086c7eb01badebc8e07f7d55873bbbc
[ "MIT" ]
null
null
null
// Copyright (c) 2015 Caleb Jones #ifndef LENS_AST_H_ #define LENS_AST_H_ #include <string> #include <vector> #include <iostream> #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Function.h" #include "llvm/IR/Module.h" enum AST_TYPES { EXPR_AST, NUMBER_AST, VARIABLE_AST, BINARY_EXPR_AST, CALL_AST, REASSIGN_AST, ASSIGNMENT_AST, RETURN_AST, STATEMENT_AST, IF_ELSE_AST }; llvm::Module *TheModule(); class StatementAST { static const int idtype = STATEMENT_AST; public: virtual ~StatementAST() {} virtual void print(std::ostream* str) const = 0; friend std::ostream& operator<<(std::ostream& out, StatementAST const& ast) { ast.print(&out); return out; } virtual bool codegen() = 0; virtual int type() { return StatementAST::idtype; } }; class ExprAST : public StatementAST { static const int idtype = EXPR_AST; public: virtual ~ExprAST() {} virtual bool codegen() { llvm::Value *res = expr_codegen(); return (res != NULL); } virtual llvm::Value *expr_codegen() = 0; virtual int type() { return ExprAST::idtype; } }; class NumberAST : public ExprAST { static const int idtype = NUMBER_AST; double value; public: virtual void print(std::ostream* out) const; explicit NumberAST(double number); virtual llvm::Value *expr_codegen(); virtual int type() { return NumberAST::idtype; } }; class VariableAST : public ExprAST { static const int idtype = VARIABLE_AST; std::string name; public: virtual void print(std::ostream* out) const; explicit VariableAST(std::string str); virtual llvm::Value *expr_codegen(); virtual int type() { return VariableAST::idtype; } }; // <expr> <op> <expr> class BinaryExprAST : public ExprAST { static const int idtype = BINARY_EXPR_AST; int op; ExprAST *lhs, *rhs; public: virtual void print(std::ostream* out) const; BinaryExprAST(ExprAST *lhs, int op, ExprAST *rhs); virtual llvm::Value *expr_codegen(); virtual int type() { return BinaryExprAST::idtype; } }; // <ident>(<ident>, ...) class CallAST : public ExprAST { static const int idtype = CALL_AST; std::string name; std::vector<ExprAST *> args; public: CallAST(std::string name, std::vector<ExprAST*> args); virtual void print(std::ostream* out) const; virtual llvm::Value *expr_codegen(); virtual int type() { return CallAST::idtype; } }; // let <ident> = <expr> class AssignmentAST : public StatementAST { static const int idtype = ASSIGNMENT_AST; std::string name; ExprAST *rhs; public: virtual void print(std::ostream* out) const; AssignmentAST(std::string name, ExprAST *rhs); virtual bool codegen(); virtual int type() { return AssignmentAST::idtype; } }; // <ident> = <expr> class ReassignAST : public StatementAST { static const int idtype = REASSIGN_AST; std::string name; ExprAST *rhs; public: virtual void print(std::ostream* out) const; ReassignAST(std::string name, ExprAST *rhs); virtual bool codegen(); virtual int type() { return ReassignAST::idtype; } }; // return <expr> class ReturnAST : public StatementAST { static const int idtype = RETURN_AST; ExprAST *rvalue; public: virtual void print(std::ostream* out) const; explicit ReturnAST(ExprAST *rhs); virtual bool codegen(); virtual int type() { return ReturnAST::idtype; } }; class IfElseAST : public StatementAST { static const int idtype = IF_ELSE_AST; ExprAST *condition; std::vector<StatementAST*> ifbody; std::vector<StatementAST*> elsebody; public: IfElseAST(ExprAST *cond, std::vector<StatementAST*> ifbody, std::vector<StatementAST*> elsebody); virtual void print(std::ostream* out) const; virtual bool codegen(); virtual int type() { return IfElseAST::idtype; } }; class PrototypeAST { public: std::string name; std::vector<std::string> args; PrototypeAST(std::string name, std::vector<std::string> args); friend std::ostream& operator<<(std::ostream& out, PrototypeAST const& ast); llvm::Function *codegen(); }; class FunctionAST { PrototypeAST *proto; std::vector<StatementAST*> body; public: FunctionAST(PrototypeAST *proto, std::vector<StatementAST*> body); friend std::ostream& operator<<(std::ostream& out, FunctionAST const& ast); llvm::Function *codegen(); }; #endif // LENS_AST_H_
27.230303
81
0.667705
[ "vector" ]
8edc56d8533aad09c20ec1dd420a21e1e9d154c1
10,460
h
C
aws-cpp-sdk-outposts/include/aws/outposts/model/CatalogItem.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-outposts/include/aws/outposts/model/CatalogItem.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-outposts/include/aws/outposts/model/CatalogItem.h
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2022-02-28T21:36:42.000Z
2022-02-28T21:36:42.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/outposts/Outposts_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/outposts/model/CatalogItemStatus.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/outposts/model/EC2Capacity.h> #include <aws/outposts/model/SupportedStorageEnum.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace Outposts { namespace Model { /** * <p> Information about a catalog item. </p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/outposts-2019-12-03/CatalogItem">AWS * API Reference</a></p> */ class AWS_OUTPOSTS_API CatalogItem { public: CatalogItem(); CatalogItem(Aws::Utils::Json::JsonView jsonValue); CatalogItem& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p> The ID of the catalog item. </p> */ inline const Aws::String& GetCatalogItemId() const{ return m_catalogItemId; } /** * <p> The ID of the catalog item. </p> */ inline bool CatalogItemIdHasBeenSet() const { return m_catalogItemIdHasBeenSet; } /** * <p> The ID of the catalog item. </p> */ inline void SetCatalogItemId(const Aws::String& value) { m_catalogItemIdHasBeenSet = true; m_catalogItemId = value; } /** * <p> The ID of the catalog item. </p> */ inline void SetCatalogItemId(Aws::String&& value) { m_catalogItemIdHasBeenSet = true; m_catalogItemId = std::move(value); } /** * <p> The ID of the catalog item. </p> */ inline void SetCatalogItemId(const char* value) { m_catalogItemIdHasBeenSet = true; m_catalogItemId.assign(value); } /** * <p> The ID of the catalog item. </p> */ inline CatalogItem& WithCatalogItemId(const Aws::String& value) { SetCatalogItemId(value); return *this;} /** * <p> The ID of the catalog item. </p> */ inline CatalogItem& WithCatalogItemId(Aws::String&& value) { SetCatalogItemId(std::move(value)); return *this;} /** * <p> The ID of the catalog item. </p> */ inline CatalogItem& WithCatalogItemId(const char* value) { SetCatalogItemId(value); return *this;} /** * <p> The status of a catalog item. </p> */ inline const CatalogItemStatus& GetItemStatus() const{ return m_itemStatus; } /** * <p> The status of a catalog item. </p> */ inline bool ItemStatusHasBeenSet() const { return m_itemStatusHasBeenSet; } /** * <p> The status of a catalog item. </p> */ inline void SetItemStatus(const CatalogItemStatus& value) { m_itemStatusHasBeenSet = true; m_itemStatus = value; } /** * <p> The status of a catalog item. </p> */ inline void SetItemStatus(CatalogItemStatus&& value) { m_itemStatusHasBeenSet = true; m_itemStatus = std::move(value); } /** * <p> The status of a catalog item. </p> */ inline CatalogItem& WithItemStatus(const CatalogItemStatus& value) { SetItemStatus(value); return *this;} /** * <p> The status of a catalog item. </p> */ inline CatalogItem& WithItemStatus(CatalogItemStatus&& value) { SetItemStatus(std::move(value)); return *this;} /** * <p> Information about the EC2 capacity of an item. </p> */ inline const Aws::Vector<EC2Capacity>& GetEC2Capacities() const{ return m_eC2Capacities; } /** * <p> Information about the EC2 capacity of an item. </p> */ inline bool EC2CapacitiesHasBeenSet() const { return m_eC2CapacitiesHasBeenSet; } /** * <p> Information about the EC2 capacity of an item. </p> */ inline void SetEC2Capacities(const Aws::Vector<EC2Capacity>& value) { m_eC2CapacitiesHasBeenSet = true; m_eC2Capacities = value; } /** * <p> Information about the EC2 capacity of an item. </p> */ inline void SetEC2Capacities(Aws::Vector<EC2Capacity>&& value) { m_eC2CapacitiesHasBeenSet = true; m_eC2Capacities = std::move(value); } /** * <p> Information about the EC2 capacity of an item. </p> */ inline CatalogItem& WithEC2Capacities(const Aws::Vector<EC2Capacity>& value) { SetEC2Capacities(value); return *this;} /** * <p> Information about the EC2 capacity of an item. </p> */ inline CatalogItem& WithEC2Capacities(Aws::Vector<EC2Capacity>&& value) { SetEC2Capacities(std::move(value)); return *this;} /** * <p> Information about the EC2 capacity of an item. </p> */ inline CatalogItem& AddEC2Capacities(const EC2Capacity& value) { m_eC2CapacitiesHasBeenSet = true; m_eC2Capacities.push_back(value); return *this; } /** * <p> Information about the EC2 capacity of an item. </p> */ inline CatalogItem& AddEC2Capacities(EC2Capacity&& value) { m_eC2CapacitiesHasBeenSet = true; m_eC2Capacities.push_back(std::move(value)); return *this; } /** * <p> Information about the power draw of an item. </p> */ inline double GetPowerKva() const{ return m_powerKva; } /** * <p> Information about the power draw of an item. </p> */ inline bool PowerKvaHasBeenSet() const { return m_powerKvaHasBeenSet; } /** * <p> Information about the power draw of an item. </p> */ inline void SetPowerKva(double value) { m_powerKvaHasBeenSet = true; m_powerKva = value; } /** * <p> Information about the power draw of an item. </p> */ inline CatalogItem& WithPowerKva(double value) { SetPowerKva(value); return *this;} /** * <p> The weight of the item in pounds. </p> */ inline int GetWeightLbs() const{ return m_weightLbs; } /** * <p> The weight of the item in pounds. </p> */ inline bool WeightLbsHasBeenSet() const { return m_weightLbsHasBeenSet; } /** * <p> The weight of the item in pounds. </p> */ inline void SetWeightLbs(int value) { m_weightLbsHasBeenSet = true; m_weightLbs = value; } /** * <p> The weight of the item in pounds. </p> */ inline CatalogItem& WithWeightLbs(int value) { SetWeightLbs(value); return *this;} /** * <p> The uplink speed this catalog item requires for the connection to the * Region. </p> */ inline const Aws::Vector<int>& GetSupportedUplinkGbps() const{ return m_supportedUplinkGbps; } /** * <p> The uplink speed this catalog item requires for the connection to the * Region. </p> */ inline bool SupportedUplinkGbpsHasBeenSet() const { return m_supportedUplinkGbpsHasBeenSet; } /** * <p> The uplink speed this catalog item requires for the connection to the * Region. </p> */ inline void SetSupportedUplinkGbps(const Aws::Vector<int>& value) { m_supportedUplinkGbpsHasBeenSet = true; m_supportedUplinkGbps = value; } /** * <p> The uplink speed this catalog item requires for the connection to the * Region. </p> */ inline void SetSupportedUplinkGbps(Aws::Vector<int>&& value) { m_supportedUplinkGbpsHasBeenSet = true; m_supportedUplinkGbps = std::move(value); } /** * <p> The uplink speed this catalog item requires for the connection to the * Region. </p> */ inline CatalogItem& WithSupportedUplinkGbps(const Aws::Vector<int>& value) { SetSupportedUplinkGbps(value); return *this;} /** * <p> The uplink speed this catalog item requires for the connection to the * Region. </p> */ inline CatalogItem& WithSupportedUplinkGbps(Aws::Vector<int>&& value) { SetSupportedUplinkGbps(std::move(value)); return *this;} /** * <p> The uplink speed this catalog item requires for the connection to the * Region. </p> */ inline CatalogItem& AddSupportedUplinkGbps(int value) { m_supportedUplinkGbpsHasBeenSet = true; m_supportedUplinkGbps.push_back(value); return *this; } /** * <p> The supported storage options for the catalog item. </p> */ inline const Aws::Vector<SupportedStorageEnum>& GetSupportedStorage() const{ return m_supportedStorage; } /** * <p> The supported storage options for the catalog item. </p> */ inline bool SupportedStorageHasBeenSet() const { return m_supportedStorageHasBeenSet; } /** * <p> The supported storage options for the catalog item. </p> */ inline void SetSupportedStorage(const Aws::Vector<SupportedStorageEnum>& value) { m_supportedStorageHasBeenSet = true; m_supportedStorage = value; } /** * <p> The supported storage options for the catalog item. </p> */ inline void SetSupportedStorage(Aws::Vector<SupportedStorageEnum>&& value) { m_supportedStorageHasBeenSet = true; m_supportedStorage = std::move(value); } /** * <p> The supported storage options for the catalog item. </p> */ inline CatalogItem& WithSupportedStorage(const Aws::Vector<SupportedStorageEnum>& value) { SetSupportedStorage(value); return *this;} /** * <p> The supported storage options for the catalog item. </p> */ inline CatalogItem& WithSupportedStorage(Aws::Vector<SupportedStorageEnum>&& value) { SetSupportedStorage(std::move(value)); return *this;} /** * <p> The supported storage options for the catalog item. </p> */ inline CatalogItem& AddSupportedStorage(const SupportedStorageEnum& value) { m_supportedStorageHasBeenSet = true; m_supportedStorage.push_back(value); return *this; } /** * <p> The supported storage options for the catalog item. </p> */ inline CatalogItem& AddSupportedStorage(SupportedStorageEnum&& value) { m_supportedStorageHasBeenSet = true; m_supportedStorage.push_back(std::move(value)); return *this; } private: Aws::String m_catalogItemId; bool m_catalogItemIdHasBeenSet; CatalogItemStatus m_itemStatus; bool m_itemStatusHasBeenSet; Aws::Vector<EC2Capacity> m_eC2Capacities; bool m_eC2CapacitiesHasBeenSet; double m_powerKva; bool m_powerKvaHasBeenSet; int m_weightLbs; bool m_weightLbsHasBeenSet; Aws::Vector<int> m_supportedUplinkGbps; bool m_supportedUplinkGbpsHasBeenSet; Aws::Vector<SupportedStorageEnum> m_supportedStorage; bool m_supportedStorageHasBeenSet; }; } // namespace Model } // namespace Outposts } // namespace Aws
33.851133
176
0.669025
[ "vector", "model" ]
8ee32ba53bc622a17b3305b06bae0646f71f03f7
914
h
C
src/app/lineParser.h
plnu/csvfilter
eb58a697fefc4fbaaa8663ba67b9d92c9cabfa90
[ "BSD-3-Clause" ]
1
2015-12-08T21:43:48.000Z
2015-12-08T21:43:48.000Z
src/app/lineParser.h
plnu/csvfilter
eb58a697fefc4fbaaa8663ba67b9d92c9cabfa90
[ "BSD-3-Clause" ]
null
null
null
src/app/lineParser.h
plnu/csvfilter
eb58a697fefc4fbaaa8663ba67b9d92c9cabfa90
[ "BSD-3-Clause" ]
null
null
null
// // csvfilter, Copyright (c) 2015, plnu // #ifndef CSVFILTER_LINEPARSER_H #define CSVFILTER_LINEPARSER_H #include "field.h" #include <vector> #include <string> /** * @brief Parse a line of csv. * * This class provides methods to parse a line of csv into individual fields, * and has full support for quoted fields. * * Once the line is parsed (using LineParser::parse) you can access the * individual fields by using LineParser::fieldCount and LineParser::field. * */ class LineParser { public: LineParser(); bool parse(char*); size_t fieldCount() const; FieldRef field(int idx) const; const std::string& errText() const; private: LineParser(const LineParser& other); LineParser& operator=(const LineParser& other); char* endOfField(char* pos); std::string error_; std::vector<FieldRef> fields_; int usedFields_; }; #endif // CSVFILTER_LINEPARSER_H
20.311111
77
0.701313
[ "vector" ]
8ee786a7044b758e53bfe4eb74500192a2cf16f9
5,557
h
C
src/cxx/libsparse/libsparse2d/FCur.h
jstarck/cosmostat
f686efe4c00073272487417da15e207a529f07e7
[ "MIT" ]
null
null
null
src/cxx/libsparse/libsparse2d/FCur.h
jstarck/cosmostat
f686efe4c00073272487417da15e207a529f07e7
[ "MIT" ]
null
null
null
src/cxx/libsparse/libsparse2d/FCur.h
jstarck/cosmostat
f686efe4c00073272487417da15e207a529f07e7
[ "MIT" ]
null
null
null
/****************************************************************************** ** Copyright (C) 2005 by CEA ******************************************************************************* ** ** UNIT ** ** Version: 1.0 ** ** Author: Jean-Luc Starck ** ** Date: 21/01/2005 ** ** File: FCur.h ** ** Modification history : ** ******************************************************************************* ** ** DESCRIPTION: Fast Curvelet Transform ** ----------- ******************************************************************************/ #ifndef _FASTCUR_H #define _FASTCUR_H #include "GlobalInc.h" #include "IM_IO.h" #include "FFTN.h" #include "FFTN_2D.h" #include "MeyerWT.h" #include "IM_Prob.h" #include "IM_Math.h" #include <fstream> /***********************************************************************/ int fct_real_get_band_size(int Nbr_Scale, int Nl, int Nc, int NDir, intarray &TabSizeNl, intarray &TabSizeNc); class FCUR: public MEYER_WT { protected: int DataNl; // Input image size must be odd. If it is not, we etend it by one line or int DataNc; // one column, and we save here the original image size Bool ModifSize; int NewNl; int NewNc; bool isset_tabsigma; // true if TabCurSigma is filled void get_wedges(Icomplex_f * &TabWT); void put_wedges(Icomplex_f * &TabWT); intarray *TabSizeNl; // Band size intarray *TabSizeNc; // Band size void get_size(); public: bool Undecimated; fltarray TabCurSigma; // Normalization array Icomplex_f **TabCF_Band; // TabCF_Band contains the curvelet transform of the Data // TabCF_Band[s][b].real() ==> real band at scale s and dir b // TabCF_Band[s][b].imag() ==> imaginary band at scale s and dir b // real part and imaginary part can be analyzed independently int NbrBandCF; // Total Number of complex bands int NbrBand; // total Number of Band intarray TabNbrBandPerScale; // Number of bands per scale intarray TabNbrAnglePerScale; // Number of directions per scale Bool RealBand; // If true, the redundancy inside the curvelet transform is used to remove // the imaginary part.Then the imaginary part equals to zero. // public: int nbr_dir(int s) {return TabNbrAnglePerScale(s);} FCUR():MEYER_WT() {TabCF_Band=NULL;NbrBand=0;NbrBandCF=0;RealBand=False;isset_tabsigma=false;Undecimated=false;} ~FCUR(); void alloc_with_tab(int Nbr_Scale, int Nl, int Nc, intarray & TabDir, Bool ExtendWT=True, Bool IsotropWT=False, Bool RealCur=False); // Allocation of the class // Nbr_Scale = number of scales used in the wavelet transform // Nl,Nc = input image size // TabDir = array of number of directions per scale (minimum 8) // ExtendWT = The image is extended for aliasing removal // IsotropWT = an isotropic wavelet transform is used instead of the meyer wavelet // in this case ExtendWT is set to false void alloc_from_coarse(int Nbr_Scale, int Nl, int Nc, int NbrDir, Bool ExtendWT=True, Bool IsotropWT=False, Bool RealCur=False); // NbrDir = number of directions at the coarsest resolution (minimum 8) void alloc_from_fine(int Nbr_Scale, int Nl, int Nc, int NbrDir, Bool ExtendWT=True, Bool IsotropWT=False, Bool RealCur=False); // NbrDir = number of directions at the finest resolution (minimum 8) void cur_write(char *Name); void cur_trans(Ifloat &Data); void cur_recons(Ifloat &Data); inline int real() { return RealBand;} inline int nbr_band(int s) { return TabNbrBandPerScale(s);} inline int nbr_tot_band() { return (int) TabNbrBandPerScale.total();} // return the number of bands at scale s //inline int size_band_nl(int s, int b) { return (real() == False) ? TabCF_Band[s][b/2].nl() : TabCF_Band[s][b].nl();} // inline int size_band_nc(int s, int b) { return (real() == False) ? TabCF_Band[s][b/2].nc() : TabCF_Band[s][b].nc();} inline int size_band_nl(int s, int b) { return (real() == False) ? TabSizeNl[s](b/2) : TabSizeNl[s](b);} inline int size_band_nc(int s, int b) { return (real() == False) ? TabSizeNc[s](b/2) : TabSizeNc[s](b);} void get_band(int s, int b, Ifloat &Band); // return a given band void put_band(int s, int b, Ifloat &Band); // return a given band // return a coefficient. If complex transform, returns the real part inline float & operator() (int s, int b, int i, int j) { int bb = RealBand ? b : b/2; complex_f *PtrCF = (TabCF_Band[s][bb]).buffer() + i * (TabCF_Band[s][bb]).nc() + j; float *Ptr = (float *) PtrCF; if (!RealBand && (b % 2 != 0)) Ptr++; return *Ptr; } void get_stat(fltarray &TabStat); void get_norm_coeff(Ifloat &ImaNoise, float N_Sigma); void set_noise_level(float N_Sigma); void get_norm_coeff(float N_Sigma); void import_norm_coef(fltarray * TabSigma); void export_norm_coef(fltarray * &TabSigma); void threshold(float SigmaNoise, float N_Sigma); void wiener_filter(float SigmaNoise, int WienerBlockSize=7); float norm_band(int s, int b) { return TabCurSigma(s,b);} bool isset_norm() {return isset_tabsigma;} void read(char *Name); void mr_io_fill_header(fitsfile *fptr); void write(char *Name); }; /***********************************************************************/ #endif
39.692857
136
0.593846
[ "transform" ]
8ee86628f0f1e75fe3c88423a290d1097605489b
5,906
c
C
cstreamgeo/src/stream.c
mrdmnd/streamgeo
6340e670f0d5000a5c8ceb6be9085efaecba78c3
[ "MIT" ]
4
2016-12-19T09:01:42.000Z
2021-03-30T04:08:30.000Z
cstreamgeo/src/stream.c
mrdmnd/streamgeo
6340e670f0d5000a5c8ceb6be9085efaecba78c3
[ "MIT" ]
1
2016-12-19T02:00:19.000Z
2016-12-19T02:00:19.000Z
cstreamgeo/src/stream.c
mrdmnd/streamgeo
6340e670f0d5000a5c8ceb6be9085efaecba78c3
[ "MIT" ]
1
2016-12-19T01:54:00.000Z
2016-12-19T01:54:00.000Z
#include <cstreamgeo/cstreamgeo.h> #include <stdbool.h> #include <stdlib.h> #include <stdarg.h> #include <stdio.h> #include <math.h> #include <assert.h> /** * General functions for interacting with a single stream. * Includes resampling, filtering, sparsity, etc. */ stream_t* stream_create(const size_t n) { stream_t* stream = malloc(sizeof(stream_t)); stream->n = n; stream->data = malloc(2 * n * sizeof(float)); return stream; } stream_t* stream_create_from_list(const size_t n, ...) { va_list args; va_start(args, n); stream_t* stream = stream_create(n); float arg; for (size_t i = 0; i < 2 * n; i++) { arg = (float) va_arg(args, double); stream->data[i] = arg; } va_end(args); return stream; } void stream_destroy(const stream_t* stream) { free(stream->data); free((void*) stream); } void stream_printf(const stream_t* stream) { const size_t n = stream->n; const float* data = stream->data; printf("Stream contains %zu points: [", n); for (size_t i = 0; i < n; i++) { printf("[%f, %f], ", data[2 * i], data[2 * i + 1]); } printf("]\n"); } void stream_geojson_printf(const stream_t* stream) { const size_t n = stream->n; const float* data = stream->data; printf("{ \"type\": \"Feature\", \"properties\": {}, \"geometry\": { \"type\": \"LineString\", \"coordinates\": ["); for (size_t i = 0; i < n-1; i++) { printf("[%f, %f], ", data[2*i + 1], data[2*i]); } printf("[%f, %f]]", data[2*(n-1) + 1], data[2*(n-1)]); printf("}}\n"); } float stream_distance(const stream_t* stream) { const size_t s_n = stream->n; const float* data = stream->data; assert(s_n >= 2); float sum = 0.0f; float lat_diff; float lng_diff; for (size_t i = 0; i < s_n - 1; i++) { lat_diff = data[2 * i + 2] - data[2 * i + 0]; lng_diff = data[2 * i + 3] - data[2 * i + 1]; sum += sqrt((lng_diff * lng_diff) + (lat_diff * lat_diff)); } return sum; } float* stream_sparsity_create(const stream_t *stream) { const size_t s_n = stream->n; const float* data = stream->data; float* sparsity = malloc(sizeof(float) * s_n); const float optimal_spacing = stream_distance(stream) / (s_n - 1); const float two_over_pi = 0.63661977236f; int i, j, k; float lat_diff, lng_diff, v; for (int n = 0; n < (int) s_n; n++) { i = (n - 1) < 0 ? 1 : n - 1; j = n; k = (n + 1) > (int) s_n - 1 ? (int) s_n - 2 : n + 1; lat_diff = data[2 * j] - data[2 * i]; lng_diff = data[2 * j + 1] - data[2 * i + 1]; float d1 = sqrtf((lng_diff * lng_diff) + (lat_diff * lat_diff)); lat_diff = data[2 * k] - data[2 * j]; lng_diff = data[2 * k + 1] - data[2 * j + 1]; float d2 = sqrtf((lng_diff * lng_diff) + (lat_diff * lat_diff)); v = (d1 + d2) / (2 * optimal_spacing); sparsity[j] = (float) (1.0 - two_over_pi * atan(v)); } return sparsity; } void stream_statistics_printf(const stream_t* stream) { const size_t n = stream->n; const float distance = stream_distance(stream); const float* sparsity = stream_sparsity_create(stream); printf("Stream contains %zu points. Total distance is %f. Sparsity array is: [", n, distance); for (size_t i = 0; i < n; i++) { printf("%f, ", sparsity[i]); } printf("]\n"); free((void*) sparsity); } float _point_line_distance(float px, float py, float sx, float sy, float ex, float ey) { return (sx == ex && sy == ey) ? (px - sx) * (px - sx) + (py - sy) * (py - sy) : fabsf((ex - sx) * (sy - py) - (sx - px) * (ey - sy)) / sqrtf((ex - sx) * (ex - sx) + (ey - sy) * (ey - sy)); } void _douglas_peucker(const stream_t* input, const size_t start, const size_t end, const float epsilon, bool* indices) { const float* input_data = input->data; float d_max = 0.0f; size_t index_max = start; float sx = input_data[2 * start]; float sy = input_data[2 * start + 1]; float ex = input_data[2 * end]; float ey = input_data[2 * end + 1]; // Identify the point with largest distance from its neighbors. for (size_t i = start + 1; i < end; ++i) { float d = _point_line_distance(input_data[2 * i], input_data[2 * i + 1], sx, sy, ex, ey); if (d > d_max) { index_max = i; d_max = d; } } // If it's at least epsilon away, we need to *keep* this point as it's "significant". if (d_max > epsilon) { // Recurse left-half. if (index_max - start > 1) { _douglas_peucker(input, start, index_max, epsilon, indices); } // Add the significant point. indices[index_max] = 1; // Recurse right-half. if (end - index_max > 1) { _douglas_peucker(input, index_max, end, epsilon, indices); } } } void downsample_rdp(stream_t *input, const float epsilon) { size_t input_n = input->n; float* input_data = input->data; bool* indices = calloc(input_n, sizeof(bool)); indices[0] = 1; indices[input_n - 1] = 1; _douglas_peucker(input, 0, input_n - 1, epsilon, indices); // Indices is an array 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, ... 1 size_t n = 0; for (size_t i = 0; i < input_n; i++) { if (indices[i]) { input_data[2*n] = input_data[2*i]; input_data[2*n + 1] = input_data[2*i + 1]; n++; } } input->n = n; input->data = realloc(input_data, 2*n*sizeof(float)); free(indices); } /* stream_t* downsample_radial_distance(const stream_t* input, const float epsilon) { printf("NOT YET IMPLEMENTED\n"); return NULL; } stream_t* resample_fixed_factor(const stream_t* input, const size_t n, const size_t m) { printf("NOT YET IMPLEMENTED\n"); return NULL; } */
31.582888
120
0.565527
[ "geometry" ]
8ef683b8795b17e6e33be13357f3eb472e0a03bb
4,668
h
C
cg/include/graphics/SceneWindowBase.h
paulo-pagliosa/Ds
99b30d1db28cce7ea1a2a7a8d4b2b0bd4cc71700
[ "Zlib" ]
2
2021-11-23T18:36:51.000Z
2021-11-24T19:38:25.000Z
cg/include/graphics/SceneWindowBase.h
paulo-pagliosa/Ds
99b30d1db28cce7ea1a2a7a8d4b2b0bd4cc71700
[ "Zlib" ]
1
2022-02-12T20:47:59.000Z
2022-03-17T02:03:25.000Z
cg/include/graphics/SceneWindowBase.h
paulo-pagliosa/Ds
99b30d1db28cce7ea1a2a7a8d4b2b0bd4cc71700
[ "Zlib" ]
1
2022-02-12T22:31:50.000Z
2022-02-12T22:31:50.000Z
//[]---------------------------------------------------------------[] //| | //| Copyright (C) 2020, 2022 Paulo Pagliosa. | //| | //| This software is provided 'as-is', without any express or | //| implied warranty. In no event will the authors be held liable | //| for any damages arising from the use of this software. | //| | //| Permission is granted to anyone to use this software for any | //| purpose, including commercial applications, and to alter it and | //| redistribute it freely, subject to the following restrictions: | //| | //| 1. The origin of this software must not be misrepresented; you | //| must not claim that you wrote the original software. If you use | //| this software in a product, an acknowledgment in the product | //| documentation would be appreciated but is not required. | //| | //| 2. Altered source versions must be plainly marked as such, and | //| must not be misrepresented as being the original software. | //| | //| 3. This notice may not be removed or altered from any source | //| distribution. | //| | //[]---------------------------------------------------------------[] // // OVERVIEW: SceneWindowBase.h // ======== // Class definition for scene window base. // // Author: Paulo Pagliosa // Last revision: 26/02/2022 #ifndef __SceneWindowBase_h #define __SceneWindowBase_h #include "graphics/GLWindow.h" #include "graphics/GLTextureFrameBuffer.h" #include "graphics/SceneEditor.h" namespace cg { // begin namespace ///////////////////////////////////////////////////////////////////// // // SceneWindowBase: scene window base class // =============== class SceneWindowBase: public GLWindow { public: GLRenderer* renderer() const { return _editor; } protected: Color _selectedWireframeColor{255, 102, 0}; bool _showEditorView{true}; bool _showPreview{true}; using GLWindow::GLWindow; SceneEditor* editor() const { return _editor; } void initialize() override; void render() override; virtual void newScene(); virtual void beginInitialize(); virtual void endInitialize(); virtual void initializeScene(); virtual bool onResize(int, int); virtual bool onPickObject(int, int); virtual bool onPressKey(int); void editorView(); void preview(Camera&); void showErrorMessage(const char*) const; Ray3f makeRay(int, int) const; static void inspectCamera(Camera&); static void inspectLight(Light&); static void inspectMaterial(Material&); private: enum class MoveBits { Left = 1, Right = 2, Forward = 4, Back = 8, Up = 16, Down = 32 }; enum class DragBits { Rotate = 1, Pan = 2 }; Reference<SceneEditor> _editor; Reference<GLTextureFramebuffer> _fbo; Flags<MoveBits> _moveFlags{}; Flags<DragBits> _dragFlags{}; struct { int px, py; int cx, cy; } _mouse; bool windowResizeEvent(int, int) override; bool scrollEvent(double, double) override; bool mouseButtonInputEvent(int, int, int) override; bool mouseMoveEvent(double, double) override; bool keyInputEvent(int, int, int) override; virtual SceneBase* makeScene() = 0; }; // SceneWindowBase } // end namespace cg namespace ImGui { // begin namespace ImGui using namespace cg; void objectNameInput(NameableObject& object); void inputText(const char* label, const char* text); inline bool dragVec2(const char* label, vec2f& v, float min = 0, float max = 0) { return ImGui::DragFloat2(label, &v.x, 0.01f, min, max, "%.2g"); } inline bool dragVec2(const char* label, vec2f& v, vec2f r) { return ImGui::SliderFloat2(label, &v.x, r.x, r.y, "%.2g"); } inline bool dragVec3(const char* label, vec3f& v, float min = 0, float max = 0) { // TODO: replace 0.1f return ImGui::DragFloat3(label, &v.x, 0.1f, min, max, "%.2g"); } inline bool dragVec3(const char* label, vec3f& v, vec2f r) { return ImGui::SliderFloat3(label, &v.x, r.x, r.y, "%.2g"); } inline bool colorEdit3(const char* label, Color& color) { return ImGui::ColorEdit3(label, &color.r); } bool showStyleSelector(const char* label); } // end namespace ImGui #endif // __SceneWindodBase_h
26.674286
69
0.575621
[ "render", "object" ]
8ef725cd0933dda78e8e826e15d377efaa057b2b
6,165
h
C
ftsoftds_vc6/include/d_map.h
guarana-x/fwg
5a56dcb4caee5dca6744fca8e21b987b07106513
[ "MIT" ]
null
null
null
ftsoftds_vc6/include/d_map.h
guarana-x/fwg
5a56dcb4caee5dca6744fca8e21b987b07106513
[ "MIT" ]
null
null
null
ftsoftds_vc6/include/d_map.h
guarana-x/fwg
5a56dcb4caee5dca6744fca8e21b987b07106513
[ "MIT" ]
null
null
null
#ifndef MINIMAP_CLASS #define MINIMAP_CLASS #include "d_pair.h" // miniPair class #include "d_stree.h" // stree class // implements a map containing key/value pairs. // a map does not contain multiple copies of the same item. // types T and Key must have a default constructor template <typename Key, typename T> class miniMap { public: typedef stree<miniPair<const Key,T> >::iterator iterator; typedef stree<miniPair<const Key,T> >::const_iterator const_iterator; // miniMap iterators are simply stree iterators. an iterator cannot // change the key in a tree node, since the key attribute // of a miniPair object in the tree is const typedef miniPair<const Key, T> value_type; // for programmer convenience miniMap(); // default constructor. create an empty map miniMap(value_type *first, value_type *last); // build a map whose key/value pairs are determined by pointer // values [first, last) bool empty() const; // is the map empty? int size() const; // return the number of elements in the map iterator find (const Key& key); // search for item in the map with the given key // and return an iterator pointing at it, or end() // if it is not found const_iterator find (const Key& key) const; // constant version of find() T& operator[] (const Key& key); // if no value is associated with key, create a new // map entry with the default value T() and return a // reference to the default value; otherwise, // return a reference to the value already associated // with the key int count(const Key& key) const; // returns 1 if an element with the key is in the map // and 0 otherwise miniPair<iterator,bool> insert(const value_type& kvpair); // if the map does not contain a key/value pair whose // key matches that of kvpair, insert a coy of kvpair // and return a miniPair object whose first element is an // iterator positioned at the new key/value pair and whose second // element is true. if the map already contains a key/value // pair whose key matches that of kvpair, return a miniPair // object whose first element is an iterator positioned at the // existing key/value pair and whose second element is false int erase(const Key& key); // erase the key/value pair with the specified key // from the map and return the number // of items erased (1 or 0) void erase(iterator pos); // erase the map key/value pair pointed by to pos void erase(iterator first, iterator last); // erase the key/value pairs in the range [first, last) iterator begin(); // return an iterator pointing at the first member // in the map const_iterator begin() const; // constant version of begin() iterator end(); // return an iterator pointing just past the last // member in the map const_iterator end() const; // constant version of end() private: // miniMap implemented using an stree of key-value pairs stree<miniPair<const Key,T> > t; }; template <typename Key, typename T> miniMap<Key,T>::miniMap() {} template <typename Key, typename T> miniMap<Key,T>::miniMap(value_type *first, value_type *last): t(first, last) {} template <typename Key, typename T> bool miniMap<Key,T>::empty() const { return t.empty(); } template <typename Key, typename T> int miniMap<Key,T>::size() const { return t.size(); } template <typename Key, typename T> miniMap<Key,T>::iterator miniMap<Key,T>::find (const Key& key) { // pass a miniPair to stree find() that contains key as its // first member and T() as its second return t.find(value_type(key, T())); } template <typename Key, typename T> miniMap<Key,T>::const_iterator miniMap<Key,T>::find (const Key& key) const { // pass a miniPair to stree find() that contains key as its // first member and T() as its second return t.find(value_type(key, T())); } template <typename Key, typename T> T& miniMap<Key,T>::operator[] (const Key& key) { // build a miniPair object consisting of key // and the default value T() value_type tmp(key, T()); // will point to a pair in the map iterator iter; // try to insert tmp into the map. the iterator // component of the pair returned by t.insert() // points at either the newly created key/value // pair or a pair already in the map. return a // reference to the value in the pair iter = t.insert(tmp).first; return (*iter).second; } template <typename Key, typename T> int miniMap<Key,T>::count(const Key& key) const { // pass a miniPair to stree count() that contains key as its // first member and T() as its second return t.count(value_type(key, T())); } template <typename Key, typename T> miniPair<miniMap<Key,T>::iterator,bool> miniMap<Key,T>::insert(const miniMap<Key,T>::value_type& kvpair) { // t.insert() returns a pair<iterator,bool> object, not a // miniPair<iterator,bool> object pair<iterator, bool> p = t.insert(kvpair); // build and return a miniPair<iterator,bool> object return miniPair<iterator, bool>(p.first, p.second); } template <typename Key, typename T> int miniMap<Key,T>::erase(const Key& key) { // pass a miniPair to stree erase() that contains key as its // first member and T() as its second return t.erase(value_type(key, T())); } template <typename Key, typename T> void miniMap<Key,T>::erase(iterator pos) { t.erase(pos); } template <typename Key, typename T> void miniMap<Key,T>::erase(iterator first, iterator last) { t.erase(first,last); } template <typename Key, typename T> miniMap<Key,T>::iterator miniMap<Key,T>::begin() { return t.begin(); } template <typename Key, typename T> miniMap<Key,T>::iterator miniMap<Key,T>::end() { return t.end(); } template <typename Key, typename T> miniMap<Key,T>::const_iterator miniMap<Key,T>::begin() const { return t.begin(); } template <typename Key, typename T> miniMap<Key,T>::const_iterator miniMap<Key,T>::end() const { return t.end(); } #endif // MINIMAP_CLASS
28.674419
75
0.678345
[ "object" ]
8efdf8752059520176deb7944e7901ae5752d779
8,298
h
C
squid/squid3-3.3.8.spaceify/src/acl/Checklist.h
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
4
2015-01-20T15:25:34.000Z
2017-12-20T06:47:42.000Z
squid/squid3-3.3.8.spaceify/src/acl/Checklist.h
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
4
2015-05-15T09:32:55.000Z
2016-02-18T13:43:31.000Z
squid/squid3-3.3.8.spaceify/src/acl/Checklist.h
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
null
null
null
/* * * SQUID Web Proxy Cache http://www.squid-cache.org/ * ---------------------------------------------------------- * * Squid is the result of efforts by numerous individuals from * the Internet community; see the CONTRIBUTORS file for full * details. Many organizations have provided support for Squid's * development; see the SPONSORS file for full details. Squid is * Copyrighted (C) 2001 by the Regents of the University of * California; see the COPYRIGHT file for full details. Squid * incorporates software developed and/or copyrighted by other * sources; see the CREDITS file for full details. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. * */ #ifndef SQUID_ACLCHECKLIST_H #define SQUID_ACLCHECKLIST_H #include "acl/Acl.h" /// ACL checklist callback typedef void ACLCB(allow_t, void *); /** \ingroup ACLAPI Base class for maintaining Squid and transaction state for access checks. Provides basic ACL checking methods. Its only child, ACLFilledChecklist, keeps the actual state data. The split is necessary to avoid exposing all ACL-related code to virtually Squid data types. */ class ACLChecklist { public: /** * State class. * This abstract class defines the behaviour of * async lookups - which can vary for different ACL types. * Today, every state object must be a singleton. * See NULLState for an example. * \note *no* state should be stored in the state object, * they are used to change the behaviour of the checklist, not * to hold information. If you need to store information in the * state object, consider subclassing ACLChecklist, converting it * to a composite, or changing the state objects from singletons to * refcounted objects. */ class AsyncState { public: virtual void checkForAsync(ACLChecklist *) const = 0; virtual ~AsyncState() {} protected: void changeState (ACLChecklist *, AsyncState *) const; }; class NullState : public AsyncState { public: static NullState *Instance(); virtual void checkForAsync(ACLChecklist *) const; virtual ~NullState() {} private: static NullState _instance; }; public: ACLChecklist(); virtual ~ACLChecklist(); /** * Start a non-blocking (async) check for a list of allow/deny rules. * Each rule comes with a list of ACLs. * * The callback specified will be called with the result of the check. * * The first rule where all ACLs match wins. If there is such a rule, * the result becomes that rule keyword (ACCESS_ALLOWED or ACCESS_DENIED). * * If there are rules but all ACL lists mismatch, an implicit rule is used. * Its result is the negation of the keyword of the last seen rule. * * Some ACLs may stop the check prematurely by setting an exceptional * check result (e.g., ACCESS_AUTH_REQUIRED) instead of declaring a * match or mismatch. * * If there are no rules to check at all, the result becomes ACCESS_DUNNO. * Calling this method with no rules to check wastes a lot of CPU cycles * and will result in a DBG_CRITICAL debugging message. */ void nonBlockingCheck(ACLCB * callback, void *callback_data); /** * Perform a blocking (immediate) check for a list of allow/deny rules. * Each rule comes with a list of ACLs. * * The first rule where all ACLs match wins. If there is such a rule, * the result becomes that rule keyword (ACCESS_ALLOWED or ACCESS_DENIED). * * If there are rules but all ACL lists mismatch, an implicit rule is used * Its result is the negation of the keyword of the last seen rule. * * Some ACLs may stop the check prematurely by setting an exceptional * check result (e.g., ACCESS_AUTH_REQUIRED) instead of declaring a * match or mismatch. * * Some ACLs may require an async lookup which is prohibited by this * method. In this case, the exceptional check result of ACCESS_DUNNO is * immediately returned. * * If there are no rules to check at all, the result becomes ACCESS_DUNNO. */ allow_t const & fastCheck(); /** * Perform a blocking (immediate) check whether a list of ACLs matches. * This method is meant to be used with squid.conf ACL-driven options that * lack allow/deny keywords and are tested one ACL list at a time. Whether * the checks for other occurrences of the same option continue after this * call is up to the caller and option semantics. * * If all ACLs match, the result becomes ACCESS_ALLOWED. * * If all ACLs mismatch, the result becomes ACCESS_DENIED. * * Some ACLs may stop the check prematurely by setting an exceptional * check result (e.g., ACCESS_AUTH_REQUIRED) instead of declaring a * match or mismatch. * * Some ACLs may require an async lookup which is prohibited by this * method. In this case, the exceptional check result of ACCESS_DUNNO is * immediately returned. * * If there are no ACLs to check at all, the result becomes ACCESS_ALLOWED. */ allow_t const & fastCheck(const ACLList * list); // whether the last checked ACL of the current rule needs // an async operation to determine whether there was a match bool asyncNeeded() const; bool asyncInProgress() const; void asyncInProgress(bool const); /// whether markFinished() was called bool finished() const; /// called when no more ACLs should be checked; sets the final answer and /// prints a debugging message explaining the reason for that answer void markFinished(const allow_t &newAnswer, const char *reason); const allow_t &currentAnswer() const { return allow_; } void changeState(AsyncState *); AsyncState *asyncState() const; // XXX: ACLs that need request or reply have to use ACLFilledChecklist and // should do their own checks so that we do not have to povide these two // for ACL::checklistMatches to use virtual bool hasRequest() const = 0; virtual bool hasReply() const = 0; private: /// Calls non-blocking check callback with the answer and destroys self. void checkCallback(allow_t answer); void checkAccessList(); void checkForAsync(); public: const acl_access *accessList; ACLCB *callback; void *callback_data; /** * Performs non-blocking check starting with the current rule. * Used by nonBlockingCheck() to initiate the checks and by * async operation callbacks to resume checks after the async * operation updates the current Squid state. See nonBlockingCheck() * for details on final result determination. */ void matchNonBlocking(); private: /* internal methods */ /// possible outcomes when trying to match a single ACL node in a list typedef enum { nmrMatch, nmrMismatch, nmrFinished, nmrNeedsAsync } NodeMatchingResult; /// prepare for checking ACLs; called once per check void preCheck(const char *what); bool matchAclList(const ACLList * list, bool const fast); bool matchNodes(const ACLList * head, bool const fast); NodeMatchingResult matchNode(const ACLList &node, bool const fast); void calcImplicitAnswer(const allow_t &lastSeenAction); bool async_; bool finished_; allow_t allow_; AsyncState *state_; bool checking_; bool checking() const; void checking (bool const); bool callerGone(); }; #endif /* SQUID_ACLCHECKLIST_H */
36.394737
79
0.690528
[ "object" ]
f11a4ba310821aaa504324374d7f607a0f31f414
3,170
h
C
mcrouter/lib/config/RouteHandleFactory-inl.h
wicky-info/mcrouter
bc8bbbcc3e9a6ef79146d4096f3e39af942ada09
[ "BSD-3-Clause" ]
1
2015-11-08T10:09:45.000Z
2015-11-08T10:09:45.000Z
mcrouter/lib/config/RouteHandleFactory-inl.h
wicky-info/mcrouter
bc8bbbcc3e9a6ef79146d4096f3e39af942ada09
[ "BSD-3-Clause" ]
null
null
null
mcrouter/lib/config/RouteHandleFactory-inl.h
wicky-info/mcrouter
bc8bbbcc3e9a6ef79146d4096f3e39af942ada09
[ "BSD-3-Clause" ]
null
null
null
/** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include <folly/dynamic.h> #include "mcrouter/lib/config/RouteHandleProviderIf.h" #include "mcrouter/lib/fbi/cpp/util.h" namespace facebook { namespace memcache { template <class RouteHandleIf> RouteHandleFactory<RouteHandleIf>::RouteHandleFactory( RouteHandleProviderIf<RouteHandleIf>& provider) : provider_(provider) { } template <class RouteHandleIf> std::shared_ptr<RouteHandleIf> RouteHandleFactory<RouteHandleIf>::create(const folly::dynamic& json) { auto result = createList(json); checkLogic(result.size() == 1, "{} RouteHandles in list, expected 1", result.size()); return result.back(); } template <class RouteHandleIf> std::vector<std::shared_ptr<RouteHandleIf>> RouteHandleFactory<RouteHandleIf>::createList(const folly::dynamic& json) { if (json.isArray()) { std::vector<std::shared_ptr<RouteHandleIf>> ret; // merge all inner lists into result for (const auto& it : json) { auto list = createList(it); ret.insert(ret.end(), list.begin(), list.end()); } return ret; } else if (json.isObject()) { checkLogic(json.count("type"), "No type field in RouteHandle json object"); checkLogic(json["type"].isString(), "Type field in RouteHandle is not string"); auto type = json["type"].asString().toStdString(); auto name = (json.count("name") && json["name"].isString()) ? json["name"].asString().toStdString() : ""; if (!name.empty()) { // got named handle auto it = seen_.find(name); if (it != seen_.end()) { // we had same named handle already. Reuse it. return it->second; } auto ret = provider_.create(*this, type, json); seen_.emplace(name, ret); return ret; } else { return provider_.create(*this, type, json); } } else if (json.isString()) { auto handleString = json.asString().toStdString(); if (handleString.empty()) { // useful for routes with optional children return {}; } // check if we already parsed same string. It can be named handle or short // form of handle. auto it = seen_.find(handleString); if (it != seen_.end()) { return it->second; } std::vector<std::shared_ptr<RouteHandleIf>> ret; auto pipeId = handleString.find("|"); if (pipeId != -1) { // short form (e.g. HashRoute|ErrorRoute) auto type = handleString.substr(0, pipeId); // split by first '|' auto def = handleString.substr(pipeId + 1); ret = provider_.create(*this, type, def); } else { // assume it is short form of route without children (e.g. ErrorRoute) ret = provider_.create(*this, handleString, nullptr); } seen_.emplace(handleString, ret); return ret; } throw std::logic_error("RouteHandle should be object, array or string"); } }} // facebook::memcache
31.386139
79
0.650158
[ "object", "vector" ]
f11d4dbe967e2c2d3b4f397c5583227106ea735a
1,664
h
C
headers/classUIContainer.h
mjjq/ballEngine
891c5bbc2b69f068dde5b28152edd9a97899d132
[ "MIT" ]
null
null
null
headers/classUIContainer.h
mjjq/ballEngine
891c5bbc2b69f068dde5b28152edd9a97899d132
[ "MIT" ]
26
2018-01-27T00:01:55.000Z
2018-08-14T19:53:02.000Z
headers/classUIContainer.h
mjjq/ballEngine
891c5bbc2b69f068dde5b28152edd9a97899d132
[ "MIT" ]
null
null
null
#ifndef CLASS_UICONTAINER_H #define CLASS_UICONTAINER_H #include "classUIWindow.h" #include "structs.h" #include "../extern/json.hpp" #include <cstdlib> #include <ctime> #include <cmath> class UIContainer { using json = nlohmann::json; static sf::RenderWindow &parentWindow; static sf::View &originalView; static sf::View &GUIView; std::vector<std::unique_ptr<UIWindow>> interfaceWindows; std::vector<int> interfaceWindowIDs; std::vector<bool> mouseIntersectionList; std::pair<bool,int> currentIntButton{false, -1}; std::pair<bool,int> currentIntWindow{false, -1}; bool canInteract = true; bool isVisible = true; public: UIContainer(bool _isVisible); //void addWindow(WindowParams &params); //template <class T> void addWindow(CompleteWindow &compWindow); void addWindow(json &j, mapstrvoid &bFuncMap, mapstrvoidfloat &sFuncMap, std::map<std::string, std::function<std::string()> > &varMap); void renderWindows(sf::RenderWindow &window, sf::View &GUIView, sf::View &originalView); UIWindow &getWindow(unsigned int windowIndex); void checkMouseIntersection(sf::RenderWindow &window, sf::View &GUIView, sf::View &originalView); std::pair<bool,int> doesMIntExist(); void clickOnUI(sf::RenderWindow &window); void resetUIClick(); bool isWindowDraggable(); void dragWindow(sf::RenderWindow &window); void destroyWindow(unsigned int index); void destroyAllWindows(); void setWindowIsVisible(int index, bool value); void setWindowCanInteract(int index, bool value); }; #endif // CLASS_UICONTAINER_H
29.192982
101
0.697115
[ "vector" ]
f11e484efb8105cacbd2e2be4c2e7e99686f85dc
16,326
h
C
Code/Components/Services/skymodel/current/tests/service/GlobalSkyModelTest.h
rtobar/askapsoft
6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
null
null
null
Code/Components/Services/skymodel/current/tests/service/GlobalSkyModelTest.h
rtobar/askapsoft
6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
null
null
null
Code/Components/Services/skymodel/current/tests/service/GlobalSkyModelTest.h
rtobar/askapsoft
6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
null
null
null
/// @file GlobalSkyModelTest.h /// /// @copyright (c) 2016 CSIRO /// Australia Telescope National Facility (ATNF) /// Commonwealth Scientific and Industrial Research Organisation (CSIRO) /// PO Box 76, Epping NSW 1710, Australia /// atnf-enquiries@csiro.au /// /// This file is part of the ASKAP software distribution. /// /// The ASKAP software distribution is free software: you can redistribute it /// and/or modify it under the terms of the GNU General Public License as /// published by the Free Software Foundation; either version 2 of the License, /// or (at your option) any later version. /// /// This program is distributed in the hope that it will be useful, /// but WITHOUT ANY WARRANTY; without even the implied warranty of /// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /// GNU General Public License for more details. /// /// You should have received a copy of the GNU General Public License /// along with this program; if not, write to the Free Software /// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /// /// @author Daniel Collins <daniel.collins@csiro.au> // CPPUnit includes #include <cppunit/extensions/HelperMacros.h> // Support classes #include <string> #include <askap/AskapError.h> #include <boost/cstdint.hpp> #include <boost/filesystem.hpp> #include <boost/date_time/posix_time/posix_time_types.hpp> #include <boost/math/constants/constants.hpp> #include <Common/ParameterSet.h> #include <votable/VOTable.h> // Classes to test #include "datamodel/Common.h" #include "datamodel/ContinuumComponent.h" #include "datamodel/ComponentStats.h" #include "service/GlobalSkyModel.h" using namespace std; using namespace askap::accessors; using namespace boost; using namespace boost::posix_time; namespace askap { namespace cp { namespace sms { using namespace datamodel; class GlobalSkyModelTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(GlobalSkyModelTest); CPPUNIT_TEST(testGsmStatsEmpty); CPPUNIT_TEST(testGsmStatsSmall); CPPUNIT_TEST(testCreateFromParsetFile); CPPUNIT_TEST(testNside); CPPUNIT_TEST(testHealpixOrder); CPPUNIT_TEST(testGetMissingComponentById); CPPUNIT_TEST(testIngestVOTableToEmptyDatabase); CPPUNIT_TEST(testIngestVOTableFailsForBadCatalog); CPPUNIT_TEST(testIngestPolarisation); CPPUNIT_TEST(testMetadata); CPPUNIT_TEST(testNonAskapDataIngest); CPPUNIT_TEST(testSimpleConeSearch); CPPUNIT_TEST(testConeSearch_frequency_criteria); CPPUNIT_TEST(testConeSearch_flux_int); CPPUNIT_TEST(testSimpleRectSearch); CPPUNIT_TEST(testRectSearch_freq_range); CPPUNIT_TEST(testLargeAreaSearch); CPPUNIT_TEST(testPixelsPerDatabaseSearchIsMultipleOfPixelsInSearch); CPPUNIT_TEST_SUITE_END(); public: GlobalSkyModelTest() : gsm(), parset(true), parsetFile("./tests/data/sms_parset.cfg"), small_components("./tests/data/votable_small_components.xml"), large_components("./tests/data/votable_large_components.xml"), invalid_components("./tests/data/votable_error_freq_units.xml"), small_polarisation("./tests/data/votable_small_polarisation.xml"), simple_cone_search("./tests/data/votable_simple_cone_search.xml") { } void setUp() { parset.clear(); parset.adoptFile(parsetFile); } void tearDown() { parset.clear(); } void initEmptyDatabase() { gsm = GlobalSkyModel::create(parset); gsm->createSchema(); } void testGsmStatsEmpty() { initEmptyDatabase(); ComponentStats stats = gsm->getComponentStats(); CPPUNIT_ASSERT_EQUAL(std::size_t(0), stats.count); } void testGsmStatsSmall() { initSearch(); ComponentStats stats = gsm->getComponentStats(); CPPUNIT_ASSERT_EQUAL(std::size_t(10), stats.count); } void testCreateFromParsetFile() { initEmptyDatabase(); CPPUNIT_ASSERT(gsm.get()); } void testNside() { initEmptyDatabase(); CPPUNIT_ASSERT_EQUAL(2l << 9, gsm->getHealpixNside()); } void testHealpixOrder() { initEmptyDatabase(); CPPUNIT_ASSERT_EQUAL(9l, gsm->getHealpixOrder()); } void testGetMissingComponentById() { initEmptyDatabase(); GlobalSkyModel::ComponentPtr component = gsm->getComponentByID(9); CPPUNIT_ASSERT(!component.get()); } void testIngestVOTableToEmptyDatabase() { parset.replace("sqlite.name", "./tests/service/ingested.dbtmp"); initEmptyDatabase(); // perform the ingest GlobalSkyModel::IdListPtr ids = gsm->ingestVOTable( small_components, "", 10, second_clock::universal_time()); CPPUNIT_ASSERT_EQUAL(size_t(10), ids->size()); // test that some expected components can be found boost::shared_ptr<ContinuumComponent> component( gsm->getComponentByID((*ids)[0])); CPPUNIT_ASSERT(component.get()); CPPUNIT_ASSERT_EQUAL( string("SB1958_image.i.LMC.cont.sb1958.taylor.0.restored_1a"), component->component_id); } void testIngestPolarisation() { parset.replace("sqlite.name", "./tests/service/polarisation.dbtmp"); initEmptyDatabase(); // perform the ingest GlobalSkyModel::IdListPtr ids = gsm->ingestVOTable( small_components, small_polarisation, 1337, second_clock::universal_time()); CPPUNIT_ASSERT_EQUAL(size_t(10), ids->size()); // each component should have a corresponding polarisation object for (GlobalSkyModel::IdList::const_iterator it = ids->begin(); it != ids->end(); it++) { boost::shared_ptr<ContinuumComponent> component(gsm->getComponentByID(*it)); // Check that we have a polarisation object CPPUNIT_ASSERT(component->polarisation.get()); // Check that we have the correct polarisation object CPPUNIT_ASSERT_EQUAL(component->component_id, component->polarisation->component_id); } } void testNonAskapDataIngest() { parset.replace("sqlite.name", "./tests/service/data_source.dbtmp"); initEmptyDatabase(); // Non-ASKAP data sources need metadata that is assumed for ASKAP sources. boost::shared_ptr<DataSource> expectedDataSource(new DataSource()); expectedDataSource->name = "Robby Dobby the Bear"; expectedDataSource->catalogue_id = "RDTB"; // perform the ingest GlobalSkyModel::IdListPtr ids = gsm->ingestVOTable( small_components, small_polarisation, expectedDataSource); for (GlobalSkyModel::IdList::const_iterator it = ids->begin(); it != ids->end(); it++) { boost::shared_ptr<ContinuumComponent> component(gsm->getComponentByID(*it)); // should have reference to the data source metadata CPPUNIT_ASSERT(component->data_source.get()); // should not have a scheduling block ID CPPUNIT_ASSERT_EQUAL(datamodel::NO_SB_ID, component->sb_id); // Don't have an observation date for now, but this might change. CPPUNIT_ASSERT(component->observation_date == date_time::not_a_date_time), CPPUNIT_ASSERT_EQUAL(expectedDataSource->name, component->data_source->name); CPPUNIT_ASSERT_EQUAL(expectedDataSource->catalogue_id, component->data_source->catalogue_id); } } void testMetadata() { parset.replace("sqlite.name", "./tests/service/metadata.dbtmp"); initEmptyDatabase(); int64_t expected_sb_id = 71414; ptime expected_obs_date = second_clock::universal_time(); // perform the ingest GlobalSkyModel::IdListPtr ids = gsm->ingestVOTable( small_components, "", expected_sb_id, expected_obs_date); for (GlobalSkyModel::IdList::const_iterator it = ids->begin(); it != ids->end(); it++) { boost::shared_ptr<ContinuumComponent> component(gsm->getComponentByID(*it)); CPPUNIT_ASSERT_EQUAL(expected_sb_id, component->sb_id); // CPPUNIT_ASSERT_EQUAL chokes on the ptime values CPPUNIT_ASSERT(expected_obs_date == component->observation_date); } } void testIngestVOTableFailsForBadCatalog() { initEmptyDatabase(); CPPUNIT_ASSERT_THROW( gsm->ingestVOTable( invalid_components, "", 14, date_time::not_a_date_time), askap::AskapError); } void testSimpleConeSearch() { initSearch(); GlobalSkyModel::ComponentListPtr results = gsm->coneSearch(Coordinate(70.2, -61.8), 1.0); CPPUNIT_ASSERT_EQUAL(size_t(1), results->size()); CPPUNIT_ASSERT_EQUAL( string("SB1958_image.i.LMC.cont.sb1958.taylor.0.restored_1a"), results->begin()->component_id); } /// @brief Simple functor for testing query results against expected component ID strings. class ComponentIdMatch { public: ComponentIdMatch(string targetComponentId) : itsTarget(targetComponentId) { } bool operator()(datamodel::ContinuumComponent& that) { return itsTarget == that.component_id; } private: std::string itsTarget; }; void testConeSearch_frequency_criteria() { initSearch(); // create a component query for frequencies in the range [1230..1250] GlobalSkyModel::ComponentQuery query( GlobalSkyModel::ComponentQuery::freq >= 1230.0 && GlobalSkyModel::ComponentQuery::freq <= 1250.0); Coordinate centre(76.0, -71.0); double radius = 1.5; GlobalSkyModel::ComponentListPtr results = gsm->coneSearch(centre, radius, query); CPPUNIT_ASSERT_EQUAL(size_t(3), results->size()); CPPUNIT_ASSERT_EQUAL(1l, std::count_if(results->begin(), results->end(), ComponentIdMatch(string("SB1958_image.i.LMC.cont.sb1958.taylor.0.restored_4b")))); CPPUNIT_ASSERT_EQUAL(1l, std::count_if(results->begin(), results->end(), ComponentIdMatch(string("SB1958_image.i.LMC.cont.sb1958.taylor.0.restored_4c")))); CPPUNIT_ASSERT_EQUAL(1l, std::count_if(results->begin(), results->end(), ComponentIdMatch(string("SB1958_image.i.LMC.cont.sb1958.taylor.0.restored_5a")))); } void testConeSearch_flux_int() { initSearch(); GlobalSkyModel::ComponentQuery query( GlobalSkyModel::ComponentQuery::flux_int >= 80.0); Coordinate centre(76.0, -71.0); double radius = 1.5; GlobalSkyModel::ComponentListPtr results = gsm->coneSearch(centre, radius, query); CPPUNIT_ASSERT_EQUAL(size_t(3), results->size()); CPPUNIT_ASSERT_EQUAL(1l, std::count_if(results->begin(), results->end(), ComponentIdMatch(string("SB1958_image.i.LMC.cont.sb1958.taylor.0.restored_2a")))); CPPUNIT_ASSERT_EQUAL(1l, std::count_if(results->begin(), results->end(), ComponentIdMatch(string("SB1958_image.i.LMC.cont.sb1958.taylor.0.restored_3a")))); CPPUNIT_ASSERT_EQUAL(1l, std::count_if(results->begin(), results->end(), ComponentIdMatch(string("SB1958_image.i.LMC.cont.sb1958.taylor.0.restored_4a")))); } void testSimpleRectSearch() { initSearch(); Rect roi(Coordinate(79.375, -71.5), Extents(0.75, 1.0)); GlobalSkyModel::ComponentListPtr results = gsm->rectSearch(roi); CPPUNIT_ASSERT_EQUAL(size_t(4), results->size()); CPPUNIT_ASSERT_EQUAL(1l, std::count_if(results->begin(), results->end(), ComponentIdMatch(string("SB1958_image.i.LMC.cont.sb1958.taylor.0.restored_1b")))); CPPUNIT_ASSERT_EQUAL(1l, std::count_if(results->begin(), results->end(), ComponentIdMatch(string("SB1958_image.i.LMC.cont.sb1958.taylor.0.restored_1c")))); CPPUNIT_ASSERT_EQUAL(1l, std::count_if(results->begin(), results->end(), ComponentIdMatch(string("SB1958_image.i.LMC.cont.sb1958.taylor.0.restored_4a")))); CPPUNIT_ASSERT_EQUAL(1l, std::count_if(results->begin(), results->end(), ComponentIdMatch(string("SB1958_image.i.LMC.cont.sb1958.taylor.0.restored_4c")))); } void testRectSearch_freq_range() { initSearch(); // use the same bounds as testSimpleRectSearch Rect roi(Coordinate(79.375, -71.5), Extents(0.75, 1.0)); GlobalSkyModel::ComponentQuery query( GlobalSkyModel::ComponentQuery::freq >= 1200.0 && GlobalSkyModel::ComponentQuery::freq <= 1260.0); GlobalSkyModel::ComponentListPtr results = gsm->rectSearch(roi, query); CPPUNIT_ASSERT_EQUAL(size_t(2), results->size()); CPPUNIT_ASSERT_EQUAL(1l, std::count_if(results->begin(), results->end(), ComponentIdMatch(string("SB1958_image.i.LMC.cont.sb1958.taylor.0.restored_4a")))); CPPUNIT_ASSERT_EQUAL(1l, std::count_if(results->begin(), results->end(), ComponentIdMatch(string("SB1958_image.i.LMC.cont.sb1958.taylor.0.restored_4c")))); } void testLargeAreaSearch() { initSearch(); GlobalSkyModel::ComponentListPtr results = gsm->coneSearch(Coordinate(70.2, -61.8), 20.0); CPPUNIT_ASSERT_EQUAL(size_t(10), results->size()); } void testPixelsPerDatabaseSearchIsMultipleOfPixelsInSearch() { // With the initial implementation of search chunking, I was getting // a fencepost error when the total number of pixels in the query // region was evenly divisible by the database query chunk size. // The values chosen here have been selected by trial and error to // reproduce the bug (in order to fix it). parset.replace("database.max_pixels_per_query", "15"); initSearch(); // The search parameters map to 60 pixels at order 9, but if the GSM // NSide/Order is ever changed, then this test may be invalidated CPPUNIT_ASSERT_EQUAL((int64_t) 9, gsm->getHealpixOrder()); CPPUNIT_ASSERT_NO_THROW(gsm->coneSearch(Coordinate(70.2, -61.8), 0.21)); } private: GlobalSkyModel::IdListPtr initSearch() { // Generate the database file for use in functional tests //parset.replace("sqlite.name", "./tests/service/small_spatial_search.db"); initEmptyDatabase(); return gsm->ingestVOTable( simple_cone_search, small_polarisation, 42, second_clock::universal_time()); } boost::shared_ptr<GlobalSkyModel> gsm; LOFAR::ParameterSet parset; const string parsetFile; const string small_components; const string large_components; const string invalid_components; const string small_polarisation; const string simple_cone_search; }; } } }
40.917293
109
0.615705
[ "object" ]
f11f04287ac432dea5548e7e554edb4b7a1a06af
187
h
C
Letter/LetterM.h
PanneauLED/Teensy-Files
288907066773acdc8ed0f4b228581ed585f9545e
[ "MIT" ]
null
null
null
Letter/LetterM.h
PanneauLED/Teensy-Files
288907066773acdc8ed0f4b228581ed585f9545e
[ "MIT" ]
null
null
null
Letter/LetterM.h
PanneauLED/Teensy-Files
288907066773acdc8ed0f4b228581ed585f9545e
[ "MIT" ]
null
null
null
#ifndef LETTERM_H #define LETTERM_H class LetterM : public Shape { public: LetterM(CRGB ledPanel[6][256], Panel connection); void place(CRGB ledPanel[6][256]); }; #endif
17
55
0.679144
[ "shape" ]
f12964255409ef13f7c0b56b1bdb7a6b5ebb1753
1,176
h
C
include/easy/pascals_triangle.h
nexes/leetcode
194abaa09bbe4544b4112bd87d3a7c772c190b2e
[ "MIT" ]
1
2020-10-10T16:37:20.000Z
2020-10-10T16:37:20.000Z
include/easy/pascals_triangle.h
nexes/leetcode
194abaa09bbe4544b4112bd87d3a7c772c190b2e
[ "MIT" ]
null
null
null
include/easy/pascals_triangle.h
nexes/leetcode
194abaa09bbe4544b4112bd87d3a7c772c190b2e
[ "MIT" ]
null
null
null
#pragma once #include <vector> namespace Leet::Easy { // Given a non-negative integer numRows, generate the first numRows of Pascal's // triangle. In Pascal's triangle, each number is the sum of the two numbers // directly above it. // Example: // Input: 5 // Output: // [ // [1], // [1,1], // [1,2,1], // [1,3,3,1], // [1,4,6,4,1] // ] struct PascalTriangle { std::vector<std::vector<int>> generate(int numRows) { std::vector<std::vector<int>> triangle{}; if (numRows == 0) return triangle; std::vector<int> row{1}; triangle.emplace_back(row); for (int i = 1; i < numRows; i++) { std::vector<int> new_row{1}; std::vector<int> prev_row = triangle[i - 1]; for (int j = 1; j < i; j++) { new_row.emplace_back(prev_row[j - 1] + prev_row[j]); } new_row.emplace_back(1); triangle.emplace_back(new_row); } return triangle; } }; } // namespace Leet::Easy
24.5
83
0.471939
[ "vector" ]
f12a82b2cb62a970fcee2c85b6166c2e1fbaf9d6
5,581
h
C
includes/Object.h
idealab-isu/GPView
27aad910e33d0e229cd3149250dc2d45eca81b11
[ "MIT" ]
20
2018-08-27T21:53:06.000Z
2022-03-05T08:11:18.000Z
includes/Object.h
idealab-isu/GPView
27aad910e33d0e229cd3149250dc2d45eca81b11
[ "MIT" ]
1
2021-03-08T23:32:20.000Z
2021-03-08T23:32:20.000Z
includes/Object.h
idealab-isu/GPView
27aad910e33d0e229cd3149250dc2d45eca81b11
[ "MIT" ]
8
2018-09-04T02:51:31.000Z
2022-03-30T14:37:52.000Z
/** * MIT License * * Copyright(c) 2018 Iowa State University (ISU) and ISU IDEALab * * 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 GPV_OBJ_H #define GPV_OBJ_H #include "Utilities.h" #include "GLParameters.h" #include "CUDAUtilities.h" #include <chrono> class Face { public: Face() { visibilityFactor = 0; this->isVertexColored = false; this->isNURBS = false; this->isMarked = false; moment0 = 0; moment1[0] = 0; moment1[1] = 0; moment1[2] = 0; }; ~Face() { triangles.clear(); }; vector<Triangle> triangles; vector<vector<int>> vertexFaces; bool trimmed; GLuint trimTexture; int trimWidth, trimHeight; Float3 kdColor; // Diffuse Color Float3 ksColor; // Specular Color float ka; // Ambient factor // float transparency; // Transparency float shininess; // Shininess float visibilityFactor; bool isVertexColored; bool isNURBS; Float3 bBoxMin; // Face bounding box Min point Float3 bBoxMax; // Face bounding box Max point GLuint dlid; // display list id int parentObjID; int surfID; void DrawFace(GLParameters*, float); // draw the face void DrawFaceNoColor(GLParameters*, float); // draw the face without color void DrawFaceTriangles(GLParameters*); // draw the triangles in the face void DrawOBB(); float GetDistanceFromSphere(float* viewMatrix); int GetCommonFace(int, int, int); void CreateVertexColors(); bool isMarked; float moment0; // Volume contribution due to surface Float3 moment1; // x,y,z-Moment contribution due to surface }; inline bool FACEgreaterTest(const Face p1, const Face p2) { return (p1.visibilityFactor > p2.visibilityFactor); } class Object { public: Object(); ~Object(); Object(const Object &that); vector<Face*> faces; float visibilityFactor; int objID; int totalNumTriangles; bool displayListCreated; float transformationMatrix[16]; // Matrix used for transformation bool identityTransformation; // True if Identity Float3 bBoxMin; // Object bounding box Min point Float3 bBoxMax; // Object bounding box Max point float maxModelSize; // Size of the model Float4 color; // Default object color VoxelData* voxelData; // Voxellised data of the object int voxelInit; float* flatCPUTriangleData; // flat triangle coordinate data for GPU algorithms Object &operator=(const Object &that); void ReadObject(char *fname); void ReadObject2(char *fname); void ReadOFFObject(char *fname); void ReadRAWObject(char *fName); void CreateDisplayLists(GLParameters*); void DrawSceneObject(GLParameters*, bool, float); // draw the object with scene transformations void DrawObject(GLParameters*, bool, float); // draw the object without transformations void ApplyTransformations(GLParameters*); void CreateFlatTriangleData(); void ClassifyInOut(GLParameters*); void ClassifyInOutCPU(GLParameters*); void ComputeDistanceFields(GLParameters*, int); void CombineDistanceFields(GLParameters*); void ClassifyInOut2x(GLParameters*); void ClassifyInOutLevel2(GLParameters*, int); void ClassifyInOut2xLevel2(GLParameters*, int); void ClassifyInOutLevel2CPU(int boundaryIndex); void ClassifyTessellation(GLParameters*); void ClassifyTessellationLevel2(GLParameters*); #ifdef USECUDA int ClassifyTessellationCUDA(GLParameters*); void CollisionInitCUDA(GLParameters*); void ClassifyTessellationLevel2CUDA(GLParameters*); void ClassifyInOutTessellationLevel2CUDA(GLParameters*); #endif void DrawInOutPoints(GLParameters*); void PerformVoxelization(GLParameters*, int); void SaveVoxelization(GLParameters*); void SaveInOutData(GLParameters*); void CreateVoxelStripDisplayLists(GLParameters* glParam); void SaveSTLFile(const char*, const char* name); void BuildHierarchy(GLParameters*); void AddPointToVoxel(int, int, int, int, int, int, bool, int); bool TestTriBox(Triangle*, Float3, Float3); bool TestTriBox(float*, Float3, Float3); void DrawVoxels(GLParameters*); void GenVoxelsDisplayLists(GLParameters*); void DrawVoxelHierarchy(GLParameters*); void DrawOBB(); void DrawFaceBoundingBoxes(GLParameters*); void DrawCOM(); void DrawTriangle(GLParameters*, int, int); float CalculateVolume(bool); //Calculate the volume of the object bool for timing bool massCenterComputed; // Flag to indicate computing center of mass float volume; // Volume of the object Float3 massCenter; // Center of mass of the object }; float GetFaceFaceClosestPoint(Face*, Face*, float*, float*, float*, float*); #endif // GPV_OBJ_H
34.664596
173
0.750045
[ "object", "vector", "model" ]
e6c7aaf9e5a1bc228015c88952503ffe6e686d38
604
h
C
source/libextract/inno.h
AutomaticFrenzy/HamSandwich
d991c840fd688cb2541806a33f152ba9aac41a1a
[ "MIT" ]
null
null
null
source/libextract/inno.h
AutomaticFrenzy/HamSandwich
d991c840fd688cb2541806a33f152ba9aac41a1a
[ "MIT" ]
null
null
null
source/libextract/inno.h
AutomaticFrenzy/HamSandwich
d991c840fd688cb2541806a33f152ba9aac41a1a
[ "MIT" ]
null
null
null
#ifndef LIBEXTRACT_INNO_H #define LIBEXTRACT_INNO_H #include <vector> #include <string> #include <map> #include <stdio.h> #include <stdint.h> #include "common.h" struct SDL_RWops; namespace inno { class Archive : public sauce::Archive { struct DataEntry { uint32_t chunk_offset; uint64_t file_size; uint64_t chunk_size; }; std::vector<DataEntry> data_entries; std::vector<uint8_t> setup_1_bin; public: explicit Archive(FILE* fptr); ~Archive(); bool is_ok() { return setup_1_bin.size(); } SDL_RWops* open_file(const char* path); }; } // namespace inno #endif // LIBEXTRACT_INNO_H
16.324324
44
0.728477
[ "vector" ]
e6cac709872c539fccc55be208f05d6b867cc43c
1,351
h
C
src/gdls_star/camera_feature_correspondence_2d_3d.h
vfragoso/gdls_star
38e2dbc9996ddf4618cbc679d41588594935c5f9
[ "MIT" ]
2
2021-05-06T18:09:16.000Z
2021-09-09T08:40:06.000Z
src/gdls_star/camera_feature_correspondence_2d_3d.h
vfragoso/gdls_star
38e2dbc9996ddf4618cbc679d41588594935c5f9
[ "MIT" ]
null
null
null
src/gdls_star/camera_feature_correspondence_2d_3d.h
vfragoso/gdls_star
38e2dbc9996ddf4618cbc679d41588594935c5f9
[ "MIT" ]
3
2020-10-29T19:25:13.000Z
2021-11-10T11:39:45.000Z
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. // // gDLS*: Generalized Pose-and-Scale Estimation Given Scale and Gravity Priors // // Victor Fragoso, Joseph DeGol, Gang Hua. // Proc. of the IEEE/CVF Conf. on Computer Vision and Pattern Recognition 2020. // // Please contact the author of this library if you have any questions. // Author: Victor Fragoso (victor.fragoso@microsoft.com) #ifndef GDLS_STAR_CAMERA_FEATURE_CORRESPONDENCE_2D_3D_H_ #define GDLS_STAR_CAMERA_FEATURE_CORRESPONDENCE_2D_3D_H_ #include <Eigen/Core> #include "gdls_star/pinhole_camera.h" namespace msft { // The goal of this structure is to hold the 2D-3D correspondence as well as // the individual camera observing the 3D point. This is necessary to build // the input to gDLS* as it uses a generalized camera model. struct CameraFeatureCorrespondence2D3D { // The pinhole camera seeing 2D feature. The camera pose must be wrt to the // generalized camera coordinate system (or query coordinate system). PinholeCamera camera; // Observed keypoint or 2D feature. Eigen::Vector2d observation; // Corresponding 3D point. This point is described wrt to the world coordinate // system. Eigen::Vector3d point; EIGEN_MAKE_ALIGNED_OPERATOR_NEW; }; } // namespace msft #endif // GDLS_STAR_CAMERA_FEATURE_CORRESPONDENCE_2D_3D_H_
32.95122
80
0.775722
[ "model", "3d" ]
e6e1f931da7706e7392856da82125b1ddd0ad822
817
h
C
src/python/include/Off_reader_interface.h
jmarino/gudhi-devel
b1824e4de6fd1d037af3c1341c3065731472ffc8
[ "MIT" ]
146
2019-03-15T14:10:31.000Z
2022-03-23T21:14:52.000Z
src/python/include/Off_reader_interface.h
jmarino/gudhi-devel
b1824e4de6fd1d037af3c1341c3065731472ffc8
[ "MIT" ]
398
2019-03-07T14:55:22.000Z
2022-03-31T14:50:40.000Z
src/python/include/Off_reader_interface.h
jmarino/gudhi-devel
b1824e4de6fd1d037af3c1341c3065731472ffc8
[ "MIT" ]
51
2019-03-08T15:58:48.000Z
2022-03-14T10:23:23.000Z
/* This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT. * See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details. * Author(s): Vincent Rouvreau * * Copyright (C) 2016 Inria * * Modification(s): * - YYYY/MM Author: Description of the modification */ #ifndef INCLUDE_OFF_READER_INTERFACE_H_ #define INCLUDE_OFF_READER_INTERFACE_H_ #include <gudhi/Points_off_io.h> #include <iostream> #include <vector> #include <string> namespace Gudhi { std::vector<std::vector<double>> read_points_from_OFF_file(const std::string& off_file) { Gudhi::Points_off_reader<std::vector<double>> off_reader(off_file); return off_reader.get_point_cloud(); } } // namespace Gudhi #endif // INCLUDE_OFF_READER_INTERFACE_H_
26.354839
101
0.72705
[ "vector" ]
e6f411414554885ba281105276c9b09bba828845
723
c
C
lib/wizards/nalle/jerusalem/monsters/grkeeper.c
vlehtola/questmud
8bc3099b5ad00a9e0261faeb6637c76b521b6dbe
[ "MIT" ]
null
null
null
lib/wizards/nalle/jerusalem/monsters/grkeeper.c
vlehtola/questmud
8bc3099b5ad00a9e0261faeb6637c76b521b6dbe
[ "MIT" ]
null
null
null
lib/wizards/nalle/jerusalem/monsters/grkeeper.c
vlehtola/questmud
8bc3099b5ad00a9e0261faeb6637c76b521b6dbe
[ "MIT" ]
null
null
null
inherit "obj/monster"; reset(arg) { object weapon; ::reset(arg); if(arg) { return; } set_race("human"); set_gender(1); call_other(this_object(), "set_level", 21); call_other(this_object(), "set_name", "groundskeeper"); call_other(this_object(), "set_alias", "grounds keeper"); call_other(this_object(), "set_short", "The groundskeeper of the orphanage"); call_other(this_object(), "set_long", "A middle-aged man sitting on his chair idly.\n"); call_other(this_object(), "set_al", 0); call_other(this_object(), "set_aggressive", 0); weapon = clone_object("/wizards/nalle/jerusalem/eq/baton"); move_object(weapon, this_object()); init_command("wield baton"); }
31.434783
92
0.666667
[ "object" ]
e6fe351d1f03c1e0a2e38b9aacdabfaed11e132c
3,847
h
C
include/Renderer/Camera.h
rasidin/LimitEngineV2
9475e0dbf5f624ab50f6490d36068d558ecdaee6
[ "MIT" ]
null
null
null
include/Renderer/Camera.h
rasidin/LimitEngineV2
9475e0dbf5f624ab50f6490d36068d558ecdaee6
[ "MIT" ]
null
null
null
include/Renderer/Camera.h
rasidin/LimitEngineV2
9475e0dbf5f624ab50f6490d36068d558ecdaee6
[ "MIT" ]
null
null
null
/*********************************************************** LIMITEngine Header File Copyright (C), LIMITGAME, 2020 ----------------------------------------------------------- @file Camera.h @brief Camera Class @author minseob (https://github.com/rasidin) ***********************************************************/ #pragma once #include <LEIntVector2.h> #include <LEFloatVector3.h> #include <LEFloatMatrix4x4.h> #include "Core/ReferenceCountedObject.h" #include "Core/MetaData.h" #include "Renderer/Frustum.h" namespace LimitEngine { class Camera : public ReferenceCountedObject<LimitEngineMemoryCategory::Graphics>, public MetaData { static const float DefaultFOVRadians; public: Camera(); virtual ~Camera(); // Update by frame virtual void Update(); // Set position of camera virtual void SetPosition(const LEMath::FloatVector3 &p) { mPosition = p; } // Get camera position const LEMath::FloatVector3& GetPosition() const { return mPosition; } // Set direction of camera void SetDirection(const LEMath::FloatVector3 &d) { mDirection = d; } // Get camera direction const LEMath::FloatVector3& GetDirection() const { return mDirection; } // Set up vector of camera void SetUp(const LEMath::FloatVector3 &u) { mUp = u; } // Get camera up vector const LEMath::FloatVector3& GetUp() const { return mUp; } // Set aim target position of camera void SetAim(const LEMath::FloatVector3 &t); // Set screen size for screen frustum virtual void SetScreenSize(int width, int height) { mScreenSize = LEMath::IntSize(width, height); if (mFrustum) mFrustum->SetAspectRatio(float(height) / width); } virtual LEMath::IntSize GetScreenSize() const { return mScreenSize; } // Get aspect ratio of frustum float GetAspectRatio() { if(mFrustum) return mFrustum->GetAspectRatio(); return 1.0f; } // Set field of view (radians) virtual void SetFovRadians(float fov) { if(mFrustum) mFrustum->SetFOVRadians(fov); } // Get field of view (radians) virtual float GetFovRadians() const { if(mFrustum) return mFrustum->GetFOVRadians(); return DefaultFOVRadians; } // Get view matrix const LEMath::FloatMatrix4x4& GetViewMatrix() const { return mViewMatrix; } // Get projection matrix LEMath::FloatMatrix4x4 GetProjectionMatrix() { if(mFrustum) return mFrustum->GetProjectionMatrix(); return LEMath::FloatMatrix4x4::Identity; } LEMath::FloatVector4 GetUVtoViewParameter() const { if (mFrustum) return mFrustum->GetUVtoViewParameter(); return LEMath::FloatVector4::Zero; } LEMath::FloatVector4 GetPerspectiveProjectionParameters() const { if (mFrustum) return mFrustum->GetPerspectiveProjectionParameters(); return LEMath::FloatVector4::Zero; } // Get exposure (EV) virtual float GetExposure() const { return 1.0f; } private: // Setup metadata for editor void setupMetaData(); private: LEMath::FloatVector3 mDirection; // Direction of camera LEMath::FloatVector3 mUp; // Up vector of camera LEMath::IntSize mScreenSize; // Screen size protected: LEMath::FloatVector3 mPosition; // Position of camera Frustum *mFrustum; // Frustum for camera view LEMath::FloatMatrix4x4 mViewMatrix; // View matrix made by camera }; }
48.696203
179
0.582272
[ "vector" ]
fc0e540e91450586c95c9cab939c1ec7880e1caa
7,770
h
C
compile/mclinker/lib/Target/Mips/MipsGOT.h
Keneral/aframeworks
af1d0010bfb88751837fb1afc355705bd8a9ad8b
[ "Unlicense" ]
75
2015-03-18T06:01:37.000Z
2022-01-27T15:17:23.000Z
compile/mclinker/lib/Target/Mips/MipsGOT.h
Keneral/aframeworks
af1d0010bfb88751837fb1afc355705bd8a9ad8b
[ "Unlicense" ]
5
2015-07-08T07:47:25.000Z
2018-10-08T12:12:04.000Z
compile/mclinker/lib/Target/Mips/MipsGOT.h
Keneral/aframeworks
af1d0010bfb88751837fb1afc355705bd8a9ad8b
[ "Unlicense" ]
28
2015-04-14T16:05:13.000Z
2021-11-18T01:31:01.000Z
//===- MipsGOT.h ----------------------------------------------------------===// // // The MCLinker Project // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef TARGET_MIPS_MIPSGOT_H_ #define TARGET_MIPS_MIPSGOT_H_ #include "mcld/ADT/SizeTraits.h" #include "mcld/Fragment/Relocation.h" #include "mcld/Support/MemoryRegion.h" #include "mcld/Target/GOT.h" #include <llvm/ADT/DenseMap.h> #include <llvm/ADT/DenseSet.h> #include <map> #include <set> #include <vector> namespace mcld { class Input; class LDSection; class LDSymbol; class OutputRelocSection; /** \class MipsGOT * \brief Mips Global Offset Table. */ class MipsGOT : public GOT { public: explicit MipsGOT(LDSection& pSection); /// Assign value to the GOT entry. virtual void setEntryValue(Fragment* entry, uint64_t pValue) = 0; /// Emit the global offset table. virtual uint64_t emit(MemoryRegion& pRegion) = 0; /// Address of _gp_disp symbol. uint64_t getGPDispAddress() const; void initializeScan(const Input& pInput); void finalizeScan(const Input& pInput); bool reserveLocalEntry(ResolveInfo& pInfo, int reloc, Relocation::DWord pAddend); bool reserveGlobalEntry(ResolveInfo& pInfo); bool reserveTLSGdEntry(ResolveInfo& pInfo); bool reserveTLSGotEntry(ResolveInfo& pInfo); bool reserveTLSLdmEntry(); size_t getLocalNum() const; ///< number of local symbols in primary GOT size_t getGlobalNum() const; ///< total number of global symbols bool isPrimaryGOTConsumed(); Fragment* consumeLocal(); Fragment* consumeGlobal(); Fragment* consumeTLS(Relocation::Type pType); uint64_t getGPAddr(const Input& pInput) const; uint64_t getGPRelOffset(const Input& pInput, const Fragment& pEntry) const; void recordGlobalEntry(const ResolveInfo* pInfo, Fragment* pEntry); Fragment* lookupGlobalEntry(const ResolveInfo* pInfo); void recordTLSEntry(const ResolveInfo* pInfo, Fragment* pEntry, Relocation::Type pType); Fragment* lookupTLSEntry(const ResolveInfo* pInfo, Relocation::Type pType); void recordLocalEntry(const ResolveInfo* pInfo, Relocation::DWord pAddend, Fragment* pEntry); Fragment* lookupLocalEntry(const ResolveInfo* pInfo, Relocation::DWord pAddend); /// hasGOT1 - return if this got section has any GOT1 entry bool hasGOT1() const; bool hasMultipleGOT() const; /// Create GOT entries and reserve dynrel entries. void finalizeScanning(OutputRelocSection& pRelDyn); /// Compare two symbols to define order in the .dynsym. bool dynSymOrderCompare(const LDSymbol* pX, const LDSymbol* pY) const; protected: /// Create GOT entry. virtual Fragment* createEntry(uint64_t pValue, SectionData* pParent) = 0; /// Size of GOT entry. virtual size_t getEntrySize() const = 0; /// Reserve GOT header entries. virtual void reserveHeader() = 0; private: /** \class GOTMultipart * \brief GOTMultipart counts local and global entries in the GOT. */ struct GOTMultipart { explicit GOTMultipart(size_t local = 0, size_t global = 0); typedef llvm::DenseSet<const Input*> InputSetType; size_t m_LocalNum; ///< number of reserved local entries size_t m_GlobalNum; ///< number of reserved global entries size_t m_TLSNum; ///< number of reserved TLS entries size_t m_TLSDynNum; ///< number of reserved TLS related dynamic relocations size_t m_ConsumedLocal; ///< consumed local entries size_t m_ConsumedGlobal; ///< consumed global entries size_t m_ConsumedTLS; ///< consumed TLS entries Fragment* m_pLastLocal; ///< the last consumed local entry Fragment* m_pLastGlobal; ///< the last consumed global entry Fragment* m_pLastTLS; ///< the last consumed TLS entry InputSetType m_Inputs; bool isConsumed() const; void consumeLocal(); void consumeGlobal(); void consumeTLS(Relocation::Type pType); }; /** \class LocalEntry * \brief LocalEntry local GOT entry descriptor. */ struct LocalEntry { const ResolveInfo* m_pInfo; Relocation::DWord m_Addend; bool m_IsGot16; LocalEntry(const ResolveInfo* pInfo, Relocation::DWord addend, bool isGot16); bool operator<(const LocalEntry& O) const; }; typedef std::vector<GOTMultipart> MultipartListType; // Set of global symbols. typedef llvm::DenseSet<const ResolveInfo*> SymbolSetType; // Map of symbols. If value is true, the symbol is referenced // in the current input only. If value is false, the symbol // is referenced in the other modules merged to the current GOT. typedef llvm::DenseMap<const ResolveInfo*, bool> SymbolUniqueMapType; // Set of local symbols. typedef std::set<LocalEntry> LocalSymbolSetType; MultipartListType m_MultipartList; ///< list of GOT's descriptors const Input* m_pInput; ///< current input // Global symbols merged to the current GOT // except symbols from the current input. SymbolSetType m_MergedGlobalSymbols; // Global symbols from the current input. SymbolUniqueMapType m_InputGlobalSymbols; // Set of symbols referenced by TLS GD relocations. SymbolSetType m_InputTLSGdSymbols; // Set of symbols referenced by TLS GOTTPREL relocation. SymbolSetType m_InputTLSGotSymbols; // There is a symbol referenced by TLS LDM relocations. bool m_HasTLSLdmSymbol; // Local symbols merged to the current GOT // except symbols from the current input. LocalSymbolSetType m_MergedLocalSymbols; // Local symbols from the current input. LocalSymbolSetType m_InputLocalSymbols; size_t m_CurrentGOTPart; typedef llvm::DenseMap<const LDSymbol*, unsigned> SymbolOrderMapType; SymbolOrderMapType m_SymbolOrderMap; void initGOTList(); void changeInput(); bool isGOTFull() const; void split(); void reserve(size_t pNum); private: struct GotEntryKey { size_t m_GOTPage; const ResolveInfo* m_pInfo; Relocation::DWord m_Addend; bool operator<(const GotEntryKey& key) const { if (m_GOTPage != key.m_GOTPage) return m_GOTPage < key.m_GOTPage; if (m_pInfo != key.m_pInfo) return m_pInfo < key.m_pInfo; return m_Addend < key.m_Addend; } }; typedef std::map<GotEntryKey, Fragment*> GotEntryMapType; GotEntryMapType m_GotLocalEntriesMap; GotEntryMapType m_GotGlobalEntriesMap; GotEntryMapType m_GotTLSGdEntriesMap; GotEntryMapType m_GotTLSGotEntriesMap; Fragment* m_GotTLSLdmEntry; }; /** \class Mips32GOT * \brief Mips 32-bit Global Offset Table. */ class Mips32GOT : public MipsGOT { public: explicit Mips32GOT(LDSection& pSection); private: typedef GOT::Entry<4> Mips32GOTEntry; // MipsGOT virtual void setEntryValue(Fragment* entry, uint64_t pValue); virtual uint64_t emit(MemoryRegion& pRegion); virtual Fragment* createEntry(uint64_t pValue, SectionData* pParent); virtual size_t getEntrySize() const; virtual void reserveHeader(); }; /** \class Mips64GOT * \brief Mips 64-bit Global Offset Table. */ class Mips64GOT : public MipsGOT { public: explicit Mips64GOT(LDSection& pSection); private: typedef GOT::Entry<8> Mips64GOTEntry; // MipsGOT virtual void setEntryValue(Fragment* entry, uint64_t pValue); virtual uint64_t emit(MemoryRegion& pRegion); virtual Fragment* createEntry(uint64_t pValue, SectionData* pParent); virtual size_t getEntrySize() const; virtual void reserveHeader(); }; } // namespace mcld #endif // TARGET_MIPS_MIPSGOT_H_
30.233463
80
0.703732
[ "vector" ]
fc16adcc57132bf5eddac2578ca54d526e66ea7b
93,928
h
C
mobile/ios/dependencies/packages/sofia-sip-1.12.11/include/sofia-sip-1.12/sofia-sip/sip_extra.h
ctdao/dektalk
2c9c7b4994b1b992d48223a5936d2566b6dd424f
[ "Apache-2.0" ]
1
2016-09-21T14:18:50.000Z
2016-09-21T14:18:50.000Z
mobile/ios/dependencies/packages/sofia-sip-1.12.11/include/sofia-sip-1.12/sofia-sip/sip_extra.h
ctdao/dektalk
2c9c7b4994b1b992d48223a5936d2566b6dd424f
[ "Apache-2.0" ]
19
2016-09-09T01:50:59.000Z
2017-01-27T10:11:20.000Z
mobile/ios/dependencies/packages/sofia-sip-1.12.11/include/sofia-sip-1.12/sofia-sip/sip_extra.h
deklab/dektalk
2c9c7b4994b1b992d48223a5936d2566b6dd424f
[ "Apache-2.0" ]
4
2016-08-18T04:12:07.000Z
2021-02-20T06:31:23.000Z
/* -*- C -*- * * This file is part of the Sofia-SIP package * * Copyright (C) 2006 Nokia Corporation. * * Contact: Pekka Pessi <pekka.pessi@nokia.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * */ #ifndef SIP_EXTRA_H /** Defined when <sofia-sip/sip_extra.h> has been included. */ #define SIP_EXTRA_H /**@file sofia-sip/sip_extra.h * * @brief Extension headers for SIP. * * This file is automatically generated from <sip_extra_headers.txt> by msg_parser.awk. * * @author Pekka Pessi <Pekka.Pessi@nokia.com>. */ #ifndef SIP_H #include <sofia-sip/sip.h> #endif #ifndef SIP_HEADER_H #include <sofia-sip/sip_header.h> #endif SOFIA_BEGIN_DECLS typedef struct sip_refer_sub_s sip_refer_sub_t; /**@ingroup sip_refer_sub * @brief Structure for @ReferSub header. */ struct sip_refer_sub_s { sip_common_t rs_common[1]; /**< Common fragment info */ sip_error_t *rs_next; /**< Dummy link to next */ char const *rs_value; /**< "true" or "false" */ msg_param_t const *rs_params; /**< List of extension parameters */ }; typedef struct sip_alert_info_s sip_alert_info_t; /**@ingroup sip_alert_info * @brief Structure for @AlertInfo header. */ struct sip_alert_info_s { sip_common_t ai_common[1]; /**< Common fragment info */ sip_alert_info_t *ai_next; /**< Link to next @AlertInfo */ url_t ai_url[1]; /**< URI to alert info */ msg_param_t const *ai_params; /**< List of optional parameters */ }; typedef struct sip_reply_to_s sip_reply_to_t; /**@ingroup sip_reply_to * @brief Structure for @ReplyTo header. */ struct sip_reply_to_s { sip_common_t rplyto_common[1]; /**< Common fragment info */ sip_error_t *rplyto_next; /**< Dummy link to next header */ char const *rplyto_display; /**< Display name */ url_t rplyto_url[1]; /**< Return URI */ msg_param_t const *rplyto_params; /**< List of optional parameters */ }; typedef struct sip_suppress_body_if_match_s sip_suppress_body_if_match_t; /**@ingroup sip_suppress_body_if_match * @brief Structure for @SuppressBodyIfMatch header. */ struct sip_suppress_body_if_match_s { sip_common_t sbim_common[1]; /**< Common fragment info */ sip_error_t *sbim_next; /**< Dummy link to next header */ char const *sbim_tag; /**< Entity-tag */ }; typedef struct sip_suppress_notify_if_match_s sip_suppress_notify_if_match_t; /**@ingroup sip_suppress_notify_if_match * @brief Structure for @SuppressNotifyIfMatch header. */ struct sip_suppress_notify_if_match_s { sip_common_t snim_common[1]; /**< Common fragment info */ sip_error_t *snim_next; /**< Dummy link to next header */ char const *snim_tag; /**< Entity-tag */ }; typedef struct sip_p_asserted_identity_s sip_p_asserted_identity_t; /**@ingroup sip_p_asserted_identity * @brief Structure for @PAssertedIdentity header. */ struct sip_p_asserted_identity_s { sip_common_t paid_common[1];/**< Common fragment info */ sip_p_asserted_identity_t *paid_next; /**< Link to next identity */ char const *paid_display; /**< Display name */ url_t paid_url[1]; /**< SIP, SIPS or TEL URL */ }; typedef struct sip_p_preferred_identity_s sip_p_preferred_identity_t; /**@ingroup sip_p_preferred_identity * @brief Structure for @PPreferredIdentity header. */ struct sip_p_preferred_identity_s { sip_common_t ppid_common[1];/**< Common fragment info */ sip_p_preferred_identity_t *ppid_next; /**< Link to next identity */ char const *ppid_display; /**< Display name */ url_t ppid_url[1]; /**< SIP, SIPS or TEL URL */ }; int sip_p_initialize_remote_party_id_headers(msg_mclass_t *mclass); typedef struct sip_remote_party_id_s sip_remote_party_id_t; /**@ingroup sip_remote_party_id * @brief Structure for @RemotePartyID header. */ struct sip_remote_party_id_s { sip_common_t rpid_common[1];/**< Common fragment info */ sip_remote_party_id_t *rpid_next; /**< Link to next identity */ char const *rpid_display; /**< Display name */ url_t rpid_url[1]; /**< URL */ sip_param_t const *rpid_params; /**< Parameters */ /** Shortcuts to screen, party, id-type and privacy parameters */ char const *rpid_screen, *rpid_party, *rpid_id_type, *rpid_privacy; }; /** Defined as 1 if the @ref sip_refer_sub "Refer-Sub header" is supported */ #define SIP_HAVE_REFER_SUB 1 enum { /**@ingroup sip_refer_sub @internal * * Hash of @ref sip_refer_sub "Refer-Sub header". * * @since New in @NEW_1_12_5. */ sip_refer_sub_hash = 14607 }; /**Header class for @ref sip_refer_sub "Refer-Sub header". * * The header class sip_refer_sub_class defines how a SIP * @ref sip_refer_sub "Refer-Sub header" is parsed and printed. * It also contains methods used by SIP parser and other functions to * manipulate the #sip_refer_sub_t header structure. * * @ingroup sip_refer_sub * * @since New in @NEW_1_12_5. */ SIP_DLL extern msg_hclass_t sip_refer_sub_class[]; /**@addtogroup sip_refer_sub * @{ */ /** Parse a SIP @ref sip_refer_sub "Refer-Sub header". @internal */ SOFIAPUBFUN issize_t sip_refer_sub_d(su_home_t *, msg_header_t *, char *s, isize_t slen); /** Print a SIP @ref sip_refer_sub "Refer-Sub header". @internal */ SOFIAPUBFUN issize_t sip_refer_sub_e(char b[], isize_t bsiz, msg_header_t const *h, int flags); /**Access a SIP @ref sip_refer_sub "Refer-Sub header" * structure #sip_refer_sub_t from #sip_t. * * @since New in @NEW_1_12_5. */ #define sip_refer_sub(sip) \ ((sip_refer_sub_t *)msg_header_access((msg_pub_t*)(sip), sip_refer_sub_class)) /**Initializer for structure #sip_refer_sub_t. * * A static #sip_refer_sub_t structure for * @ref sip_refer_sub "Refer-Sub header" must be initialized with * the SIP_REFER_SUB_INIT() macro. * For instance, * @code * * sip_refer_sub_t sip_refer_sub = SIP_REFER_SUB_INIT; * * @endcode * @HI * * @since New in @NEW_1_12_5. */ #define SIP_REFER_SUB_INIT() SIP_HDR_INIT(refer_sub) /**Initialize a structure #sip_refer_sub_t. * * An #sip_refer_sub_t structure for * @ref sip_refer_sub "Refer-Sub header" can be initialized with the * sip_refer_sub_init() function/macro. For instance, * @code * * sip_refer_sub_t sip_refer_sub; * * sip_refer_sub_init(&sip_refer_sub); * * @endcode * @HI * * @since New in @NEW_1_12_5. */ #if SU_HAVE_INLINE su_inline sip_refer_sub_t *sip_refer_sub_init(sip_refer_sub_t x[1]) { return SIP_HEADER_INIT(x, sip_refer_sub_class, sizeof(sip_refer_sub_t)); } #else #define sip_refer_sub_init(x) \ SIP_HEADER_INIT(x, sip_refer_sub_class, sizeof(sip_refer_sub_t)) #endif /**Test if header object is instance of #sip_refer_sub_t. * * Check if the header class is an instance of * @ref sip_refer_sub "Refer-Sub header" object and return true (nonzero), * otherwise return false (zero). * * @param header pointer to the header structure to be tested * * @retval 1 (true) if the @a header is an instance of header refer_sub * @retval 0 (false) otherwise * * @since New in @NEW_1_12_5. */ #if SU_HAVE_INLINE su_inline int sip_is_refer_sub(sip_header_t const *header) { return header && header->sh_class->hc_hash == sip_refer_sub_hash; } #else int sip_is_refer_sub(sip_header_t const *header); #endif #define sip_refer_sub_p(h) sip_is_refer_sub((h)) /**Duplicate a list of @ref sip_refer_sub "Refer-Sub header" header structures #sip_refer_sub_t. * * Duplicate a header * structure @a hdr. If the header structure @a hdr * contains a reference (@c hdr->x_next) to a list of * headers, all the headers in the list are duplicated, too. * * @param home memory home used to allocate new structure * @param hdr header structure to be duplicated * * When duplicating, all parameter lists and non-constant * strings attached to the header are copied, too. The * function uses given memory @a home to allocate all the * memory areas used to copy the header. * * @par Example * @code * * refer_sub = sip_refer_sub_dup(home, sip->sip_refer_sub); * * @endcode * * @return * A pointer to the * newly duplicated #sip_refer_sub_t header structure, or NULL * upon an error. * * @since New in @NEW_1_12_5. */ #if SU_HAVE_INLINE su_inline #endif sip_refer_sub_t *sip_refer_sub_dup(su_home_t *home, sip_refer_sub_t const *hdr) __attribute__((__malloc__)); #if SU_HAVE_INLINE su_inline sip_refer_sub_t *sip_refer_sub_dup(su_home_t *home, sip_refer_sub_t const *hdr) { return (sip_refer_sub_t *) msg_header_dup_as(home, sip_refer_sub_class, (msg_header_t const *)hdr); } #endif /**Copy a list of @ref sip_refer_sub "Refer-Sub header" header structures #sip_refer_sub_t. * * The function sip_refer_sub_copy() copies a header structure @a * hdr. If the header structure @a hdr contains a reference (@c * hdr->h_next) to a list of headers, all the headers in that * list are copied, too. The function uses given memory @a home * to allocate all the memory areas used to copy the list of header * structure @a hdr. * * @param home memory home used to allocate new structure * @param hdr pointer to the header structure to be copied * * When copying, only the header structure and parameter lists attached to * it are duplicated. The new header structure retains all the references to * the strings within the old @a hdr header, including the encoding of the * old header, if present. * * @par Example * @code * * refer_sub = sip_refer_sub_copy(home, sip->sip_refer_sub); * * @endcode * * @return * A pointer to newly copied header structure, or NULL upon an error. * * @since New in @NEW_1_12_5. */ #if SU_HAVE_INLINE su_inline #endif sip_refer_sub_t *sip_refer_sub_copy(su_home_t *home, sip_refer_sub_t const *hdr) __attribute__((__malloc__)); #if SU_HAVE_INLINE su_inline sip_refer_sub_t *sip_refer_sub_copy(su_home_t *home, sip_refer_sub_t const *hdr) { return (sip_refer_sub_t *) msg_header_copy_as(home, sip_refer_sub_class, (msg_header_t const *)hdr); } #endif /**Make a @ref sip_refer_sub "Refer-Sub header" structure #sip_refer_sub_t. * * The function sip_refer_sub_make() makes a new * #sip_refer_sub_t header structure. It allocates a new * header structure, and decodes the string @a s as the * value of the structure. * * @param home memory home used to allocate new header structure. * @param s string to be decoded as value of the new header structure * * @return * A pointer to newly maked #sip_refer_sub_t header structure, or NULL upon an * error. * * @since New in @NEW_1_12_5. */ #if SU_HAVE_INLINE su_inline #endif sip_refer_sub_t *sip_refer_sub_make(su_home_t *home, char const *s) __attribute__((__malloc__)); #if SU_HAVE_INLINE su_inline sip_refer_sub_t *sip_refer_sub_make(su_home_t *home, char const *s) { return (sip_refer_sub_t *)sip_header_make(home, sip_refer_sub_class, s); } #endif /**Make a @ref sip_refer_sub "Refer-Sub header" from formatting result. * * Make a new #sip_refer_sub_t object using formatting result as its value. * The function first prints the arguments according to the format @a fmt * specified. Then it allocates a new header structure, and parses the * formatting result to the structure #sip_refer_sub_t. * * @param home memory home used to allocate new header structure. * @param fmt string used as a printf()-style format * @param ... argument list for format * * @return * A pointer to newly * makes header structure, or NULL upon an error. * * @HIDE * * @since New in @NEW_1_12_5. */ #if SU_HAVE_INLINE su_inline #endif sip_refer_sub_t *sip_refer_sub_format(su_home_t *home, char const *fmt, ...) __attribute__((__malloc__, __format__ (printf, 2, 3))); #if SU_HAVE_INLINE su_inline sip_refer_sub_t *sip_refer_sub_format(su_home_t *home, char const *fmt, ...) { sip_header_t *h; va_list ap; va_start(ap, fmt); h = sip_header_vformat(home, sip_refer_sub_class, fmt, ap); va_end(ap); return (sip_refer_sub_t *)h; } #endif /** @} */ /**@ingroup sip_refer_sub * * Tag list item for pointer to a @ref sip_refer_sub "Refer-Sub header" * structure #sip_refer_sub_t. * * The SIPTAG_REFER_SUB() macro is used to include a tag item with a * pointer to a #sip_refer_sub_t structure in a tag list. * * @param x pointer to a #sip_refer_sub_t structure, or NULL. * * The corresponding tag taking reference parameter is * SIPTAG_REFER_SUB_REF(). * * @since New in @NEW_1_12_5. * * @HIDE */ #define SIPTAG_REFER_SUB(x) siptag_refer_sub, siptag_refer_sub_v(x) SOFIAPUBVAR tag_typedef_t siptag_refer_sub; /**@ingroup sip_refer_sub * Tag list item for reference to a * @ref sip_refer_sub "Refer-Sub header" pointer. */ #define SIPTAG_REFER_SUB_REF(x) siptag_refer_sub_ref, siptag_refer_sub_vr(&(x)) SOFIAPUBVAR tag_typedef_t siptag_refer_sub_ref; /**@ingroup sip_refer_sub * * Tag list item for string with @ref sip_refer_sub "Refer-Sub header" value. * * The SIPTAG_REFER_SUB_STR() macro is used to include a tag item with a * string containing value of a #sip_refer_sub_t header in a tag list. * * @param s pointer to a string containing * @ref sip_refer_sub "Refer-Sub header" value, or NULL. * * The string in SIPTAG_REFER_SUB_STR() can be converted to a * #sip_refer_sub_t header structure by giving the string @a s has * second argument to function sip_refer_sub_make(). * * The corresponding tag taking reference parameter is * SIPTAG_REFER_SUB_STR_REF(). * * @since New in @NEW_1_12_5. * * @HIDE */ #define SIPTAG_REFER_SUB_STR(s) siptag_refer_sub_str, tag_str_v(s) SOFIAPUBVAR tag_typedef_t siptag_refer_sub_str; /**@ingroup sip_refer_sub * Tag list item for reference to a * @ref sip_refer_sub "Refer-Sub header" string. */ #define SIPTAG_REFER_SUB_STR_REF(x) siptag_refer_sub_str_ref, tag_str_vr(&(x)) SOFIAPUBVAR tag_typedef_t siptag_refer_sub_str_ref; #if SU_INLINE_TAG_CAST su_inline tag_value_t siptag_refer_sub_v(sip_refer_sub_t const *v) { return (tag_value_t)v; } su_inline tag_value_t siptag_refer_sub_vr(sip_refer_sub_t const **vp) { return (tag_value_t)vp; } #else #define siptag_refer_sub_v(v) (tag_value_t)(v) #define siptag_refer_sub_vr(vp) (tag_value_t)(vp) #endif /** Defined as 1 if the @ref sip_alert_info "Alert-Info header" is supported */ #define SIP_HAVE_ALERT_INFO 1 enum { /**@ingroup sip_alert_info @internal * * Hash of @ref sip_alert_info "Alert-Info header". * * @since New in @NEW_1_12_7. */ sip_alert_info_hash = 53913 }; /**Header class for @ref sip_alert_info "Alert-Info header". * * The header class sip_alert_info_class defines how a SIP * @ref sip_alert_info "Alert-Info header" is parsed and printed. * It also contains methods used by SIP parser and other functions to * manipulate the #sip_alert_info_t header structure. * * @ingroup sip_alert_info * * @since New in @NEW_1_12_7. */ SIP_DLL extern msg_hclass_t sip_alert_info_class[]; /**@addtogroup sip_alert_info * @{ */ /** Parse a SIP @ref sip_alert_info "Alert-Info header". @internal */ SOFIAPUBFUN issize_t sip_alert_info_d(su_home_t *, msg_header_t *, char *s, isize_t slen); /** Print a SIP @ref sip_alert_info "Alert-Info header". @internal */ SOFIAPUBFUN issize_t sip_alert_info_e(char b[], isize_t bsiz, msg_header_t const *h, int flags); /**Access a SIP @ref sip_alert_info "Alert-Info header" * structure #sip_alert_info_t from #sip_t. * * @since New in @NEW_1_12_7. */ #define sip_alert_info(sip) \ ((sip_alert_info_t *)msg_header_access((msg_pub_t*)(sip), sip_alert_info_class)) /**Initializer for structure #sip_alert_info_t. * * A static #sip_alert_info_t structure for * @ref sip_alert_info "Alert-Info header" must be initialized with * the SIP_ALERT_INFO_INIT() macro. * For instance, * @code * * sip_alert_info_t sip_alert_info = SIP_ALERT_INFO_INIT; * * @endcode * @HI * * @since New in @NEW_1_12_7. */ #define SIP_ALERT_INFO_INIT() SIP_HDR_INIT(alert_info) /**Initialize a structure #sip_alert_info_t. * * An #sip_alert_info_t structure for * @ref sip_alert_info "Alert-Info header" can be initialized with the * sip_alert_info_init() function/macro. For instance, * @code * * sip_alert_info_t sip_alert_info; * * sip_alert_info_init(&sip_alert_info); * * @endcode * @HI * * @since New in @NEW_1_12_7. */ #if SU_HAVE_INLINE su_inline sip_alert_info_t *sip_alert_info_init(sip_alert_info_t x[1]) { return SIP_HEADER_INIT(x, sip_alert_info_class, sizeof(sip_alert_info_t)); } #else #define sip_alert_info_init(x) \ SIP_HEADER_INIT(x, sip_alert_info_class, sizeof(sip_alert_info_t)) #endif /**Test if header object is instance of #sip_alert_info_t. * * Check if the header class is an instance of * @ref sip_alert_info "Alert-Info header" object and return true (nonzero), * otherwise return false (zero). * * @param header pointer to the header structure to be tested * * @retval 1 (true) if the @a header is an instance of header alert_info * @retval 0 (false) otherwise * * @since New in @NEW_1_12_7. */ #if SU_HAVE_INLINE su_inline int sip_is_alert_info(sip_header_t const *header) { return header && header->sh_class->hc_hash == sip_alert_info_hash; } #else int sip_is_alert_info(sip_header_t const *header); #endif #define sip_alert_info_p(h) sip_is_alert_info((h)) /**Duplicate a list of @ref sip_alert_info "Alert-Info header" header structures #sip_alert_info_t. * * Duplicate a header * structure @a hdr. If the header structure @a hdr * contains a reference (@c hdr->x_next) to a list of * headers, all the headers in the list are duplicated, too. * * @param home memory home used to allocate new structure * @param hdr header structure to be duplicated * * When duplicating, all parameter lists and non-constant * strings attached to the header are copied, too. The * function uses given memory @a home to allocate all the * memory areas used to copy the header. * * @par Example * @code * * alert_info = sip_alert_info_dup(home, sip->sip_alert_info); * * @endcode * * @return * A pointer to the * newly duplicated #sip_alert_info_t header structure, or NULL * upon an error. * * @since New in @NEW_1_12_7. */ #if SU_HAVE_INLINE su_inline #endif sip_alert_info_t *sip_alert_info_dup(su_home_t *home, sip_alert_info_t const *hdr) __attribute__((__malloc__)); #if SU_HAVE_INLINE su_inline sip_alert_info_t *sip_alert_info_dup(su_home_t *home, sip_alert_info_t const *hdr) { return (sip_alert_info_t *) msg_header_dup_as(home, sip_alert_info_class, (msg_header_t const *)hdr); } #endif /**Copy a list of @ref sip_alert_info "Alert-Info header" header structures #sip_alert_info_t. * * The function sip_alert_info_copy() copies a header structure @a * hdr. If the header structure @a hdr contains a reference (@c * hdr->h_next) to a list of headers, all the headers in that * list are copied, too. The function uses given memory @a home * to allocate all the memory areas used to copy the list of header * structure @a hdr. * * @param home memory home used to allocate new structure * @param hdr pointer to the header structure to be copied * * When copying, only the header structure and parameter lists attached to * it are duplicated. The new header structure retains all the references to * the strings within the old @a hdr header, including the encoding of the * old header, if present. * * @par Example * @code * * alert_info = sip_alert_info_copy(home, sip->sip_alert_info); * * @endcode * * @return * A pointer to newly copied header structure, or NULL upon an error. * * @since New in @NEW_1_12_7. */ #if SU_HAVE_INLINE su_inline #endif sip_alert_info_t *sip_alert_info_copy(su_home_t *home, sip_alert_info_t const *hdr) __attribute__((__malloc__)); #if SU_HAVE_INLINE su_inline sip_alert_info_t *sip_alert_info_copy(su_home_t *home, sip_alert_info_t const *hdr) { return (sip_alert_info_t *) msg_header_copy_as(home, sip_alert_info_class, (msg_header_t const *)hdr); } #endif /**Make a @ref sip_alert_info "Alert-Info header" structure #sip_alert_info_t. * * The function sip_alert_info_make() makes a new * #sip_alert_info_t header structure. It allocates a new * header structure, and decodes the string @a s as the * value of the structure. * * @param home memory home used to allocate new header structure. * @param s string to be decoded as value of the new header structure * * @return * A pointer to newly maked #sip_alert_info_t header structure, or NULL upon an * error. * * @since New in @NEW_1_12_7. */ #if SU_HAVE_INLINE su_inline #endif sip_alert_info_t *sip_alert_info_make(su_home_t *home, char const *s) __attribute__((__malloc__)); #if SU_HAVE_INLINE su_inline sip_alert_info_t *sip_alert_info_make(su_home_t *home, char const *s) { return (sip_alert_info_t *)sip_header_make(home, sip_alert_info_class, s); } #endif /**Make a @ref sip_alert_info "Alert-Info header" from formatting result. * * Make a new #sip_alert_info_t object using formatting result as its value. * The function first prints the arguments according to the format @a fmt * specified. Then it allocates a new header structure, and parses the * formatting result to the structure #sip_alert_info_t. * * @param home memory home used to allocate new header structure. * @param fmt string used as a printf()-style format * @param ... argument list for format * * @return * A pointer to newly * makes header structure, or NULL upon an error. * * @HIDE * * @since New in @NEW_1_12_7. */ #if SU_HAVE_INLINE su_inline #endif sip_alert_info_t *sip_alert_info_format(su_home_t *home, char const *fmt, ...) __attribute__((__malloc__, __format__ (printf, 2, 3))); #if SU_HAVE_INLINE su_inline sip_alert_info_t *sip_alert_info_format(su_home_t *home, char const *fmt, ...) { sip_header_t *h; va_list ap; va_start(ap, fmt); h = sip_header_vformat(home, sip_alert_info_class, fmt, ap); va_end(ap); return (sip_alert_info_t *)h; } #endif /** @} */ /**@ingroup sip_alert_info * * Tag list item for pointer to a @ref sip_alert_info "Alert-Info header" * structure #sip_alert_info_t. * * The SIPTAG_ALERT_INFO() macro is used to include a tag item with a * pointer to a #sip_alert_info_t structure in a tag list. * * @param x pointer to a #sip_alert_info_t structure, or NULL. * * The corresponding tag taking reference parameter is * SIPTAG_ALERT_INFO_REF(). * * @since New in @NEW_1_12_7. * * @HIDE */ #define SIPTAG_ALERT_INFO(x) siptag_alert_info, siptag_alert_info_v(x) SOFIAPUBVAR tag_typedef_t siptag_alert_info; /**@ingroup sip_alert_info * Tag list item for reference to a * @ref sip_alert_info "Alert-Info header" pointer. */ #define SIPTAG_ALERT_INFO_REF(x) siptag_alert_info_ref, siptag_alert_info_vr(&(x)) SOFIAPUBVAR tag_typedef_t siptag_alert_info_ref; /**@ingroup sip_alert_info * * Tag list item for string with @ref sip_alert_info "Alert-Info header" value. * * The SIPTAG_ALERT_INFO_STR() macro is used to include a tag item with a * string containing value of a #sip_alert_info_t header in a tag list. * * @param s pointer to a string containing * @ref sip_alert_info "Alert-Info header" value, or NULL. * * The string in SIPTAG_ALERT_INFO_STR() can be converted to a * #sip_alert_info_t header structure by giving the string @a s has * second argument to function sip_alert_info_make(). * * The corresponding tag taking reference parameter is * SIPTAG_ALERT_INFO_STR_REF(). * * @since New in @NEW_1_12_7. * * @HIDE */ #define SIPTAG_ALERT_INFO_STR(s) siptag_alert_info_str, tag_str_v(s) SOFIAPUBVAR tag_typedef_t siptag_alert_info_str; /**@ingroup sip_alert_info * Tag list item for reference to a * @ref sip_alert_info "Alert-Info header" string. */ #define SIPTAG_ALERT_INFO_STR_REF(x) siptag_alert_info_str_ref, tag_str_vr(&(x)) SOFIAPUBVAR tag_typedef_t siptag_alert_info_str_ref; #if SU_INLINE_TAG_CAST su_inline tag_value_t siptag_alert_info_v(sip_alert_info_t const *v) { return (tag_value_t)v; } su_inline tag_value_t siptag_alert_info_vr(sip_alert_info_t const **vp) { return (tag_value_t)vp; } #else #define siptag_alert_info_v(v) (tag_value_t)(v) #define siptag_alert_info_vr(vp) (tag_value_t)(vp) #endif /** Defined as 1 if the @ref sip_reply_to "Reply-To header" is supported */ #define SIP_HAVE_REPLY_TO 1 enum { /**@ingroup sip_reply_to @internal * * Hash of @ref sip_reply_to "Reply-To header". * * @since New in @NEW_1_12_7. */ sip_reply_to_hash = 38016 }; /**Header class for @ref sip_reply_to "Reply-To header". * * The header class sip_reply_to_class defines how a SIP * @ref sip_reply_to "Reply-To header" is parsed and printed. * It also contains methods used by SIP parser and other functions to * manipulate the #sip_reply_to_t header structure. * * @ingroup sip_reply_to * * @since New in @NEW_1_12_7. */ SIP_DLL extern msg_hclass_t sip_reply_to_class[]; /**@addtogroup sip_reply_to * @{ */ /** Parse a SIP @ref sip_reply_to "Reply-To header". @internal */ SOFIAPUBFUN issize_t sip_reply_to_d(su_home_t *, msg_header_t *, char *s, isize_t slen); /** Print a SIP @ref sip_reply_to "Reply-To header". @internal */ SOFIAPUBFUN issize_t sip_reply_to_e(char b[], isize_t bsiz, msg_header_t const *h, int flags); /**Access a SIP @ref sip_reply_to "Reply-To header" * structure #sip_reply_to_t from #sip_t. * * @since New in @NEW_1_12_7. */ #define sip_reply_to(sip) \ ((sip_reply_to_t *)msg_header_access((msg_pub_t*)(sip), sip_reply_to_class)) /**Initializer for structure #sip_reply_to_t. * * A static #sip_reply_to_t structure for * @ref sip_reply_to "Reply-To header" must be initialized with * the SIP_REPLY_TO_INIT() macro. * For instance, * @code * * sip_reply_to_t sip_reply_to = SIP_REPLY_TO_INIT; * * @endcode * @HI * * @since New in @NEW_1_12_7. */ #define SIP_REPLY_TO_INIT() SIP_HDR_INIT(reply_to) /**Initialize a structure #sip_reply_to_t. * * An #sip_reply_to_t structure for * @ref sip_reply_to "Reply-To header" can be initialized with the * sip_reply_to_init() function/macro. For instance, * @code * * sip_reply_to_t sip_reply_to; * * sip_reply_to_init(&sip_reply_to); * * @endcode * @HI * * @since New in @NEW_1_12_7. */ #if SU_HAVE_INLINE su_inline sip_reply_to_t *sip_reply_to_init(sip_reply_to_t x[1]) { return SIP_HEADER_INIT(x, sip_reply_to_class, sizeof(sip_reply_to_t)); } #else #define sip_reply_to_init(x) \ SIP_HEADER_INIT(x, sip_reply_to_class, sizeof(sip_reply_to_t)) #endif /**Test if header object is instance of #sip_reply_to_t. * * Check if the header class is an instance of * @ref sip_reply_to "Reply-To header" object and return true (nonzero), * otherwise return false (zero). * * @param header pointer to the header structure to be tested * * @retval 1 (true) if the @a header is an instance of header reply_to * @retval 0 (false) otherwise * * @since New in @NEW_1_12_7. */ #if SU_HAVE_INLINE su_inline int sip_is_reply_to(sip_header_t const *header) { return header && header->sh_class->hc_hash == sip_reply_to_hash; } #else int sip_is_reply_to(sip_header_t const *header); #endif #define sip_reply_to_p(h) sip_is_reply_to((h)) /**Duplicate a list of @ref sip_reply_to "Reply-To header" header structures #sip_reply_to_t. * * Duplicate a header * structure @a hdr. If the header structure @a hdr * contains a reference (@c hdr->x_next) to a list of * headers, all the headers in the list are duplicated, too. * * @param home memory home used to allocate new structure * @param hdr header structure to be duplicated * * When duplicating, all parameter lists and non-constant * strings attached to the header are copied, too. The * function uses given memory @a home to allocate all the * memory areas used to copy the header. * * @par Example * @code * * reply_to = sip_reply_to_dup(home, sip->sip_reply_to); * * @endcode * * @return * A pointer to the * newly duplicated #sip_reply_to_t header structure, or NULL * upon an error. * * @since New in @NEW_1_12_7. */ #if SU_HAVE_INLINE su_inline #endif sip_reply_to_t *sip_reply_to_dup(su_home_t *home, sip_reply_to_t const *hdr) __attribute__((__malloc__)); #if SU_HAVE_INLINE su_inline sip_reply_to_t *sip_reply_to_dup(su_home_t *home, sip_reply_to_t const *hdr) { return (sip_reply_to_t *) msg_header_dup_as(home, sip_reply_to_class, (msg_header_t const *)hdr); } #endif /**Copy a list of @ref sip_reply_to "Reply-To header" header structures #sip_reply_to_t. * * The function sip_reply_to_copy() copies a header structure @a * hdr. If the header structure @a hdr contains a reference (@c * hdr->h_next) to a list of headers, all the headers in that * list are copied, too. The function uses given memory @a home * to allocate all the memory areas used to copy the list of header * structure @a hdr. * * @param home memory home used to allocate new structure * @param hdr pointer to the header structure to be copied * * When copying, only the header structure and parameter lists attached to * it are duplicated. The new header structure retains all the references to * the strings within the old @a hdr header, including the encoding of the * old header, if present. * * @par Example * @code * * reply_to = sip_reply_to_copy(home, sip->sip_reply_to); * * @endcode * * @return * A pointer to newly copied header structure, or NULL upon an error. * * @since New in @NEW_1_12_7. */ #if SU_HAVE_INLINE su_inline #endif sip_reply_to_t *sip_reply_to_copy(su_home_t *home, sip_reply_to_t const *hdr) __attribute__((__malloc__)); #if SU_HAVE_INLINE su_inline sip_reply_to_t *sip_reply_to_copy(su_home_t *home, sip_reply_to_t const *hdr) { return (sip_reply_to_t *) msg_header_copy_as(home, sip_reply_to_class, (msg_header_t const *)hdr); } #endif /**Make a @ref sip_reply_to "Reply-To header" structure #sip_reply_to_t. * * The function sip_reply_to_make() makes a new * #sip_reply_to_t header structure. It allocates a new * header structure, and decodes the string @a s as the * value of the structure. * * @param home memory home used to allocate new header structure. * @param s string to be decoded as value of the new header structure * * @return * A pointer to newly maked #sip_reply_to_t header structure, or NULL upon an * error. * * @since New in @NEW_1_12_7. */ #if SU_HAVE_INLINE su_inline #endif sip_reply_to_t *sip_reply_to_make(su_home_t *home, char const *s) __attribute__((__malloc__)); #if SU_HAVE_INLINE su_inline sip_reply_to_t *sip_reply_to_make(su_home_t *home, char const *s) { return (sip_reply_to_t *)sip_header_make(home, sip_reply_to_class, s); } #endif /**Make a @ref sip_reply_to "Reply-To header" from formatting result. * * Make a new #sip_reply_to_t object using formatting result as its value. * The function first prints the arguments according to the format @a fmt * specified. Then it allocates a new header structure, and parses the * formatting result to the structure #sip_reply_to_t. * * @param home memory home used to allocate new header structure. * @param fmt string used as a printf()-style format * @param ... argument list for format * * @return * A pointer to newly * makes header structure, or NULL upon an error. * * @HIDE * * @since New in @NEW_1_12_7. */ #if SU_HAVE_INLINE su_inline #endif sip_reply_to_t *sip_reply_to_format(su_home_t *home, char const *fmt, ...) __attribute__((__malloc__, __format__ (printf, 2, 3))); #if SU_HAVE_INLINE su_inline sip_reply_to_t *sip_reply_to_format(su_home_t *home, char const *fmt, ...) { sip_header_t *h; va_list ap; va_start(ap, fmt); h = sip_header_vformat(home, sip_reply_to_class, fmt, ap); va_end(ap); return (sip_reply_to_t *)h; } #endif /** @} */ /**@ingroup sip_reply_to * * Tag list item for pointer to a @ref sip_reply_to "Reply-To header" * structure #sip_reply_to_t. * * The SIPTAG_REPLY_TO() macro is used to include a tag item with a * pointer to a #sip_reply_to_t structure in a tag list. * * @param x pointer to a #sip_reply_to_t structure, or NULL. * * The corresponding tag taking reference parameter is * SIPTAG_REPLY_TO_REF(). * * @since New in @NEW_1_12_7. * * @HIDE */ #define SIPTAG_REPLY_TO(x) siptag_reply_to, siptag_reply_to_v(x) SOFIAPUBVAR tag_typedef_t siptag_reply_to; /**@ingroup sip_reply_to * Tag list item for reference to a * @ref sip_reply_to "Reply-To header" pointer. */ #define SIPTAG_REPLY_TO_REF(x) siptag_reply_to_ref, siptag_reply_to_vr(&(x)) SOFIAPUBVAR tag_typedef_t siptag_reply_to_ref; /**@ingroup sip_reply_to * * Tag list item for string with @ref sip_reply_to "Reply-To header" value. * * The SIPTAG_REPLY_TO_STR() macro is used to include a tag item with a * string containing value of a #sip_reply_to_t header in a tag list. * * @param s pointer to a string containing * @ref sip_reply_to "Reply-To header" value, or NULL. * * The string in SIPTAG_REPLY_TO_STR() can be converted to a * #sip_reply_to_t header structure by giving the string @a s has * second argument to function sip_reply_to_make(). * * The corresponding tag taking reference parameter is * SIPTAG_REPLY_TO_STR_REF(). * * @since New in @NEW_1_12_7. * * @HIDE */ #define SIPTAG_REPLY_TO_STR(s) siptag_reply_to_str, tag_str_v(s) SOFIAPUBVAR tag_typedef_t siptag_reply_to_str; /**@ingroup sip_reply_to * Tag list item for reference to a * @ref sip_reply_to "Reply-To header" string. */ #define SIPTAG_REPLY_TO_STR_REF(x) siptag_reply_to_str_ref, tag_str_vr(&(x)) SOFIAPUBVAR tag_typedef_t siptag_reply_to_str_ref; #if SU_INLINE_TAG_CAST su_inline tag_value_t siptag_reply_to_v(sip_reply_to_t const *v) { return (tag_value_t)v; } su_inline tag_value_t siptag_reply_to_vr(sip_reply_to_t const **vp) { return (tag_value_t)vp; } #else #define siptag_reply_to_v(v) (tag_value_t)(v) #define siptag_reply_to_vr(vp) (tag_value_t)(vp) #endif /** Defined as 1 if the @ref sip_remote_party_id "Remote-Party-ID header" is supported */ #define SIP_HAVE_REMOTE_PARTY_ID 1 enum { /**@ingroup sip_remote_party_id @internal * * Hash of @ref sip_remote_party_id "Remote-Party-ID header". * * @since New in @NEW_1_12_7. */ sip_remote_party_id_hash = 59907 }; /**Header class for @ref sip_remote_party_id "Remote-Party-ID header". * * The header class sip_remote_party_id_class defines how a SIP * @ref sip_remote_party_id "Remote-Party-ID header" is parsed and printed. * It also contains methods used by SIP parser and other functions to * manipulate the #sip_remote_party_id_t header structure. * * @ingroup sip_remote_party_id * * @since New in @NEW_1_12_7. */ SIP_DLL extern msg_hclass_t sip_remote_party_id_class[]; /**@addtogroup sip_remote_party_id * @{ */ /** Parse a SIP @ref sip_remote_party_id "Remote-Party-ID header". @internal */ SOFIAPUBFUN issize_t sip_remote_party_id_d(su_home_t *, msg_header_t *, char *s, isize_t slen); /** Print a SIP @ref sip_remote_party_id "Remote-Party-ID header". @internal */ SOFIAPUBFUN issize_t sip_remote_party_id_e(char b[], isize_t bsiz, msg_header_t const *h, int flags); /**Access a SIP @ref sip_remote_party_id "Remote-Party-ID header" * structure #sip_remote_party_id_t from #sip_t. * * @since New in @NEW_1_12_7. */ #define sip_remote_party_id(sip) \ ((sip_remote_party_id_t *)msg_header_access((msg_pub_t*)(sip), sip_remote_party_id_class)) /**Initializer for structure #sip_remote_party_id_t. * * A static #sip_remote_party_id_t structure for * @ref sip_remote_party_id "Remote-Party-ID header" must be initialized with * the SIP_REMOTE_PARTY_ID_INIT() macro. * For instance, * @code * * sip_remote_party_id_t sip_remote_party_id = SIP_REMOTE_PARTY_ID_INIT; * * @endcode * @HI * * @since New in @NEW_1_12_7. */ #define SIP_REMOTE_PARTY_ID_INIT() SIP_HDR_INIT(remote_party_id) /**Initialize a structure #sip_remote_party_id_t. * * An #sip_remote_party_id_t structure for * @ref sip_remote_party_id "Remote-Party-ID header" can be initialized with the * sip_remote_party_id_init() function/macro. For instance, * @code * * sip_remote_party_id_t sip_remote_party_id; * * sip_remote_party_id_init(&sip_remote_party_id); * * @endcode * @HI * * @since New in @NEW_1_12_7. */ #if SU_HAVE_INLINE su_inline sip_remote_party_id_t *sip_remote_party_id_init(sip_remote_party_id_t x[1]) { return SIP_HEADER_INIT(x, sip_remote_party_id_class, sizeof(sip_remote_party_id_t)); } #else #define sip_remote_party_id_init(x) \ SIP_HEADER_INIT(x, sip_remote_party_id_class, sizeof(sip_remote_party_id_t)) #endif /**Test if header object is instance of #sip_remote_party_id_t. * * Check if the header class is an instance of * @ref sip_remote_party_id "Remote-Party-ID header" object and return true (nonzero), * otherwise return false (zero). * * @param header pointer to the header structure to be tested * * @retval 1 (true) if the @a header is an instance of header remote_party_id * @retval 0 (false) otherwise * * @since New in @NEW_1_12_7. */ #if SU_HAVE_INLINE su_inline int sip_is_remote_party_id(sip_header_t const *header) { return header && header->sh_class->hc_hash == sip_remote_party_id_hash; } #else int sip_is_remote_party_id(sip_header_t const *header); #endif #define sip_remote_party_id_p(h) sip_is_remote_party_id((h)) /**Duplicate a list of @ref sip_remote_party_id "Remote-Party-ID header" header structures #sip_remote_party_id_t. * * Duplicate a header * structure @a hdr. If the header structure @a hdr * contains a reference (@c hdr->x_next) to a list of * headers, all the headers in the list are duplicated, too. * * @param home memory home used to allocate new structure * @param hdr header structure to be duplicated * * When duplicating, all parameter lists and non-constant * strings attached to the header are copied, too. The * function uses given memory @a home to allocate all the * memory areas used to copy the header. * * @par Example * @code * * remote_party_id = sip_remote_party_id_dup(home, sip->sip_remote_party_id); * * @endcode * * @return * A pointer to the * newly duplicated #sip_remote_party_id_t header structure, or NULL * upon an error. * * @since New in @NEW_1_12_7. */ #if SU_HAVE_INLINE su_inline #endif sip_remote_party_id_t *sip_remote_party_id_dup(su_home_t *home, sip_remote_party_id_t const *hdr) __attribute__((__malloc__)); #if SU_HAVE_INLINE su_inline sip_remote_party_id_t *sip_remote_party_id_dup(su_home_t *home, sip_remote_party_id_t const *hdr) { return (sip_remote_party_id_t *) msg_header_dup_as(home, sip_remote_party_id_class, (msg_header_t const *)hdr); } #endif /**Copy a list of @ref sip_remote_party_id "Remote-Party-ID header" header structures #sip_remote_party_id_t. * * The function sip_remote_party_id_copy() copies a header structure @a * hdr. If the header structure @a hdr contains a reference (@c * hdr->h_next) to a list of headers, all the headers in that * list are copied, too. The function uses given memory @a home * to allocate all the memory areas used to copy the list of header * structure @a hdr. * * @param home memory home used to allocate new structure * @param hdr pointer to the header structure to be copied * * When copying, only the header structure and parameter lists attached to * it are duplicated. The new header structure retains all the references to * the strings within the old @a hdr header, including the encoding of the * old header, if present. * * @par Example * @code * * remote_party_id = sip_remote_party_id_copy(home, sip->sip_remote_party_id); * * @endcode * * @return * A pointer to newly copied header structure, or NULL upon an error. * * @since New in @NEW_1_12_7. */ #if SU_HAVE_INLINE su_inline #endif sip_remote_party_id_t *sip_remote_party_id_copy(su_home_t *home, sip_remote_party_id_t const *hdr) __attribute__((__malloc__)); #if SU_HAVE_INLINE su_inline sip_remote_party_id_t *sip_remote_party_id_copy(su_home_t *home, sip_remote_party_id_t const *hdr) { return (sip_remote_party_id_t *) msg_header_copy_as(home, sip_remote_party_id_class, (msg_header_t const *)hdr); } #endif /**Make a @ref sip_remote_party_id "Remote-Party-ID header" structure #sip_remote_party_id_t. * * The function sip_remote_party_id_make() makes a new * #sip_remote_party_id_t header structure. It allocates a new * header structure, and decodes the string @a s as the * value of the structure. * * @param home memory home used to allocate new header structure. * @param s string to be decoded as value of the new header structure * * @return * A pointer to newly maked #sip_remote_party_id_t header structure, or NULL upon an * error. * * @since New in @NEW_1_12_7. */ #if SU_HAVE_INLINE su_inline #endif sip_remote_party_id_t *sip_remote_party_id_make(su_home_t *home, char const *s) __attribute__((__malloc__)); #if SU_HAVE_INLINE su_inline sip_remote_party_id_t *sip_remote_party_id_make(su_home_t *home, char const *s) { return (sip_remote_party_id_t *)sip_header_make(home, sip_remote_party_id_class, s); } #endif /**Make a @ref sip_remote_party_id "Remote-Party-ID header" from formatting result. * * Make a new #sip_remote_party_id_t object using formatting result as its value. * The function first prints the arguments according to the format @a fmt * specified. Then it allocates a new header structure, and parses the * formatting result to the structure #sip_remote_party_id_t. * * @param home memory home used to allocate new header structure. * @param fmt string used as a printf()-style format * @param ... argument list for format * * @return * A pointer to newly * makes header structure, or NULL upon an error. * * @HIDE * * @since New in @NEW_1_12_7. */ #if SU_HAVE_INLINE su_inline #endif sip_remote_party_id_t *sip_remote_party_id_format(su_home_t *home, char const *fmt, ...) __attribute__((__malloc__, __format__ (printf, 2, 3))); #if SU_HAVE_INLINE su_inline sip_remote_party_id_t *sip_remote_party_id_format(su_home_t *home, char const *fmt, ...) { sip_header_t *h; va_list ap; va_start(ap, fmt); h = sip_header_vformat(home, sip_remote_party_id_class, fmt, ap); va_end(ap); return (sip_remote_party_id_t *)h; } #endif /** @} */ /**@ingroup sip_remote_party_id * * Tag list item for pointer to a @ref sip_remote_party_id "Remote-Party-ID header" * structure #sip_remote_party_id_t. * * The SIPTAG_REMOTE_PARTY_ID() macro is used to include a tag item with a * pointer to a #sip_remote_party_id_t structure in a tag list. * * @param x pointer to a #sip_remote_party_id_t structure, or NULL. * * The corresponding tag taking reference parameter is * SIPTAG_REMOTE_PARTY_ID_REF(). * * @since New in @NEW_1_12_7. * * @HIDE */ #define SIPTAG_REMOTE_PARTY_ID(x) siptag_remote_party_id, siptag_remote_party_id_v(x) SOFIAPUBVAR tag_typedef_t siptag_remote_party_id; /**@ingroup sip_remote_party_id * Tag list item for reference to a * @ref sip_remote_party_id "Remote-Party-ID header" pointer. */ #define SIPTAG_REMOTE_PARTY_ID_REF(x) siptag_remote_party_id_ref, siptag_remote_party_id_vr(&(x)) SOFIAPUBVAR tag_typedef_t siptag_remote_party_id_ref; /**@ingroup sip_remote_party_id * * Tag list item for string with @ref sip_remote_party_id "Remote-Party-ID header" value. * * The SIPTAG_REMOTE_PARTY_ID_STR() macro is used to include a tag item with a * string containing value of a #sip_remote_party_id_t header in a tag list. * * @param s pointer to a string containing * @ref sip_remote_party_id "Remote-Party-ID header" value, or NULL. * * The string in SIPTAG_REMOTE_PARTY_ID_STR() can be converted to a * #sip_remote_party_id_t header structure by giving the string @a s has * second argument to function sip_remote_party_id_make(). * * The corresponding tag taking reference parameter is * SIPTAG_REMOTE_PARTY_ID_STR_REF(). * * @since New in @NEW_1_12_7. * * @HIDE */ #define SIPTAG_REMOTE_PARTY_ID_STR(s) siptag_remote_party_id_str, tag_str_v(s) SOFIAPUBVAR tag_typedef_t siptag_remote_party_id_str; /**@ingroup sip_remote_party_id * Tag list item for reference to a * @ref sip_remote_party_id "Remote-Party-ID header" string. */ #define SIPTAG_REMOTE_PARTY_ID_STR_REF(x) siptag_remote_party_id_str_ref, tag_str_vr(&(x)) SOFIAPUBVAR tag_typedef_t siptag_remote_party_id_str_ref; #if SU_INLINE_TAG_CAST su_inline tag_value_t siptag_remote_party_id_v(sip_remote_party_id_t const *v) { return (tag_value_t)v; } su_inline tag_value_t siptag_remote_party_id_vr(sip_remote_party_id_t const **vp) { return (tag_value_t)vp; } #else #define siptag_remote_party_id_v(v) (tag_value_t)(v) #define siptag_remote_party_id_vr(vp) (tag_value_t)(vp) #endif /** Defined as 1 if the @ref sip_p_asserted_identity "P-Asserted-Identity header" is supported */ #define SIP_HAVE_P_ASSERTED_IDENTITY 1 enum { /**@ingroup sip_p_asserted_identity @internal * * Hash of @ref sip_p_asserted_identity "P-Asserted-Identity header". * * @since New in @NEW_1_12_7. */ sip_p_asserted_identity_hash = 16399 }; /**Header class for @ref sip_p_asserted_identity "P-Asserted-Identity header". * * The header class sip_p_asserted_identity_class defines how a SIP * @ref sip_p_asserted_identity "P-Asserted-Identity header" is parsed and printed. * It also contains methods used by SIP parser and other functions to * manipulate the #sip_p_asserted_identity_t header structure. * * @ingroup sip_p_asserted_identity * * @since New in @NEW_1_12_7. */ SIP_DLL extern msg_hclass_t sip_p_asserted_identity_class[]; /**@addtogroup sip_p_asserted_identity * @{ */ /** Parse a SIP @ref sip_p_asserted_identity "P-Asserted-Identity header". @internal */ SOFIAPUBFUN issize_t sip_p_asserted_identity_d(su_home_t *, msg_header_t *, char *s, isize_t slen); /** Print a SIP @ref sip_p_asserted_identity "P-Asserted-Identity header". @internal */ SOFIAPUBFUN issize_t sip_p_asserted_identity_e(char b[], isize_t bsiz, msg_header_t const *h, int flags); /**Access a SIP @ref sip_p_asserted_identity "P-Asserted-Identity header" * structure #sip_p_asserted_identity_t from #sip_t. * * @since New in @NEW_1_12_7. */ #define sip_p_asserted_identity(sip) \ ((sip_p_asserted_identity_t *)msg_header_access((msg_pub_t*)(sip), sip_p_asserted_identity_class)) /**Initializer for structure #sip_p_asserted_identity_t. * * A static #sip_p_asserted_identity_t structure for * @ref sip_p_asserted_identity "P-Asserted-Identity header" must be initialized with * the SIP_P_ASSERTED_IDENTITY_INIT() macro. * For instance, * @code * * sip_p_asserted_identity_t sip_p_asserted_identity = SIP_P_ASSERTED_IDENTITY_INIT; * * @endcode * @HI * * @since New in @NEW_1_12_7. */ #define SIP_P_ASSERTED_IDENTITY_INIT() SIP_HDR_INIT(p_asserted_identity) /**Initialize a structure #sip_p_asserted_identity_t. * * An #sip_p_asserted_identity_t structure for * @ref sip_p_asserted_identity "P-Asserted-Identity header" can be initialized with the * sip_p_asserted_identity_init() function/macro. For instance, * @code * * sip_p_asserted_identity_t sip_p_asserted_identity; * * sip_p_asserted_identity_init(&sip_p_asserted_identity); * * @endcode * @HI * * @since New in @NEW_1_12_7. */ #if SU_HAVE_INLINE su_inline sip_p_asserted_identity_t *sip_p_asserted_identity_init(sip_p_asserted_identity_t x[1]) { return SIP_HEADER_INIT(x, sip_p_asserted_identity_class, sizeof(sip_p_asserted_identity_t)); } #else #define sip_p_asserted_identity_init(x) \ SIP_HEADER_INIT(x, sip_p_asserted_identity_class, sizeof(sip_p_asserted_identity_t)) #endif /**Test if header object is instance of #sip_p_asserted_identity_t. * * Check if the header class is an instance of * @ref sip_p_asserted_identity "P-Asserted-Identity header" object and return true (nonzero), * otherwise return false (zero). * * @param header pointer to the header structure to be tested * * @retval 1 (true) if the @a header is an instance of header p_asserted_identity * @retval 0 (false) otherwise * * @since New in @NEW_1_12_7. */ #if SU_HAVE_INLINE su_inline int sip_is_p_asserted_identity(sip_header_t const *header) { return header && header->sh_class->hc_hash == sip_p_asserted_identity_hash; } #else int sip_is_p_asserted_identity(sip_header_t const *header); #endif #define sip_p_asserted_identity_p(h) sip_is_p_asserted_identity((h)) /**Duplicate a list of @ref sip_p_asserted_identity "P-Asserted-Identity header" header structures #sip_p_asserted_identity_t. * * Duplicate a header * structure @a hdr. If the header structure @a hdr * contains a reference (@c hdr->x_next) to a list of * headers, all the headers in the list are duplicated, too. * * @param home memory home used to allocate new structure * @param hdr header structure to be duplicated * * When duplicating, all parameter lists and non-constant * strings attached to the header are copied, too. The * function uses given memory @a home to allocate all the * memory areas used to copy the header. * * @par Example * @code * * p_asserted_identity = sip_p_asserted_identity_dup(home, sip->sip_p_asserted_identity); * * @endcode * * @return * A pointer to the * newly duplicated #sip_p_asserted_identity_t header structure, or NULL * upon an error. * * @since New in @NEW_1_12_7. */ #if SU_HAVE_INLINE su_inline #endif sip_p_asserted_identity_t *sip_p_asserted_identity_dup(su_home_t *home, sip_p_asserted_identity_t const *hdr) __attribute__((__malloc__)); #if SU_HAVE_INLINE su_inline sip_p_asserted_identity_t *sip_p_asserted_identity_dup(su_home_t *home, sip_p_asserted_identity_t const *hdr) { return (sip_p_asserted_identity_t *) msg_header_dup_as(home, sip_p_asserted_identity_class, (msg_header_t const *)hdr); } #endif /**Copy a list of @ref sip_p_asserted_identity "P-Asserted-Identity header" header structures #sip_p_asserted_identity_t. * * The function sip_p_asserted_identity_copy() copies a header structure @a * hdr. If the header structure @a hdr contains a reference (@c * hdr->h_next) to a list of headers, all the headers in that * list are copied, too. The function uses given memory @a home * to allocate all the memory areas used to copy the list of header * structure @a hdr. * * @param home memory home used to allocate new structure * @param hdr pointer to the header structure to be copied * * When copying, only the header structure and parameter lists attached to * it are duplicated. The new header structure retains all the references to * the strings within the old @a hdr header, including the encoding of the * old header, if present. * * @par Example * @code * * p_asserted_identity = sip_p_asserted_identity_copy(home, sip->sip_p_asserted_identity); * * @endcode * * @return * A pointer to newly copied header structure, or NULL upon an error. * * @since New in @NEW_1_12_7. */ #if SU_HAVE_INLINE su_inline #endif sip_p_asserted_identity_t *sip_p_asserted_identity_copy(su_home_t *home, sip_p_asserted_identity_t const *hdr) __attribute__((__malloc__)); #if SU_HAVE_INLINE su_inline sip_p_asserted_identity_t *sip_p_asserted_identity_copy(su_home_t *home, sip_p_asserted_identity_t const *hdr) { return (sip_p_asserted_identity_t *) msg_header_copy_as(home, sip_p_asserted_identity_class, (msg_header_t const *)hdr); } #endif /**Make a @ref sip_p_asserted_identity "P-Asserted-Identity header" structure #sip_p_asserted_identity_t. * * The function sip_p_asserted_identity_make() makes a new * #sip_p_asserted_identity_t header structure. It allocates a new * header structure, and decodes the string @a s as the * value of the structure. * * @param home memory home used to allocate new header structure. * @param s string to be decoded as value of the new header structure * * @return * A pointer to newly maked #sip_p_asserted_identity_t header structure, or NULL upon an * error. * * @since New in @NEW_1_12_7. */ #if SU_HAVE_INLINE su_inline #endif sip_p_asserted_identity_t *sip_p_asserted_identity_make(su_home_t *home, char const *s) __attribute__((__malloc__)); #if SU_HAVE_INLINE su_inline sip_p_asserted_identity_t *sip_p_asserted_identity_make(su_home_t *home, char const *s) { return (sip_p_asserted_identity_t *)sip_header_make(home, sip_p_asserted_identity_class, s); } #endif /**Make a @ref sip_p_asserted_identity "P-Asserted-Identity header" from formatting result. * * Make a new #sip_p_asserted_identity_t object using formatting result as its value. * The function first prints the arguments according to the format @a fmt * specified. Then it allocates a new header structure, and parses the * formatting result to the structure #sip_p_asserted_identity_t. * * @param home memory home used to allocate new header structure. * @param fmt string used as a printf()-style format * @param ... argument list for format * * @return * A pointer to newly * makes header structure, or NULL upon an error. * * @HIDE * * @since New in @NEW_1_12_7. */ #if SU_HAVE_INLINE su_inline #endif sip_p_asserted_identity_t *sip_p_asserted_identity_format(su_home_t *home, char const *fmt, ...) __attribute__((__malloc__, __format__ (printf, 2, 3))); #if SU_HAVE_INLINE su_inline sip_p_asserted_identity_t *sip_p_asserted_identity_format(su_home_t *home, char const *fmt, ...) { sip_header_t *h; va_list ap; va_start(ap, fmt); h = sip_header_vformat(home, sip_p_asserted_identity_class, fmt, ap); va_end(ap); return (sip_p_asserted_identity_t *)h; } #endif /** @} */ /**@ingroup sip_p_asserted_identity * * Tag list item for pointer to a @ref sip_p_asserted_identity "P-Asserted-Identity header" * structure #sip_p_asserted_identity_t. * * The SIPTAG_P_ASSERTED_IDENTITY() macro is used to include a tag item with a * pointer to a #sip_p_asserted_identity_t structure in a tag list. * * @param x pointer to a #sip_p_asserted_identity_t structure, or NULL. * * The corresponding tag taking reference parameter is * SIPTAG_P_ASSERTED_IDENTITY_REF(). * * @since New in @NEW_1_12_7. * * @HIDE */ #define SIPTAG_P_ASSERTED_IDENTITY(x) siptag_p_asserted_identity, siptag_p_asserted_identity_v(x) SOFIAPUBVAR tag_typedef_t siptag_p_asserted_identity; /**@ingroup sip_p_asserted_identity * Tag list item for reference to a * @ref sip_p_asserted_identity "P-Asserted-Identity header" pointer. */ #define SIPTAG_P_ASSERTED_IDENTITY_REF(x) siptag_p_asserted_identity_ref, siptag_p_asserted_identity_vr(&(x)) SOFIAPUBVAR tag_typedef_t siptag_p_asserted_identity_ref; /**@ingroup sip_p_asserted_identity * * Tag list item for string with @ref sip_p_asserted_identity "P-Asserted-Identity header" value. * * The SIPTAG_P_ASSERTED_IDENTITY_STR() macro is used to include a tag item with a * string containing value of a #sip_p_asserted_identity_t header in a tag list. * * @param s pointer to a string containing * @ref sip_p_asserted_identity "P-Asserted-Identity header" value, or NULL. * * The string in SIPTAG_P_ASSERTED_IDENTITY_STR() can be converted to a * #sip_p_asserted_identity_t header structure by giving the string @a s has * second argument to function sip_p_asserted_identity_make(). * * The corresponding tag taking reference parameter is * SIPTAG_P_ASSERTED_IDENTITY_STR_REF(). * * @since New in @NEW_1_12_7. * * @HIDE */ #define SIPTAG_P_ASSERTED_IDENTITY_STR(s) siptag_p_asserted_identity_str, tag_str_v(s) SOFIAPUBVAR tag_typedef_t siptag_p_asserted_identity_str; /**@ingroup sip_p_asserted_identity * Tag list item for reference to a * @ref sip_p_asserted_identity "P-Asserted-Identity header" string. */ #define SIPTAG_P_ASSERTED_IDENTITY_STR_REF(x) siptag_p_asserted_identity_str_ref, tag_str_vr(&(x)) SOFIAPUBVAR tag_typedef_t siptag_p_asserted_identity_str_ref; #if SU_INLINE_TAG_CAST su_inline tag_value_t siptag_p_asserted_identity_v(sip_p_asserted_identity_t const *v) { return (tag_value_t)v; } su_inline tag_value_t siptag_p_asserted_identity_vr(sip_p_asserted_identity_t const **vp) { return (tag_value_t)vp; } #else #define siptag_p_asserted_identity_v(v) (tag_value_t)(v) #define siptag_p_asserted_identity_vr(vp) (tag_value_t)(vp) #endif /** Defined as 1 if the @ref sip_p_preferred_identity "P-Preferred-Identity header" is supported */ #define SIP_HAVE_P_PREFERRED_IDENTITY 1 enum { /**@ingroup sip_p_preferred_identity @internal * * Hash of @ref sip_p_preferred_identity "P-Preferred-Identity header". * * @since New in @NEW_1_12_7. */ sip_p_preferred_identity_hash = 44591 }; /**Header class for @ref sip_p_preferred_identity "P-Preferred-Identity header". * * The header class sip_p_preferred_identity_class defines how a SIP * @ref sip_p_preferred_identity "P-Preferred-Identity header" is parsed and printed. * It also contains methods used by SIP parser and other functions to * manipulate the #sip_p_preferred_identity_t header structure. * * @ingroup sip_p_preferred_identity * * @since New in @NEW_1_12_7. */ SIP_DLL extern msg_hclass_t sip_p_preferred_identity_class[]; /**@addtogroup sip_p_preferred_identity * @{ */ /** Parse a SIP @ref sip_p_preferred_identity "P-Preferred-Identity header". @internal */ SOFIAPUBFUN issize_t sip_p_preferred_identity_d(su_home_t *, msg_header_t *, char *s, isize_t slen); /** Print a SIP @ref sip_p_preferred_identity "P-Preferred-Identity header". @internal */ SOFIAPUBFUN issize_t sip_p_preferred_identity_e(char b[], isize_t bsiz, msg_header_t const *h, int flags); /**Access a SIP @ref sip_p_preferred_identity "P-Preferred-Identity header" * structure #sip_p_preferred_identity_t from #sip_t. * * @since New in @NEW_1_12_7. */ #define sip_p_preferred_identity(sip) \ ((sip_p_preferred_identity_t *)msg_header_access((msg_pub_t*)(sip), sip_p_preferred_identity_class)) /**Initializer for structure #sip_p_preferred_identity_t. * * A static #sip_p_preferred_identity_t structure for * @ref sip_p_preferred_identity "P-Preferred-Identity header" must be initialized with * the SIP_P_PREFERRED_IDENTITY_INIT() macro. * For instance, * @code * * sip_p_preferred_identity_t sip_p_preferred_identity = SIP_P_PREFERRED_IDENTITY_INIT; * * @endcode * @HI * * @since New in @NEW_1_12_7. */ #define SIP_P_PREFERRED_IDENTITY_INIT() SIP_HDR_INIT(p_preferred_identity) /**Initialize a structure #sip_p_preferred_identity_t. * * An #sip_p_preferred_identity_t structure for * @ref sip_p_preferred_identity "P-Preferred-Identity header" can be initialized with the * sip_p_preferred_identity_init() function/macro. For instance, * @code * * sip_p_preferred_identity_t sip_p_preferred_identity; * * sip_p_preferred_identity_init(&sip_p_preferred_identity); * * @endcode * @HI * * @since New in @NEW_1_12_7. */ #if SU_HAVE_INLINE su_inline sip_p_preferred_identity_t *sip_p_preferred_identity_init(sip_p_preferred_identity_t x[1]) { return SIP_HEADER_INIT(x, sip_p_preferred_identity_class, sizeof(sip_p_preferred_identity_t)); } #else #define sip_p_preferred_identity_init(x) \ SIP_HEADER_INIT(x, sip_p_preferred_identity_class, sizeof(sip_p_preferred_identity_t)) #endif /**Test if header object is instance of #sip_p_preferred_identity_t. * * Check if the header class is an instance of * @ref sip_p_preferred_identity "P-Preferred-Identity header" object and return true (nonzero), * otherwise return false (zero). * * @param header pointer to the header structure to be tested * * @retval 1 (true) if the @a header is an instance of header p_preferred_identity * @retval 0 (false) otherwise * * @since New in @NEW_1_12_7. */ #if SU_HAVE_INLINE su_inline int sip_is_p_preferred_identity(sip_header_t const *header) { return header && header->sh_class->hc_hash == sip_p_preferred_identity_hash; } #else int sip_is_p_preferred_identity(sip_header_t const *header); #endif #define sip_p_preferred_identity_p(h) sip_is_p_preferred_identity((h)) /**Duplicate a list of @ref sip_p_preferred_identity "P-Preferred-Identity header" header structures #sip_p_preferred_identity_t. * * Duplicate a header * structure @a hdr. If the header structure @a hdr * contains a reference (@c hdr->x_next) to a list of * headers, all the headers in the list are duplicated, too. * * @param home memory home used to allocate new structure * @param hdr header structure to be duplicated * * When duplicating, all parameter lists and non-constant * strings attached to the header are copied, too. The * function uses given memory @a home to allocate all the * memory areas used to copy the header. * * @par Example * @code * * p_preferred_identity = sip_p_preferred_identity_dup(home, sip->sip_p_preferred_identity); * * @endcode * * @return * A pointer to the * newly duplicated #sip_p_preferred_identity_t header structure, or NULL * upon an error. * * @since New in @NEW_1_12_7. */ #if SU_HAVE_INLINE su_inline #endif sip_p_preferred_identity_t *sip_p_preferred_identity_dup(su_home_t *home, sip_p_preferred_identity_t const *hdr) __attribute__((__malloc__)); #if SU_HAVE_INLINE su_inline sip_p_preferred_identity_t *sip_p_preferred_identity_dup(su_home_t *home, sip_p_preferred_identity_t const *hdr) { return (sip_p_preferred_identity_t *) msg_header_dup_as(home, sip_p_preferred_identity_class, (msg_header_t const *)hdr); } #endif /**Copy a list of @ref sip_p_preferred_identity "P-Preferred-Identity header" header structures #sip_p_preferred_identity_t. * * The function sip_p_preferred_identity_copy() copies a header structure @a * hdr. If the header structure @a hdr contains a reference (@c * hdr->h_next) to a list of headers, all the headers in that * list are copied, too. The function uses given memory @a home * to allocate all the memory areas used to copy the list of header * structure @a hdr. * * @param home memory home used to allocate new structure * @param hdr pointer to the header structure to be copied * * When copying, only the header structure and parameter lists attached to * it are duplicated. The new header structure retains all the references to * the strings within the old @a hdr header, including the encoding of the * old header, if present. * * @par Example * @code * * p_preferred_identity = sip_p_preferred_identity_copy(home, sip->sip_p_preferred_identity); * * @endcode * * @return * A pointer to newly copied header structure, or NULL upon an error. * * @since New in @NEW_1_12_7. */ #if SU_HAVE_INLINE su_inline #endif sip_p_preferred_identity_t *sip_p_preferred_identity_copy(su_home_t *home, sip_p_preferred_identity_t const *hdr) __attribute__((__malloc__)); #if SU_HAVE_INLINE su_inline sip_p_preferred_identity_t *sip_p_preferred_identity_copy(su_home_t *home, sip_p_preferred_identity_t const *hdr) { return (sip_p_preferred_identity_t *) msg_header_copy_as(home, sip_p_preferred_identity_class, (msg_header_t const *)hdr); } #endif /**Make a @ref sip_p_preferred_identity "P-Preferred-Identity header" structure #sip_p_preferred_identity_t. * * The function sip_p_preferred_identity_make() makes a new * #sip_p_preferred_identity_t header structure. It allocates a new * header structure, and decodes the string @a s as the * value of the structure. * * @param home memory home used to allocate new header structure. * @param s string to be decoded as value of the new header structure * * @return * A pointer to newly maked #sip_p_preferred_identity_t header structure, or NULL upon an * error. * * @since New in @NEW_1_12_7. */ #if SU_HAVE_INLINE su_inline #endif sip_p_preferred_identity_t *sip_p_preferred_identity_make(su_home_t *home, char const *s) __attribute__((__malloc__)); #if SU_HAVE_INLINE su_inline sip_p_preferred_identity_t *sip_p_preferred_identity_make(su_home_t *home, char const *s) { return (sip_p_preferred_identity_t *)sip_header_make(home, sip_p_preferred_identity_class, s); } #endif /**Make a @ref sip_p_preferred_identity "P-Preferred-Identity header" from formatting result. * * Make a new #sip_p_preferred_identity_t object using formatting result as its value. * The function first prints the arguments according to the format @a fmt * specified. Then it allocates a new header structure, and parses the * formatting result to the structure #sip_p_preferred_identity_t. * * @param home memory home used to allocate new header structure. * @param fmt string used as a printf()-style format * @param ... argument list for format * * @return * A pointer to newly * makes header structure, or NULL upon an error. * * @HIDE * * @since New in @NEW_1_12_7. */ #if SU_HAVE_INLINE su_inline #endif sip_p_preferred_identity_t *sip_p_preferred_identity_format(su_home_t *home, char const *fmt, ...) __attribute__((__malloc__, __format__ (printf, 2, 3))); #if SU_HAVE_INLINE su_inline sip_p_preferred_identity_t *sip_p_preferred_identity_format(su_home_t *home, char const *fmt, ...) { sip_header_t *h; va_list ap; va_start(ap, fmt); h = sip_header_vformat(home, sip_p_preferred_identity_class, fmt, ap); va_end(ap); return (sip_p_preferred_identity_t *)h; } #endif /** @} */ /**@ingroup sip_p_preferred_identity * * Tag list item for pointer to a @ref sip_p_preferred_identity "P-Preferred-Identity header" * structure #sip_p_preferred_identity_t. * * The SIPTAG_P_PREFERRED_IDENTITY() macro is used to include a tag item with a * pointer to a #sip_p_preferred_identity_t structure in a tag list. * * @param x pointer to a #sip_p_preferred_identity_t structure, or NULL. * * The corresponding tag taking reference parameter is * SIPTAG_P_PREFERRED_IDENTITY_REF(). * * @since New in @NEW_1_12_7. * * @HIDE */ #define SIPTAG_P_PREFERRED_IDENTITY(x) siptag_p_preferred_identity, siptag_p_preferred_identity_v(x) SOFIAPUBVAR tag_typedef_t siptag_p_preferred_identity; /**@ingroup sip_p_preferred_identity * Tag list item for reference to a * @ref sip_p_preferred_identity "P-Preferred-Identity header" pointer. */ #define SIPTAG_P_PREFERRED_IDENTITY_REF(x) siptag_p_preferred_identity_ref, siptag_p_preferred_identity_vr(&(x)) SOFIAPUBVAR tag_typedef_t siptag_p_preferred_identity_ref; /**@ingroup sip_p_preferred_identity * * Tag list item for string with @ref sip_p_preferred_identity "P-Preferred-Identity header" value. * * The SIPTAG_P_PREFERRED_IDENTITY_STR() macro is used to include a tag item with a * string containing value of a #sip_p_preferred_identity_t header in a tag list. * * @param s pointer to a string containing * @ref sip_p_preferred_identity "P-Preferred-Identity header" value, or NULL. * * The string in SIPTAG_P_PREFERRED_IDENTITY_STR() can be converted to a * #sip_p_preferred_identity_t header structure by giving the string @a s has * second argument to function sip_p_preferred_identity_make(). * * The corresponding tag taking reference parameter is * SIPTAG_P_PREFERRED_IDENTITY_STR_REF(). * * @since New in @NEW_1_12_7. * * @HIDE */ #define SIPTAG_P_PREFERRED_IDENTITY_STR(s) siptag_p_preferred_identity_str, tag_str_v(s) SOFIAPUBVAR tag_typedef_t siptag_p_preferred_identity_str; /**@ingroup sip_p_preferred_identity * Tag list item for reference to a * @ref sip_p_preferred_identity "P-Preferred-Identity header" string. */ #define SIPTAG_P_PREFERRED_IDENTITY_STR_REF(x) siptag_p_preferred_identity_str_ref, tag_str_vr(&(x)) SOFIAPUBVAR tag_typedef_t siptag_p_preferred_identity_str_ref; #if SU_INLINE_TAG_CAST su_inline tag_value_t siptag_p_preferred_identity_v(sip_p_preferred_identity_t const *v) { return (tag_value_t)v; } su_inline tag_value_t siptag_p_preferred_identity_vr(sip_p_preferred_identity_t const **vp) { return (tag_value_t)vp; } #else #define siptag_p_preferred_identity_v(v) (tag_value_t)(v) #define siptag_p_preferred_identity_vr(vp) (tag_value_t)(vp) #endif #if SU_HAVE_EXPERIMENTAL /** Defined as 1 if the @ref sip_suppress_body_if_match "Suppress-Body-If-Match header" is supported */ #define SIP_HAVE_SUPPRESS_BODY_IF_MATCH 1 enum { /**@ingroup sip_suppress_body_if_match @internal * * Hash of @ref sip_suppress_body_if_match "Suppress-Body-If-Match header". * * @since New in @EXP_1_12_5. */ sip_suppress_body_if_match_hash = 49874 }; /**Header class for @ref sip_suppress_body_if_match "Suppress-Body-If-Match header". * * The header class sip_suppress_body_if_match_class defines how a SIP * @ref sip_suppress_body_if_match "Suppress-Body-If-Match header" is parsed and printed. * It also contains methods used by SIP parser and other functions to * manipulate the #sip_suppress_body_if_match_t header structure. * * @ingroup sip_suppress_body_if_match * * @since New in @EXP_1_12_5. */ SIP_DLL extern msg_hclass_t sip_suppress_body_if_match_class[]; /**@addtogroup sip_suppress_body_if_match * @{ */ /** Parse a SIP @ref sip_suppress_body_if_match "Suppress-Body-If-Match header". @internal */ SOFIAPUBFUN issize_t sip_suppress_body_if_match_d(su_home_t *, msg_header_t *, char *s, isize_t slen); /** Print a SIP @ref sip_suppress_body_if_match "Suppress-Body-If-Match header". @internal */ SOFIAPUBFUN issize_t sip_suppress_body_if_match_e(char b[], isize_t bsiz, msg_header_t const *h, int flags); /**Access a SIP @ref sip_suppress_body_if_match "Suppress-Body-If-Match header" * structure #sip_suppress_body_if_match_t from #sip_t. * * @since New in @EXP_1_12_5. */ #define sip_suppress_body_if_match(sip) \ ((sip_suppress_body_if_match_t *)msg_header_access((msg_pub_t*)(sip), sip_suppress_body_if_match_class)) /**Initializer for structure #sip_suppress_body_if_match_t. * * A static #sip_suppress_body_if_match_t structure for * @ref sip_suppress_body_if_match "Suppress-Body-If-Match header" must be initialized with * the SIP_SUPPRESS_BODY_IF_MATCH_INIT() macro. * For instance, * @code * * sip_suppress_body_if_match_t sip_suppress_body_if_match = SIP_SUPPRESS_BODY_IF_MATCH_INIT; * * @endcode * @HI * * @since New in @EXP_1_12_5. */ #define SIP_SUPPRESS_BODY_IF_MATCH_INIT() SIP_HDR_INIT(suppress_body_if_match) /**Initialize a structure #sip_suppress_body_if_match_t. * * An #sip_suppress_body_if_match_t structure for * @ref sip_suppress_body_if_match "Suppress-Body-If-Match header" can be initialized with the * sip_suppress_body_if_match_init() function/macro. For instance, * @code * * sip_suppress_body_if_match_t sip_suppress_body_if_match; * * sip_suppress_body_if_match_init(&sip_suppress_body_if_match); * * @endcode * @HI * * @since New in @EXP_1_12_5. */ #if SU_HAVE_INLINE su_inline sip_suppress_body_if_match_t *sip_suppress_body_if_match_init(sip_suppress_body_if_match_t x[1]) { return SIP_HEADER_INIT(x, sip_suppress_body_if_match_class, sizeof(sip_suppress_body_if_match_t)); } #else #define sip_suppress_body_if_match_init(x) \ SIP_HEADER_INIT(x, sip_suppress_body_if_match_class, sizeof(sip_suppress_body_if_match_t)) #endif /**Test if header object is instance of #sip_suppress_body_if_match_t. * * Check if the header class is an instance of * @ref sip_suppress_body_if_match "Suppress-Body-If-Match header" object and return true (nonzero), * otherwise return false (zero). * * @param header pointer to the header structure to be tested * * @retval 1 (true) if the @a header is an instance of header suppress_body_if_match * @retval 0 (false) otherwise * * @since New in @EXP_1_12_5. */ #if SU_HAVE_INLINE su_inline int sip_is_suppress_body_if_match(sip_header_t const *header) { return header && header->sh_class->hc_hash == sip_suppress_body_if_match_hash; } #else int sip_is_suppress_body_if_match(sip_header_t const *header); #endif #define sip_suppress_body_if_match_p(h) sip_is_suppress_body_if_match((h)) /**Duplicate a list of @ref sip_suppress_body_if_match "Suppress-Body-If-Match header" header structures #sip_suppress_body_if_match_t. * * Duplicate a header * structure @a hdr. If the header structure @a hdr * contains a reference (@c hdr->x_next) to a list of * headers, all the headers in the list are duplicated, too. * * @param home memory home used to allocate new structure * @param hdr header structure to be duplicated * * When duplicating, all parameter lists and non-constant * strings attached to the header are copied, too. The * function uses given memory @a home to allocate all the * memory areas used to copy the header. * * @par Example * @code * * suppress_body_if_match = sip_suppress_body_if_match_dup(home, sip->sip_suppress_body_if_match); * * @endcode * * @return * A pointer to the * newly duplicated #sip_suppress_body_if_match_t header structure, or NULL * upon an error. * * @since New in @EXP_1_12_5. */ #if SU_HAVE_INLINE su_inline #endif sip_suppress_body_if_match_t *sip_suppress_body_if_match_dup(su_home_t *home, sip_suppress_body_if_match_t const *hdr) __attribute__((__malloc__)); #if SU_HAVE_INLINE su_inline sip_suppress_body_if_match_t *sip_suppress_body_if_match_dup(su_home_t *home, sip_suppress_body_if_match_t const *hdr) { return (sip_suppress_body_if_match_t *) msg_header_dup_as(home, sip_suppress_body_if_match_class, (msg_header_t const *)hdr); } #endif /**Copy a list of @ref sip_suppress_body_if_match "Suppress-Body-If-Match header" header structures #sip_suppress_body_if_match_t. * * The function sip_suppress_body_if_match_copy() copies a header structure @a * hdr. If the header structure @a hdr contains a reference (@c * hdr->h_next) to a list of headers, all the headers in that * list are copied, too. The function uses given memory @a home * to allocate all the memory areas used to copy the list of header * structure @a hdr. * * @param home memory home used to allocate new structure * @param hdr pointer to the header structure to be copied * * When copying, only the header structure and parameter lists attached to * it are duplicated. The new header structure retains all the references to * the strings within the old @a hdr header, including the encoding of the * old header, if present. * * @par Example * @code * * suppress_body_if_match = sip_suppress_body_if_match_copy(home, sip->sip_suppress_body_if_match); * * @endcode * * @return * A pointer to newly copied header structure, or NULL upon an error. * * @since New in @EXP_1_12_5. */ #if SU_HAVE_INLINE su_inline #endif sip_suppress_body_if_match_t *sip_suppress_body_if_match_copy(su_home_t *home, sip_suppress_body_if_match_t const *hdr) __attribute__((__malloc__)); #if SU_HAVE_INLINE su_inline sip_suppress_body_if_match_t *sip_suppress_body_if_match_copy(su_home_t *home, sip_suppress_body_if_match_t const *hdr) { return (sip_suppress_body_if_match_t *) msg_header_copy_as(home, sip_suppress_body_if_match_class, (msg_header_t const *)hdr); } #endif /**Make a @ref sip_suppress_body_if_match "Suppress-Body-If-Match header" structure #sip_suppress_body_if_match_t. * * The function sip_suppress_body_if_match_make() makes a new * #sip_suppress_body_if_match_t header structure. It allocates a new * header structure, and decodes the string @a s as the * value of the structure. * * @param home memory home used to allocate new header structure. * @param s string to be decoded as value of the new header structure * * @return * A pointer to newly maked #sip_suppress_body_if_match_t header structure, or NULL upon an * error. * * @since New in @EXP_1_12_5. */ #if SU_HAVE_INLINE su_inline #endif sip_suppress_body_if_match_t *sip_suppress_body_if_match_make(su_home_t *home, char const *s) __attribute__((__malloc__)); #if SU_HAVE_INLINE su_inline sip_suppress_body_if_match_t *sip_suppress_body_if_match_make(su_home_t *home, char const *s) { return (sip_suppress_body_if_match_t *)sip_header_make(home, sip_suppress_body_if_match_class, s); } #endif /**Make a @ref sip_suppress_body_if_match "Suppress-Body-If-Match header" from formatting result. * * Make a new #sip_suppress_body_if_match_t object using formatting result as its value. * The function first prints the arguments according to the format @a fmt * specified. Then it allocates a new header structure, and parses the * formatting result to the structure #sip_suppress_body_if_match_t. * * @param home memory home used to allocate new header structure. * @param fmt string used as a printf()-style format * @param ... argument list for format * * @return * A pointer to newly * makes header structure, or NULL upon an error. * * @HIDE * * @since New in @EXP_1_12_5. */ #if SU_HAVE_INLINE su_inline #endif sip_suppress_body_if_match_t *sip_suppress_body_if_match_format(su_home_t *home, char const *fmt, ...) __attribute__((__malloc__, __format__ (printf, 2, 3))); #if SU_HAVE_INLINE su_inline sip_suppress_body_if_match_t *sip_suppress_body_if_match_format(su_home_t *home, char const *fmt, ...) { sip_header_t *h; va_list ap; va_start(ap, fmt); h = sip_header_vformat(home, sip_suppress_body_if_match_class, fmt, ap); va_end(ap); return (sip_suppress_body_if_match_t *)h; } #endif /** @} */ /**@ingroup sip_suppress_body_if_match * * Tag list item for pointer to a @ref sip_suppress_body_if_match "Suppress-Body-If-Match header" * structure #sip_suppress_body_if_match_t. * * The SIPTAG_SUPPRESS_BODY_IF_MATCH() macro is used to include a tag item with a * pointer to a #sip_suppress_body_if_match_t structure in a tag list. * * @param x pointer to a #sip_suppress_body_if_match_t structure, or NULL. * * The corresponding tag taking reference parameter is * SIPTAG_SUPPRESS_BODY_IF_MATCH_REF(). * * @since New in @EXP_1_12_5. * * @HIDE */ #define SIPTAG_SUPPRESS_BODY_IF_MATCH(x) siptag_suppress_body_if_match, siptag_suppress_body_if_match_v(x) SOFIAPUBVAR tag_typedef_t siptag_suppress_body_if_match; /**@ingroup sip_suppress_body_if_match * Tag list item for reference to a * @ref sip_suppress_body_if_match "Suppress-Body-If-Match header" pointer. */ #define SIPTAG_SUPPRESS_BODY_IF_MATCH_REF(x) siptag_suppress_body_if_match_ref, siptag_suppress_body_if_match_vr(&(x)) SOFIAPUBVAR tag_typedef_t siptag_suppress_body_if_match_ref; /**@ingroup sip_suppress_body_if_match * * Tag list item for string with @ref sip_suppress_body_if_match "Suppress-Body-If-Match header" value. * * The SIPTAG_SUPPRESS_BODY_IF_MATCH_STR() macro is used to include a tag item with a * string containing value of a #sip_suppress_body_if_match_t header in a tag list. * * @param s pointer to a string containing * @ref sip_suppress_body_if_match "Suppress-Body-If-Match header" value, or NULL. * * The string in SIPTAG_SUPPRESS_BODY_IF_MATCH_STR() can be converted to a * #sip_suppress_body_if_match_t header structure by giving the string @a s has * second argument to function sip_suppress_body_if_match_make(). * * The corresponding tag taking reference parameter is * SIPTAG_SUPPRESS_BODY_IF_MATCH_STR_REF(). * * @since New in @EXP_1_12_5. * * @HIDE */ #define SIPTAG_SUPPRESS_BODY_IF_MATCH_STR(s) siptag_suppress_body_if_match_str, tag_str_v(s) SOFIAPUBVAR tag_typedef_t siptag_suppress_body_if_match_str; /**@ingroup sip_suppress_body_if_match * Tag list item for reference to a * @ref sip_suppress_body_if_match "Suppress-Body-If-Match header" string. */ #define SIPTAG_SUPPRESS_BODY_IF_MATCH_STR_REF(x) siptag_suppress_body_if_match_str_ref, tag_str_vr(&(x)) SOFIAPUBVAR tag_typedef_t siptag_suppress_body_if_match_str_ref; #if SU_INLINE_TAG_CAST su_inline tag_value_t siptag_suppress_body_if_match_v(sip_suppress_body_if_match_t const *v) { return (tag_value_t)v; } su_inline tag_value_t siptag_suppress_body_if_match_vr(sip_suppress_body_if_match_t const **vp) { return (tag_value_t)vp; } #else #define siptag_suppress_body_if_match_v(v) (tag_value_t)(v) #define siptag_suppress_body_if_match_vr(vp) (tag_value_t)(vp) #endif #endif /* SU_HAVE_EXPERIMENTAL */ #if SU_HAVE_EXPERIMENTAL /** Defined as 1 if the @ref sip_suppress_notify_if_match "Suppress-Notify-If-Match header" is supported */ #define SIP_HAVE_SUPPRESS_NOTIFY_IF_MATCH 1 enum { /**@ingroup sip_suppress_notify_if_match @internal * * Hash of @ref sip_suppress_notify_if_match "Suppress-Notify-If-Match header". * * @since New in @EXP_1_12_5. */ sip_suppress_notify_if_match_hash = 51341 }; /**Header class for @ref sip_suppress_notify_if_match "Suppress-Notify-If-Match header". * * The header class sip_suppress_notify_if_match_class defines how a SIP * @ref sip_suppress_notify_if_match "Suppress-Notify-If-Match header" is parsed and printed. * It also contains methods used by SIP parser and other functions to * manipulate the #sip_suppress_notify_if_match_t header structure. * * @ingroup sip_suppress_notify_if_match * * @since New in @EXP_1_12_5. */ SIP_DLL extern msg_hclass_t sip_suppress_notify_if_match_class[]; /**@addtogroup sip_suppress_notify_if_match * @{ */ /** Parse a SIP @ref sip_suppress_notify_if_match "Suppress-Notify-If-Match header". @internal */ SOFIAPUBFUN issize_t sip_suppress_notify_if_match_d(su_home_t *, msg_header_t *, char *s, isize_t slen); /** Print a SIP @ref sip_suppress_notify_if_match "Suppress-Notify-If-Match header". @internal */ SOFIAPUBFUN issize_t sip_suppress_notify_if_match_e(char b[], isize_t bsiz, msg_header_t const *h, int flags); /**Access a SIP @ref sip_suppress_notify_if_match "Suppress-Notify-If-Match header" * structure #sip_suppress_notify_if_match_t from #sip_t. * * @since New in @EXP_1_12_5. */ #define sip_suppress_notify_if_match(sip) \ ((sip_suppress_notify_if_match_t *)msg_header_access((msg_pub_t*)(sip), sip_suppress_notify_if_match_class)) /**Initializer for structure #sip_suppress_notify_if_match_t. * * A static #sip_suppress_notify_if_match_t structure for * @ref sip_suppress_notify_if_match "Suppress-Notify-If-Match header" must be initialized with * the SIP_SUPPRESS_NOTIFY_IF_MATCH_INIT() macro. * For instance, * @code * * sip_suppress_notify_if_match_t sip_suppress_notify_if_match = SIP_SUPPRESS_NOTIFY_IF_MATCH_INIT; * * @endcode * @HI * * @since New in @EXP_1_12_5. */ #define SIP_SUPPRESS_NOTIFY_IF_MATCH_INIT() SIP_HDR_INIT(suppress_notify_if_match) /**Initialize a structure #sip_suppress_notify_if_match_t. * * An #sip_suppress_notify_if_match_t structure for * @ref sip_suppress_notify_if_match "Suppress-Notify-If-Match header" can be initialized with the * sip_suppress_notify_if_match_init() function/macro. For instance, * @code * * sip_suppress_notify_if_match_t sip_suppress_notify_if_match; * * sip_suppress_notify_if_match_init(&sip_suppress_notify_if_match); * * @endcode * @HI * * @since New in @EXP_1_12_5. */ #if SU_HAVE_INLINE su_inline sip_suppress_notify_if_match_t *sip_suppress_notify_if_match_init(sip_suppress_notify_if_match_t x[1]) { return SIP_HEADER_INIT(x, sip_suppress_notify_if_match_class, sizeof(sip_suppress_notify_if_match_t)); } #else #define sip_suppress_notify_if_match_init(x) \ SIP_HEADER_INIT(x, sip_suppress_notify_if_match_class, sizeof(sip_suppress_notify_if_match_t)) #endif /**Test if header object is instance of #sip_suppress_notify_if_match_t. * * Check if the header class is an instance of * @ref sip_suppress_notify_if_match "Suppress-Notify-If-Match header" object and return true (nonzero), * otherwise return false (zero). * * @param header pointer to the header structure to be tested * * @retval 1 (true) if the @a header is an instance of header suppress_notify_if_match * @retval 0 (false) otherwise * * @since New in @EXP_1_12_5. */ #if SU_HAVE_INLINE su_inline int sip_is_suppress_notify_if_match(sip_header_t const *header) { return header && header->sh_class->hc_hash == sip_suppress_notify_if_match_hash; } #else int sip_is_suppress_notify_if_match(sip_header_t const *header); #endif #define sip_suppress_notify_if_match_p(h) sip_is_suppress_notify_if_match((h)) /**Duplicate a list of @ref sip_suppress_notify_if_match "Suppress-Notify-If-Match header" header structures #sip_suppress_notify_if_match_t. * * Duplicate a header * structure @a hdr. If the header structure @a hdr * contains a reference (@c hdr->x_next) to a list of * headers, all the headers in the list are duplicated, too. * * @param home memory home used to allocate new structure * @param hdr header structure to be duplicated * * When duplicating, all parameter lists and non-constant * strings attached to the header are copied, too. The * function uses given memory @a home to allocate all the * memory areas used to copy the header. * * @par Example * @code * * suppress_notify_if_match = sip_suppress_notify_if_match_dup(home, sip->sip_suppress_notify_if_match); * * @endcode * * @return * A pointer to the * newly duplicated #sip_suppress_notify_if_match_t header structure, or NULL * upon an error. * * @since New in @EXP_1_12_5. */ #if SU_HAVE_INLINE su_inline #endif sip_suppress_notify_if_match_t *sip_suppress_notify_if_match_dup(su_home_t *home, sip_suppress_notify_if_match_t const *hdr) __attribute__((__malloc__)); #if SU_HAVE_INLINE su_inline sip_suppress_notify_if_match_t *sip_suppress_notify_if_match_dup(su_home_t *home, sip_suppress_notify_if_match_t const *hdr) { return (sip_suppress_notify_if_match_t *) msg_header_dup_as(home, sip_suppress_notify_if_match_class, (msg_header_t const *)hdr); } #endif /**Copy a list of @ref sip_suppress_notify_if_match "Suppress-Notify-If-Match header" header structures #sip_suppress_notify_if_match_t. * * The function sip_suppress_notify_if_match_copy() copies a header structure @a * hdr. If the header structure @a hdr contains a reference (@c * hdr->h_next) to a list of headers, all the headers in that * list are copied, too. The function uses given memory @a home * to allocate all the memory areas used to copy the list of header * structure @a hdr. * * @param home memory home used to allocate new structure * @param hdr pointer to the header structure to be copied * * When copying, only the header structure and parameter lists attached to * it are duplicated. The new header structure retains all the references to * the strings within the old @a hdr header, including the encoding of the * old header, if present. * * @par Example * @code * * suppress_notify_if_match = sip_suppress_notify_if_match_copy(home, sip->sip_suppress_notify_if_match); * * @endcode * * @return * A pointer to newly copied header structure, or NULL upon an error. * * @since New in @EXP_1_12_5. */ #if SU_HAVE_INLINE su_inline #endif sip_suppress_notify_if_match_t *sip_suppress_notify_if_match_copy(su_home_t *home, sip_suppress_notify_if_match_t const *hdr) __attribute__((__malloc__)); #if SU_HAVE_INLINE su_inline sip_suppress_notify_if_match_t *sip_suppress_notify_if_match_copy(su_home_t *home, sip_suppress_notify_if_match_t const *hdr) { return (sip_suppress_notify_if_match_t *) msg_header_copy_as(home, sip_suppress_notify_if_match_class, (msg_header_t const *)hdr); } #endif /**Make a @ref sip_suppress_notify_if_match "Suppress-Notify-If-Match header" structure #sip_suppress_notify_if_match_t. * * The function sip_suppress_notify_if_match_make() makes a new * #sip_suppress_notify_if_match_t header structure. It allocates a new * header structure, and decodes the string @a s as the * value of the structure. * * @param home memory home used to allocate new header structure. * @param s string to be decoded as value of the new header structure * * @return * A pointer to newly maked #sip_suppress_notify_if_match_t header structure, or NULL upon an * error. * * @since New in @EXP_1_12_5. */ #if SU_HAVE_INLINE su_inline #endif sip_suppress_notify_if_match_t *sip_suppress_notify_if_match_make(su_home_t *home, char const *s) __attribute__((__malloc__)); #if SU_HAVE_INLINE su_inline sip_suppress_notify_if_match_t *sip_suppress_notify_if_match_make(su_home_t *home, char const *s) { return (sip_suppress_notify_if_match_t *)sip_header_make(home, sip_suppress_notify_if_match_class, s); } #endif /**Make a @ref sip_suppress_notify_if_match "Suppress-Notify-If-Match header" from formatting result. * * Make a new #sip_suppress_notify_if_match_t object using formatting result as its value. * The function first prints the arguments according to the format @a fmt * specified. Then it allocates a new header structure, and parses the * formatting result to the structure #sip_suppress_notify_if_match_t. * * @param home memory home used to allocate new header structure. * @param fmt string used as a printf()-style format * @param ... argument list for format * * @return * A pointer to newly * makes header structure, or NULL upon an error. * * @HIDE * * @since New in @EXP_1_12_5. */ #if SU_HAVE_INLINE su_inline #endif sip_suppress_notify_if_match_t *sip_suppress_notify_if_match_format(su_home_t *home, char const *fmt, ...) __attribute__((__malloc__, __format__ (printf, 2, 3))); #if SU_HAVE_INLINE su_inline sip_suppress_notify_if_match_t *sip_suppress_notify_if_match_format(su_home_t *home, char const *fmt, ...) { sip_header_t *h; va_list ap; va_start(ap, fmt); h = sip_header_vformat(home, sip_suppress_notify_if_match_class, fmt, ap); va_end(ap); return (sip_suppress_notify_if_match_t *)h; } #endif /** @} */ /**@ingroup sip_suppress_notify_if_match * * Tag list item for pointer to a @ref sip_suppress_notify_if_match "Suppress-Notify-If-Match header" * structure #sip_suppress_notify_if_match_t. * * The SIPTAG_SUPPRESS_NOTIFY_IF_MATCH() macro is used to include a tag item with a * pointer to a #sip_suppress_notify_if_match_t structure in a tag list. * * @param x pointer to a #sip_suppress_notify_if_match_t structure, or NULL. * * The corresponding tag taking reference parameter is * SIPTAG_SUPPRESS_NOTIFY_IF_MATCH_REF(). * * @since New in @EXP_1_12_5. * * @HIDE */ #define SIPTAG_SUPPRESS_NOTIFY_IF_MATCH(x) siptag_suppress_notify_if_match, siptag_suppress_notify_if_match_v(x) SOFIAPUBVAR tag_typedef_t siptag_suppress_notify_if_match; /**@ingroup sip_suppress_notify_if_match * Tag list item for reference to a * @ref sip_suppress_notify_if_match "Suppress-Notify-If-Match header" pointer. */ #define SIPTAG_SUPPRESS_NOTIFY_IF_MATCH_REF(x) siptag_suppress_notify_if_match_ref, siptag_suppress_notify_if_match_vr(&(x)) SOFIAPUBVAR tag_typedef_t siptag_suppress_notify_if_match_ref; /**@ingroup sip_suppress_notify_if_match * * Tag list item for string with @ref sip_suppress_notify_if_match "Suppress-Notify-If-Match header" value. * * The SIPTAG_SUPPRESS_NOTIFY_IF_MATCH_STR() macro is used to include a tag item with a * string containing value of a #sip_suppress_notify_if_match_t header in a tag list. * * @param s pointer to a string containing * @ref sip_suppress_notify_if_match "Suppress-Notify-If-Match header" value, or NULL. * * The string in SIPTAG_SUPPRESS_NOTIFY_IF_MATCH_STR() can be converted to a * #sip_suppress_notify_if_match_t header structure by giving the string @a s has * second argument to function sip_suppress_notify_if_match_make(). * * The corresponding tag taking reference parameter is * SIPTAG_SUPPRESS_NOTIFY_IF_MATCH_STR_REF(). * * @since New in @EXP_1_12_5. * * @HIDE */ #define SIPTAG_SUPPRESS_NOTIFY_IF_MATCH_STR(s) siptag_suppress_notify_if_match_str, tag_str_v(s) SOFIAPUBVAR tag_typedef_t siptag_suppress_notify_if_match_str; /**@ingroup sip_suppress_notify_if_match * Tag list item for reference to a * @ref sip_suppress_notify_if_match "Suppress-Notify-If-Match header" string. */ #define SIPTAG_SUPPRESS_NOTIFY_IF_MATCH_STR_REF(x) siptag_suppress_notify_if_match_str_ref, tag_str_vr(&(x)) SOFIAPUBVAR tag_typedef_t siptag_suppress_notify_if_match_str_ref; #if SU_INLINE_TAG_CAST su_inline tag_value_t siptag_suppress_notify_if_match_v(sip_suppress_notify_if_match_t const *v) { return (tag_value_t)v; } su_inline tag_value_t siptag_suppress_notify_if_match_vr(sip_suppress_notify_if_match_t const **vp) { return (tag_value_t)vp; } #else #define siptag_suppress_notify_if_match_v(v) (tag_value_t)(v) #define siptag_suppress_notify_if_match_vr(vp) (tag_value_t)(vp) #endif #endif /* SU_HAVE_EXPERIMENTAL */ SOFIA_END_DECLS #endif /** !defined(SIP_EXTRA_H) */
31.593676
141
0.757857
[ "object" ]
fc1ac5731b251f9f74e9a2870a0c3f6d3c8df412
326
h
C
kernel/include/arch/arm/arch/kernel/thread.h
Nexusoft/LLL-OS
7b0ad5afb339e9bebc65142ee89bded5344cedbe
[ "BSD-2-Clause" ]
4
2020-08-07T19:48:01.000Z
2020-10-16T20:05:17.000Z
kernel/include/arch/arm/arch/kernel/thread.h
Nexusoft/LX-OS
7b0ad5afb339e9bebc65142ee89bded5344cedbe
[ "BSD-2-Clause" ]
null
null
null
kernel/include/arch/arm/arch/kernel/thread.h
Nexusoft/LX-OS
7b0ad5afb339e9bebc65142ee89bded5344cedbe
[ "BSD-2-Clause" ]
2
2020-08-13T01:48:40.000Z
2020-09-17T07:34:42.000Z
/* * Copyright 2014, General Dynamics C4 Systems * * SPDX-License-Identifier: GPL-2.0-only */ #pragma once #include <object.h> #include <mode/kernel/thread.h> void Arch_switchToThread(tcb_t *tcb); void Arch_switchToIdleThread(void); void Arch_configureIdleThread(tcb_t *tcb); void Arch_activateIdleThread(tcb_t *tcb);
19.176471
46
0.760736
[ "object" ]
fc21fa1d01553591c4f12a209149f976c4b7d0b6
4,284
h
C
rlButton/rlButton.h
OkiStuff/rl_singleHeaders
33ff2332ef2ea198a7da519af541941415bfe547
[ "MIT" ]
null
null
null
rlButton/rlButton.h
OkiStuff/rl_singleHeaders
33ff2332ef2ea198a7da519af541941415bfe547
[ "MIT" ]
null
null
null
rlButton/rlButton.h
OkiStuff/rl_singleHeaders
33ff2332ef2ea198a7da519af541941415bfe547
[ "MIT" ]
null
null
null
/* MIT License Copyright (c) 2021 OkiStuff 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. Developed By Okistuff Requires Raylib This is a single-header library that handles button collision and some basic rendering Example: https://github.com/OkiStuff/rl_singleHeaders/tree/main/rlButton */ #pragma once #include "raylib.h" // Rendering Framework #include <stdbool.h> // Required for bool, //(??, sometimes its not needed but sometimes bools wont work without it. its weird, lets just include to be safe) #define RL_BUTTON_MOUSE_COLLIDER_SIZE_DEFAULT 60 // Defining // Mouse collison typedef Rectangle rlMouseCollider; // Button Object typedef struct rlButton { Rectangle box; char *buttonText; } rlButton; /* Create a mouse collider set width & height to 0 or RL_BUTTON_MOUSE_COLLIDER_SIZE_DEFAULT if you want to use the default collider size (60,60) */ rlMouseCollider NewMouseCollider(int width, int height); // Updates the mouse collider rlMouseCollider UpdateMouseCollider(rlMouseCollider collider); /* Returns true if the passed rlButton has been pressed by the passed rlMouseCollider else, returns false */ bool IsButtonPressed(rlButton button, rlMouseCollider collider); /* Returns true if the passed rlButton is being hovered over by the passed rlMouseCollider else, returns false */ bool IsButtonHovered(rlButton button, rlMouseCollider collider); /* Renders the passed rlButton with text, only use this if you arent going to be using the button with a sprite or rendering it a different way*/ void DrawButton(rlButton button, int fontSize, Color tint); // Render the collison boxes of passed rlButton void rlButtonDrawDebug(rlButton button); // Render the collison boxes of passed rlMouseCollider void rlMouseColliderDrawDebug(rlMouseCollider collider); // Implemention rlMouseCollider NewMouseCollider(int width, int height) { rlMouseCollider temp; // Initalize the box that is rendered if rlButtonDebugMode is enabled if (width == 0 && height == 0) { temp.x = 0; temp.y = 0; temp.width = 60; temp.height = 60; } else { temp.x = 0; temp.y = 0; temp.width = width; temp.height = height; } return temp; } rlMouseCollider UpdateMouseCollider(rlMouseCollider collider) { collider.x = GetMouseX() - collider.width/2; collider.y = GetMouseY() - collider.height/2; return collider; } bool IsButtonPressed(rlButton button, rlMouseCollider collider) { if (CheckCollisionRecs(button.box, collider) && IsMouseButtonDown(MOUSE_LEFT_BUTTON)) return true; return false; } bool IsButtonHovered(rlButton button, rlMouseCollider collider) { // Check if mouse collider is colliding and the mouse is not being pressed if (CheckCollisionRecs(button.box, collider) && !IsMouseButtonDown(MOUSE_LEFT_BUTTON)) return true; return false; } void DrawButton(rlButton button, int fontSize, Color tint) { DrawText(button.buttonText, button.box.x, button.box.y, fontSize, tint); } void rlButtonDrawDebug(rlButton button) { DrawRectangle(button.box.x, button.box.y, button.box.width, button.box.height, YELLOW); } void rlMouseColliderDrawDebug(rlMouseCollider collider) { DrawRectangle(collider.x, collider.y, collider.width, collider.height, BLUE); }
32.454545
117
0.761438
[ "render", "object" ]
fc2350127f0176de726ab315548d979876178e07
2,592
c
C
externals/mpir-3.0.0/tests/mpz/t-sizeinbase.c
JaminChan/eos_win
c03e57151cfe152d0d3120abb13226f4df74f37e
[ "MIT" ]
12
2021-09-29T14:50:06.000Z
2022-03-31T15:01:21.000Z
externals/mpir-3.0.0/tests/mpz/t-sizeinbase.c
JaminChan/eos_win
c03e57151cfe152d0d3120abb13226f4df74f37e
[ "MIT" ]
15
2021-12-24T22:53:49.000Z
2021-12-25T10:03:13.000Z
LibSource/mpir/tests/mpz/t-sizeinbase.c
ekzyis/CrypTool-2
1af234b4f74486fbfeb3b3c49228cc36533a8c89
[ "Apache-2.0" ]
10
2021-10-17T19:46:51.000Z
2022-03-18T02:57:57.000Z
/* Test mpz_sizeinbase. Copyright 2001, 2002 Free Software Foundation, Inc. This file is part of the GNU MP Library. The GNU MP Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU MP Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU MP Library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <stdio.h> #include <stdlib.h> #include "mpir.h" #include "gmp-impl.h" #include "tests.h" #if 0 /* Disabled due to the bogosity of trying to fake an _mp_d pointer to below an object. Has been seen to fail on a hppa system and on ia64. */ /* Create a fake mpz consisting of just a single 1 bit, with totbits being the total number of bits, inclusive of that 1 bit. */ void mpz_fake_bits (mpz_ptr z, unsigned long totbits) { static mp_limb_t n; unsigned long zero_bits, zero_limbs; zero_bits = totbits - 1; zero_limbs = zero_bits / GMP_NUMB_BITS; zero_bits %= GMP_NUMB_BITS; SIZ(z) = zero_limbs + 1; PTR(z) = (&n) - (SIZ(z) - 1); n = CNST_LIMB(1) << zero_bits; ASSERT_ALWAYS (mpz_sizeinbase (z, 2) == totbits); } /* This was seen to fail on a GNU/Linux powerpc32 with gcc 2.95.2, apparently due to a doubtful value of mp_bases[10].chars_per_bit_exactly (0X1.34413509F79FDP-2 whereas 0X1.34413509F79FFP-2 is believed correct). Presumably this is a glibc problem when gcc converts the decimal string in mp_bases.c, or maybe it's only a function of the rounding mode during compilation. */ void check_sample (void) { unsigned long totbits = 198096465; int base = 10; size_t want = 59632979; size_t got; mpz_t z; mpz_fake_bits (z, totbits); got = mpz_sizeinbase (z, base); if (got != want) { printf ("mpz_sizeinbase\n"); printf (" base %d\n", base); printf (" totbits %lu\n", totbits); printf (" got %u\n", got); printf (" want %u\n", want); abort (); } } #endif int main (void) { tests_start (); /* check_sample (); */ tests_end (); exit (0); }
27.870968
78
0.689815
[ "object" ]