repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
shirobusa1997/UE-PhotonSandbox
Source/photon-import.h
<reponame>shirobusa1997/UE-PhotonSandbox #pragma once #ifdef __clang__ #pragma clang diagnostic ignored "-Woverloaded-virtual" #endif #if _EG_WINDOWS_PLATFORM #include "AllowWindowsPlatformTypes.h" #pragma warning (disable: 4263) #pragma warning (disable: 4264) #endif #include "LoadBalancing-cpp/inc/Client.h" #if _EG_WINDOWS_PLATFORM #pragma warning (default: 4263) #pragma warning (default: 4264) #include "HideWindowsPlatformTypes.h" #endif
shirobusa1997/UE-PhotonSandbox
Source/Photon/Common-cpp/inc/Common.h
<filename>Source/Photon/Common-cpp/inc/Common.h<gh_stars>0 /* Exit Games Common - C++ Client Lib * Copyright (C) 2004-2020 by Exit Games GmbH. All rights reserved. * http://www.photonengine.com * mailto:<EMAIL> */ #pragma once #include "Common-cpp/inc/porting.h" #include "Common-cpp/inc/platformLayer.h" #include "Common-cpp/inc/Dictionary.h" #include "Common-cpp/inc/ANSIString.h" #include "Common-cpp/inc/EGTime.h" #include "Common-cpp/inc/Serializer.h" #include "Common-cpp/inc/DeSerializer.h" #include "Common-cpp/inc/Helpers/EnableIf.h" #include "Common-cpp/inc/Helpers/Lockguard.h" #include "Common-cpp/inc/Helpers/SmartPointers/SharedPointer.h" #include "Common-cpp/inc/Helpers/SmartPointers/UniquePointer.h" /** @file */
shirobusa1997/UE-PhotonSandbox
Source/Photon/Photon-cpp/inc/TrafficStatsGameLevel.h
<gh_stars>0 /* Exit Games Photon - C++ Client Lib * Copyright (C) 2004-2020 by Exit Games GmbH. All rights reserved. * http://www.photonengine.com * mailto:<EMAIL> */ #pragma once #include "Common-cpp/inc/Common.h" namespace ExitGames { namespace Photon { class TrafficStatsGameLevel : public Common::Base { public: using Common::ToString::toString; virtual ~TrafficStatsGameLevel(void); int getOperationByteCount(void) const; int getOperationCount(void) const; int getResultByteCount(void) const; int getResultCount(void) const; int getEventByteCount(void) const; int getEventCount(void) const; int getLongestOpResponseCallback(void) const; nByte getLongestOpResponseCallbackOpCode(void) const; int getLongestEventCallback(void) const; nByte getLongestEventCallbackCode(void) const; int getLongestDeltaBetweenDispatching(void) const; int getLongestDeltaBetweenSending(void) const; int getDispatchIncomingCommandsCalls(void) const; int getSendOutgoingCommandsCalls(void) const; int getTotalByteCount(void) const; int getTotalMessageCount(void) const; int getTotalIncomingByteCount(void) const; int getTotalIncomingMessageCount(void) const; int getTotalOutgoingByteCount(void) const; int getTotalOutgoingMessageCount(void) const; void resetMaximumCounters(void); // use PhotonPeer::resetTrafficStatsMaximumCounters() to call this on peer's stats virtual Common::JString& toString(Common::JString& retStr, bool withTypes=false) const; virtual Common::JString toStringVitalStats(void) const; protected: TrafficStatsGameLevel(void); int mTimeOfLastDispatchCall; int mTimeOfLastSendCall; int mOperationByteCount; int mOperationCount; int mResultByteCount; int mResultCount; int mEventByteCount; int mEventCount; int mLongestOpResponseCallback; nByte mLongestOpResponseCallbackOpCode; int mLongestEventCallback;; nByte mLongestEventCallbackCode; int mLongestDeltaBetweenDispatching; int mLongestDeltaBetweenSending; int mDispatchIncomingCommandsCalls; int mSendOutgoingCommandsCalls; }; } }
shirobusa1997/UE-PhotonSandbox
Source/Photon/LoadBalancing-cpp/inc/Internal/Enums/Properties/Player.h
/* Exit Games Photon LoadBalancing - C++ Client Lib * Copyright (C) 2004-2020 by Exit Games GmbH. All rights reserved. * http://www.photonengine.com * mailto:<EMAIL> */ #pragma once #include "Photon-cpp/inc/PhotonPeer.h" namespace ExitGames { namespace LoadBalancing { namespace Internal { // Photon properties, internally set by LoadBalancing (LoadBalancing builtin properties) namespace Properties { namespace Player { /// (255) Name of a player/actor. static const nByte PLAYERNAME = 255; /// (254) Tells you if the player is currently in this game (getting events live). /// A server-set value for async games, where players can leave the game and return later. static const nByte IS_INACTIVE = 254; static const nByte USER_ID = 253; } } } } }
shirobusa1997/UE-PhotonSandbox
Source/PhotonSandbox/PhotonAPI2UE4/PA2U_BaseView.h
#pragma once #include "Common-cpp/inc/Common.h" class PA2U_BaseView { public: virtual void updateState(int state, const ExitGames::Common::JString& stateStr, const ExitGames::JString& joinedRoomName); virtual void initPlayers(void); virtual void addPlayer(int playerNumber, const ExitGames::Common::JString& playerName, bool isLocal); virtual void removePlayer(int playerNumber); virtual void changePlayerTransform(int playerNumber, double Pos_x, double Pos_y, double Pos_z); virtual void setupScene(); virtual void updateRoomList(const ExitGames::Common::JVector<ExitGames::Common::JString>& roomNames); };
shirobusa1997/UE-PhotonSandbox
Source/Photon/LoadBalancing-cpp/inc/Peer.h
/* Exit Games Photon LoadBalancing - C++ Client Lib * Copyright (C) 2004-2020 by Exit Games GmbH. All rights reserved. * http://www.photonengine.com * mailto:<EMAIL> */ #pragma once #include "Photon-cpp/inc/PhotonPeer.h" #include "LoadBalancing-cpp/inc/Enums/MatchmakingMode.h" #include "LoadBalancing-cpp/inc/LobbyStatsRequest.h" #include "LoadBalancing-cpp/inc/AuthenticationValues.h" #include "LoadBalancing-cpp/inc/RaiseEventOptions.h" #include "LoadBalancing-cpp/inc/RoomOptions.h" namespace ExitGames { namespace LoadBalancing { class Peer : public Photon::PhotonPeer { public: Peer(Photon::PhotonListener& listener, nByte connectionProtocol=Photon::ConnectionProtocol::DEFAULT); virtual ~Peer(void); #if defined EG_DOC virtual void disconnect(void); #endif virtual bool opJoinLobby(const Common::JString& lobbyName=Common::JString(), nByte lobbyType=LobbyType::DEFAULT); virtual bool opLeaveLobby(void); virtual bool opCreateRoom(const Common::JString& gameID=Common::JString(), const RoomOptions& options=RoomOptions(), const Common::Hashtable& customLocalPlayerProperties=Common::Hashtable(), const Common::JVector<Common::JString>& expectedUsers=Common::JVector<Common::JString>()); virtual bool opJoinRoom(const Common::JString& gameID, const RoomOptions& options=RoomOptions(), const Common::Hashtable& customLocalPlayerProperties=Common::Hashtable(), bool createIfNotExists=false, bool rejoin=false, int cacheSliceIndex=0, const Common::JVector<Common::JString>& expectedUsers=Common::JVector<Common::JString>()); virtual bool opJoinRandomRoom(const Common::JString& gameID=Common::JString(), const RoomOptions& options=RoomOptions(), bool createIfNotExists=false, const Common::Hashtable& customRoomProperties=Common::Hashtable(), nByte maxPlayers=0, nByte matchmakingMode=MatchmakingMode::FILL_ROOM, const Common::JString& lobbyName=Common::JString(), nByte lobbyType=LobbyType::DEFAULT, const Common::JString& sqlLobbyFilter=Common::JString(), const Common::JVector<Common::JString>& expectedUsers=Common::JVector<Common::JString>()); virtual bool opLeaveRoom(bool willComeBack=false, bool sendAuthCookie=false); template<typename Ftype> bool opRaiseEvent(bool reliable, const Ftype& parameters, nByte eventCode, const RaiseEventOptions& options=RaiseEventOptions()); template<typename Ftype> bool opRaiseEvent(bool reliable, const Ftype pParameterArray, typename Common::Helpers::ArrayLengthType<Ftype>::type arrSize, nByte eventCode, const RaiseEventOptions& options=RaiseEventOptions()); template<typename Ftype> bool opRaiseEvent(bool reliable, const Ftype pParameterArray, const short* pArrSizes, nByte eventCode, const RaiseEventOptions& options=RaiseEventOptions()); virtual bool opAuthenticate(const Common::JString& appID, const Common::JString& appVersion, bool encrypted, const AuthenticationValues& authenticationValues=AuthenticationValues(), bool lobbyStats=false, const Common::JString& regionCode=Common::JString()); virtual bool opAuthenticateOnce(const Common::JString& appID, const Common::JString& appVersion, nByte connectionProtocol, nByte encryptionMode, const AuthenticationValues& authenticationValues=AuthenticationValues(), bool lobbyStats=false, const Common::JString& regionCode=Common::JString()); virtual bool opFindFriends(const Common::JString* friendsToFind, short numFriendsToFind); virtual bool opLobbyStats(const Common::JVector<LoadBalancing::LobbyStatsRequest>& lobbiesToQuery=Common::JVector<LoadBalancing::LobbyStatsRequest>()); virtual bool opChangeGroups(const Common::JVector<nByte>* pGroupsToRemove, const Common::JVector<nByte>* pGroupsToAdd); virtual bool opWebRpc(const Common::JString& uriPath); template<typename Ftype> bool opWebRpc(const Common::JString& uriPath, const Ftype& parameters, bool sendAuthCookie=false); template<typename Ftype> bool opWebRpc(const Common::JString& uriPath, const Ftype pParameterArray, typename Common::Helpers::ArrayLengthType<Ftype>::type arrSize, bool sendAuthCookie=false); template<typename Ftype> bool opWebRpc(const Common::JString& uriPath, const Ftype pParameterArray, const short* pArrSizes, bool sendAuthCookie=false); virtual bool opGetRoomList(const Common::JString& lobby, const Common::JString& sqlLobbyFilter); virtual bool opGetRegions(bool encrypted, const Common::JString& appID); virtual bool opSetPropertiesOfPlayer(int playerNr, const Common::Hashtable& properties, const Common::Hashtable& expectedProperties=Common::Hashtable(), WebFlags webFlags=WebFlags()); virtual bool opSetPropertiesOfRoom(const Common::Hashtable& properties, const Common::Hashtable& expectedProperties=Common::Hashtable(), WebFlags webFlags=WebFlags()); private: Photon::OperationRequestParameters opCreateRoomImplementation(const Common::JString& gameID, const RoomOptions& options, const Common::Hashtable& customLocalPlayerProperties, const Common::JVector<Common::JString>& expectedUsers); Photon::OperationRequestParameters opJoinRoomImplementation(const Common::JString& gameID, const RoomOptions& options, const Common::Hashtable& customLocalPlayerProperties, bool createIfNotExists, bool rejoin, int cacheSliceIndex, const Common::JVector<Common::JString>& expectedUsers); Photon::OperationRequestParameters opJoinRandomRoomImplementation(const Common::JString& gameID, const RoomOptions& options, bool createIfNotExists, const Common::Hashtable& customRoomProperties, nByte maxPlayers, nByte matchmakingMode, const Common::JString& lobbyName, nByte lobbyType, const Common::JString& sqlLobbyFilter, const Common::JVector<Common::JString>& expectedUsers); Photon::OperationRequestParameters enterRoomImplementation(const RoomOptions* pOptions, const Common::Hashtable& customLocalPlayerProperties, const Common::JVector<Common::JString>& expectedUsers); #ifndef EG_NO_CPP11 // workaround for a weird compiler bug in Clang when building against libstdc++ in C++98 mode virtual #endif bool opRaiseEvent(bool reliable, const Common::Object& parameters, nByte eventCode, const RaiseEventOptions& options); virtual bool opWebRpc(const Common::JString& uriPath, const Common::Object& parameters, bool sendAuthCookie); typedef PhotonPeer super; friend class Client; }; template<typename Ftype> bool Peer::opRaiseEvent(bool reliable, const Ftype& parameters, nByte eventCode, const RaiseEventOptions& options) { COMPILE_TIME_ASSERT2_TRUE_MSG(!Common::Helpers::ConfirmAllowed<Ftype>::dimensions, ERROR_THIS_OVERLOAD_IS_ONLY_FOR_SINGLE_VALUES); return opRaiseEvent(reliable, Common::Helpers::ValueToObject::get(parameters), eventCode, options); } template<typename Ftype> bool Peer::opRaiseEvent(bool reliable, const Ftype pParameterArray, typename Common::Helpers::ArrayLengthType<Ftype>::type arrSize, nByte eventCode, const RaiseEventOptions& options) { COMPILE_TIME_ASSERT2_TRUE_MSG(Common::Helpers::ConfirmAllowed<Ftype>::dimensions==1, ERROR_THIS_OVERLOAD_IS_ONLY_FOR_1D_ARRAYS); return opRaiseEvent(reliable, Common::Helpers::ValueToObject::get(pParameterArray, arrSize), eventCode, options); } template<typename Ftype> bool Peer::opRaiseEvent(bool reliable, const Ftype pParameterArray, const short* pArrSizes, nByte eventCode, const RaiseEventOptions& options) { COMPILE_TIME_ASSERT2_TRUE_MSG((Common::Helpers::ConfirmAllowed<Ftype>::dimensions>1), ERROR_THIS_OVERLOAD_IS_ONLY_FOR_MULTIDIMENSIONAL_ARRAYS); return opRaiseEvent(reliable, Common::Helpers::ValueToObject::get(pParameterArray, pArrSizes), eventCode, options); } template<typename Ftype> bool Peer::opWebRpc(const Common::JString& uriPath, const Ftype& parameters, bool sendAuthCookie) { COMPILE_TIME_ASSERT2_TRUE_MSG(!Common::Helpers::ConfirmAllowed<Ftype>::dimensions, ERROR_THIS_OVERLOAD_IS_ONLY_FOR_SINGLE_VALUES); return opWebRpc(uriPath, Common::Helpers::ValueToObject::get(parameters), sendAuthCookie); } template<typename Ftype> bool Peer::opWebRpc(const Common::JString& uriPath, const Ftype pParameterArray, typename Common::Helpers::ArrayLengthType<Ftype>::type arrSize, bool sendAuthCookie) { COMPILE_TIME_ASSERT2_TRUE_MSG(Common::Helpers::ConfirmAllowed<Ftype>::dimensions==1, ERROR_THIS_OVERLOAD_IS_ONLY_FOR_1D_ARRAYS); return opWebRpc(uriPath, Common::Helpers::ValueToObject::get(pParameterArray, arrSize), sendAuthCookie); } template<typename Ftype> bool Peer::opWebRpc(const Common::JString& uriPath, const Ftype pParameterArray, const short* pArrSizes, bool sendAuthCookie) { COMPILE_TIME_ASSERT2_TRUE_MSG((Common::Helpers::ConfirmAllowed<Ftype>::dimensions>1), ERROR_THIS_OVERLOAD_IS_ONLY_FOR_MULTIDIMENSIONAL_ARRAYS); return opWebRpc(uriPath, Common::Helpers::ValueToObject::get(pParameterArray, pArrSizes), sendAuthCookie); } } }
gme/three20
samples/TTCatalog/Classes/StyledTextTableTestController.h
<reponame>gme/three20 #import <Three20/Three20.h> @interface StyledTextTableTestController : TTTableViewController { } @end
gme/three20
src/Three20/TTAppearance.h
<reponame>gme/three20<filename>src/Three20/TTAppearance.h #import "Three20/TTGlobal.h" typedef enum { TTStyleNone, TTStyleFill, TTStyleFillInverted, TTStyleReflection, TTStyleInnerShadow, TTStyleRoundInnerShadow, TTStyleStrokeTop, TTStyleStrokeRight, TTStyleStrokeBottom, TTStyleStrokeLeft } TTStyle; #define TT_RADIUS_ROUNDED NSIntegerMax /** * TTAppearance is a singleton which holds all of the standard visual styles used by various views. * * When you'd like to "skin" your app by changing some of the colors and styles that are used * by standard Three20 components, you can just modify the properties of TTAppearance. */ @interface TTAppearance : NSObject { UIColor* _navigationBarTintColor; UIColor* _toolbarTintColor; UIColor* _searchBarTintColor; UIColor* _linkTextColor; UIColor* _moreLinkTextColor; UIColor* _tableActivityTextColor; UIColor* _tableErrorTextColor; UIColor* _tableSubTextColor; UIColor* _tableTitleTextColor; UIColor* _placeholderTextColor; UIColor* _searchTableBackgroundColor; UIColor* _searchTableSeparatorColor; UIColor* _tableHeaderTextColor; UIColor* _tableHeaderShadowColor; UIColor* _tableHeaderTintColor; UIImage* _blackButtonImage; UIImage* _textBoxDarkImage; UIImage* _textBoxLightImage; } + (TTAppearance*)appearance; + (void)setAppearance:(TTAppearance*)appearance; /** * Color used for tinting all navigation bars. */ @property(nonatomic,retain) UIColor* navigationBarTintColor; /** * Color used for tinting toolbars. */ @property(nonatomic,retain) UIColor* toolbarTintColor; /** * Color used for tinting search bars. */ @property(nonatomic,retain) UIColor* searchBarTintColor; /** * Color used for hyperlinks. */ @property(nonatomic,retain) UIColor* linkTextColor; /** * Color used for the "load more" links in table views. */ @property(nonatomic,retain) UIColor* moreLinkTextColor; /** * Color used for the text describing errors in a table view. */ @property(nonatomic,retain) UIColor* tableActivityTextColor; /** * Color used for the text describing errors in a table view. */ @property(nonatomic,retain) UIColor* tableErrorTextColor; /** * Color used for subtext in a table view. */ @property(nonatomic,retain) UIColor* tableSubTextColor; /** * Color used for titels (the left side of a titled field cell) in a table view. */ @property(nonatomic,retain) UIColor* tableTitleTextColor; /** * Color used for placeholder text in text fields. */ @property(nonatomic,retain) UIColor* placeholderTextColor; /** * Color used for the background of search result tables. */ @property(nonatomic,retain) UIColor* searchTableBackgroundColor; /** * Color used for the separators in search result tables. */ @property(nonatomic,retain) UIColor* searchTableSeparatorColor; /** * Color used for text in table header views. */ @property(nonatomic,retain) UIColor* tableHeaderTextColor; /** * Color used for text shadow in table header views. */ @property(nonatomic,retain) UIColor* tableHeaderShadowColor; /** * Color used for tinting table header views. */ @property(nonatomic,retain) UIColor* tableHeaderTintColor; /** * Image used for the background of black buttons. */ @property(nonatomic,retain) UIImage* blackButtonImage; /** * Image used for the background of text boxes against a dark background */ @property(nonatomic,retain) UIImage* textBoxDarkImage; /** * Image used for the background of text boxes against a light background */ @property(nonatomic,retain) UIImage* textBoxLightImage; - (void)draw:(TTStyle)background rect:(CGRect)rect fill:(UIColor**)fillColor fillCount:(int)fillCount stroke:(UIColor*)strokeColor radius:(CGFloat)radius; - (void)draw:(TTStyle)background rect:(CGRect)rect fill:(UIColor**)fillColor fillCount:(int)fillCount stroke:(UIColor*)strokeColor thickness:(CGFloat)thickness radius:(CGFloat)radius; - (void)draw:(TTStyle)background rect:(CGRect)rect; - (void)drawLine:(CGPoint)from to:(CGPoint)to color:(UIColor*)color thickness:(CGFloat)thickness; - (void)fill:(CGRect)rect fillColors:(UIColor**)fillColors count:(int)count; - (void)stroke:(UIColor*)strokeColor thickness:(CGFloat)thickness; @end
gme/three20
src/Three20/TTThumbView.h
<gh_stars>1-10 #import "Three20/TTLinkView.h" @class TTImageView; @class TTStyledView; @interface TTThumbView : TTLinkView { TTImageView* imageView; TTStyledView* borderView; } @property(nonatomic,copy) NSString* thumbURL; - (void)suspendLoading:(BOOL)suspended; @end
gme/three20
src/Three20/UIColorAdditions.h
<reponame>gme/three20 #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @interface UIColor (TTCategory) - (UIColor*)transformHue:(CGFloat)hd saturation:(CGFloat)sd value:(CGFloat)vd; /** * Uses transformHue to create a lighter version of the color. */ - (UIColor*)highlight; /** * Uses transformHue to create a darker version of the color. */ - (UIColor*)shadow; - (CGFloat)hue; - (CGFloat)saturation; - (CGFloat)value; @end
therockstorm/openapi-generator
samples/client/petstore/objc/core-data/SwaggerClient/Model/SWGUserManagedObjectBuilder.h
<filename>samples/client/petstore/objc/core-data/SwaggerClient/Model/SWGUserManagedObjectBuilder.h #import <Foundation/Foundation.h> #import <CoreData/CoreData.h> #import "SWGUserManagedObject.h" #import "SWGUser.h" /** * OpenAPI Petstore * This is a sample server Petstore server. For this sample, you can use the api key \"special-key\" to test the authorization filters * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ @interface SWGUserManagedObjectBuilder : NSObject -(SWGUserManagedObject*)createNewSWGUserManagedObjectInContext:(NSManagedObjectContext*)context; -(SWGUserManagedObject*)SWGUserManagedObjectFromSWGUser:(SWGUser*)object context:(NSManagedObjectContext*)context; -(void)updateSWGUserManagedObject:(SWGUserManagedObject*)object withSWGUser:(SWGUser*)object2; -(SWGUser*)SWGUserFromSWGUserManagedObject:(SWGUserManagedObject*)obj; -(void)updateSWGUser:(SWGUser*)object withSWGUserManagedObject:(SWGUserManagedObject*)object2; @end
therockstorm/openapi-generator
samples/client/petstore/objc/core-data/SwaggerClient/Model/SWGInlineObjectManagedObjectBuilder.h
#import <Foundation/Foundation.h> #import <CoreData/CoreData.h> #import "SWGInlineObjectManagedObject.h" #import "SWGInlineObject.h" /** * OpenAPI Petstore * This is a sample server Petstore server. For this sample, you can use the api key \"special-key\" to test the authorization filters * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ @interface SWGInlineObjectManagedObjectBuilder : NSObject -(SWGInlineObjectManagedObject*)createNewSWGInlineObjectManagedObjectInContext:(NSManagedObjectContext*)context; -(SWGInlineObjectManagedObject*)SWGInlineObjectManagedObjectFromSWGInlineObject:(SWGInlineObject*)object context:(NSManagedObjectContext*)context; -(void)updateSWGInlineObjectManagedObject:(SWGInlineObjectManagedObject*)object withSWGInlineObject:(SWGInlineObject*)object2; -(SWGInlineObject*)SWGInlineObjectFromSWGInlineObjectManagedObject:(SWGInlineObjectManagedObject*)obj; -(void)updateSWGInlineObject:(SWGInlineObject*)object withSWGInlineObjectManagedObject:(SWGInlineObjectManagedObject*)object2; @end
therockstorm/openapi-generator
samples/client/petstore/objc/core-data/SwaggerClient/Model/SWGInlineObject1ManagedObjectBuilder.h
#import <Foundation/Foundation.h> #import <CoreData/CoreData.h> #import "SWGInlineObject1ManagedObject.h" #import "SWGInlineObject1.h" /** * OpenAPI Petstore * This is a sample server Petstore server. For this sample, you can use the api key \"special-key\" to test the authorization filters * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ @interface SWGInlineObject1ManagedObjectBuilder : NSObject -(SWGInlineObject1ManagedObject*)createNewSWGInlineObject1ManagedObjectInContext:(NSManagedObjectContext*)context; -(SWGInlineObject1ManagedObject*)SWGInlineObject1ManagedObjectFromSWGInlineObject1:(SWGInlineObject1*)object context:(NSManagedObjectContext*)context; -(void)updateSWGInlineObject1ManagedObject:(SWGInlineObject1ManagedObject*)object withSWGInlineObject1:(SWGInlineObject1*)object2; -(SWGInlineObject1*)SWGInlineObject1FromSWGInlineObject1ManagedObject:(SWGInlineObject1ManagedObject*)obj; -(void)updateSWGInlineObject1:(SWGInlineObject1*)object withSWGInlineObject1ManagedObject:(SWGInlineObject1ManagedObject*)object2; @end
therockstorm/openapi-generator
samples/client/petstore/objc/default/SwaggerClient/Model/SWGInlineObject.h
<gh_stars>1000+ #import <Foundation/Foundation.h> #import "SWGObject.h" /** * OpenAPI Petstore * This is a sample server Petstore server. For this sample, you can use the api key \"special-key\" to test the authorization filters * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ @protocol SWGInlineObject @end @interface SWGInlineObject : SWGObject /* Updated name of the pet [optional] */ @property(nonatomic) NSString* name; /* Updated status of the pet [optional] */ @property(nonatomic) NSString* status; @end
therockstorm/openapi-generator
samples/client/petstore/objc/core-data/SwaggerClient/Model/SWGInlineObjectManagedObject.h
#import <Foundation/Foundation.h> #import <CoreData/CoreData.h> /** * OpenAPI Petstore * This is a sample server Petstore server. For this sample, you can use the api key \"special-key\" to test the authorization filters * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ NS_ASSUME_NONNULL_BEGIN @interface SWGInlineObjectManagedObject : NSManagedObject /* Updated name of the pet [optional] */ @property (nullable, nonatomic, retain) NSString* name; /* Updated status of the pet [optional] */ @property (nullable, nonatomic, retain) NSString* status; @end @interface SWGInlineObjectManagedObject (GeneratedAccessors) @end NS_ASSUME_NONNULL_END
therockstorm/openapi-generator
samples/server/petstore/cpp-qt5-qhttpengine-server/server/src/models/OAIOrder.h
<reponame>therockstorm/openapi-generator<gh_stars>1000+ /** * OpenAPI Petstore * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * * The version of the OpenAPI document: 1.0.0 * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ /* * OAIOrder.h * * An order for a pets from the pet store */ #ifndef OAIOrder_H #define OAIOrder_H #include <QJsonObject> #include <QDateTime> #include <QString> #include "OAIEnum.h" #include "OAIObject.h" namespace OpenAPI { class OAIOrder : public OAIObject { public: OAIOrder(); OAIOrder(QString json); ~OAIOrder() override; QString asJson() const override; QJsonObject asJsonObject() const override; void fromJsonObject(QJsonObject json) override; void fromJson(QString jsonString) override; qint64 getId() const; void setId(const qint64 &id); bool is_id_Set() const; bool is_id_Valid() const; qint64 getPetId() const; void setPetId(const qint64 &pet_id); bool is_pet_id_Set() const; bool is_pet_id_Valid() const; qint32 getQuantity() const; void setQuantity(const qint32 &quantity); bool is_quantity_Set() const; bool is_quantity_Valid() const; QDateTime getShipDate() const; void setShipDate(const QDateTime &ship_date); bool is_ship_date_Set() const; bool is_ship_date_Valid() const; QString getStatus() const; void setStatus(const QString &status); bool is_status_Set() const; bool is_status_Valid() const; bool isComplete() const; void setComplete(const bool &complete); bool is_complete_Set() const; bool is_complete_Valid() const; virtual bool isSet() const override; virtual bool isValid() const override; private: void initializeModel(); qint64 id; bool m_id_isSet; bool m_id_isValid; qint64 pet_id; bool m_pet_id_isSet; bool m_pet_id_isValid; qint32 quantity; bool m_quantity_isSet; bool m_quantity_isValid; QDateTime ship_date; bool m_ship_date_isSet; bool m_ship_date_isValid; QString status; bool m_status_isSet; bool m_status_isValid; bool complete; bool m_complete_isSet; bool m_complete_isValid; }; } // namespace OpenAPI Q_DECLARE_METATYPE(OpenAPI::OAIOrder) #endif // OAIOrder_H
therockstorm/openapi-generator
samples/client/petstore/c/unit-tests/manual-UserAPI.c
<filename>samples/client/petstore/c/unit-tests/manual-UserAPI.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include "../api/UserAPI.h" #define USER_ID 1234 #define USER_NAME "example123" #define FIRST_NAME "Example1" #define LAST_NAME "Example2Last" #define LAST_NAME1 "LastName" #define EMAIL "<EMAIL>" #define PASSWORD "<PASSWORD>" #define PHONE "+123456789" #define USER_STATUS 4 int main() { // create user test apiClient_t *apiClient = apiClient_create(); char *username = malloc(strlen(USER_NAME) + 1); strcpy(username, USER_NAME); char *firstname = malloc(strlen(FIRST_NAME) + 1); strcpy(firstname, FIRST_NAME); char *lastname = malloc(strlen(LAST_NAME) + 1); strcpy(lastname, LAST_NAME); char *email = malloc(strlen(EMAIL) + 1); strcpy(email, EMAIL); char *password = malloc(strlen(PASSWORD) + 1); strcpy(password, PASSWORD); char *phone = malloc(strlen(PHONE) + 1); strcpy(phone, PHONE); user_t *newuser = user_create(USER_ID, username, firstname, lastname, email, password, phone, USER_STATUS); UserAPI_createUser(apiClient, newuser); user_free(newuser); apiClient_free(apiClient); // get user by name test apiClient_t *apiClient1 = apiClient_create(); user_t *returnUser = UserAPI_getUserByName(apiClient1, USER_NAME); cJSON *JSONNODE = user_convertToJSON(returnUser); char *dataToPrint = cJSON_Print(JSONNODE); printf("User is: \n%s\n", dataToPrint); user_free(returnUser); cJSON_Delete(JSONNODE); free(dataToPrint); apiClient_free(apiClient1); // update user test { apiClient_t *apiClient2 = apiClient_create(); char *username1 = malloc(strlen(USER_NAME) + 1); strcpy(username1, USER_NAME); char *firstname = malloc(strlen(FIRST_NAME) + 1); strcpy(firstname, FIRST_NAME); char *lastname = malloc(strlen(LAST_NAME) + 1); strcpy(lastname, LAST_NAME); char *email = malloc(strlen(EMAIL) + 1); strcpy(email, EMAIL); char *password = malloc(strlen(PASSWORD) + 1); strcpy(password, PASSWORD); char *phone = malloc(strlen(PHONE) + 1); strcpy(phone, PHONE); user_t *newuser1 = user_create(USER_ID, username1, firstname, lastname, email, password, phone, USER_STATUS); UserAPI_updateUser(apiClient2, username1, newuser1); user_free(newuser1); apiClient_free(apiClient2); } // login user test { char *username1 = malloc(strlen(USER_NAME) + 1); strcpy(username1, USER_NAME); char *password = malloc(strlen(PASSWORD) + 1); strcpy(password, PASSWORD); apiClient_t *apiClient3 = apiClient_create(); char *loginuserreturn = UserAPI_loginUser(apiClient3, username1, password); printf("Login User: %s\n", loginuserreturn); free(loginuserreturn); free(username1); free(password); apiClient_free(apiClient3); } // logout user test apiClient_t *apiClient4 = apiClient_create(); UserAPI_logoutUser(apiClient4); apiClient_free(apiClient4); // delete user test apiClient_t *apiClient5 = apiClient_create(); UserAPI_deleteUser(apiClient5, "example123"); apiClient_free(apiClient5); apiClient_unsetupGlobalEnv(); }
therockstorm/openapi-generator
samples/client/petstore/objc/core-data/SwaggerClient/Model/SWGPetManagedObject.h
<reponame>therockstorm/openapi-generator #import <Foundation/Foundation.h> #import <CoreData/CoreData.h> /** * OpenAPI Petstore * This is a sample server Petstore server. For this sample, you can use the api key \"special-key\" to test the authorization filters * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ #import "SWGCategoryManagedObject.h" #import "SWGTagManagedObject.h" NS_ASSUME_NONNULL_BEGIN @interface SWGPetManagedObject : NSManagedObject @property (nullable, nonatomic, retain) NSNumber* _id; @property (nullable, nonatomic, retain) SWGCategoryManagedObject* category; @property (nullable, nonatomic, retain) NSString* name; @property (nullable, nonatomic, retain) NSArray<NSString*>* photoUrls; @property (nullable, nonatomic, retain) NSOrderedSet<SWGTagManagedObject*>* tags; /* pet status in the store [optional] */ @property (nullable, nonatomic, retain) NSString* status; @end @interface SWGPetManagedObject (GeneratedAccessors) - (void)addTagsObject:(SWGTagManagedObject *)value; - (void)removeTagsObject:(SWGTagManagedObject *)value; - (void)addTags:(NSOrderedSet<SWGTagManagedObject*> *)values; - (void)removeTags:(NSOrderedSet<SWGTagManagedObject*> *)values; @end NS_ASSUME_NONNULL_END
therockstorm/openapi-generator
samples/client/petstore/cpp-ue4/Public/OpenAPIBaseModel.h
<reponame>therockstorm/openapi-generator /** * OpenAPI Petstore * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * * OpenAPI spec version: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator * https://github.com/OpenAPITools/openapi-generator * Do not edit the class manually. */ #pragma once #include "Interfaces/IHttpRequest.h" #include "Interfaces/IHttpResponse.h" #include "Serialization/JsonWriter.h" #include "Dom/JsonObject.h" namespace OpenAPI { typedef TSharedRef<TJsonWriter<>> JsonWriter; class OPENAPI_API Model { public: virtual ~Model() {} virtual void WriteJson(JsonWriter& Writer) const = 0; virtual bool FromJson(const TSharedPtr<FJsonValue>& JsonValue) = 0; }; class OPENAPI_API Request { public: virtual ~Request() {} virtual void SetupHttpRequest(const TSharedRef<IHttpRequest>& HttpRequest) const = 0; virtual FString ComputePath() const = 0; }; class OPENAPI_API Response { public: virtual ~Response() {} virtual bool FromJson(const TSharedPtr<FJsonValue>& JsonValue) = 0; void SetSuccessful(bool InSuccessful) { Successful = InSuccessful; } bool IsSuccessful() const { return Successful; } virtual void SetHttpResponseCode(EHttpResponseCodes::Type InHttpResponseCode); EHttpResponseCodes::Type GetHttpResponseCode() const { return ResponseCode; } void SetResponseString(const FString& InResponseString) { ResponseString = InResponseString; } const FString& GetResponseString() const { return ResponseString; } void SetHttpResponse(const FHttpResponsePtr& InHttpResponse) { HttpResponse = InHttpResponse; } const FHttpResponsePtr& GetHttpResponse() const { return HttpResponse; } private: bool Successful; EHttpResponseCodes::Type ResponseCode; FString ResponseString; FHttpResponsePtr HttpResponse; }; }
therockstorm/openapi-generator
samples/client/petstore/cpp-ue4/Public/OpenAPIUserApiOperations.h
/** * OpenAPI Petstore * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * * OpenAPI spec version: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator * https://github.com/OpenAPITools/openapi-generator * Do not edit the class manually. */ #pragma once #include "OpenAPIBaseModel.h" #include "OpenAPIUserApi.h" #include "OpenAPIUser.h" namespace OpenAPI { /* Create user * * This can only be done by the logged in user. */ class OPENAPI_API OpenAPIUserApi::CreateUserRequest : public Request { public: virtual ~CreateUserRequest() {} void SetupHttpRequest(const TSharedRef<IHttpRequest>& HttpRequest) const final; FString ComputePath() const final; /* Created user object */ OpenAPIUser Body; }; class OPENAPI_API OpenAPIUserApi::CreateUserResponse : public Response { public: virtual ~CreateUserResponse() {} void SetHttpResponseCode(EHttpResponseCodes::Type InHttpResponseCode) final; bool FromJson(const TSharedPtr<FJsonValue>& JsonValue) final; }; /* Creates list of users with given input array */ class OPENAPI_API OpenAPIUserApi::CreateUsersWithArrayInputRequest : public Request { public: virtual ~CreateUsersWithArrayInputRequest() {} void SetupHttpRequest(const TSharedRef<IHttpRequest>& HttpRequest) const final; FString ComputePath() const final; /* List of user object */ TArray<OpenAPIUser> Body; }; class OPENAPI_API OpenAPIUserApi::CreateUsersWithArrayInputResponse : public Response { public: virtual ~CreateUsersWithArrayInputResponse() {} void SetHttpResponseCode(EHttpResponseCodes::Type InHttpResponseCode) final; bool FromJson(const TSharedPtr<FJsonValue>& JsonValue) final; }; /* Creates list of users with given input array */ class OPENAPI_API OpenAPIUserApi::CreateUsersWithListInputRequest : public Request { public: virtual ~CreateUsersWithListInputRequest() {} void SetupHttpRequest(const TSharedRef<IHttpRequest>& HttpRequest) const final; FString ComputePath() const final; /* List of user object */ TArray<OpenAPIUser> Body; }; class OPENAPI_API OpenAPIUserApi::CreateUsersWithListInputResponse : public Response { public: virtual ~CreateUsersWithListInputResponse() {} void SetHttpResponseCode(EHttpResponseCodes::Type InHttpResponseCode) final; bool FromJson(const TSharedPtr<FJsonValue>& JsonValue) final; }; /* Delete user * * This can only be done by the logged in user. */ class OPENAPI_API OpenAPIUserApi::DeleteUserRequest : public Request { public: virtual ~DeleteUserRequest() {} void SetupHttpRequest(const TSharedRef<IHttpRequest>& HttpRequest) const final; FString ComputePath() const final; /* The name that needs to be deleted */ FString Username; }; class OPENAPI_API OpenAPIUserApi::DeleteUserResponse : public Response { public: virtual ~DeleteUserResponse() {} void SetHttpResponseCode(EHttpResponseCodes::Type InHttpResponseCode) final; bool FromJson(const TSharedPtr<FJsonValue>& JsonValue) final; }; /* Get user by user name */ class OPENAPI_API OpenAPIUserApi::GetUserByNameRequest : public Request { public: virtual ~GetUserByNameRequest() {} void SetupHttpRequest(const TSharedRef<IHttpRequest>& HttpRequest) const final; FString ComputePath() const final; /* The name that needs to be fetched. Use user1 for testing. */ FString Username; }; class OPENAPI_API OpenAPIUserApi::GetUserByNameResponse : public Response { public: virtual ~GetUserByNameResponse() {} void SetHttpResponseCode(EHttpResponseCodes::Type InHttpResponseCode) final; bool FromJson(const TSharedPtr<FJsonValue>& JsonValue) final; OpenAPIUser Content; }; /* Logs user into the system */ class OPENAPI_API OpenAPIUserApi::LoginUserRequest : public Request { public: virtual ~LoginUserRequest() {} void SetupHttpRequest(const TSharedRef<IHttpRequest>& HttpRequest) const final; FString ComputePath() const final; /* The user name for login */ FString Username; /* The password for login in clear text */ FString Password; }; class OPENAPI_API OpenAPIUserApi::LoginUserResponse : public Response { public: virtual ~LoginUserResponse() {} void SetHttpResponseCode(EHttpResponseCodes::Type InHttpResponseCode) final; bool FromJson(const TSharedPtr<FJsonValue>& JsonValue) final; FString Content; }; /* Logs out current logged in user session */ class OPENAPI_API OpenAPIUserApi::LogoutUserRequest : public Request { public: virtual ~LogoutUserRequest() {} void SetupHttpRequest(const TSharedRef<IHttpRequest>& HttpRequest) const final; FString ComputePath() const final; }; class OPENAPI_API OpenAPIUserApi::LogoutUserResponse : public Response { public: virtual ~LogoutUserResponse() {} void SetHttpResponseCode(EHttpResponseCodes::Type InHttpResponseCode) final; bool FromJson(const TSharedPtr<FJsonValue>& JsonValue) final; }; /* Updated user * * This can only be done by the logged in user. */ class OPENAPI_API OpenAPIUserApi::UpdateUserRequest : public Request { public: virtual ~UpdateUserRequest() {} void SetupHttpRequest(const TSharedRef<IHttpRequest>& HttpRequest) const final; FString ComputePath() const final; /* name that need to be deleted */ FString Username; /* Updated user object */ OpenAPIUser Body; }; class OPENAPI_API OpenAPIUserApi::UpdateUserResponse : public Response { public: virtual ~UpdateUserResponse() {} void SetHttpResponseCode(EHttpResponseCodes::Type InHttpResponseCode) final; bool FromJson(const TSharedPtr<FJsonValue>& JsonValue) final; }; }
therockstorm/openapi-generator
samples/client/petstore/cpp-ue4/Public/OpenAPIUserApi.h
<filename>samples/client/petstore/cpp-ue4/Public/OpenAPIUserApi.h /** * OpenAPI Petstore * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * * OpenAPI spec version: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator * https://github.com/OpenAPITools/openapi-generator * Do not edit the class manually. */ #pragma once #include "CoreMinimal.h" #include "OpenAPIBaseModel.h" namespace OpenAPI { class OPENAPI_API OpenAPIUserApi { public: OpenAPIUserApi(); ~OpenAPIUserApi(); void SetURL(const FString& Url); void AddHeaderParam(const FString& Key, const FString& Value); void ClearHeaderParams(); class CreateUserRequest; class CreateUserResponse; class CreateUsersWithArrayInputRequest; class CreateUsersWithArrayInputResponse; class CreateUsersWithListInputRequest; class CreateUsersWithListInputResponse; class DeleteUserRequest; class DeleteUserResponse; class GetUserByNameRequest; class GetUserByNameResponse; class LoginUserRequest; class LoginUserResponse; class LogoutUserRequest; class LogoutUserResponse; class UpdateUserRequest; class UpdateUserResponse; DECLARE_DELEGATE_OneParam(FCreateUserDelegate, const CreateUserResponse&); DECLARE_DELEGATE_OneParam(FCreateUsersWithArrayInputDelegate, const CreateUsersWithArrayInputResponse&); DECLARE_DELEGATE_OneParam(FCreateUsersWithListInputDelegate, const CreateUsersWithListInputResponse&); DECLARE_DELEGATE_OneParam(FDeleteUserDelegate, const DeleteUserResponse&); DECLARE_DELEGATE_OneParam(FGetUserByNameDelegate, const GetUserByNameResponse&); DECLARE_DELEGATE_OneParam(FLoginUserDelegate, const LoginUserResponse&); DECLARE_DELEGATE_OneParam(FLogoutUserDelegate, const LogoutUserResponse&); DECLARE_DELEGATE_OneParam(FUpdateUserDelegate, const UpdateUserResponse&); bool CreateUser(const CreateUserRequest& Request, const FCreateUserDelegate& Delegate = FCreateUserDelegate()) const; bool CreateUsersWithArrayInput(const CreateUsersWithArrayInputRequest& Request, const FCreateUsersWithArrayInputDelegate& Delegate = FCreateUsersWithArrayInputDelegate()) const; bool CreateUsersWithListInput(const CreateUsersWithListInputRequest& Request, const FCreateUsersWithListInputDelegate& Delegate = FCreateUsersWithListInputDelegate()) const; bool DeleteUser(const DeleteUserRequest& Request, const FDeleteUserDelegate& Delegate = FDeleteUserDelegate()) const; bool GetUserByName(const GetUserByNameRequest& Request, const FGetUserByNameDelegate& Delegate = FGetUserByNameDelegate()) const; bool LoginUser(const LoginUserRequest& Request, const FLoginUserDelegate& Delegate = FLoginUserDelegate()) const; bool LogoutUser(const LogoutUserRequest& Request, const FLogoutUserDelegate& Delegate = FLogoutUserDelegate()) const; bool UpdateUser(const UpdateUserRequest& Request, const FUpdateUserDelegate& Delegate = FUpdateUserDelegate()) const; private: void OnCreateUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FCreateUserDelegate Delegate) const; void OnCreateUsersWithArrayInputResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FCreateUsersWithArrayInputDelegate Delegate) const; void OnCreateUsersWithListInputResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FCreateUsersWithListInputDelegate Delegate) const; void OnDeleteUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FDeleteUserDelegate Delegate) const; void OnGetUserByNameResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetUserByNameDelegate Delegate) const; void OnLoginUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FLoginUserDelegate Delegate) const; void OnLogoutUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FLogoutUserDelegate Delegate) const; void OnUpdateUserResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdateUserDelegate Delegate) const; bool IsValid() const; void HandleResponse(FHttpResponsePtr HttpResponse, bool bSucceeded, Response& InOutResponse) const; FString Url; TMap<FString,FString> AdditionalHeaderParams; }; }
remicollet/php-ext-brotli
brotli.c
<reponame>remicollet/php-ext-brotli #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <php.h> #include <SAPI.h> #include <php_ini.h> #include <ext/standard/info.h> #if ZEND_MODULE_API_NO >= 20141001 #include <ext/standard/php_smart_string.h> #else #include <ext/standard/php_smart_str.h> #endif #include "php_brotli.h" /* brotli */ #include "brotli/encode.h" #include "brotli/decode.h" ZEND_DECLARE_MODULE_GLOBALS(brotli); static ZEND_FUNCTION(brotli_compress); static ZEND_FUNCTION(brotli_uncompress); ZEND_BEGIN_ARG_INFO_EX(arginfo_brotli_compress, 0, 0, 1) ZEND_ARG_INFO(0, data) ZEND_ARG_INFO(0, quality) ZEND_ARG_INFO(0, mode) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_brotli_uncompress, 0, 0, 1) ZEND_ARG_INFO(0, data) ZEND_ARG_INFO(0, max) ZEND_END_ARG_INFO() static zend_function_entry brotli_functions[] = { ZEND_FE(brotli_compress, arginfo_brotli_compress) ZEND_FE(brotli_uncompress, arginfo_brotli_uncompress) ZEND_FE_END }; #if PHP_VERSION_ID > 50400 // Output Handler: 5.4+ #define PHP_BROTLI_OUTPUT_HANDLER "ob_brotli_handler" typedef struct _php_brotli_context { BrotliEncoderState *state; size_t available_in; const uint8_t *next_in; size_t available_out; uint8_t *next_out; uint8_t *output; } php_brotli_context; static int php_brotli_output_encoding(void) { #if PHP_MAJOR_VERSION >= 7 zval *enc; #else zval **enc; TSRMLS_FETCH(); #endif if (!BROTLI_G(compression_coding)) { #if PHP_MAJOR_VERSION >= 7 if ((Z_TYPE(PG(http_globals)[TRACK_VARS_SERVER]) == IS_ARRAY || zend_is_auto_global_str(ZEND_STRL("_SERVER"))) && (enc = zend_hash_str_find( Z_ARRVAL(PG(http_globals)[TRACK_VARS_SERVER]), "HTTP_ACCEPT_ENCODING", sizeof("HTTP_ACCEPT_ENCODING") - 1))) { convert_to_string(enc); if (strstr(Z_STRVAL_P(enc), "br")) { BROTLI_G(compression_coding) = 1; } } #else if ((PG(http_globals)[TRACK_VARS_SERVER] || zend_is_auto_global(ZEND_STRL("_SERVER") TSRMLS_CC)) && SUCCESS == zend_hash_find(Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_SERVER]), "HTTP_ACCEPT_ENCODING", sizeof("HTTP_ACCEPT_ENCODING"), (void *) &enc)) { convert_to_string(*enc); if (strstr(Z_STRVAL_PP(enc), "br")) { BROTLI_G(compression_coding) = 1; } } #endif } return BROTLI_G(compression_coding); } static int php_brotli_encoder_create(php_brotli_context *ctx) { #if PHP_MAJOR_VERSION < 7 TSRMLS_FETCH(); #endif ctx->state = BrotliEncoderCreateInstance(NULL, NULL, NULL); if (!ctx->state) { return FAILURE; } long quality = BROTLI_G(output_compression_level); if (quality < BROTLI_MIN_QUALITY || quality > BROTLI_MAX_QUALITY) { quality = BROTLI_DEFAULT_QUALITY; } int lgwin = BROTLI_DEFAULT_WINDOW; BrotliEncoderSetParameter(ctx->state, BROTLI_PARAM_QUALITY, quality); BrotliEncoderSetParameter(ctx->state, BROTLI_PARAM_LGWIN, lgwin); return SUCCESS; } static void php_brotli_encoder_destroy(php_brotli_context *ctx) { if (ctx->state) { BrotliEncoderDestroyInstance(ctx->state); ctx->state = NULL; } } static int php_brotli_output_handler(void **handler_context, php_output_context *output_context) { php_brotli_context *ctx = *(php_brotli_context **)handler_context; #if PHP_MAJOR_VERSION < 7 TSRMLS_FETCH(); #endif if (!php_brotli_output_encoding()) { if ((output_context->op & PHP_OUTPUT_HANDLER_START) && (output_context->op != (PHP_OUTPUT_HANDLER_START |PHP_OUTPUT_HANDLER_CLEAN|PHP_OUTPUT_HANDLER_FINAL))) { sapi_add_header_ex(ZEND_STRL("Vary: Accept-Encoding"), 1, 0 TSRMLS_CC); } return FAILURE; } if (!BROTLI_G(output_compression)) { return FAILURE; } if (output_context->op & PHP_OUTPUT_HANDLER_START) { if (php_brotli_encoder_create(ctx) != SUCCESS) { return FAILURE; } } if (!(output_context->op & PHP_OUTPUT_HANDLER_CLEAN)) { if (output_context->in.used) { size_t size = BrotliEncoderMaxCompressedSize(output_context->in.used); if (!ctx->output) { ctx->output = (uint8_t *)emalloc(size); ctx->available_out = size; ctx->next_out = ctx->output; } else { ctx->available_out += size; ctx->output = (uint8_t *)erealloc(ctx->output, ctx->available_out); if (!ctx->output) { php_brotli_encoder_destroy(ctx); return FAILURE; } ctx->next_out = ctx->output; } // append input ctx->available_in = output_context->in.used; ctx->next_in = (uint8_t *)output_context->in.data; } else { ctx->available_in = 0; ctx->next_in = NULL; } if (!BrotliEncoderCompressStream(ctx->state, (output_context->op & PHP_OUTPUT_HANDLER_FINAL) ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS, &ctx->available_in, &ctx->next_in, &ctx->available_out, &ctx->next_out, NULL)) { php_brotli_encoder_destroy(ctx); return FAILURE; } if (output_context->op & PHP_OUTPUT_HANDLER_FINAL) { size_t size = (size_t)(ctx->next_out - ctx->output); output_context->out.data = ctx->output; output_context->out.used = size; output_context->out.free = 1; php_brotli_encoder_destroy(ctx); if (!SG(headers_sent)) { sapi_add_header_ex(ZEND_STRL("Content-Encoding: br"), 1, 1 TSRMLS_CC); sapi_add_header_ex(ZEND_STRL("Vary: Accept-Encoding"), 1, 0 TSRMLS_CC); } // reset BROTLI_G(output_compression) = 0; } } else { php_brotli_encoder_destroy(ctx); if (output_context->op & PHP_OUTPUT_HANDLER_FINAL) { // discard return SUCCESS; } else { // restart if (php_brotli_encoder_create(ctx) != SUCCESS) { return FAILURE; } } } return SUCCESS; } static php_brotli_context *php_brotli_output_handler_context_init(void) { php_brotli_context *ctx = (php_brotli_context *)ecalloc(1, sizeof(php_brotli_context)); ctx->state = NULL; ctx->available_in = 0; ctx->next_in = NULL; ctx->available_out = 0; ctx->next_out = NULL; ctx->output = NULL; return ctx; } static void php_brotli_output_handler_context_dtor(void *opaq TSRMLS_DC) { php_brotli_context *ctx = (php_brotli_context *)opaq; if (ctx) { php_brotli_encoder_destroy(ctx); if (ctx->output) { efree(ctx->output); } efree(ctx); } } static php_output_handler* php_brotli_output_handler_init(const char *handler_name, size_t handler_name_len, size_t chunk_size, int flags) { php_output_handler *handler = NULL; #if PHP_MAJOR_VERSION < 7 TSRMLS_FETCH(); #endif BROTLI_G(handler_registered) = 1; handler = php_output_handler_create_internal(handler_name, handler_name_len, php_brotli_output_handler, chunk_size, flags TSRMLS_CC); if (!handler) { return NULL; } php_output_handler_set_context(handler, php_brotli_output_handler_context_init(), php_brotli_output_handler_context_dtor TSRMLS_CC); BROTLI_G(output_compression) = 1; return handler; } static void php_brotli_output_compression_start(void) { zval zoh; php_output_handler *h; #if PHP_MAJOR_VERSION < 7 TSRMLS_FETCH(); #endif switch (BROTLI_G(output_compression)) { case 0: break; case 1: /* break omitted intentionally */ default: if (php_brotli_output_encoding() && (h = php_brotli_output_handler_init( ZEND_STRL(PHP_BROTLI_OUTPUT_HANDLER), PHP_OUTPUT_HANDLER_DEFAULT_SIZE, PHP_OUTPUT_HANDLER_STDFLAGS))) { php_output_handler_start(h TSRMLS_CC); } break; } } static PHP_INI_MH(OnUpdate_brotli_output_compression) { int int_value, status; char *ini_value; zend_long *p; #ifndef ZTS char *base = (char *)mh_arg2; #else char *base; base = (char *)ts_resource(*((int *) mh_arg2)); #endif if (new_value == NULL) { return FAILURE; } #if PHP_MAJOR_VERSION >= 7 if (!strncasecmp(ZSTR_VAL(new_value), "off", sizeof("off"))) { int_value = 0; } else if (!strncasecmp(ZSTR_VAL(new_value), "on", sizeof("on"))) { int_value = 1; } else if (zend_atoi(ZSTR_VAL(new_value), ZSTR_LEN(new_value))) { int_value = 1; } else { int_value = 0; } #else if (!strncasecmp(new_value, "off", sizeof("off"))) { int_value = 0; } else if (!strncasecmp(new_value, "on", sizeof("on"))) { int_value = 1; } else if (zend_atoi(new_value, new_value_length)) { int_value = 1; } else { int_value = 0; } #endif if (stage == PHP_INI_STAGE_RUNTIME) { status = php_output_get_status(TSRMLS_C); if (status & PHP_OUTPUT_SENT) { php_error_docref("ref.outcontrol" TSRMLS_CC, E_WARNING, "Cannot change brotli.output_compression" " - headers already sent"); return FAILURE; } } p = (zend_long *)(base+(size_t) mh_arg1); *p = int_value; if (stage == PHP_INI_STAGE_RUNTIME && int_value) { if (!php_output_handler_started(ZEND_STRL(PHP_BROTLI_OUTPUT_HANDLER) TSRMLS_CC)) { php_brotli_output_compression_start(); } } return SUCCESS; } static int php_brotli_output_conflict(const char *handler_name, size_t handler_name_len TSRMLS_DC) { if (php_output_get_level(TSRMLS_C)) { if (php_output_handler_conflict(handler_name, handler_name_len, ZEND_STRL(PHP_BROTLI_OUTPUT_HANDLER) TSRMLS_CC) || php_output_handler_conflict(handler_name, handler_name_len, ZEND_STRL("ob_gzhandler") TSRMLS_CC)) { return FAILURE; } } return SUCCESS; } PHP_INI_BEGIN() STD_PHP_INI_ENTRY("brotli.output_compression", "0", PHP_INI_ALL, OnUpdate_brotli_output_compression, output_compression, zend_brotli_globals, brotli_globals) STD_PHP_INI_ENTRY("brotli.output_compression_level", "-1", PHP_INI_ALL, OnUpdateLong, output_compression_level, zend_brotli_globals, brotli_globals) PHP_INI_END() static void php_brotli_init_globals(zend_brotli_globals *brotli_globals) { brotli_globals->handler_registered = 0; brotli_globals->compression_coding = 0; } #endif ZEND_MINIT_FUNCTION(brotli) { #if PHP_VERSION_ID > 50400 ZEND_INIT_MODULE_GLOBALS(brotli, php_brotli_init_globals, NULL); #endif REGISTER_LONG_CONSTANT("BROTLI_GENERIC", BROTLI_MODE_GENERIC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("BROTLI_TEXT", BROTLI_MODE_TEXT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("BROTLI_FONT", BROTLI_MODE_FONT, CONST_CS | CONST_PERSISTENT); #if PHP_VERSION_ID > 50400 php_output_handler_alias_register(ZEND_STRL(PHP_BROTLI_OUTPUT_HANDLER), php_brotli_output_handler_init TSRMLS_CC); php_output_handler_conflict_register(ZEND_STRL(PHP_BROTLI_OUTPUT_HANDLER), php_brotli_output_conflict TSRMLS_CC); REGISTER_INI_ENTRIES(); #endif return SUCCESS; } ZEND_MSHUTDOWN_FUNCTION(brotli) { #if PHP_VERSION_ID > 50400 UNREGISTER_INI_ENTRIES(); #endif return SUCCESS; } ZEND_RINIT_FUNCTION(brotli) { #if PHP_VERSION_ID > 50400 BROTLI_G(compression_coding) = 0; if (!BROTLI_G(handler_registered)) { php_brotli_output_compression_start(); } #endif return SUCCESS; } ZEND_RSHUTDOWN_FUNCTION(brotli) { #if PHP_VERSION_ID > 50400 BROTLI_G(handler_registered) = 0; #endif return SUCCESS; } ZEND_MINFO_FUNCTION(brotli) { php_info_print_table_start(); php_info_print_table_row(2, "Brotli support", "enabled"); php_info_print_table_row(2, "Extension Version", BROTLI_EXT_VERSION); php_info_print_table_row(2, "Library Version", BROTLI_LIB_VERSION); php_info_print_table_end(); } zend_module_entry brotli_module_entry = { #if ZEND_MODULE_API_NO >= 20010901 STANDARD_MODULE_HEADER, #endif "brotli", brotli_functions, ZEND_MINIT(brotli), ZEND_MSHUTDOWN(brotli), ZEND_RINIT(brotli), ZEND_RSHUTDOWN(brotli), ZEND_MINFO(brotli), #if ZEND_MODULE_API_NO >= 20010901 BROTLI_EXT_VERSION, #endif STANDARD_MODULE_PROPERTIES }; #ifdef COMPILE_DL_BROTLI ZEND_GET_MODULE(brotli) #endif static ZEND_FUNCTION(brotli_compress) { char *in; #if ZEND_MODULE_API_NO >= 20141001 size_t in_size; #else int in_size; #endif long quality = BROTLI_DEFAULT_QUALITY; long mode = BROTLI_MODE_GENERIC; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ll", &in, &in_size, &quality, &mode) == FAILURE) { RETURN_FALSE; } size_t out_size = BrotliEncoderMaxCompressedSize(in_size); char *out = (char *)emalloc(out_size); if (!out) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Brotli compress memory allocate failed\n"); RETURN_FALSE; } if (mode != BROTLI_MODE_GENERIC && mode != BROTLI_MODE_TEXT && mode != BROTLI_MODE_FONT) { mode = BROTLI_MODE_GENERIC; } if (quality < BROTLI_MIN_QUALITY || quality > BROTLI_MAX_QUALITY) { quality = BROTLI_DEFAULT_QUALITY; } int lgwin = BROTLI_DEFAULT_WINDOW; if (!BrotliEncoderCompress((int)quality, lgwin, (BrotliEncoderMode)mode, in_size, (const uint8_t*)in, &out_size, (uint8_t*)out)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Brotli compress failed\n"); efree(out); RETURN_FALSE; } #if ZEND_MODULE_API_NO >= 20141001 RETVAL_STRINGL(out, out_size); #else RETVAL_STRINGL(out, out_size, 1); #endif efree(out); } static ZEND_FUNCTION(brotli_uncompress) { long max_size = 0; char *in; #if ZEND_MODULE_API_NO >= 20141001 size_t in_size; smart_string out = {0}; #else int in_size; smart_str out = {0}; #endif if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &in, &in_size, &max_size) == FAILURE) { RETURN_FALSE; } if (max_size && max_size < in_size) { in_size = max_size; } BrotliDecoderState *state = BrotliDecoderCreateInstance(NULL, NULL, NULL); if (!state) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid Brotli state\n"); RETURN_FALSE; } const size_t kFileBufferSize = 65536; size_t available_in = in_size; const uint8_t *next_in = (const uint8_t *)in; size_t buffer_size = kFileBufferSize; uint8_t *buffer = (uint8_t *)emalloc(buffer_size); BrotliDecoderResult result = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT; while (result == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) { size_t available_out = buffer_size; uint8_t *next_out = buffer; size_t total_out = 0; result = BrotliDecoderDecompressStream(state, &available_in, &next_in, &available_out, &next_out, &total_out); size_t used_out = buffer_size - available_out; if (used_out != 0) { #if ZEND_MODULE_API_NO >= 20141001 smart_string_appendl(&out, buffer, used_out); #else smart_str_appendl(&out, buffer, used_out); #endif } } BrotliDecoderDestroyInstance(state); efree(buffer); if (result != BROTLI_DECODER_RESULT_SUCCESS) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Brotli decompress failed\n"); #if ZEND_MODULE_API_NO >= 20141001 smart_string_free(&out); #else smart_str_free(&out); #endif RETURN_FALSE; } #if ZEND_MODULE_API_NO >= 20141001 RETVAL_STRINGL(out.c, out.len); #else RETVAL_STRINGL(out.c, out.len, 1); #endif #if ZEND_MODULE_API_NO >= 20141001 smart_string_free(&out); #else smart_str_free(&out); #endif }
mfnovriansyah/MiniProjectPTK
EnkripDekrip1.0.c
<reponame>mfnovriansyah/MiniProjectPTK #include <stdio.h> #include <stdlib.h> int hitung = 0; // inisiasi dengan angka 0 untuk menghitung maksimal percobaan login masuk yaitu 3 char pilihan; // untuk memilih pilihan void menu(); //prototype void judulprogram();//prototype int i; // membantu looping ekripsi dekripsi Ascii char string[100]; // inputan berupa string yang akan didekripsi atau enkripsi FILE *hasilenkripsi; int main() { login(); // fungsi login dipanggil menu(); // fungsi menu di panggil } void petunjukprogramEDAscii()// fungsi menu pentunjuk program enkripsi dekripsi { system("cls"); // membuat layar menjadi bersih printf("\n\n-------------------------------------------------------------------------------\n"); printf("\t\t\tPETUNJUK PROGRAM ENKRIPSI DEKRIPSI Ascii \n"); printf("-------------------------------------------------------------------------------\n"); printf("Tekan [1] Untuk melakukan Ekripsi dan Dekripsi Dengan Metode RSA \n\n"); printf("Tekan [2] Untuk melakukan Ekripsi dan Dekripsi Dengan Metode +- Nilai Ascii\n\n"); printf("Tekan [3] Untuk Menuju Petunjuk Program Enkripsi Dekripsi \n\n"); printf("Tekan [4] Untuk Keluar dari Program \n\n"); system("pause");// mendelay program sampai ada inputan menu(); // memanggil fungsi menu } void petunjukprogramED()// fungsi menu pentunjuk program enkripsi dekripsi { system("cls"); // membuat layar menjadi bersih printf("\n\n-------------------------------------------------------------------------------\n"); printf("\t\t\tPETUNJUK PROGRAM ENKRIPSI DEKRIPSI \n"); printf("-------------------------------------------------------------------------------\n"); printf("Tekan [1] Untuk melakukan Ekripsi dan Dekripsi Dengan Metode RSA \n\n"); printf("Tekan [2] Untuk melakukan Ekripsi dan Dekripsi Dengan Metode +- Nilai Ascii\n\n"); printf("Tekan [3] Untuk Menuju Petunjuk Program Enkripsi Dekripsi \n\n"); printf("Tekan [4] Untuk Keluar dari Program \n\n"); system("pause");// mendelay program sampai ada inputan menu(); // memanggil fungsi menu } void DekripsiAscii() // fungsi dekripsi nilai Ascii { printf("\n\tMasukan Text:\t"); fflush (stdin); // menghapus outputan sebelumnya fgets(string,100,stdin); // memeriksa inputan yang akan di enkripsi for(i = 0; (i < 100 && string[i] != '\0'); i++) //string akan disimpan sampai string jika kurang dari 100 dan tidak null(\0) { string[i] = string[i] - 5; //the key for encryption is 3 that is subtracted to ASCII value } printf("\n\tHasil Dekripsi: %s\n", string); system("pause"); // mendelay program sampai ada inputan menu(); // memanggil fungsi menu } int EnkripsiAscii() // fungsi enkripsi nilai Ascii { printf("\n\tMasukan Text:\t"); fflush (stdin); // menghapus outputan sebelumnya fgets(string,100,stdin); // memeriksa inputan yang akan di enkripsi for(i = 0; (i < 100 && string[i] != '\0'); i++) // string akan disimpan sampai string jika kurang dari 100 dan tidak null(\0) { string[i] = string[i] + 5; //the key for encryption is 3 that is added to ASCII value } printf("\n\tHasil Dekripsi: %s\n", string); hasilenkripsi = fopen ("hasilenkripsi.txt", "w"); // membuka file hasilenkripsi.txt jika tidak ada maka membuatnya "w" if(hasilenkripsi == NULL) { printf("Hasil Enkripsi Tidak dapat disimpan "); } fprintf (hasilenkripsi, "%s", string); // memasukan nilai di string ke hasilenkripsi fclose (hasilenkripsi); //menutup folder e system("pause"); // mendelay program sampai ada inputan menu(); // memanggil fungsi menu } void helpEDAscii() { system("cls"); // membuat layar menjadi bersih printf("\n\n-------------------------------------------------------------------------------\n"); printf("\t\tPETUNJUK PROGRAM ENKRIPSI DEKRIPSI +- NILAI ASCII \n"); printf("-------------------------------------------------------------------------------\n"); printf("Tekan [1] Untuk melakukan Ekripsi Lalu Masukan Text yang akan di Enkripsi\n\n"); printf("Tekan [2] Untuk melakukan Dekripsi Lalu Masukan Text yang akan di Dekripsi\n\n"); printf("Tekan [3] Untuk Menuju Petunjuk Program Enkripsi Dekripsi \n\n"); printf("Tekan [4] Untuk Keluar dari Program \n\n"); system("pause");// mendelay program sampai ada inputan system("cls"); // membuat layar menjadi bersih judulprogram(); // memanggil fungsi judulprogram EDAscii(); // memanggil fungsi EDAscii } int EDAscii() // fungsi enkripsi dekripsi dengan -+ Ascii { fflush(stdin); // menghapus input sebelumnya printf("\n\tSilahkan Pilih :\n"); printf("\t\t[1] Text di Enkripsi\n"); printf("\t\t[2] Text di Deskripsi\n"); printf("\t\t[3] Help\n"); printf("\t\t[4] Kembali\n"); printf("\t\t[5] Keluar\n"); printf("\n\t\tPilihan:"); scanf("%d", &pilihan); //fgets() switch(pilihan) { case 1: EnkripsiAscii(); // memanggil fungsi EnkripsiAscii break; case 2: DekripsiAscii();// memanggil fungsi DekripsiAscii break; case 3: helpEDAscii(); // memanggil fungsi helpEDAscii case 4: menu(); // memanggil fungsi menu break; case 5: exit(1); // keluar dari program break; default: printf("\n\tHarap Masukan Pilihan Yang Benar!\n"); system("Pause"); // mendelay program sampai ada inputan system("cls"); // membuat layar menjadi bersih fflush(stdin); // menghapus input sebelumnya judulprogram(); // memanggi fungsi judulprogram EDAscii(); // memanggil fungsi menu break; } } void judulprogram() { printf("---------------------------------------------------------------------\n"); printf("\t\tPROGRAM ENKRIPSI DAN DEKRIPSI\n"); printf("\t\tDibuat <NAME> Samuel\n"); printf("---------------------------------------------------------------------\n"); } void menu() // fungsi menu pada program dekripsi dan enkripsi { system("cls"); // membuat layar menjadi bersih judulprogram(); printf("\tSilahkan Pilih\n"); printf("\t\t[1] Program Enkripsi dan Dekripsi dengan RSA\n"); printf("\t\t[2] Program Enkripsi dan Dekripsi dengan +- Nilai ASCII\n"); printf("\t\t[3] Help\n"); printf("\t\t[4] Keluar\n"); printf("\n\t\tPilihan :"); scanf("%d",&pilihan); switch(pilihan) { case 1: printf("\n\t\t[Sedang Dalam Pembuatan]\n"); system("pause"); system("cls"); menu(); break; case 2: EDAscii(); break; case 3: petunjukprogramED(); break; case 4: exit(1); // keluar dari program break; default : printf("\n\tHarap Masukan Pilihan Yang Benar!\n"); system("Pause"); // mendelay program sampai ada inputan system("cls"); // membuat layar menjadi bersih lagi fflush(stdin); // menghapus input sebelumnya menu(); break; } } int login()// fungsi login untuk verifikasi data supaya lebih aman { char username[15],password[15]; // type char untuk username dan password dengan ukuran data maks 10 printf("---------------------------------------------------------------------\n"); printf("\t\tPROGRAM ENKRIPSI DAN DEKRIPSI\n"); printf("\t\t\t LOGIN \n"); printf("\t\tDibuat <NAME>\n"); printf("---------------------------------------------------------------------\n"); printf("\tMasukan Username : "); scanf("%s",&username); printf("\tMasukan Password : "); scanf("%s",&password); if(strcmp(username,"fahrizasamuel")==0 && strcmp(password,"<PASSWORD>")==0)//strcmp yaitu membandingkan isi yang pada dua data { printf("\n\t\t[Login sukses]\n"); system("pause"); system("cls"); } else { hitung = hitung+1; printf("\n\t[ Username dan Password tidak sama [%d] ] \n", hitung); if(hitung < 3) { printf("\n\t[ Percobaan Login Maksimal 3 kali ]\n"); system("pause"); // mendelay program sampai ada inputan system("cls"); // membuat layar menjadi bersih lagi login(); } else { printf("\t[ Percobaan Login Sudah Melebihi Batas Maksimal ] \n"); printf("\n\t[ Anda akan Keluar Otomatis ]"); exit(1); } } }
handar/ThreadRacer
pthread_race.c
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> #include <time.h> #include <sys/time.h> /** * THESE DEFINE VALUES CANNOT BE CHANGED. * DOING SO WILL CAUSE POINTS TO BE DEDUCTED * FROM YOUR GRADE (15 points) */ /** BEGIN VALUES THAT CANNOT BE CHANGED */ #define MAX_THREADS 16 #define MAX_ITERATIONS 40 /** END VALUES THAT CANNOT BE CHANGED */ /** * use this struct as a parameter for the function * nanosleep. * For exmaple : nanosleep(&ts, NULL); */ struct ThreadArgs { pthread_t tid; int id; //int count; }; struct timespec ts = {0, 12}; int globalValue = 0; /*void* thread_func(void * arg) { struct ThreadArgs* args = (struct ThreadArgs*)arg; int i; for(i =0; i <= args->count;i++) { printf("Thread id: %-4d,Count Value: %-5d\n", args->id, i); } return NULL; }*/ void* adderThread (void * arg) { struct ThreadArgs* args = (struct ThreadArgs*)arg; int i ; nanosleep(&ts, NULL); for (i = 0; i <= MAX_ITERATIONS; i++){ //nanosleep(&ts, NULL); int temp = globalValue; nanosleep(&ts, NULL); temp = temp + 3; globalValue = temp; printf("Current Value written to Global Variables by ADDER thread id: %lu is %d\n", args -> tid, globalValue); } } void* subtractorThread (void * arg) { struct ThreadArgs* args = (struct ThreadArgs*)arg; int i ; nanosleep(&ts, NULL); for (i = 0; i <= MAX_ITERATIONS; i++){ //nanosleep(&ts, NULL); int temp = globalValue; nanosleep(&ts, NULL); temp = temp - 3; globalValue = temp; printf("Current Value written to Global Variables by SUBTRACTOR thread id: %lu is %d\n", args -> tid, globalValue); } } int main(int argc, char const *argv[]) { //declare an array of structs of size MAX_THREADS struct ThreadArgs thread_info[MAX_THREADS]; int i, ret_val; nanosleep(&ts, NULL); //create MAX_THREADS threads for(i=0; i < MAX_THREADS;i++) { nanosleep(&ts, NULL); //save thread-s info in next struct thread_info[i].id = i+1; //thread_info[i].count = 10-i; //ret_val = pthread_create(&thread_info[i].tid, NULL, thread_func, (void *)&thread_info[i]); if(ret_val < 0) { perror("Error creating thread.."); return -2; } //even numbered iterations if (i % 2 == 0){ ret_val = pthread_create(&thread_info[i].tid, NULL, adderThread, (void *)&thread_info[i]); //nanosleep(&ts, NULL); //adderThread(ret_val); } //odd numbered iterations else { ret_val = pthread_create(&thread_info[i].tid, NULL, subtractorThread, (void *)&thread_info[i]); //nanosleep(&ts, NULL); //subtractorThread(ret_val); } } for(i = 0; i < MAX_THREADS; i++) { ret_val = pthread_join(thread_info[i].tid, NULL); if(ret_val) { perror("Error joining thread: "); return -3; } } //printf("Main Has Joined All Threads\n"); printf("Final Value of Shared Var: %d\n", globalValue); return 0; }
brmmm3/engraver
plot.c
/* For Emacs: -*- mode:c; eval: (folding-mode 1) -*- */ /* {{{ include, define, vars */ #define USE_MULTI_SHABAL #define _GNU_SOURCE #define _LARGEFILE64_SOURCE #include <errno.h> #include <stdint.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <inttypes.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <pthread.h> #include <time.h> #include <sys/time.h> #include "shabal.h" #include "mshabal256.h" #include "mshabal.h" #include "helper.h" #define DEFAULTDIR "plots/" // Not to be changed below this #define SCOOP_SIZE 64 #define NUM_SCOOPS 4096 #define NONCE_SIZE (NUM_SCOOPS * SCOOP_SIZE) #define HASH_SIZE 32 #define HASH_CAP 4096 // This is used to set the pthread stack size to 8MB. // Otherwise we overflow the stack on macOS, which has a default // pthread stack size of 512KB. Linux's default is 8MB // I believe 4MB "works" but using 8MB to match Linux. #define REQUIRED_STACK_SIZE (8 * 1048576) uint64_t addr = 0; uint64_t startnonce = 0; uint32_t nonces = 0; uint32_t staggersize = 0; uint32_t threads = 0; uint32_t noncesperthread, noncearguments; uint32_t selecttype = 0; uint32_t asyncmode = 0; uint32_t verbose = 0; uint32_t resumeid = 0xaffeaffe; double createtime = 0.0; uint64_t maxmemory = 0; uint64_t leavespace = 0; uint64_t plotfilesize; uint64_t starttime; uint64_t run, lastrun, thisrun; int userleavespace; int lastspeed, lasthours, lastminutes, lastseconds; int ofd; char *cache, *wcache, *acache[2]; char *outputdir = DEFAULTDIR; #define SET_NONCE(gendata, nonce, offset) \ xv = (char*)&nonce; \ gendata[NONCE_SIZE + offset] = xv[7]; \ gendata[NONCE_SIZE + offset + 1] = xv[6]; \ gendata[NONCE_SIZE + offset + 2] = xv[5]; \ gendata[NONCE_SIZE + offset + 3] = xv[4]; \ gendata[NONCE_SIZE + offset + 4] = xv[3]; \ gendata[NONCE_SIZE + offset + 5] = xv[2]; \ gendata[NONCE_SIZE + offset + 6] = xv[1]; \ gendata[NONCE_SIZE + offset + 7] = xv[0] #if __APPLE__ // A fallocate implementation for macOS int posix_fallocate(int fd, off_t offset, off_t len) { fstore_t store = {F_ALLOCATECONTIG, F_PEOFPOSMODE, offset, len, 0}; if (verbose) { printf("Allocating file of size %d.\n", len); } int res = fcntl(fd, F_PREALLOCATE, &store); if (res == -1) { // try and allocate space with fragments if (verbose) { printf("Failed to allocate contiguous space. Allocating space with fragments.\n"); } store.fst_flags = F_ALLOCATEALL; res = fcntl(fd, F_PREALLOCATE, &store); } if (res != -1) { if (verbose) { printf("Truncating file to length.\n"); } res = ftruncate(fd, offset+len); } return res; } // Also, on MacOS, there is no lseek64. off_t is already 64 bit #define LSEEK lseek #else // On Linux, use lseek64 #define LSEEK lseek64 #endif int use_direct_io = 0; static void *alloc(size_t nmemb, size_t size) { if (! use_direct_io) { return calloc( nmemb, size ); } else { // allocate memory on a 4K boundary for O_DIRECT. Otherwise `write` gives `errno` 22 return aligned_alloc( 4096, nmemb * size ); } } /* }}} */ /* {{{ nonce original algorithm */ void nonce(uint64_t addr, uint64_t nonce, uint64_t cachepos) { char final[32]; char gendata[16 + NONCE_SIZE]; char *xv; SET_NONCE(gendata, addr, 0); SET_NONCE(gendata, nonce, 8); shabal_context init_x, x; uint32_t len; shabal_init(&init_x, 256); for (uint32_t i = NONCE_SIZE; i > 0; i -= HASH_SIZE) { memcpy(&x, &init_x, sizeof(init_x)); len = NONCE_SIZE + 16 - i; if (len > HASH_CAP) len = HASH_CAP; shabal(&x, &gendata[i], len); shabal_close(&x, 0, 0, &gendata[i - HASH_SIZE]); } shabal_init(&x, 256); shabal(&x, gendata, 16 + NONCE_SIZE); shabal_close(&x, 0, 0, final); // XOR with final uint64_t *start = (uint64_t*)gendata; uint64_t *fint = (uint64_t*)&final; for (uint32_t i = 0; i < NONCE_SIZE; i += 32) { *start ^= fint[0]; start++; *start ^= fint[1]; start++; *start ^= fint[2]; start++; *start ^= fint[3]; start++; } // Sort them (PoC2): uint64_t revPosition = NONCE_SIZE-SCOOP_SIZE; for (uint32_t i = 0; i < NONCE_SIZE; i += SCOOP_SIZE){ memmove(&cache[cachepos * SCOOP_SIZE + (uint64_t)i * staggersize], &gendata[i], 32); memmove(&cache[cachepos * SCOOP_SIZE + 32 + revPosition * staggersize], &gendata[i+32], 32); revPosition -= SCOOP_SIZE; } } /* }}} */ /* {{{ mnonce SSE4 version */ int mnonce(uint64_t addr, uint64_t nonce1, uint64_t nonce2, uint64_t nonce3, uint64_t nonce4, uint64_t cachepos1, uint64_t cachepos2, uint64_t cachepos3, uint64_t cachepos4) { char final1[32], final2[32], final3[32], final4[32]; char gendata1[16 + NONCE_SIZE], gendata2[16 + NONCE_SIZE], gendata3[16 + NONCE_SIZE], gendata4[16 + NONCE_SIZE]; char *xv; SET_NONCE(gendata1, addr, 0); for (int i = NONCE_SIZE; i <= NONCE_SIZE + 7; ++i) { gendata2[i] = gendata1[i]; gendata3[i] = gendata1[i]; gendata4[i] = gendata1[i]; } SET_NONCE(gendata1, nonce1, 8); SET_NONCE(gendata2, nonce2, 8); SET_NONCE(gendata3, nonce3, 8); SET_NONCE(gendata4, nonce4, 8); mshabal_context x; int len; for (int i = NONCE_SIZE; i > 0; i -= HASH_SIZE) { sse4_mshabal_init(&x, 256); len = NONCE_SIZE + 16 - i; if (len > HASH_CAP) len = HASH_CAP; sse4_mshabal(&x, &gendata1[i], &gendata2[i], &gendata3[i], &gendata4[i], len); sse4_mshabal_close(&x, 0, 0, 0, 0, 0, &gendata1[i - HASH_SIZE], &gendata2[i - HASH_SIZE], &gendata3[i - HASH_SIZE], &gendata4[i - HASH_SIZE]); } sse4_mshabal_init(&x, 256); sse4_mshabal(&x, gendata1, gendata2, gendata3, gendata4, 16 + NONCE_SIZE); sse4_mshabal_close(&x, 0, 0, 0, 0, 0, final1, final2, final3, final4); // XOR with final for (int i = 0; i < NONCE_SIZE; i++) { gendata1[i] ^= (final1[i % 32]); gendata2[i] ^= (final2[i % 32]); gendata3[i] ^= (final3[i % 32]); gendata4[i] ^= (final4[i % 32]); } // Sort them (PoC2): uint64_t revPosition = NONCE_SIZE-SCOOP_SIZE; for (int i = 0; i < NONCE_SIZE; i += 64) { memmove(&cache[cachepos1 * 64 + (uint64_t)i * staggersize], &gendata1[i], 32); memmove(&cache[cachepos2 * 64 + (uint64_t)i * staggersize], &gendata2[i], 32); memmove(&cache[cachepos3 * 64 + (uint64_t)i * staggersize], &gendata3[i], 32); memmove(&cache[cachepos4 * 64 + (uint64_t)i * staggersize], &gendata4[i], 32); memmove(&cache[cachepos1 * 64 + 32 + revPosition * staggersize], &gendata1[i+32], 32); memmove(&cache[cachepos2 * 64 + 32 + revPosition * staggersize], &gendata2[i+32], 32); memmove(&cache[cachepos3 * 64 + 32 + revPosition * staggersize], &gendata3[i+32], 32); memmove(&cache[cachepos4 * 64 + 32 + revPosition * staggersize], &gendata4[i+32], 32); revPosition -= SCOOP_SIZE; } return 0; } // }}} // {{{ m256nonce AVX2 version int m256nonce(uint64_t addr, uint64_t nonce1, uint64_t nonce2, uint64_t nonce3, uint64_t nonce4, uint64_t nonce5, uint64_t nonce6, uint64_t nonce7, uint64_t nonce8, uint64_t cachepos) { char final1[32], final2[32], final3[32], final4[32]; char final5[32], final6[32], final7[32], final8[32]; char gendata1[16 + NONCE_SIZE], gendata2[16 + NONCE_SIZE], gendata3[16 + NONCE_SIZE], gendata4[16 + NONCE_SIZE]; char gendata5[16 + NONCE_SIZE], gendata6[16 + NONCE_SIZE], gendata7[16 + NONCE_SIZE], gendata8[16 + NONCE_SIZE]; char *xv; SET_NONCE(gendata1, addr, 0); for (int i = NONCE_SIZE; i <= NONCE_SIZE + 7; ++i) { gendata2[i] = gendata1[i]; gendata3[i] = gendata1[i]; gendata4[i] = gendata1[i]; gendata5[i] = gendata1[i]; gendata6[i] = gendata1[i]; gendata7[i] = gendata1[i]; gendata8[i] = gendata1[i]; } SET_NONCE(gendata1, nonce1, 8); SET_NONCE(gendata2, nonce2, 8); SET_NONCE(gendata3, nonce3, 8); SET_NONCE(gendata4, nonce4, 8); SET_NONCE(gendata5, nonce5, 8); SET_NONCE(gendata6, nonce6, 8); SET_NONCE(gendata7, nonce7, 8); SET_NONCE(gendata8, nonce8, 8); mshabal256_context x; int len; for (int i = NONCE_SIZE; i;) { mshabal256_init(&x); len = NONCE_SIZE + 16 - i; if (len > HASH_CAP) len = HASH_CAP; mshabal256(&x, &gendata1[i], &gendata2[i], &gendata3[i], &gendata4[i], &gendata5[i], &gendata6[i], &gendata7[i], &gendata8[i], len); i -= HASH_SIZE; mshabal256_close(&x, (uint32_t *)&gendata1[i], (uint32_t *)&gendata2[i], (uint32_t *)&gendata3[i], (uint32_t *)&gendata4[i], (uint32_t *)&gendata5[i], (uint32_t *)&gendata6[i], (uint32_t *)&gendata7[i], (uint32_t *)&gendata8[i]); } mshabal256_init(&x); mshabal256(&x, gendata1, gendata2, gendata3, gendata4, gendata5, gendata6, gendata7, gendata8, 16 + NONCE_SIZE); mshabal256_close(&x, (uint32_t *)final1, (uint32_t *)final2, (uint32_t *)final3, (uint32_t *)final4, (uint32_t *)final5, (uint32_t *)final6, (uint32_t *)final7, (uint32_t *)final8); // XOR with final for (int i = 0; i < NONCE_SIZE; i++) { gendata1[i] ^= final1[i % 32]; gendata2[i] ^= final2[i % 32]; gendata3[i] ^= final3[i % 32]; gendata4[i] ^= final4[i % 32]; gendata5[i] ^= final5[i % 32]; gendata6[i] ^= final6[i % 32]; gendata7[i] ^= final7[i % 32]; gendata8[i] ^= final8[i % 32]; } // Sort them (PoC2): uint64_t revPosition = NONCE_SIZE-SCOOP_SIZE; for (int i = 0; i < NONCE_SIZE; i += 64) { memmove(&cache[cachepos * 64 + (uint64_t)i * staggersize], &gendata1[i], 32); memmove(&cache[cachepos * 64 + 64 + (uint64_t)i * staggersize], &gendata2[i], 32); memmove(&cache[cachepos * 64 + 128 + (uint64_t)i * staggersize], &gendata3[i], 32); memmove(&cache[cachepos * 64 + 192 + (uint64_t)i * staggersize], &gendata4[i], 32); memmove(&cache[cachepos * 64 + 256 + (uint64_t)i * staggersize], &gendata5[i], 32); memmove(&cache[cachepos * 64 + 320 + (uint64_t)i * staggersize], &gendata6[i], 32); memmove(&cache[cachepos * 64 + 384 + (uint64_t)i * staggersize], &gendata7[i], 32); memmove(&cache[cachepos * 64 + 448 + (uint64_t)i * staggersize], &gendata8[i], 32); memmove(&cache[cachepos * 64 + + 32 + revPosition * staggersize], &gendata1[i+32], 32); memmove(&cache[cachepos * 64 + 64 + 32 + revPosition * staggersize], &gendata2[i+32], 32); memmove(&cache[cachepos * 64 + 128 + 32 + revPosition * staggersize], &gendata3[i+32], 32); memmove(&cache[cachepos * 64 + 192 + 32 + revPosition * staggersize], &gendata4[i+32], 32); memmove(&cache[cachepos * 64 + 256 + 32 + revPosition * staggersize], &gendata5[i+32], 32); memmove(&cache[cachepos * 64 + 320 + 32 + revPosition * staggersize], &gendata6[i+32], 32); memmove(&cache[cachepos * 64 + 384 + 32 + revPosition * staggersize], &gendata7[i+32], 32); memmove(&cache[cachepos * 64 + 448 + 32 + revPosition * staggersize], &gendata8[i+32], 32); revPosition -= SCOOP_SIZE; } return 0; } // }}} // {{{ work_i void * work_i(void *x_void_ptr) { uint64_t i = *(uint64_t *)x_void_ptr; uint32_t n; for (n = 0; n < noncesperthread; n += noncearguments) { if (selecttype == 1) { // SSE4 mnonce(addr, (i + n), (i + n + 1), (i + n + 2), (i + n + 3), (uint64_t)(i - startnonce + n), (uint64_t)(i - startnonce + n + 1), (uint64_t)(i - startnonce + n + 2), (uint64_t)(i - startnonce + n + 3)); } else if (selecttype == 2) { // AVX2 m256nonce(addr, (i + n + 0), (i + n + 1), (i + n + 2), (i + n + 3), (i + n + 4), (i + n + 5), (i + n + 6), (i + n + 7), (i - startnonce + n)); } else { // STANDARD nonce(addr, (i + n), (uint64_t)(i - startnonce + n)); } // If verbose mode is set print out actual nonce plot state if (verbose == 1) { static unsigned int oldn = 1; if (oldn != n) { oldn = n; printf("Nonces %lu from %u nonces %2.2f %% done...\r\n", ((uint64_t)(n * threads)) + run, nonces, ((float) ((n * threads) + run) / (float) nonces) * 100); fflush(stdout); } } } return NULL; } /* }}} */ /* {{{ getMS get miliseconds */ uint64_t getMS() { struct timeval time; gettimeofday(&time, NULL); return ((uint64_t)time.tv_sec * 1000000) + time.tv_usec; } /* }}} */ /* {{{ usage print usage info */ void usage(char **argv) { printf("Usage: %s -k KEY [ -x CORE ] [-v VERBOSE] [-d DIRECTORY] [-s STARTNONCE] [-n NONCES] [-m STAGGERSIZE] [-t THREADS] [-b MAXMEMORY] [-p PLOTFILESIZE] [-a] [-R] [-D]\n\n", argv[0]); printf(" see README.md\n"); exit(-1); } /* }}} */ /* {{{ writecache */ void * writecache(void *arguments) { uint64_t cacheblocksize = staggersize * SCOOP_SIZE; uint64_t thisnonce; float percent; percent = ((double)100 * lastrun / nonces); if (lastseconds) { printf("\r\n\33[2K\r%5.2f%% done. %i nonces per minute, %02i:%02i:%02i left [writing%s]", percent, (lastspeed * 60), lasthours, lastminutes, lastseconds, (asyncmode) ? " asynchronously" : ""); } else { printf("\33[2K\r%5.2f%% done. [writing%s]", percent, (asyncmode) ? " asynchronously" : ""); } fflush(stdout); for (thisnonce = 0; thisnonce < NUM_SCOOPS; thisnonce++ ) { uint64_t cacheposition = thisnonce * cacheblocksize; uint64_t fileposition = (uint64_t)(thisnonce * (uint64_t)nonces * (uint64_t)SCOOP_SIZE + thisrun * (uint64_t)SCOOP_SIZE); if ( LSEEK(ofd, fileposition, SEEK_SET) < 0 ) { printf("\n\nError while lseek()ing in file: %d\n\n", errno); exit(1); } if ( write(ofd, &wcache[cacheposition], cacheblocksize) < 0 ) { perror("writecache"); printf("\n\nError while writing to file: %d\n\n", errno); exit(1); } } uint64_t ms = getMS() - starttime; percent = ((double)100 * lastrun / nonces); double runsecs = (double)ms / 1000000; lastspeed = (int)(staggersize / runsecs); int seconds = (int)(nonces - run) / lastspeed; int remainder = seconds % 3600; lasthours = (int)seconds / 3600; lastminutes = remainder / 60;; lastseconds = remainder % 60; printf("\r\n\33[2K\r%5.2f%% done. %i nonces per minute, %02i:%02i:%02i left", percent, (lastspeed * 60), lasthours, lastminutes, lastseconds); fflush(stdout); return NULL; } /* }}} */ /* {{{ writestatus */ void writestatus(void) { // Write current status to the end of the file if ( LSEEK(ofd, -sizeof run, SEEK_END) < 0 ) { printf("\n\nError while lseek()ing in file: %d\n\n", errno); exit(1); } if ( write(ofd, &run, sizeof run) < 0 ) { perror("writestatus"); printf("\n\nError while writing to file: %d\n\n", errno); exit(1); } } /* }}} */ /* {{{ main */ int main(int argc, char **argv) { if (argc < 2) { usage(argv); } int i; int startgiven = 0; int resume = 0; for (uint8_t i = 1; i < argc; i++) { // Ignore unknown argument if(argv[i][0] != '-') continue; if (!strcmp(argv[i],"-a")) { asyncmode = 1; printf("Async mode set.\n"); continue; } if (!strcmp(argv[i],"-v")) { verbose = 1; printf("Verbose mode set.\n"); continue; } if (!strcmp(argv[i],"-R")) { resume = 1; continue; } if (!strcmp(argv[i],"-D")) { use_direct_io = 1; continue; } char *parse = NULL; uint64_t parsed; char param = argv[i][1]; int modified, ds; if (argv[i][2] == 0) { if (i < argc - 1) parse = argv[++i]; } else { parse = &(argv[i][2]); } if (parse != NULL) { modified = 0; parsed = strtoull(parse, 0, 10); switch(parse[strlen(parse) - 1]) { case 't': case 'T': parsed *= 1024; case 'g': case 'G': parsed *= 1024; case 'm': case 'M': parsed *= 1024; case 'k': case 'K': parsed *= 1024; modified = 1; } switch(param) { case 'k': addr = parsed; break; case 's': startnonce = parsed; startgiven = 1; break; case 'n': if (modified == 1) { nonces = (uint64_t)(parsed / NONCE_SIZE); } else { nonces = parsed; } break; case 'm': if (modified == 1) { staggersize = (uint64_t)(parsed / NONCE_SIZE); } else { staggersize = parsed; } break; case 't': threads = parsed; break; case 'b': maxmemory = parsed; break; case 'f': userleavespace = 1; leavespace = parsed; break; case 'p': plotfilesize = parsed; break; case 'x': selecttype = parsed; break; case 'd': ds = strlen(parse); outputdir = (char*) malloc(ds + 2); memcpy(outputdir, parse, ds); // Add final slash? if (outputdir[ds - 1] != '/') { outputdir[ds] = '/'; outputdir[ds + 1] = 0; } else { outputdir[ds] = 0; } } } } // Autodetect threads if (threads == 0) threads = getNumberOfCores(); if (selecttype == 1) { noncearguments = 4; printf("Using SSE4 core.\n"); } else if (selecttype == 2) { noncearguments = 8; printf("Using AVX2 core.\n"); } else { noncearguments = 1; printf("Using ORIG core.\n"); selecttype = 0; } if (noncearguments > 1 && nonces % (threads * noncearguments)) { if (staggersize > 0) { printf("Stagger size is predefined, but number of nonces is not divisible by threads * %d. Unable to use selected hashing core.\n", noncearguments); exit(-1); } else { printf("Number of nonces is not divisible by threads * %d, and will be adjusted when calculating stagger size.\n", noncearguments); } } if (addr == 0) { usage(argv); } // No startnonce given: Just pick random one if (startgiven == 0) { // Just some randomness srand(time(NULL)); startnonce = (uint64_t)rand() * (1 << 30) + rand(); } if (nonces > 0 && plotfilesize > 0) { printf("Both number of nonces and size of plot file is specified. Choose one, and the other will be calculated automatically.\n"); return(1); } // No nonces specified. Calculate nonces based on disk space if (nonces == 0) { uint64_t fs = freespace(outputdir); if (plotfilesize == 0 && (leavespace == 0 && userleavespace != 1)) { // Neither plot file size nor remaining disk space is specified. // Leave maximum 1GB if available, or 50% of the remaining diskspace otherwise. leavespace = (fs > 1024*1024*1024) ? 1024 * 1024 * 1024 : fs * 0.5; } uint64_t usespace = (plotfilesize > 0) ? plotfilesize : fs - leavespace; if (plotfilesize > 0 && leavespace > 0 && (plotfilesize + leavespace > fs)) { printf("Plot file size is set to %0.2f GB and we should leave %0.2f GB of free space, but the disk only has %0.2f GB available.\n", (double)plotfilesize / 1024 / 1024 / 1024, (double)leavespace / 1024 / 1024 / 1024, (double)fs / 1024 / 1024 / 1024); exit(1); } if ((fs < usespace) || ((usespace / NONCE_SIZE) < 1)) { printf("Not enough free space on device. Disk has %0.2f GB available, and we're configured to use %0.2f GB, leaving %0.2f GB.\n", (double)fs / 1024 / 1024 / 1024, (double)usespace / 1024 / 1024 / 1024, (double)leavespace / 1024 / 1024 / 1024); exit(-1); } nonces = (uint64_t)(usespace / NONCE_SIZE); if (noncearguments > 1 && nonces % (threads * noncearguments)) { nonces -= nonces % (threads * noncearguments); } printf("Number of nonces not specified. Attempting to create %d nonces (%0.2f GB), leaving %0.2f GB remaining free space.\n", nonces, ((double)nonces * NONCE_SIZE / 1024 / 1024 / 1024), ((double)(fs - usespace) / 1024 / 1024 / 1024)); } // Autodetect stagger size if (staggersize == 0) { // Use max 80% (40% if async mode) of total available memory, unless the user has specified a limit uint64_t usememory = (maxmemory > 0) ? maxmemory : freemem() * 0.8; if (asyncmode) { usememory = (uint64_t)usememory / 2; } if (usememory < NONCE_SIZE) { printf("Unable to plot any nonces (%d bytes) with only %" PRIu64 " bytes of memory available.\n", NONCE_SIZE, usememory); exit(1); } uint64_t memstag = usememory / NONCE_SIZE; int staggerdiff = (memstag > 1000) ? 1000 : 1; if (nonces < memstag) { // Small stack: all at once if (noncearguments > 1 && nonces % (threads * noncearguments)) { printf("All nonces would fit in memory, but number of nonces is not divisible by threads * %d. Adjusting nonces from %d to %d.\n", noncearguments, nonces, (nonces - (nonces % (threads * noncearguments)))); nonces -= (nonces % (threads * noncearguments)); } else { printf("All nonces will fit in memory. Setting stagger size to %d\n", nonces); } staggersize = nonces; } else { // Determine stagger that (almost) fits nonces for (i = memstag; i >= staggerdiff; i--) { if (i - (i % (threads * noncearguments)) <= 0) { printf("Unable to find suitable stagger size for selected hashing core based on %d nonces and %d thread(s). Could indicate lack of memory (%0.2f GB).\n", nonces, threads, (double)usememory / 1024 / 1024 / 1024); return(1); } if (nonces % (i - (i % (threads * noncearguments))) <= staggerdiff) { if (selecttype > 0) { // Optimize stagger sizes for nonces processed per hashing core i = i - (i % (threads * noncearguments)); } staggersize = i; printf("Stagger size was set to %u, based on available memory and selected hashing algorithm.\n", staggersize); if ((nonces % staggersize) > 0) { printf("Adjusting nonces from %u to %u to comply with stagger size.\n", nonces, (nonces - (nonces % i))); nonces -= (nonces % i); } i = 0; } } } } if (nonces == 0 || staggersize == 0) { printf("Ended up with %d nonces and a stagger size of %d. Unable to proceed.", nonces, staggersize); return(1); } // Adjust according to stagger size if (nonces % staggersize != 0) { nonces -= nonces % staggersize; nonces += staggersize; printf("Adjusting total nonces to %u to match stagger size\n", nonces); } printf("Creating plots for %u nonces (%" PRIu64 " to %" PRIu64 ", %0.2f GB) with stagger size %u, using %0.2f MB memory and %u threads\n", nonces, startnonce, (startnonce + nonces), ((double)nonces * NONCE_SIZE / 1024 / 1024 / 1024), staggersize, ((double)staggersize / 4 * (1 + asyncmode)), threads); // Comment this out/change it if you really want more than 128 Threads if (threads > 128) { printf("%u threads? Sure?\n", threads); exit(-1); } if (asyncmode == 1) { acache[0] = alloc( NONCE_SIZE, staggersize ); acache[1] = alloc( NONCE_SIZE, staggersize ); if (acache[0] == NULL || acache[1] == NULL) { printf("Error allocating memory. Try lower stagger size or removing ASYNC mode.\n"); exit(-1); } } else { cache = alloc( NONCE_SIZE, staggersize ); if (cache == NULL) { printf("Error allocating memory. Try lower stagger size.\n"); exit(-1); } } mkdir(outputdir, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IROTH); char name[200]; char finalname[200]; sprintf(name, "%s%"PRIu64"_%"PRIu64"_%u.plotting", outputdir, addr, startnonce, nonces); sprintf(finalname, "%s%"PRIu64"_%"PRIu64"_%u", outputdir, addr, startnonce, nonces); int readconfig = 0; if ( !resume ) { unlink(name); // no need to see if file exists: unlink can handle that } else if( access( name, F_OK ) != -1 ) { readconfig = 1; } #if __APPLE__ ofd = open(name, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); #else if (! use_direct_io) { ofd = open(name, O_CREAT | O_LARGEFILE | O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); } else { printf("Using Direct I/O to avoid flushing buffer cache\n"); ofd = open(name, O_CREAT | O_LARGEFILE | O_RDWR | O_DIRECT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); } #endif if (ofd < 0) { perror(name); printf("Error opening file %s\n", name); exit(1); } if ( readconfig ) { uint32_t id; // Read last status from the end of the file if ( LSEEK(ofd, -sizeof run - sizeof id, SEEK_END) < 0 ) { printf("\n\nError while lseek()ing in file: %d\n\n", errno); exit(1); } if ( read(ofd, &id, sizeof id) < sizeof id ) { printf("\n\nError while reading from file: %d\n\n", errno); exit(1); } if (id != resumeid) { printf("\n\nThis plot file does not support resuming!\n\n"); } else if ( read(ofd, &run, sizeof run) < sizeof run ) { printf("\n\nError while reading from file: %d\n\n", errno); exit(1); } startnonce += run; printf("Resuming at nonce %ld with staggersize %d...\n", startnonce, staggersize); } else { // pre-allocate space to prevent fragmentation uint64_t filesize = (uint64_t)nonces * NONCE_SIZE; printf("Pre-allocating space for file (%ld bytes)...\n", filesize); if ( posix_fallocate(ofd, 0, filesize) != 0 ) { printf("File pre-allocation failed.\n"); return 1; } else { printf("Done pre-allocating space.\n"); } // Write resume id to the end of the file if ( LSEEK(ofd, -sizeof run - sizeof resumeid, SEEK_END) < 0 ) { printf("\n\nError while lseek()ing in file: %d\n\n", errno); exit(1); } if ( write(ofd, &resumeid, sizeof resumeid) < 0 ) { perror("write"); printf("\n\nError while writing to file: %d\n\n", errno); exit(1); } writestatus(); } // Threads: noncesperthread = (uint64_t)(staggersize / threads); if (noncesperthread == 0) { threads = staggersize; noncesperthread = 1; } // Check the size of the stack and increase if necessary int err = 0; pthread_attr_t stackSizeAttribute; size_t stackSize = 0; /* Initialize the attribute */ err = pthread_attr_init(&stackSizeAttribute); if (err) { printf("Error retreiving the pthread stack size attribute: %d\n", err); return 1; } /* Get the default value */ err = pthread_attr_getstacksize(&stackSizeAttribute, &stackSize); if (err) { printf("Error retreving the pthread stack size: %d\n", err); return 1; } if (verbose) { printf("Current stack size is: %ld\n", stackSize); } /* If the default size does not fit our needs, set the attribute with our required value */ if (stackSize < REQUIRED_STACK_SIZE) { if (verbose) { printf("Initializing pthreads with increased stack size: %d\n", REQUIRED_STACK_SIZE); } err = pthread_attr_setstacksize (&stackSizeAttribute, REQUIRED_STACK_SIZE); if (err) { printf("Error setting pthreads stack size attribute: %d\n", err); } } pthread_t worker[threads], writeworker; int workerrunning = 0; uint64_t nonceoffset[threads]; int asyncbuf = 0; double totalcreatetime = 0.0; uint64_t astarttime; if (asyncmode == 1) cache = acache[asyncbuf]; else wcache = cache; for (; run < nonces; run += staggersize) { astarttime = getMS(); for (i = 0; i < threads; i++) { nonceoffset[i] = startnonce + i * noncesperthread; if (pthread_create(&worker[i], &stackSizeAttribute, work_i, &nonceoffset[i])) { printf("Error creating thread. Out of memory? Try lower stagger size / less threads\n"); exit(-1); } } for (i = 0; i < threads; i++) { // Wait for Threads to finish; pthread_join(worker[i], NULL); } for (i = threads * noncesperthread; i < staggersize; i++) // Run leftover nonces nonce(addr, startnonce + i, (uint64_t)i); // Write plot to disk: createtime = ((double)getMS() - (double)astarttime) / 1000000.0; totalcreatetime += createtime; starttime = astarttime; if (asyncmode == 1) { if (workerrunning) pthread_join(writeworker, NULL); else workerrunning = 1; thisrun = run; lastrun = run + staggersize; wcache = cache; if (pthread_create(&writeworker, NULL, writecache, (void *)NULL)) { printf("Error creating thread. Out of memory? Try lower stagger size / fewer threads / remove async mode\n"); exit(-1); } asyncbuf = 1 - asyncbuf; cache = acache[asyncbuf]; } else { thisrun = run; lastrun = run + staggersize; if (pthread_create(&writeworker, NULL, writecache, (void *)NULL)) { printf("Error creating thread. Out of memory? Try lower stagger size / fewer threads\n"); exit(-1); } pthread_join(writeworker, NULL); } writestatus(); startnonce += staggersize; } if (asyncmode == 1) pthread_join(writeworker, NULL); close(ofd); printf("\nFinished plotting. %d nonces created in %.1fs; renaming file...\n", nonces, totalcreatetime); unlink(finalname); if ( rename(name, finalname) < 0 ) { printf("Error while renaming file: %d\n", errno); return 1; } return 0; } /* }}} */
brmmm3/engraver
helper.c
#include <string.h> #include <stdio.h> #ifdef _WIN32 #include <windows.h> #elif MACOS #include <sys/param.h> #include <sys/sysctl.h> #else #include <unistd.h> #include <netdb.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/statvfs.h> #endif // Following 2 routines taken from: http://stackoverflow.com/questions/1557400/hex-to-char-array-in-c int xdigit( char digit ){ int val; if( '0' <= digit && digit <= '9' ) val = digit -'0'; else if( 'a' <= digit && digit <= 'f' ) val = digit -'a'+10; else if( 'A' <= digit && digit <= 'F' ) val = digit -'A'+10; else val = -1; return val; } int xstr2strr(char *buf, unsigned bufsize, const char *in) { if( !in ) return -1; // missing input string unsigned inlen=strlen(in); if( inlen%2 != 0 ) inlen--; // hex string must even sized unsigned int i,j; for(i=0; i<inlen; i++ ) if( xdigit(in[i])<0 ) return -3; // bad character in hex string if( !buf || bufsize<inlen/2+1 ) return -4; // no buffer or too small for(i=0,j=0; i<inlen; i+=2,j++ ) buf[j] = xdigit(in[i])*16 + xdigit(in[i+1]); buf[inlen/2] = '\0'; return inlen/2+1; } // END (taken from) // Detect number of CPUs (by <NAME>) int getNumberOfCores() { #ifdef WIN32 SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); return sysinfo.dwNumberOfProcessors; #elif MACOS int nm[2]; size_t len = 4; uint32_t count; nm[0] = CTL_HW; nm[1] = HW_AVAILCPU; sysctl(nm, 2, &count, &len, NULL, 0); if(count < 1) { nm[1] = HW_NCPU; sysctl(nm, 2, &count, &len, NULL, 0); if(count < 1) { count = 1; } } return count; #else return sysconf(_SC_NPROCESSORS_ONLN); #endif } // From http://www.binarytides.com/hostname-to-ip-address-c-sockets-linux/ int hostname_to_ip(char * hostname , char* ip) { struct hostent *he; struct in_addr **addr_list; int i; if ( (he = gethostbyname( hostname ) ) == NULL) { herror("gethostbyname"); return 1; } addr_list = (struct in_addr **) he->h_addr_list; for(i = 0; addr_list[i] != NULL; i++) { //Return the first one; strcpy(ip , inet_ntoa(*addr_list[i]) ); return 0; } return 1; } unsigned long long freespace(char *path) { struct statvfs fData; if(statvfs(path,&fData) != 0) { printf("Failed to get free disk space on %s\n", path); return 0; } return (unsigned long long)fData.f_bsize * fData.f_bavail; } // Free memory. Taken from http://stackoverflow.com/questions/2513505/how-to-get-available-memory-c-g unsigned long long freemem() { #ifdef _WIN32 MEMORYSTATUSEX status; status.dwLength = sizeof(status); GlobalMemoryStatusEx(&status); return status.ullTotalPhys; #else long pages = sysconf(_SC_PHYS_PAGES); long page_size = sysconf(_SC_PAGE_SIZE); return (unsigned long long)pages * page_size; #endif }
g1050/recipes
thread/test/vim.h
#ifndef vim_H #define vim_H class Vim{ public: inline int func(int a); private: int a; }; #endif
g1050/recipes
thread/Thread.h
// excerpts from http://code.google.com/p/muduo/ // // Use of this source code is governed by a BSD-style license // that can be found in the License file. // // Author: <NAME> (giantchen at gmail dot com) #ifndef MUDUO_BASE_THREAD_H #define MUDUO_BASE_THREAD_H #include "./Atomic.h" #include <boost/function.hpp> #include <boost/noncopyable.hpp> #include <boost/shared_ptr.hpp> #include <pthread.h> namespace muduo { /* muduo库对thread的封装 */ class Thread : boost::noncopyable { public: typedef boost::function<void ()> ThreadFunc;//函数模板类 /* 构造函数传入一个回调函数和name ,name默认值是一个串*/ explicit Thread(const ThreadFunc&, const std::string& name = std::string()); ~Thread(); void start(); void join(); bool started() const { return started_; } // pthread_t pthreadId() const { return pthreadId_; } pid_t tid() const { return *tid_; } const std::string& name() const { return name_; } //计数器,所有通过Thread类来创建的线程都会+1 static int numCreated() { return numCreated_.get(); } private: bool started_;// bool joined_; pthread_t pthreadId_;//类型不缺定,且不唯一 boost::shared_ptr<pid_t> tid_;//pid_t的智能指针 ThreadFunc func_;//回调函数 std::string name_;//啥名字啊? static AtomicInt32 numCreated_;//静态对象 }; namespace CurrentThread { pid_t tid(); const char* name(); bool isMainThread(); } } #endif
infancy/ky
smallpt/erand48.h
<gh_stars>1-10 /*------------------------------------------------------------------------- * * erand48.c * * This file supplies versions of erand48(), lrand48(), and srand48() * for machines that lack them. (These are all the members of the drand48 * family that Postgres currently requires. We name the file after erand48 * because that is the one that configure tests for.) * * * Copyright (c) 1993 <NAME> * All rights reserved. * * You may redistribute unmodified or modified versions of this source * code provided that the above copyright notice and this and the * following conditions are retained. * * This software is provided ``as is'', and comes with no warranties * of any kind. I shall in no event be liable for anything that happens * to anyone/anything when using this software. * * IDENTIFICATION * $PostgreSQL: pgsql/src/port/erand48.c,v 1.1 2009/07/16 17:43:52 tgl Exp $ * *------------------------------------------------------------------------- */ //#include "c.h" #include <math.h> #define RAND48_SEED_0 (0x330e) #define RAND48_SEED_1 (0xabcd) #define RAND48_SEED_2 (0x1234) #define RAND48_MULT_0 (0xe66d) #define RAND48_MULT_1 (0xdeec) #define RAND48_MULT_2 (0x0005) #define RAND48_ADD (0x000b) static unsigned short _rand48_seed[3] = { RAND48_SEED_0, RAND48_SEED_1, RAND48_SEED_2 }; static unsigned short _rand48_mult[3] = { RAND48_MULT_0, RAND48_MULT_1, RAND48_MULT_2 }; static unsigned short _rand48_add = RAND48_ADD; __forceinline static void _dorand48(unsigned short xseed[3]) { unsigned long accu; unsigned short temp[2]; accu = (unsigned long) _rand48_mult[0] * (unsigned long) xseed[0] + (unsigned long) _rand48_add; temp[0] = (unsigned short) accu; /* lower 16 bits */ accu >>= sizeof(unsigned short) * 8; accu += (unsigned long) _rand48_mult[0] * (unsigned long) xseed[1] + (unsigned long) _rand48_mult[1] * (unsigned long) xseed[0]; temp[1] = (unsigned short) accu; /* middle 16 bits */ accu >>= sizeof(unsigned short) * 8; accu += _rand48_mult[0] * xseed[2] + _rand48_mult[1] * xseed[1] + _rand48_mult[2] * xseed[0]; xseed[0] = temp[0]; xseed[1] = temp[1]; xseed[2] = (unsigned short) accu; } __forceinline double erand48(unsigned short xseed[3]) { _dorand48(xseed); return ldexp((double) xseed[0], -48) + ldexp((double) xseed[1], -32) + ldexp((double) xseed[2], -16); } __forceinline long lrand48(void) { _dorand48(_rand48_seed); return ((long) _rand48_seed[2] << 15) + ((long) _rand48_seed[1] >> 1); } __forceinline void srand48(long seed) { _rand48_seed[0] = RAND48_SEED_0; _rand48_seed[1] = (unsigned short) seed; _rand48_seed[2] = (unsigned short) (seed > 16); _rand48_mult[0] = RAND48_MULT_0; _rand48_mult[1] = RAND48_MULT_1; _rand48_mult[2] = RAND48_MULT_2; _rand48_add = RAND48_ADD; }
enbiso/esp-restclient
RestClient.h
#ifndef RestClient_h #define RestClient_h #include <Arduino.h> #include <WiFiClientSecure.h> class RestClient { public: RestClient(String host) { RestClient(host, 80); } RestClient(String host, int port) { RestClient(host, port, "http"); } RestClient(String host, int port, String protocol) { RestClient(host, port, protocol, ""); } RestClient(String host, int port, String protocol, String basePath); int request(String method, String path, const char *body, String *response); void setHeader(String header); void setContentType(String contentType); void setProtocol(String protocol); int get(String path) { return request("GET", path, NULL, NULL); } int get(String path, String *response) { return request("GET", path, NULL, response); } int post(String path, String body) { return request("POST", path, body.c_str(), NULL); } int post(String path, String body, String *response) { return request("POST", path, body.c_str(), response); } int patch(String path, String body) { return request("PATCH", path, body.c_str(), NULL); } int patch(String path, String body, String *response) { return request("PATCH", path, body.c_str(), response); } int put(String path, String body) { return request("PUT", path, body.c_str(), NULL); } int put(String path, String body, String *response) { return request("PUT", path, body.c_str(), response); } int del(String path) { return request("DELETE", path, NULL, NULL); } int del(String path, String *response) { return request("DELETE", path, NULL, response); } int del(String path, String body) { return request("DELETE", path, body.c_str(), NULL); } int del(String path, String body, String *response) { return request("DELETE", path, body.c_str(), response); } private: WiFiClient *client; int _readResponse(String *response); String host; int port; int num_headers; String headers[10]; String contentType; int ssl; String basePath; }; #endif
DeveloperLY/LYXcodeExtension
LYXcodeExtension/ViewController.h
<reponame>DeveloperLY/LYXcodeExtension<gh_stars>0 // // ViewController.h // LYXcodeExtension // // Created by LiuY on 2019/9/18. // Copyright © 2019 DeveloperLY. All rights reserved. // #import <Cocoa/Cocoa.h> @interface ViewController : NSViewController @end
DeveloperLY/LYXcodeExtension
LYExtension/SourceEditorCommand.h
// // SourceEditorCommand.h // LYExtension // // Created by LiuY on 2019/9/18. // Copyright © 2019 DeveloperLY. All rights reserved. // #import <XcodeKit/XcodeKit.h> @interface SourceEditorCommand : NSObject <XCSourceEditorCommand> @end
DeveloperLY/LYXcodeExtension
LYExtension/Tools/NSMutableArray+LYExtension.h
// // NSMutableArray+LYExtension.h // LYExtension // // Created by LiuY on 2019/9/18. // Copyright © 2019 DeveloperLY. All rights reserved. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface NSMutableArray (LYExtension) - (NSInteger)indexOfFirstItemContainStrsArray:(NSArray *)strsArray; - (NSInteger)indexOfFirstItemContainStr:(NSString *)str; - (NSInteger)indexOfFirstItemContainStr:(NSString *)str fromIndex:(NSInteger)fromIndex; - (NSInteger)indexOfFirstItemContainStr:(NSString *)str fromIndex:(NSInteger)fromIndex andToIndex:(NSInteger)toIndex; - (void)insertItemsOfArray:(NSArray *)itemsArray fromIndex:(NSInteger)insertIndex; - (NSString *)fetchClassName; - (NSString *)fetchCurrentClassNameWithCurrentIndex:(NSInteger)currentIndex; - (void)deleteItemsFromFirstItemContains:(NSString *)firstStr andLastItemsContainsStr:(NSString *)lastStr; - (void)printList; - (NSMutableArray *)arrayWithNoSameItem; @end NS_ASSUME_NONNULL_END
DeveloperLY/LYXcodeExtension
LYXcodeExtension/AppDelegate.h
// // AppDelegate.h // LYXcodeExtension // // Created by LiuY on 2019/9/18. // Copyright © 2019 DeveloperLY. All rights reserved. // #import <Cocoa/Cocoa.h> @interface AppDelegate : NSObject <NSApplicationDelegate> @end
DeveloperLY/LYXcodeExtension
LYExtension/AddImport/LYAddImportManager.h
<gh_stars>0 // // LYAddImportManager.h // LYExtension // // Created by LiuY on 2019/9/18. // Copyright © 2019 DeveloperLY. All rights reserved. // #import <XcodeKit/XcodeKit.h> NS_ASSUME_NONNULL_BEGIN @interface LYAddImportManager : NSObject + (instancetype)sharedInstance; - (void)processCodeWithInvocation:(XCSourceEditorCommandInvocation *)invocation; @end NS_ASSUME_NONNULL_END
DeveloperLY/LYXcodeExtension
LYExtension/Tools/NSString+LYExtension.h
<gh_stars>0 // // NSString+LYExtension.h // LYExtension // // Created by LiuY on 2019/9/18. // Copyright © 2019 DeveloperLY. All rights reserved. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface NSString (LYExtension) /* * 返回中间字符串 * 如果 leftStr 为 nil , 则返回 rightStr 之前的字符串 */ - (NSString *)stringBetweenLeftStr:(nullable NSString *)leftStr andRightStr:(nullable NSString *)rightStr; // 删除空格和换行符 - (NSString *)deleteSpaceAndNewLine; // 获取类型字符串 - (NSString *)fetchClassNameStr; // 获取属性名 - (NSString *)fetchPropertyNameStr; - (BOOL)checkHasContainsOneOfStrs:(NSArray *)strArray andNotContainsOneOfStrs:(NSArray *)noHasStrsArray; @end NS_ASSUME_NONNULL_END
DeveloperLY/LYXcodeExtension
LYExtension/AddComment/LYAddCommentManager.h
// // LYAddCommentManager.h // LYExtension // // Created by LiuY on 2019/9/18. // Copyright © 2019 DeveloperLY. All rights reserved. // #import <XcodeKit/XcodeKit.h> NS_ASSUME_NONNULL_BEGIN @interface LYAddCommentManager : NSObject + (instancetype)sharedInstance; - (void)processCodeWithInvocation:(XCSourceEditorCommandInvocation *)invocation; @end NS_ASSUME_NONNULL_END
tsturm/flatbuffers
tests/namespace_test/namespace_test1_generated.h
// automatically generated by the FlatBuffers compiler, do not modify #ifndef FLATBUFFERS_GENERATED_NAMESPACETEST1_NAMESPACEA_NAMESPACEB_H_ #define FLATBUFFERS_GENERATED_NAMESPACETEST1_NAMESPACEA_NAMESPACEB_H_ #include "flatbuffers/flatbuffers.h" namespace NamespaceA { namespace NamespaceB { struct TableInNestedNS; struct TableInNestedNSBuilder; struct TableInNestedNST; struct StructInNestedNS; bool operator==(const TableInNestedNST &lhs, const TableInNestedNST &rhs); bool operator!=(const TableInNestedNST &lhs, const TableInNestedNST &rhs); bool operator==(const StructInNestedNS &lhs, const StructInNestedNS &rhs); bool operator!=(const StructInNestedNS &lhs, const StructInNestedNS &rhs); inline const flatbuffers::TypeTable *TableInNestedNSTypeTable(); inline const flatbuffers::TypeTable *StructInNestedNSTypeTable(); enum UnionInNestedNS : uint8_t { UnionInNestedNS_NONE = 0, UnionInNestedNS_TableInNestedNS = 1, UnionInNestedNS_MIN = UnionInNestedNS_NONE, UnionInNestedNS_MAX = UnionInNestedNS_TableInNestedNS }; inline const UnionInNestedNS (&EnumValuesUnionInNestedNS())[2] { static const UnionInNestedNS values[] = { UnionInNestedNS_NONE, UnionInNestedNS_TableInNestedNS }; return values; } inline const char * const *EnumNamesUnionInNestedNS() { static const char * const names[3] = { "NONE", "TableInNestedNS", nullptr }; return names; } inline const char *EnumNameUnionInNestedNS(UnionInNestedNS e) { if (flatbuffers::IsOutRange(e, UnionInNestedNS_NONE, UnionInNestedNS_TableInNestedNS)) return ""; const size_t index = static_cast<size_t>(e); return EnumNamesUnionInNestedNS()[index]; } template<typename T> struct UnionInNestedNSTraits { static const UnionInNestedNS enum_value = UnionInNestedNS_NONE; }; template<> struct UnionInNestedNSTraits<NamespaceA::NamespaceB::TableInNestedNS> { static const UnionInNestedNS enum_value = UnionInNestedNS_TableInNestedNS; }; template<typename T> struct UnionInNestedNSUnionTraits { static const UnionInNestedNS enum_value = UnionInNestedNS_NONE; }; template<> struct UnionInNestedNSUnionTraits<NamespaceA::NamespaceB::TableInNestedNST> { static const UnionInNestedNS enum_value = UnionInNestedNS_TableInNestedNS; }; struct UnionInNestedNSUnion { UnionInNestedNS type; void *value; UnionInNestedNSUnion() : type(UnionInNestedNS_NONE), value(nullptr) {} UnionInNestedNSUnion(UnionInNestedNSUnion&& u) FLATBUFFERS_NOEXCEPT : type(UnionInNestedNS_NONE), value(nullptr) { std::swap(type, u.type); std::swap(value, u.value); } UnionInNestedNSUnion(const UnionInNestedNSUnion &); UnionInNestedNSUnion &operator=(const UnionInNestedNSUnion &u) { UnionInNestedNSUnion t(u); std::swap(type, t.type); std::swap(value, t.value); return *this; } UnionInNestedNSUnion &operator=(UnionInNestedNSUnion &&u) FLATBUFFERS_NOEXCEPT { std::swap(type, u.type); std::swap(value, u.value); return *this; } ~UnionInNestedNSUnion() { Reset(); } void Reset(); template <typename T> void Set(T&& val) { typedef typename std::remove_reference<T>::type RT; Reset(); type = UnionInNestedNSUnionTraits<RT>::enum_value; if (type != UnionInNestedNS_NONE) { value = new RT(std::forward<T>(val)); } } static void *UnPack(const void *obj, UnionInNestedNS type, const flatbuffers::resolver_function_t *resolver); flatbuffers::Offset<void> Pack(flatbuffers::FlatBufferBuilder &_fbb, const flatbuffers::rehasher_function_t *_rehasher = nullptr) const; NamespaceA::NamespaceB::TableInNestedNST *AsTableInNestedNS() { return type == UnionInNestedNS_TableInNestedNS ? reinterpret_cast<NamespaceA::NamespaceB::TableInNestedNST *>(value) : nullptr; } const NamespaceA::NamespaceB::TableInNestedNST *AsTableInNestedNS() const { return type == UnionInNestedNS_TableInNestedNS ? reinterpret_cast<const NamespaceA::NamespaceB::TableInNestedNST *>(value) : nullptr; } }; inline bool operator==(const UnionInNestedNSUnion &lhs, const UnionInNestedNSUnion &rhs) { if (lhs.type != rhs.type) return false; switch (lhs.type) { case UnionInNestedNS_NONE: { return true; } case UnionInNestedNS_TableInNestedNS: { return *(reinterpret_cast<const NamespaceA::NamespaceB::TableInNestedNST *>(lhs.value)) == *(reinterpret_cast<const NamespaceA::NamespaceB::TableInNestedNST *>(rhs.value)); } default: { return false; } } } inline bool operator!=(const UnionInNestedNSUnion &lhs, const UnionInNestedNSUnion &rhs) { return !(lhs == rhs); } bool VerifyUnionInNestedNS(flatbuffers::Verifier &verifier, const void *obj, UnionInNestedNS type); bool VerifyUnionInNestedNSVector(flatbuffers::Verifier &verifier, const flatbuffers::Vector<flatbuffers::Offset<void>> *values, const flatbuffers::Vector<uint8_t> *types); enum EnumInNestedNS : int8_t { EnumInNestedNS_A = 0, EnumInNestedNS_B = 1, EnumInNestedNS_C = 2, EnumInNestedNS_MIN = EnumInNestedNS_A, EnumInNestedNS_MAX = EnumInNestedNS_C }; inline const EnumInNestedNS (&EnumValuesEnumInNestedNS())[3] { static const EnumInNestedNS values[] = { EnumInNestedNS_A, EnumInNestedNS_B, EnumInNestedNS_C }; return values; } inline const char * const *EnumNamesEnumInNestedNS() { static const char * const names[4] = { "A", "B", "C", nullptr }; return names; } inline const char *EnumNameEnumInNestedNS(EnumInNestedNS e) { if (flatbuffers::IsOutRange(e, EnumInNestedNS_A, EnumInNestedNS_C)) return ""; const size_t index = static_cast<size_t>(e); return EnumNamesEnumInNestedNS()[index]; } FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) StructInNestedNS FLATBUFFERS_FINAL_CLASS { private: int32_t a_; int32_t b_; public: static const flatbuffers::TypeTable *MiniReflectTypeTable() { return StructInNestedNSTypeTable(); } static FLATBUFFERS_CONSTEXPR_CPP11 const char *GetFullyQualifiedName() { return "NamespaceA.NamespaceB.StructInNestedNS"; } StructInNestedNS() : a_(0), b_(0) { } StructInNestedNS(int32_t _a, int32_t _b) : a_(flatbuffers::EndianScalar(_a)), b_(flatbuffers::EndianScalar(_b)) { } int32_t a() const { return flatbuffers::EndianScalar(a_); } void mutate_a(int32_t _a) { flatbuffers::WriteScalar(&a_, _a); } int32_t b() const { return flatbuffers::EndianScalar(b_); } void mutate_b(int32_t _b) { flatbuffers::WriteScalar(&b_, _b); } }; FLATBUFFERS_STRUCT_END(StructInNestedNS, 8); inline bool operator==(const StructInNestedNS &lhs, const StructInNestedNS &rhs) { return (lhs.a() == rhs.a()) && (lhs.b() == rhs.b()); } inline bool operator!=(const StructInNestedNS &lhs, const StructInNestedNS &rhs) { return !(lhs == rhs); } struct TableInNestedNST : public flatbuffers::NativeTable { typedef TableInNestedNS TableType; static FLATBUFFERS_CONSTEXPR_CPP11 const char *GetFullyQualifiedName() { return "NamespaceA.NamespaceB.TableInNestedNST"; } int32_t foo = 0; }; struct TableInNestedNS FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table { typedef TableInNestedNST NativeTableType; typedef TableInNestedNSBuilder Builder; static const flatbuffers::TypeTable *MiniReflectTypeTable() { return TableInNestedNSTypeTable(); } static FLATBUFFERS_CONSTEXPR_CPP11 const char *GetFullyQualifiedName() { return "NamespaceA.NamespaceB.TableInNestedNS"; } enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { VT_FOO = 4 }; int32_t foo() const { return GetField<int32_t>(VT_FOO, 0); } bool mutate_foo(int32_t _foo = 0) { return SetField<int32_t>(VT_FOO, _foo, 0); } bool Verify(flatbuffers::Verifier &verifier) const { return VerifyTableStart(verifier) && VerifyField<int32_t>(verifier, VT_FOO, 4) && verifier.EndTable(); } TableInNestedNST *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const; void UnPackTo(TableInNestedNST *_o, const flatbuffers::resolver_function_t *_resolver = nullptr) const; static flatbuffers::Offset<TableInNestedNS> Pack(flatbuffers::FlatBufferBuilder &_fbb, const TableInNestedNST* _o, const flatbuffers::rehasher_function_t *_rehasher = nullptr); }; struct TableInNestedNSBuilder { typedef TableInNestedNS Table; flatbuffers::FlatBufferBuilder &fbb_; flatbuffers::uoffset_t start_; void add_foo(int32_t foo) { fbb_.AddElement<int32_t>(TableInNestedNS::VT_FOO, foo, 0); } explicit TableInNestedNSBuilder(flatbuffers::FlatBufferBuilder &_fbb) : fbb_(_fbb) { start_ = fbb_.StartTable(); } flatbuffers::Offset<TableInNestedNS> Finish() { const auto end = fbb_.EndTable(start_); auto o = flatbuffers::Offset<TableInNestedNS>(end); return o; } }; inline flatbuffers::Offset<TableInNestedNS> CreateTableInNestedNS( flatbuffers::FlatBufferBuilder &_fbb, int32_t foo = 0) { TableInNestedNSBuilder builder_(_fbb); builder_.add_foo(foo); return builder_.Finish(); } flatbuffers::Offset<TableInNestedNS> CreateTableInNestedNS(flatbuffers::FlatBufferBuilder &_fbb, const TableInNestedNST *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr); inline bool operator==(const TableInNestedNST &lhs, const TableInNestedNST &rhs) { return (lhs.foo == rhs.foo); } inline bool operator!=(const TableInNestedNST &lhs, const TableInNestedNST &rhs) { return !(lhs == rhs); } inline TableInNestedNST *TableInNestedNS::UnPack(const flatbuffers::resolver_function_t *_resolver) const { auto _o = std::unique_ptr<TableInNestedNST>(new TableInNestedNST()); UnPackTo(_o.get(), _resolver); return _o.release(); } inline void TableInNestedNS::UnPackTo(TableInNestedNST *_o, const flatbuffers::resolver_function_t *_resolver) const { (void)_o; (void)_resolver; { auto _e = foo(); _o->foo = _e; } } inline flatbuffers::Offset<TableInNestedNS> TableInNestedNS::Pack(flatbuffers::FlatBufferBuilder &_fbb, const TableInNestedNST* _o, const flatbuffers::rehasher_function_t *_rehasher) { return CreateTableInNestedNS(_fbb, _o, _rehasher); } inline flatbuffers::Offset<TableInNestedNS> CreateTableInNestedNS(flatbuffers::FlatBufferBuilder &_fbb, const TableInNestedNST *_o, const flatbuffers::rehasher_function_t *_rehasher) { (void)_rehasher; (void)_o; struct _VectorArgs { flatbuffers::FlatBufferBuilder *__fbb; const TableInNestedNST* __o; const flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; auto _foo = _o->foo; return NamespaceA::NamespaceB::CreateTableInNestedNS( _fbb, _foo); } inline bool VerifyUnionInNestedNS(flatbuffers::Verifier &verifier, const void *obj, UnionInNestedNS type) { switch (type) { case UnionInNestedNS_NONE: { return true; } case UnionInNestedNS_TableInNestedNS: { auto ptr = reinterpret_cast<const NamespaceA::NamespaceB::TableInNestedNS *>(obj); return verifier.VerifyTable(ptr); } default: return true; } } inline bool VerifyUnionInNestedNSVector(flatbuffers::Verifier &verifier, const flatbuffers::Vector<flatbuffers::Offset<void>> *values, const flatbuffers::Vector<uint8_t> *types) { if (!values || !types) return !values && !types; if (values->size() != types->size()) return false; for (flatbuffers::uoffset_t i = 0; i < values->size(); ++i) { if (!VerifyUnionInNestedNS( verifier, values->Get(i), types->GetEnum<UnionInNestedNS>(i))) { return false; } } return true; } inline void *UnionInNestedNSUnion::UnPack(const void *obj, UnionInNestedNS type, const flatbuffers::resolver_function_t *resolver) { (void)resolver; switch (type) { case UnionInNestedNS_TableInNestedNS: { auto ptr = reinterpret_cast<const NamespaceA::NamespaceB::TableInNestedNS *>(obj); return ptr->UnPack(resolver); } default: return nullptr; } } inline flatbuffers::Offset<void> UnionInNestedNSUnion::Pack(flatbuffers::FlatBufferBuilder &_fbb, const flatbuffers::rehasher_function_t *_rehasher) const { (void)_rehasher; switch (type) { case UnionInNestedNS_TableInNestedNS: { auto ptr = reinterpret_cast<const NamespaceA::NamespaceB::TableInNestedNST *>(value); return CreateTableInNestedNS(_fbb, ptr, _rehasher).Union(); } default: return 0; } } inline UnionInNestedNSUnion::UnionInNestedNSUnion(const UnionInNestedNSUnion &u) : type(u.type), value(nullptr) { switch (type) { case UnionInNestedNS_TableInNestedNS: { value = new NamespaceA::NamespaceB::TableInNestedNST(*reinterpret_cast<NamespaceA::NamespaceB::TableInNestedNST *>(u.value)); break; } default: break; } } inline void UnionInNestedNSUnion::Reset() { switch (type) { case UnionInNestedNS_TableInNestedNS: { auto ptr = reinterpret_cast<NamespaceA::NamespaceB::TableInNestedNST *>(value); delete ptr; break; } default: break; } value = nullptr; type = UnionInNestedNS_NONE; } inline const flatbuffers::TypeTable *UnionInNestedNSTypeTable() { static const flatbuffers::TypeCode type_codes[] = { { flatbuffers::ET_SEQUENCE, 0, -1 }, { flatbuffers::ET_SEQUENCE, 0, 0 } }; static const flatbuffers::TypeFunction type_refs[] = { NamespaceA::NamespaceB::TableInNestedNSTypeTable }; static const char * const names[] = { "NONE", "TableInNestedNS" }; static const flatbuffers::TypeTable tt = { flatbuffers::ST_UNION, 2, type_codes, type_refs, nullptr, nullptr, names }; return &tt; } inline const flatbuffers::TypeTable *EnumInNestedNSTypeTable() { static const flatbuffers::TypeCode type_codes[] = { { flatbuffers::ET_CHAR, 0, 0 }, { flatbuffers::ET_CHAR, 0, 0 }, { flatbuffers::ET_CHAR, 0, 0 } }; static const flatbuffers::TypeFunction type_refs[] = { NamespaceA::NamespaceB::EnumInNestedNSTypeTable }; static const char * const names[] = { "A", "B", "C" }; static const flatbuffers::TypeTable tt = { flatbuffers::ST_ENUM, 3, type_codes, type_refs, nullptr, nullptr, names }; return &tt; } inline const flatbuffers::TypeTable *TableInNestedNSTypeTable() { static const flatbuffers::TypeCode type_codes[] = { { flatbuffers::ET_INT, 0, -1 } }; static const char * const names[] = { "foo" }; static const flatbuffers::TypeTable tt = { flatbuffers::ST_TABLE, 1, type_codes, nullptr, nullptr, nullptr, names }; return &tt; } inline const flatbuffers::TypeTable *StructInNestedNSTypeTable() { static const flatbuffers::TypeCode type_codes[] = { { flatbuffers::ET_INT, 0, -1 }, { flatbuffers::ET_INT, 0, -1 } }; static const int64_t values[] = { 0, 4, 8 }; static const char * const names[] = { "a", "b" }; static const flatbuffers::TypeTable tt = { flatbuffers::ST_STRUCT, 2, type_codes, nullptr, nullptr, values, names }; return &tt; } } // namespace NamespaceB } // namespace NamespaceA #endif // FLATBUFFERS_GENERATED_NAMESPACETEST1_NAMESPACEA_NAMESPACEB_H_
tsturm/flatbuffers
include/flatbuffers/default_allocator.h
/* * Copyright 2021 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef FLATBUFFERS_DEFAULT_ALLOCATOR_H_ #define FLATBUFFERS_DEFAULT_ALLOCATOR_H_ #include "flatbuffers/allocator.h" #include "flatbuffers/base.h" namespace flatbuffers { // DefaultAllocator uses new/delete to allocate memory regions class DefaultAllocator : public Allocator { public: uint8_t *allocate(size_t size) FLATBUFFERS_OVERRIDE { return new uint8_t[size]; } void deallocate(uint8_t *p, size_t) FLATBUFFERS_OVERRIDE { delete[] p; } static void dealloc(void *p, size_t) { delete[] static_cast<uint8_t *>(p); } }; // These functions allow for a null allocator to mean use the default allocator, // as used by DetachedBuffer and vector_downward below. // This is to avoid having a statically or dynamically allocated default // allocator, or having to move it between the classes that may own it. inline uint8_t *Allocate(Allocator *allocator, size_t size) { return allocator ? allocator->allocate(size) : DefaultAllocator().allocate(size); } inline void Deallocate(Allocator *allocator, uint8_t *p, size_t size) { if (allocator) allocator->deallocate(p, size); else DefaultAllocator().deallocate(p, size); } inline uint8_t *ReallocateDownward(Allocator *allocator, uint8_t *old_p, size_t old_size, size_t new_size, size_t in_use_back, size_t in_use_front) { return allocator ? allocator->reallocate_downward(old_p, old_size, new_size, in_use_back, in_use_front) : DefaultAllocator().reallocate_downward( old_p, old_size, new_size, in_use_back, in_use_front); } } // namespace flatbuffers #endif // FLATBUFFERS_DEFAULT_ALLOCATOR_H_
tsturm/flatbuffers
include/flatbuffers/grpc.h
/* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef FLATBUFFERS_GRPC_H_ #define FLATBUFFERS_GRPC_H_ // Helper functionality to glue FlatBuffers and GRPC. #include "flatbuffers/flatbuffers.h" #include "grpc/byte_buffer_reader.h" #include "grpcpp/support/byte_buffer.h" #include "grpcpp/support/slice.h" namespace flatbuffers { namespace grpc { // Message is a typed wrapper around a buffer that manages the underlying // `grpc_slice` and also provides flatbuffers-specific helpers such as `Verify` // and `GetRoot`. Since it is backed by a `grpc_slice`, the underlying buffer // is refcounted and ownership is be managed automatically. template<class T> class Message { public: Message() {} Message(::grpc::Slice slice) : slice_(slice) {} Message &operator=(const Message &other) = delete; Message(Message &&other) = default; Message(const Message &other) = delete; Message &operator=(Message &&other) = default; const uint8_t *mutable_data() const { return slice_.begin(); } const uint8_t *data() const { return slice_.begin(); } size_t size() const { return slice_.size(); } bool Verify() const { Verifier verifier(data(), size()); return verifier.VerifyBuffer<T>(nullptr); } T *GetMutableRoot() { return flatbuffers::GetMutableRoot<T>(mutable_data()); } const T *GetRoot() const { return flatbuffers::GetRoot<T>(data()); } // This is only intended for serializer use, or if you know what you're doing const ::grpc::Slice &BorrowSlice() const { return slice_; } private: ::grpc::Slice slice_; }; class MessageBuilder; // SliceAllocator is a gRPC-specific allocator that uses the `grpc_slice` // refcounted slices to manage memory ownership. This makes it easy and // efficient to transfer buffers to gRPC. class SliceAllocator : public Allocator { public: SliceAllocator() {} SliceAllocator(const SliceAllocator &other) = delete; SliceAllocator &operator=(const SliceAllocator &other) = delete; SliceAllocator(SliceAllocator &&other) { // default-construct and swap idiom swap(other); } SliceAllocator &operator=(SliceAllocator &&other) { // move-construct and swap idiom SliceAllocator temp(std::move(other)); swap(temp); return *this; } void swap(SliceAllocator &other) { using std::swap; swap(slice_, other.slice_); } virtual ~SliceAllocator() {} virtual uint8_t *allocate(size_t size) override { FLATBUFFERS_ASSERT(slice_.size() == 0); slice_ = ::grpc::Slice(size); return const_cast<uint8_t *>(slice_.begin()); } virtual void deallocate(uint8_t *p, size_t size) override { FLATBUFFERS_ASSERT(p == slice_.begin()); FLATBUFFERS_ASSERT(size == slice_.size()); slice_ = ::grpc::Slice(); } virtual uint8_t *reallocate_downward(uint8_t *old_p, size_t old_size, size_t new_size, size_t in_use_back, size_t in_use_front) override { FLATBUFFERS_ASSERT(old_p == slice_.begin()); FLATBUFFERS_ASSERT(old_size == slice_.size()); FLATBUFFERS_ASSERT(new_size > old_size); ::grpc::Slice old_slice = slice_; ::grpc::Slice new_slice = ::grpc::Slice(new_size); uint8_t *new_p = const_cast<uint8_t *>(new_slice.begin()); memcpy_downward(old_p, old_size, new_p, new_size, in_use_back, in_use_front); slice_ = new_slice; return new_p; } private: ::grpc::Slice &get_slice(uint8_t *p, size_t size) { FLATBUFFERS_ASSERT(p == slice_.begin()); FLATBUFFERS_ASSERT(size == slice_.size()); return slice_; } ::grpc::Slice slice_; friend class MessageBuilder; }; // SliceAllocatorMember is a hack to ensure that the MessageBuilder's // slice_allocator_ member is constructed before the FlatBufferBuilder, since // the allocator is used in the FlatBufferBuilder ctor. namespace detail { struct SliceAllocatorMember { SliceAllocator slice_allocator_; }; } // namespace detail // MessageBuilder is a gRPC-specific FlatBufferBuilder that uses SliceAllocator // to allocate gRPC buffers. class MessageBuilder : private detail::SliceAllocatorMember, public FlatBufferBuilder { public: explicit MessageBuilder(uoffset_t initial_size = 1024) : FlatBufferBuilder(initial_size, &slice_allocator_, false) {} MessageBuilder(const MessageBuilder &other) = delete; MessageBuilder &operator=(const MessageBuilder &other) = delete; MessageBuilder(MessageBuilder &&other) : FlatBufferBuilder(1024, &slice_allocator_, false) { // Default construct and swap idiom. Swap(other); } /// Create a MessageBuilder from a FlatBufferBuilder. explicit MessageBuilder(FlatBufferBuilder &&src, void (*dealloc)(void *, size_t) = &DefaultAllocator::dealloc) : FlatBufferBuilder(1024, &slice_allocator_, false) { src.Swap(*this); src.SwapBufAllocator(*this); if (buf_.capacity()) { uint8_t *buf = buf_.scratch_data(); // pointer to memory size_t capacity = buf_.capacity(); // size of memory slice_allocator_.slice_ = ::grpc::Slice(buf, capacity, dealloc); } else { slice_allocator_.slice_ = ::grpc::Slice(); } } /// Move-assign a FlatBufferBuilder to a MessageBuilder. /// Only FlatBufferBuilder with default allocator (basically, nullptr) is /// supported. MessageBuilder &operator=(FlatBufferBuilder &&src) { // Move construct a temporary and swap MessageBuilder temp(std::move(src)); Swap(temp); return *this; } MessageBuilder &operator=(MessageBuilder &&other) { // Move construct a temporary and swap MessageBuilder temp(std::move(other)); Swap(temp); return *this; } void Swap(MessageBuilder &other) { slice_allocator_.swap(other.slice_allocator_); FlatBufferBuilder::Swap(other); // After swapping the FlatBufferBuilder, we swap back the allocator, which // restores the original allocator back in place. This is necessary because // MessageBuilder's allocator is its own member (SliceAllocatorMember). The // allocator passed to FlatBufferBuilder::vector_downward must point to this // member. buf_.swap_allocator(other.buf_); } // Releases the ownership of the buffer pointer. // Returns the size, offset, and the original grpc_slice that // allocated the buffer. Also see grpc_slice_unref(). uint8_t *ReleaseRaw(size_t &size, size_t &offset, ::grpc::Slice &slice) { uint8_t *buf = FlatBufferBuilder::ReleaseRaw(size, offset); slice = slice_allocator_.slice_; slice_allocator_.slice_ = ::grpc::Slice(); return buf; } ~MessageBuilder() {} // GetMessage extracts the subslice of the buffer corresponding to the // flatbuffers-encoded region and wraps it in a `Message<T>` to handle buffer // ownership. template<class T> Message<T> GetMessage() { auto buf_data = buf_.scratch_data(); // pointer to memory auto buf_size = buf_.capacity(); // size of memory auto msg_data = buf_.data(); // pointer to msg auto msg_size = buf_.size(); // size of msg // Do some sanity checks on data/size FLATBUFFERS_ASSERT(msg_data); FLATBUFFERS_ASSERT(msg_size); FLATBUFFERS_ASSERT(msg_data >= buf_data); FLATBUFFERS_ASSERT(msg_data + msg_size <= buf_data + buf_size); // Calculate offsets from the buffer start auto begin = msg_data - buf_data; auto end = begin + msg_size; // Get the slice we are working with (no refcount change) ::grpc::Slice slice = slice_allocator_.get_slice(buf_data, buf_size); // Extract a subslice of the existing slice (increment refcount) ::grpc::Slice subslice = slice.sub(begin, end); // Wrap the subslice in a `Message<T>`, but don't increment refcount Message<T> msg(subslice); return msg; } template<class T> Message<T> ReleaseMessage() { Message<T> msg = GetMessage<T>(); Reset(); return msg; } private: // SliceAllocator slice_allocator_; // part of SliceAllocatorMember }; } // namespace grpc } // namespace flatbuffers namespace grpc { template<class T> class SerializationTraits<flatbuffers::grpc::Message<T>> { public: static grpc::Status Serialize(const flatbuffers::grpc::Message<T> &msg, ByteBuffer *buffer, bool *own_buffer) { // Package the single slice into a `ByteBuffer`, // incrementing the refcount in the process. *buffer = ByteBuffer(&msg.BorrowSlice(), 1); *own_buffer = true; return grpc::Status::OK; } // Deserialize by pulling the static grpc::Status Deserialize(ByteBuffer *buf, flatbuffers::grpc::Message<T> *msg) { Slice slice; if (!buf->TrySingleSlice(&slice).ok()) { if (!buf->DumpToSingleSlice(&slice).ok()) { buf->Clear(); return ::grpc::Status(::grpc::StatusCode::INTERNAL, "No payload"); } } *msg = flatbuffers::grpc::Message<T>(slice); buf->Clear(); #if FLATBUFFERS_GRPC_DISABLE_AUTO_VERIFICATION return ::grpc::Status::OK; #else if (msg->Verify()) { return ::grpc::Status::OK; } else { return ::grpc::Status(::grpc::StatusCode::INTERNAL, "Message verification failed"); } #endif } }; } // namespace grpc #endif // FLATBUFFERS_GRPC_H_
tsturm/flatbuffers
benchmarks/cpp/bench.h
<gh_stars>0 #ifndef BENCHMARKS_CPP_BENCH_H_ #define BENCHMARKS_CPP_BENCH_H_ #include <cstdint> struct Bench { virtual ~Bench() {} inline void Add(int64_t value) { sum += value; } virtual uint8_t *Encode(void *buf, int64_t &len) = 0; virtual void *Decode(void *buf, int64_t len) = 0; virtual int64_t Use(void *decoded) = 0; virtual void Dealloc(void *decoded) = 0; int64_t sum = 0; }; #endif // BENCHMARKS_CPP_BENCH_H_
tsturm/flatbuffers
include/flatbuffers/detached_buffer.h
/* * Copyright 2021 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef FLATBUFFERS_DETACHED_BUFFER_H_ #define FLATBUFFERS_DETACHED_BUFFER_H_ #include "flatbuffers/allocator.h" #include "flatbuffers/base.h" #include "flatbuffers/default_allocator.h" namespace flatbuffers { // DetachedBuffer is a finished flatbuffer memory region, detached from its // builder. The original memory region and allocator are also stored so that // the DetachedBuffer can manage the memory lifetime. class DetachedBuffer { public: DetachedBuffer() : allocator_(nullptr), own_allocator_(false), buf_(nullptr), reserved_(0), cur_(nullptr), size_(0) {} DetachedBuffer(Allocator *allocator, bool own_allocator, uint8_t *buf, size_t reserved, uint8_t *cur, size_t sz) : allocator_(allocator), own_allocator_(own_allocator), buf_(buf), reserved_(reserved), cur_(cur), size_(sz) {} DetachedBuffer(DetachedBuffer &&other) : allocator_(other.allocator_), own_allocator_(other.own_allocator_), buf_(other.buf_), reserved_(other.reserved_), cur_(other.cur_), size_(other.size_) { other.reset(); } DetachedBuffer &operator=(DetachedBuffer &&other) { if (this == &other) return *this; destroy(); allocator_ = other.allocator_; own_allocator_ = other.own_allocator_; buf_ = other.buf_; reserved_ = other.reserved_; cur_ = other.cur_; size_ = other.size_; other.reset(); return *this; } ~DetachedBuffer() { destroy(); } const uint8_t *data() const { return cur_; } uint8_t *data() { return cur_; } size_t size() const { return size_; } // These may change access mode, leave these at end of public section FLATBUFFERS_DELETE_FUNC(DetachedBuffer(const DetachedBuffer &other)); FLATBUFFERS_DELETE_FUNC( DetachedBuffer &operator=(const DetachedBuffer &other)); protected: Allocator *allocator_; bool own_allocator_; uint8_t *buf_; size_t reserved_; uint8_t *cur_; size_t size_; inline void destroy() { if (buf_) Deallocate(allocator_, buf_, reserved_); if (own_allocator_ && allocator_) { delete allocator_; } reset(); } inline void reset() { allocator_ = nullptr; own_allocator_ = false; buf_ = nullptr; reserved_ = 0; cur_ = nullptr; size_ = 0; } }; } // namespace flatbuffers #endif // FLATBUFFERS_DETACHED_BUFFER_H_
tsturm/flatbuffers
grpc/src/compiler/ts_generator.h
<reponame>tsturm/flatbuffers #include <memory> #include <set> #include <vector> #include "src/compiler/schema_interface.h" #ifndef GRPC_CUSTOM_STRING # include <string> # define GRPC_CUSTOM_STRING std::string #endif namespace grpc { typedef GRPC_CUSTOM_STRING string; } // namespace grpc namespace grpc_ts_generator { grpc::string Generate(grpc_generator::File *file, const grpc_generator::Service *service, const grpc::string &filename); grpc::string GenerateInterface(grpc_generator::File *file, const grpc_generator::Service *service, const grpc::string &filename); } // namespace grpc_ts_generator
tsturm/flatbuffers
include/flatbuffers/buffer_ref.h
<filename>include/flatbuffers/buffer_ref.h /* * Copyright 2021 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef FLATBUFFERS_BUFFER_REF_H_ #define FLATBUFFERS_BUFFER_REF_H_ #include "flatbuffers/base.h" #include "flatbuffers/verifier.h" namespace flatbuffers { // Convenient way to bundle a buffer and its length, to pass it around // typed by its root. // A BufferRef does not own its buffer. struct BufferRefBase {}; // for std::is_base_of template<typename T> struct BufferRef : BufferRefBase { BufferRef() : buf(nullptr), len(0), must_free(false) {} BufferRef(uint8_t *_buf, uoffset_t _len) : buf(_buf), len(_len), must_free(false) {} ~BufferRef() { if (must_free) free(buf); } const T *GetRoot() const { return flatbuffers::GetRoot<T>(buf); } bool Verify() { Verifier verifier(buf, len); return verifier.VerifyBuffer<T>(nullptr); } uint8_t *buf; uoffset_t len; bool must_free; }; } // namespace flatbuffers #endif // FLATBUFFERS_BUFFER_REF_H_
tsturm/flatbuffers
include/flatbuffers/allocator.h
<reponame>tsturm/flatbuffers<gh_stars>10-100 /* * Copyright 2021 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef FLATBUFFERS_ALLOCATOR_H_ #define FLATBUFFERS_ALLOCATOR_H_ #include "flatbuffers/base.h" namespace flatbuffers { // Allocator interface. This is flatbuffers-specific and meant only for // `vector_downward` usage. class Allocator { public: virtual ~Allocator() {} // Allocate `size` bytes of memory. virtual uint8_t *allocate(size_t size) = 0; // Deallocate `size` bytes of memory at `p` allocated by this allocator. virtual void deallocate(uint8_t *p, size_t size) = 0; // Reallocate `new_size` bytes of memory, replacing the old region of size // `old_size` at `p`. In contrast to a normal realloc, this grows downwards, // and is intended specifcally for `vector_downward` use. // `in_use_back` and `in_use_front` indicate how much of `old_size` is // actually in use at each end, and needs to be copied. virtual uint8_t *reallocate_downward(uint8_t *old_p, size_t old_size, size_t new_size, size_t in_use_back, size_t in_use_front) { FLATBUFFERS_ASSERT(new_size > old_size); // vector_downward only grows uint8_t *new_p = allocate(new_size); memcpy_downward(old_p, old_size, new_p, new_size, in_use_back, in_use_front); deallocate(old_p, old_size); return new_p; } protected: // Called by `reallocate_downward` to copy memory from `old_p` of `old_size` // to `new_p` of `new_size`. Only memory of size `in_use_front` and // `in_use_back` will be copied from the front and back of the old memory // allocation. void memcpy_downward(uint8_t *old_p, size_t old_size, uint8_t *new_p, size_t new_size, size_t in_use_back, size_t in_use_front) { memcpy(new_p + new_size - in_use_back, old_p + old_size - in_use_back, in_use_back); memcpy(new_p, old_p, in_use_front); } }; } // namespace flatbuffers #endif // FLATBUFFERS_ALLOCATOR_H_
tsturm/flatbuffers
benchmarks/cpp/flatbuffers/fb_bench.h
<gh_stars>0 #ifndef BENCHMARKS_CPP_FLATBUFFERS_FB_BENCH_H_ #define BENCHMARKS_CPP_FLATBUFFERS_FB_BENCH_H_ #include <cstdint> #include <memory> #include "benchmarks/cpp/bench.h" #include "include/flatbuffers/flatbuffers.h" struct StaticAllocator : public flatbuffers::Allocator { explicit StaticAllocator(uint8_t *buffer) : buffer_(buffer) {} uint8_t *allocate(size_t) override { return buffer_; } void deallocate(uint8_t *, size_t) override {} uint8_t *buffer_; }; std::unique_ptr<Bench> NewFlatBuffersBench( int64_t initial_size = 1024, flatbuffers::Allocator *allocator = nullptr); #endif // BENCHMARKS_CPP_FLATBUFFERS_FB_BENCH_H_
tsturm/flatbuffers
benchmarks/cpp/raw/raw_bench.h
#ifndef BENCHMARKS_CPP_RAW_RAW_BENCH_H_ #define BENCHMARKS_CPP_RAW_RAW_BENCH_H_ #include <memory> #include "benchmarks/cpp/bench.h" std::unique_ptr<Bench> NewRawBench(); #endif // BENCHMARKS_CPP_RAW_RAW_BENCH_H_
tsturm/flatbuffers
grpc/src/compiler/go_generator.h
<gh_stars>0 #ifndef GRPC_INTERNAL_COMPILER_GO_GENERATOR_H #define GRPC_INTERNAL_COMPILER_GO_GENERATOR_H // go generator is used to generate GRPC code for serialization system, such as // flatbuffers #include <memory> #include <vector> #include "src/compiler/schema_interface.h" namespace grpc_go_generator { struct Parameters { // Defines the custom parameter types for methods // eg: flatbuffers uses flatbuffers.Builder as input for the client and output // for the server grpc::string custom_method_io_type; // Package name for the service grpc::string package_name; // Prefix for RPC Calls grpc::string service_prefix; }; // Return the source of the generated service file. grpc::string GenerateServiceSource(grpc_generator::File *file, const grpc_generator::Service *service, grpc_go_generator::Parameters *parameters); } // namespace grpc_go_generator #endif // GRPC_INTERNAL_COMPILER_GO_GENERATOR_H
tsturm/flatbuffers
include/flatbuffers/string.h
/* * Copyright 2021 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef FLATBUFFERS_STRING_H_ #define FLATBUFFERS_STRING_H_ #include "flatbuffers/base.h" #include "flatbuffers/vector.h" namespace flatbuffers { struct String : public Vector<char> { const char *c_str() const { return reinterpret_cast<const char *>(Data()); } std::string str() const { return std::string(c_str(), size()); } // clang-format off #ifdef FLATBUFFERS_HAS_STRING_VIEW flatbuffers::string_view string_view() const { return flatbuffers::string_view(c_str(), size()); } #endif // FLATBUFFERS_HAS_STRING_VIEW // clang-format on bool operator<(const String &o) const { return StringLessThan(this->data(), this->size(), o.data(), o.size()); } }; // Convenience function to get std::string from a String returning an empty // string on null pointer. static inline std::string GetString(const String *str) { return str ? str->str() : ""; } // Convenience function to get char* from a String returning an empty string on // null pointer. static inline const char *GetCstring(const String *str) { return str ? str->c_str() : ""; } #ifdef FLATBUFFERS_HAS_STRING_VIEW // Convenience function to get string_view from a String returning an empty // string_view on null pointer. static inline flatbuffers::string_view GetStringView(const String *str) { return str ? str->string_view() : flatbuffers::string_view(); } #endif // FLATBUFFERS_HAS_STRING_VIEW } // namespace flatbuffers #endif // FLATBUFFERS_STRING_H_
tsturm/flatbuffers
include/flatbuffers/bfbs_generator.h
/* * Copyright 2021 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef FLATBUFFERS_BFBS_GENERATOR_H_ #define FLATBUFFERS_BFBS_GENERATOR_H_ #include <cstdint> namespace flatbuffers { enum GeneratorStatus { OK, FAILED, FAILED_VERIFICATION, }; // A Flatbuffer Code Generator that receives a binary serialized reflection.fbs // and generates code from it. class BfbsGenerator { public: virtual ~BfbsGenerator() {} // Generate code from the provided `buffer` of given `length`. The buffer is // a serialized reflection.fbs. virtual GeneratorStatus Generate(const uint8_t *buffer, int64_t length) = 0; }; } // namespace flatbuffers #endif // FLATBUFFERS_BFBS_GENERATOR_H_
MaxDesiatov/swift-corelibs-foundation
CoreFoundation/Base.subproj/CFAsmMacros.h
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // #if !defined(__COREFOUNDATION_CFASMMACROS__) #define __COREFOUNDATION_CFASMMACROS__ 1 #define CONCAT(a,b) a##b #define CONCAT_EXPANDED(a,b) CONCAT(a,b) #define _C_LABEL(name) CONCAT_EXPANDED(__USER_LABEL_PREFIX__,name) #if defined(__GNU__) || defined(__ANDROID__) || defined(__FreeBSD__) #define NO_EXEC_STACK_DIRECTIVE .section .note.GNU-stack,"",%progbits #else #define NO_EXEC_STACK_DIRECTIVE #endif #endif
MaxDesiatov/swift-corelibs-foundation
CoreFoundation/Base.subproj/SwiftRuntime/CoreFoundation.h
<reponame>MaxDesiatov/swift-corelibs-foundation // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // /* This version of CoreFoundation.h is for the "Swift Runtime" mode of CF only. Note: The contents of this file are only meant for compiling the Swift Foundation module. The library is not ABI or API stable and is not meant to be used as a general-purpose C library on Linux. */ #if !defined(__COREFOUNDATION_COREFOUNDATION__) #define __COREFOUNDATION_COREFOUNDATION__ 1 #define __COREFOUNDATION__ 1 #define DEPLOYMENT_RUNTIME_SWIFT 1 #if !defined(CF_EXCLUDE_CSTD_HEADERS) #include <sys/types.h> #include <stdarg.h> #include <assert.h> #include <ctype.h> #include <errno.h> #include <float.h> #include <limits.h> #include <locale.h> #include <math.h> #include <setjmp.h> #include <signal.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #if __has_include(<netdb.h>) #include <netdb.h> // for NSHost.swift #endif #if defined(__STDC_VERSION__) && (199901L <= __STDC_VERSION__) #include <inttypes.h> #include <stdbool.h> #include <stdint.h> #endif #endif #include <CoreFoundation/CFBase.h> #include <CoreFoundation/CFArray.h> #include <CoreFoundation/CFBag.h> #include <CoreFoundation/CFBinaryHeap.h> #include <CoreFoundation/CFBitVector.h> #include <CoreFoundation/CFByteOrder.h> #include <CoreFoundation/CFCalendar.h> #include <CoreFoundation/CFCharacterSet.h> #include <CoreFoundation/CFData.h> #include <CoreFoundation/CFDate.h> #include <CoreFoundation/CFDateFormatter.h> #include <CoreFoundation/CFDictionary.h> #include <CoreFoundation/CFError.h> #include <CoreFoundation/CFLocale.h> #include <CoreFoundation/CFNumber.h> #include <CoreFoundation/CFNumberFormatter.h> #include <CoreFoundation/CFPreferences.h> #include <CoreFoundation/CFPropertyList.h> #include <CoreFoundation/CFSet.h> #include <CoreFoundation/CFString.h> #include <CoreFoundation/CFStringEncodingExt.h> #include <CoreFoundation/CFTimeZone.h> #include <CoreFoundation/CFTree.h> #include <CoreFoundation/CFURL.h> #include <CoreFoundation/CFURLAccess.h> #include <CoreFoundation/CFUUID.h> #include <CoreFoundation/CFUtilities.h> #include <CoreFoundation/CFBundle.h> #include <CoreFoundation/CFMessagePort.h> #include <CoreFoundation/CFPlugIn.h> #include <CoreFoundation/CFRunLoop.h> #include <CoreFoundation/CFStream.h> #include <CoreFoundation/CFSocket.h> #include <CoreFoundation/CFMachPort.h> #include <CoreFoundation/CFAttributedString.h> #include <CoreFoundation/CFURLPriv.h> #include <CoreFoundation/CFURLComponents.h> #include <CoreFoundation/CFRunArray.h> #include <CoreFoundation/ForSwiftFoundationOnly.h> #endif /* ! __COREFOUNDATION_COREFOUNDATION__ */
MaxDesiatov/swift-corelibs-foundation
CoreFoundation/Locale.subproj/CFNumberFormatter.c
<gh_stars>1-10 // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // /* CFNumberFormatter.c Copyright (c) 2002 - 2015 Apple Inc. and the Swift project authors Responsibility: <NAME> */ #include <CoreFoundation/CFNumberFormatter.h> #include <CoreFoundation/ForFoundationOnly.h> #include <CoreFoundation/CFBigNumber.h> #include "CFInternal.h" #include "CFLocaleInternal.h" #include "CFICULogging.h" #include <math.h> #include <float.h> static void __CFNumberFormatterCustomize(CFNumberFormatterRef formatter); static CFStringRef __CFNumberFormatterCreateCompressedString(CFStringRef inString, Boolean isFormat, CFRange *rangep); static UErrorCode __CFNumberFormatterApplyPattern(CFNumberFormatterRef formatter, CFStringRef pattern); CONST_STRING_DECL(kCFNumberFormatterFormattingContextKey, "kCFNumberFormatterFormattingContextKey"); #define BUFFER_SIZE 768 struct __CFNumberFormatter { CFRuntimeBase _base; UNumberFormat *_nf; CFLocaleRef _locale; CFNumberFormatterStyle _style; CFStringRef _format; // NULL for RBNFs CFStringRef _defformat; CFStringRef _compformat; CFNumberRef _multiplier; CFStringRef _zeroSym; Boolean _isLenient; Boolean _userSetMultiplier; Boolean _usesCharacterDirection; }; static CFStringRef __CFNumberFormatterCopyDescription(CFTypeRef cf) { CFNumberFormatterRef formatter = (CFNumberFormatterRef)cf; return CFStringCreateWithFormat(CFGetAllocator(formatter), NULL, CFSTR("<CFNumberFormatter %p [%p]>"), cf, CFGetAllocator(formatter)); } static void __CFNumberFormatterDeallocate(CFTypeRef cf) { CFNumberFormatterRef formatter = (CFNumberFormatterRef)cf; if (formatter->_nf) __cficu_unum_close(formatter->_nf); if (formatter->_locale) CFRelease(formatter->_locale); if (formatter->_format) CFRelease(formatter->_format); if (formatter->_defformat) CFRelease(formatter->_defformat); if (formatter->_compformat) CFRelease(formatter->_compformat); if (formatter->_multiplier) CFRelease(formatter->_multiplier); if (formatter->_zeroSym) CFRelease(formatter->_zeroSym); } static CFTypeID __kCFNumberFormatterTypeID = _kCFRuntimeNotATypeID; static const CFRuntimeClass __CFNumberFormatterClass = { 0, "CFNumberFormatter", NULL, // init NULL, // copy __CFNumberFormatterDeallocate, NULL, NULL, NULL, // __CFNumberFormatterCopyDescription }; CFTypeID CFNumberFormatterGetTypeID(void) { static dispatch_once_t initOnce = 0; dispatch_once(&initOnce, ^{ __kCFNumberFormatterTypeID = _CFRuntimeRegisterClass(&__CFNumberFormatterClass); }); return __kCFNumberFormatterTypeID; } CFNumberFormatterRef CFNumberFormatterCreate(CFAllocatorRef allocator, CFLocaleRef locale, CFNumberFormatterStyle style) { struct __CFNumberFormatter *memory; uint32_t size = sizeof(struct __CFNumberFormatter) - sizeof(CFRuntimeBase); if (allocator == NULL) allocator = __CFGetDefaultAllocator(); __CFGenericValidateType(allocator, CFAllocatorGetTypeID()); __CFGenericValidateType(locale, CFLocaleGetTypeID()); memory = (struct __CFNumberFormatter *)_CFRuntimeCreateInstance(allocator, CFNumberFormatterGetTypeID(), size, NULL); if (NULL == memory) { return NULL; } memory->_nf = NULL; memory->_locale = NULL; memory->_format = NULL; memory->_defformat = NULL; memory->_compformat = NULL; memory->_multiplier = NULL; memory->_zeroSym = NULL; memory->_isLenient = false; memory->_userSetMultiplier = false; memory->_usesCharacterDirection = false; if (NULL == locale) locale = CFLocaleGetSystem(); memory->_style = style; uint32_t ustyle; switch (style) { case kCFNumberFormatterNoStyle: ustyle = UNUM_IGNORE; break; case kCFNumberFormatterDecimalStyle: ustyle = UNUM_DECIMAL; break; case kCFNumberFormatterCurrencyStyle: ustyle = UNUM_CURRENCY; break; case kCFNumberFormatterPercentStyle: ustyle = UNUM_PERCENT; break; case kCFNumberFormatterScientificStyle: ustyle = UNUM_SCIENTIFIC; break; case kCFNumberFormatterSpellOutStyle: ustyle = UNUM_SPELLOUT; break; case kCFNumberFormatterOrdinalStyle: ustyle = UNUM_ORDINAL; break; case kCFNumberFormatterDurationStyle: ustyle = UNUM_DURATION; break; case kCFNumberFormatterCurrencyISOCodeStyle: ustyle = UNUM_CURRENCY_ISO; break; case kCFNumberFormatterCurrencyPluralStyle: ustyle = UNUM_CURRENCY_PLURAL; break; #if U_ICU_VERSION_MAJOR_NUM >= 55 case kCFNumberFormatterCurrencyAccountingStyle: ustyle = UNUM_CURRENCY_ACCOUNTING; break; #endif default: CFAssert(0, __kCFLogAssertion, "%s(): unknown style %d", __PRETTY_FUNCTION__, style); ustyle = UNUM_DECIMAL; memory->_style = kCFNumberFormatterDecimalStyle; break; } CFStringRef localeName = locale ? CFLocaleGetIdentifier(locale) : CFSTR(""); char buffer[BUFFER_SIZE]; const char *cstr = CFStringGetCStringPtr(localeName, kCFStringEncodingASCII); if (NULL == cstr) { if (CFStringGetCString(localeName, buffer, BUFFER_SIZE, kCFStringEncodingASCII)) cstr = buffer; } if (NULL == cstr) { CFRelease(memory); return NULL; } UErrorCode status = U_ZERO_ERROR; memory->_nf = __cficu_unum_open((UNumberFormatStyle)ustyle, NULL, 0, cstr, NULL, &status); CFAssert(memory->_nf, __kCFLogAssertion, "%s(): error (%d) creating number formatter", __PRETTY_FUNCTION__, status); if (NULL == memory->_nf) { CFRelease(memory); return NULL; } UChar ubuff[4]; if (kCFNumberFormatterNoStyle == style) { status = U_ZERO_ERROR; ubuff[0] = '#'; ubuff[1] = ';'; ubuff[2] = '#'; __cficu_unum_applyPattern(memory->_nf, false, ubuff, 3, NULL, &status); __cficu_unum_setAttribute(memory->_nf, UNUM_MAX_INTEGER_DIGITS, 42); __cficu_unum_setAttribute(memory->_nf, UNUM_MAX_FRACTION_DIGITS, 0); } //Prior to Gala, CFLocaleCreateCopy() always just retained. This caused problems because CFLocaleGetValue(locale, kCFLocaleCalendarKey) would create a calendar, then set its locale to self, leading to a retain cycle //Since we're not in that situation here, and this is a frequently used path, we retain as we used to memory->_locale = locale ? CFRetain(locale) : CFLocaleGetSystem(); __CFNumberFormatterCustomize(memory); if (kCFNumberFormatterSpellOutStyle != memory->_style && kCFNumberFormatterOrdinalStyle != memory->_style && kCFNumberFormatterCurrencyPluralStyle != memory->_style && kCFNumberFormatterDurationStyle != memory->_style) { UChar ubuffer[BUFFER_SIZE]; status = U_ZERO_ERROR; int32_t ret = __cficu_unum_toPattern(memory->_nf, false, ubuffer, BUFFER_SIZE, &status); if (U_SUCCESS(status) && ret <= BUFFER_SIZE) { memory->_format = CFStringCreateWithCharacters(allocator, (const UniChar *)ubuffer, ret); } } memory->_defformat = memory->_format ? (CFStringRef)CFRetain(memory->_format) : NULL; memory->_compformat = memory->_format ? __CFNumberFormatterCreateCompressedString(memory->_format, true, NULL) : NULL; if (kCFNumberFormatterSpellOutStyle != memory->_style && kCFNumberFormatterOrdinalStyle != memory->_style && kCFNumberFormatterCurrencyPluralStyle != memory->_style && kCFNumberFormatterDurationStyle != memory->_style) { int32_t n = __cficu_unum_getAttribute(memory->_nf, UNUM_MULTIPLIER); if (1 != n) { memory->_multiplier = CFNumberCreate(allocator, kCFNumberSInt32Type, &n); __cficu_unum_setAttribute(memory->_nf, UNUM_MULTIPLIER, 1); } } __cficu_unum_setAttribute(memory->_nf, UNUM_LENIENT_PARSE, 0); #if U_ICU_VERSION_MAJOR_NUM >= 53 __cficu_unum_setContext(memory->_nf, UDISPCTX_CAPITALIZATION_NONE, &status); #endif return (CFNumberFormatterRef)memory; } extern CFDictionaryRef __CFLocaleGetPrefs(CFLocaleRef locale); static void __substituteFormatStringFromPrefsNF(CFNumberFormatterRef formatter) { CFIndex formatStyle = formatter->_style; if (kCFNumberFormatterSpellOutStyle == formatStyle) return; if (kCFNumberFormatterOrdinalStyle == formatStyle) return; if (kCFNumberFormatterDurationStyle == formatStyle) return; if (kCFNumberFormatterCurrencyPluralStyle == formatStyle) return; CFStringRef prefName = CFSTR("AppleICUNumberFormatStrings"); if (kCFNumberFormatterNoStyle != formatStyle) { CFStringRef pref = NULL; CFDictionaryRef prefs = __CFLocaleGetPrefs(formatter->_locale); CFPropertyListRef metapref = prefs ? CFDictionaryGetValue(prefs, prefName) : NULL; if (NULL != metapref && CFGetTypeID(metapref) == CFDictionaryGetTypeID()) { CFStringRef key; switch (formatStyle) { case kCFNumberFormatterDecimalStyle: key = CFSTR("1"); break; case kCFNumberFormatterCurrencyStyle: key = CFSTR("2"); break; case kCFNumberFormatterPercentStyle: key = CFSTR("3"); break; case kCFNumberFormatterScientificStyle: key = CFSTR("4"); break; case kCFNumberFormatterSpellOutStyle: key = CFSTR("5"); break; case kCFNumberFormatterOrdinalStyle: key = CFSTR("6"); break; case kCFNumberFormatterDurationStyle: key = CFSTR("7"); break; case kCFNumberFormatterCurrencyISOCodeStyle: key = CFSTR("8"); break; case kCFNumberFormatterCurrencyPluralStyle: key = CFSTR("9"); break; #if U_ICU_VERSION_MAJOR_NUM >= 55 case kCFNumberFormatterCurrencyAccountingStyle: key = CFSTR("10"); break; #endif default: key = CFSTR("0"); break; } pref = (CFStringRef)CFDictionaryGetValue((CFDictionaryRef)metapref, key); } if (NULL != pref && CFGetTypeID(pref) == CFStringGetTypeID()) { int32_t icustyle = UNUM_IGNORE; switch (formatStyle) { case kCFNumberFormatterDecimalStyle: icustyle = UNUM_DECIMAL; break; case kCFNumberFormatterCurrencyStyle: icustyle = UNUM_CURRENCY; break; case kCFNumberFormatterPercentStyle: icustyle = UNUM_PERCENT; break; case kCFNumberFormatterScientificStyle: icustyle = UNUM_SCIENTIFIC; break; case kCFNumberFormatterSpellOutStyle: icustyle = UNUM_SPELLOUT; break; case kCFNumberFormatterOrdinalStyle: icustyle = UNUM_ORDINAL; break; case kCFNumberFormatterDurationStyle: icustyle = UNUM_DURATION; break; case kCFNumberFormatterCurrencyISOCodeStyle: icustyle = UNUM_CURRENCY_ISO; break; case kCFNumberFormatterCurrencyPluralStyle: icustyle = UNUM_CURRENCY_PLURAL; break; #if U_ICU_VERSION_MAJOR_NUM >= 55 case kCFNumberFormatterCurrencyAccountingStyle: icustyle = UNUM_CURRENCY_ACCOUNTING; break; #endif } CFStringRef localeName = CFLocaleGetIdentifier(formatter->_locale); char buffer[BUFFER_SIZE]; const char *cstr = CFStringGetCStringPtr(localeName, kCFStringEncodingASCII); if (NULL == cstr) { if (CFStringGetCString(localeName, buffer, BUFFER_SIZE, kCFStringEncodingASCII)) cstr = buffer; } UErrorCode status = U_ZERO_ERROR; UNumberFormat *nf = __cficu_unum_open((UNumberFormatStyle)icustyle, NULL, 0, cstr, NULL, &status); if (NULL != nf) { UChar ubuffer[BUFFER_SIZE]; status = U_ZERO_ERROR; int32_t number_len = __cficu_unum_toPattern(nf, false, ubuffer, BUFFER_SIZE, &status); if (U_SUCCESS(status) && number_len <= BUFFER_SIZE) { CFStringRef numberString = CFStringCreateWithCharacters(kCFAllocatorSystemDefault, (const UniChar *)ubuffer, number_len); status = U_ZERO_ERROR; int32_t formatter_len = __cficu_unum_toPattern(formatter->_nf, false, ubuffer, BUFFER_SIZE, &status); if (U_SUCCESS(status) && formatter_len <= BUFFER_SIZE) { CFMutableStringRef formatString = CFStringCreateMutable(kCFAllocatorSystemDefault, 0); CFStringAppendCharacters(formatString, (const UniChar *)ubuffer, formatter_len); // find numberString inside formatString, substitute the pref in that range CFRange result; if (CFStringFindWithOptions(formatString, numberString, CFRangeMake(0, formatter_len), 0, &result)) { CFStringReplace(formatString, result, pref); __CFNumberFormatterApplyPattern(formatter, formatString); } CFRelease(formatString); } CFRelease(numberString); } __cficu_unum_close(nf); } } } } static UniChar __CFNumberFormatterNormalizeCharacter(UniChar c) { if (CFCharacterSetIsCharacterMember(CFCharacterSetGetPredefined(kCFCharacterSetWhitespace), c)) { return ' '; } else { return c; } } /* Attempt to match the unimplemented lenient parsing behavior described at http://www.unicode.org/reports/tr35/#Lenient_Parsing -- specifically any whitespace is ignored that does not exist between two letters or two numbers, and no-break spaces map to spaces. */ static CFStringRef __CFNumberFormatterCreateCompressedString(CFStringRef inString, Boolean isFormat, CFRange *rangep) { if (!inString) return NULL; CFRange range = { 0, 0 }; if (rangep) { range = *rangep; } else { range.length = CFStringGetLength(inString); } CFMutableStringRef outString = CFStringCreateMutable(kCFAllocatorSystemDefault, 0); CFCharacterSetRef letters = CFCharacterSetGetPredefined(kCFCharacterSetLetter); CFCharacterSetRef numbers = CFCharacterSetGetPredefined(kCFCharacterSetDecimalDigit); UniChar prevCh = 0, nextCh = 0; Boolean inQuote = false; for (CFIndex in_idx = range.location; in_idx < range.location + range.length; in_idx++) { UniChar ch = __CFNumberFormatterNormalizeCharacter(CFStringGetCharacterAtIndex(inString, in_idx)); nextCh = (in_idx+1 < range.length) ? CFStringGetCharacterAtIndex(inString, in_idx+1) : 0; if (isFormat && ch == '\'') inQuote = !inQuote; if (inQuote || ch != ' ' || (CFCharacterSetIsCharacterMember(letters, prevCh) && CFCharacterSetIsCharacterMember(letters, nextCh)) || (CFCharacterSetIsCharacterMember(numbers, prevCh) && CFCharacterSetIsCharacterMember(numbers, nextCh))) { CFStringAppendCharacters(outString, &ch, 1); prevCh = ch; } } return outString; } // Should not be called for rule-based ICU formatters; not supported static void __CFNumberFormatterApplySymbolPrefs(const void *key, const void *value, void *context) { if (CFGetTypeID(key) == CFStringGetTypeID() && CFGetTypeID(value) == CFStringGetTypeID()) { CFNumberFormatterRef formatter = (CFNumberFormatterRef)context; UNumberFormatSymbol sym = (UNumberFormatSymbol)CFStringGetIntValue((CFStringRef)key); CFStringRef item = (CFStringRef)value; CFIndex item_cnt = CFStringGetLength(item); STACK_BUFFER_DECL(UChar, item_buffer, item_cnt); UChar *item_ustr = (UChar *)CFStringGetCharactersPtr(item); if (NULL == item_ustr) { CFStringGetCharacters(item, CFRangeMake(0, __CFMin(BUFFER_SIZE, item_cnt)), (UniChar *)item_buffer); item_ustr = item_buffer; } UErrorCode status = U_ZERO_ERROR; __cficu_unum_setSymbol(formatter->_nf, sym, item_ustr, item_cnt, &status); } } // Should not be called for rule-based ICU formatters static UErrorCode __CFNumberFormatterApplyPattern(CFNumberFormatterRef formatter, CFStringRef pattern) { if (kCFNumberFormatterSpellOutStyle == formatter->_style) return U_UNSUPPORTED_ERROR; if (kCFNumberFormatterOrdinalStyle == formatter->_style) return U_UNSUPPORTED_ERROR; if (kCFNumberFormatterDurationStyle == formatter->_style) return U_UNSUPPORTED_ERROR; if (kCFNumberFormatterCurrencyPluralStyle == formatter->_style) return U_UNSUPPORTED_ERROR; CFIndex cnt = CFStringGetLength(pattern); STACK_BUFFER_DECL(UChar, ubuffer, cnt); const UChar *ustr = (const UChar *)CFStringGetCharactersPtr(pattern); if (NULL == ustr) { CFStringGetCharacters(pattern, CFRangeMake(0, cnt), (UniChar *)ubuffer); ustr = ubuffer; } UErrorCode status = U_ZERO_ERROR; __cficu_unum_applyPattern(formatter->_nf, false, ustr, cnt, NULL, &status); // __cficu_unum_applyPattern() may have magically changed other attributes based on // the contents of the format string; we simply expose that ICU behavior, except // for UNUM_MULTIPLIER, which we re-read and reset, like we did at initialization // time though any user-set multiplier state takes precedence. if (formatter->_userSetMultiplier) { __cficu_unum_setAttribute(formatter->_nf, UNUM_MULTIPLIER, 1); } else { if (formatter->_multiplier) CFRelease(formatter->_multiplier); formatter->_multiplier = NULL; int32_t n = __cficu_unum_getAttribute(formatter->_nf, UNUM_MULTIPLIER); if (1 != n) { formatter->_multiplier = CFNumberCreate(CFGetAllocator(formatter), kCFNumberSInt32Type, &n); __cficu_unum_setAttribute(formatter->_nf, UNUM_MULTIPLIER, 1); } } return status; } static void __CFNumberFormatterCustomize(CFNumberFormatterRef formatter) { __substituteFormatStringFromPrefsNF(formatter); CFDictionaryRef prefs = __CFLocaleGetPrefs(formatter->_locale); CFPropertyListRef metapref = prefs ? CFDictionaryGetValue(prefs, CFSTR("AppleICUNumberSymbols")) : NULL; if (NULL != metapref && CFGetTypeID(metapref) == CFDictionaryGetTypeID()) { CFDictionaryApplyFunction((CFDictionaryRef)metapref, __CFNumberFormatterApplySymbolPrefs, formatter); } } CFLocaleRef CFNumberFormatterGetLocale(CFNumberFormatterRef formatter) { __CFGenericValidateType(formatter, CFNumberFormatterGetTypeID()); return formatter->_locale; } CFNumberFormatterStyle CFNumberFormatterGetStyle(CFNumberFormatterRef formatter) { __CFGenericValidateType(formatter, CFNumberFormatterGetTypeID()); return formatter->_style; } CFStringRef CFNumberFormatterGetFormat(CFNumberFormatterRef formatter) { __CFGenericValidateType(formatter, CFNumberFormatterGetTypeID()); if (kCFNumberFormatterSpellOutStyle == formatter->_style) return NULL; if (kCFNumberFormatterOrdinalStyle == formatter->_style) return NULL; if (kCFNumberFormatterDurationStyle == formatter->_style) return NULL; if (kCFNumberFormatterCurrencyPluralStyle == formatter->_style) return NULL; UChar ubuffer[BUFFER_SIZE]; CFStringRef newString = NULL; UErrorCode status = U_ZERO_ERROR; int32_t ret = __cficu_unum_toPattern(formatter->_nf, false, ubuffer, BUFFER_SIZE, &status); if (U_SUCCESS(status) && ret <= BUFFER_SIZE) { newString = CFStringCreateWithCharacters(CFGetAllocator(formatter), (const UniChar *)ubuffer, ret); } if (newString && !formatter->_format) { formatter->_format = newString; if (formatter->_compformat) CFRelease(formatter->_compformat); formatter->_compformat = __CFNumberFormatterCreateCompressedString(formatter->_format, true, NULL); } else if (newString && !CFEqual(newString, formatter->_format)) { CFRelease(formatter->_format); formatter->_format = newString; if (formatter->_compformat) CFRelease(formatter->_compformat); formatter->_compformat = __CFNumberFormatterCreateCompressedString(formatter->_format, true, NULL); } else if (newString) { CFRelease(newString); } return formatter->_format; } void CFNumberFormatterSetFormat(CFNumberFormatterRef formatter, CFStringRef formatString) { __CFGenericValidateType(formatter, CFNumberFormatterGetTypeID()); __CFGenericValidateType(formatString, CFStringGetTypeID()); if (kCFNumberFormatterSpellOutStyle == formatter->_style) return; if (kCFNumberFormatterOrdinalStyle == formatter->_style) return; if (kCFNumberFormatterDurationStyle == formatter->_style) return; if (kCFNumberFormatterCurrencyPluralStyle == formatter->_style) return; CFIndex cnt = CFStringGetLength(formatString); CFAssert(cnt <= 1024, __kCFLogAssertion, "%s(): format string too long", __PRETTY_FUNCTION__); if ((!formatter->_format || !CFEqual(formatter->_format, formatString)) && cnt <= 1024) { UErrorCode status = __CFNumberFormatterApplyPattern(formatter, formatString); if (U_SUCCESS(status)) { UChar ubuffer2[BUFFER_SIZE]; status = U_ZERO_ERROR; int32_t ret = __cficu_unum_toPattern(formatter->_nf, false, ubuffer2, BUFFER_SIZE, &status); if (U_SUCCESS(status) && ret <= BUFFER_SIZE) { if (formatter->_format) CFRelease(formatter->_format); formatter->_format = CFStringCreateWithCharacters(CFGetAllocator(formatter), (const UniChar *)ubuffer2, ret); if (formatter->_compformat) CFRelease(formatter->_compformat); formatter->_compformat = __CFNumberFormatterCreateCompressedString(formatter->_format, true, NULL); } } } } #define GET_MULTIPLIER \ double multiplier = 1.0; \ double dummy = 0.0; \ if (formatter->_multiplier) { \ if (!CFNumberGetValue(formatter->_multiplier, kCFNumberFloat64Type, &multiplier)) { \ multiplier = 1.0; \ } \ } \ if (modf(multiplier, &dummy) < FLT_EPSILON) { \ multiplier = floor(multiplier); \ } CFStringRef CFNumberFormatterCreateStringWithNumber(CFAllocatorRef allocator, CFNumberFormatterRef formatter, CFNumberRef number) { if (allocator == NULL) allocator = __CFGetDefaultAllocator(); __CFGenericValidateType(allocator, CFAllocatorGetTypeID()); __CFGenericValidateType(formatter, CFNumberFormatterGetTypeID()); __CFGenericValidateType(number, CFNumberGetTypeID()); // The values of CFNumbers with large unsigned 64-bit ints don't survive well through this CFNumberType type = CFNumberGetType(number); char buffer[64]; CFNumberGetValue(number, type, buffer); return CFNumberFormatterCreateStringWithValue(allocator, formatter, type, buffer); } #define FORMAT_FLT(T, FUNC) \ T value;\ memcpy(&value, valuePtr, sizeof(T));\ if (0 == value && formatter->_zeroSym) { return (CFStringRef)CFRetain(formatter->_zeroSym); } \ if (1.0 != multiplier) { \ value = (T)(value * multiplier); \ } \ status = U_ZERO_ERROR; \ used = FUNC(formatter->_nf, value, ubuffer + 1, cnt, NULL, &status); \ if (status == U_BUFFER_OVERFLOW_ERROR || cnt < used) { \ cnt = used + 1 + 1; \ ustr = (UChar *)CFAllocatorAllocate(kCFAllocatorSystemDefault, sizeof(UChar) * cnt, 0); \ status = U_ZERO_ERROR; \ used = FUNC(formatter->_nf, value, ustr + 1, cnt, NULL, &status); \ } #define FORMAT_INT(T, FUN) \ T value;\ memcpy(&value, valuePtr, sizeof(T));\ if (0 == value && formatter->_zeroSym) { return (CFStringRef)CFRetain(formatter->_zeroSym); } \ if (1.0 != multiplier) { \ value = (T)(value * multiplier); \ } \ _CFBigNum bignum; \ FUN(&bignum, value); \ char buffer[BUFFER_SIZE + 1]; \ _CFBigNumToCString(&bignum, false, true, buffer, BUFFER_SIZE); \ status = U_ZERO_ERROR; \ used = __cficu_unum_formatDecimal(formatter->_nf, buffer, strlen(buffer), ubuffer + 1, BUFFER_SIZE, NULL, &status); \ if (status == U_BUFFER_OVERFLOW_ERROR || cnt < used) { \ cnt = used + 1 + 1; \ ustr = (UChar *)CFAllocatorAllocate(kCFAllocatorSystemDefault, sizeof(UChar) * cnt, 0); \ status = U_ZERO_ERROR; \ used = __cficu_unum_formatDecimal(formatter->_nf, buffer, strlen(buffer), ustr + 1, cnt, NULL, &status); \ } \ CFStringRef CFNumberFormatterCreateStringWithValue(CFAllocatorRef allocator, CFNumberFormatterRef formatter, CFNumberType numberType, const void *valuePtr) { if (allocator == NULL) allocator = __CFGetDefaultAllocator(); __CFGenericValidateType(allocator, CFAllocatorGetTypeID()); __CFGenericValidateType(formatter, CFNumberFormatterGetTypeID()); GET_MULTIPLIER; UChar *ustr = NULL, ubuffer[BUFFER_SIZE + 1]; UErrorCode status = U_ZERO_ERROR; CFIndex used, cnt = BUFFER_SIZE; if (numberType == kCFNumberFloat64Type || numberType == kCFNumberDoubleType) { FORMAT_FLT(double, __cficu_unum_formatDouble) } else if (numberType == kCFNumberFloat32Type || numberType == kCFNumberFloatType) { FORMAT_FLT(float, __cficu_unum_formatDouble) } else if (numberType == kCFNumberSInt64Type || numberType == kCFNumberLongLongType) { FORMAT_INT(int64_t, _CFBigNumInitWithInt64) } else if (numberType == kCFNumberLongType || numberType == kCFNumberCFIndexType) { #if __LP64__ FORMAT_INT(int64_t, _CFBigNumInitWithInt64) #else FORMAT_INT(int32_t, _CFBigNumInitWithInt32) #endif } else if (numberType == kCFNumberSInt32Type || numberType == kCFNumberIntType) { FORMAT_INT(int32_t, _CFBigNumInitWithInt32) } else if (numberType == kCFNumberSInt16Type || numberType == kCFNumberShortType) { FORMAT_INT(int16_t, _CFBigNumInitWithInt16) } else if (numberType == kCFNumberSInt8Type || numberType == kCFNumberCharType) { FORMAT_INT(int8_t, _CFBigNumInitWithInt8) } else { CFAssert(0, __kCFLogAssertion, "%s(): unknown CFNumberType (%d)", __PRETTY_FUNCTION__, numberType); return NULL; } CFStringRef string = NULL; if (U_SUCCESS(status)) { UniChar *bufferToUse = ustr ? (UniChar *)ustr : (UniChar *)ubuffer; if (formatter->_usesCharacterDirection && CFLocaleGetLanguageCharacterDirection(CFLocaleGetIdentifier(formatter->_locale)) == kCFLocaleLanguageDirectionRightToLeft) { // Insert Unicode RTL marker bufferToUse[0] = 0x200F; used++; } else { // Move past direction marker bufferToUse++; } string = CFStringCreateWithCharacters(allocator, bufferToUse, used); } if (ustr) CFAllocatorDeallocate(kCFAllocatorSystemDefault, ustr); return string; } #undef FORMAT_FLT #undef FORMAT_INT #undef GET_MULTIPLIER CFNumberRef CFNumberFormatterCreateNumberFromString(CFAllocatorRef allocator, CFNumberFormatterRef formatter, CFStringRef string, CFRange *rangep, CFOptionFlags options) { if (allocator == NULL) allocator = __CFGetDefaultAllocator(); __CFGenericValidateType(allocator, CFAllocatorGetTypeID()); __CFGenericValidateType(formatter, CFNumberFormatterGetTypeID()); __CFGenericValidateType(string, CFStringGetTypeID()); char buffer[16] __attribute__ ((aligned (8))); CFRange r = rangep ? *rangep : CFRangeMake(0, CFStringGetLength(string)); CFNumberRef multiplierRef = formatter->_multiplier; formatter->_multiplier = NULL; Boolean b = CFNumberFormatterGetValueFromString(formatter, string, &r, kCFNumberSInt64Type, buffer); formatter->_multiplier = multiplierRef; if (b) { Boolean passedMultiplier = true; // We handle the multiplier case here manually; the final // result is supposed to be (parsed value) / (multiplier), but // the int case here should only succeed if the parsed value // is an exact multiple of the multiplier. if (multiplierRef) { int64_t tmp = *(int64_t *)buffer; double multiplier = 1.0; if (!CFNumberGetValue(multiplierRef, kCFNumberFloat64Type, &multiplier)) { multiplier = 1.0; } double dummy; if (llabs(tmp) < fabs(multiplier)) { passedMultiplier = false; } else if (fabs(multiplier) < 1.0) { // We can't handle this math yet passedMultiplier = false; } else if (modf(multiplier, &dummy) == 0.0) { // multiplier is an integer int64_t imult = (int64_t)multiplier; int64_t rem = tmp % imult; if (rem != 0) passedMultiplier = false; if (passedMultiplier) { tmp = tmp / imult; *(int64_t *)buffer = tmp; } } else if (multiplier == -1.0) { // simple tmp = tmp * -1; *(int64_t *)buffer = tmp; } else if (multiplier != 1.0) { // First, throw away integer multiples of the multiplier to // bring the value down to less than 2^53, so that we can // cast it to double without losing any precision, important // for the "remainder is zero" test. // Find power of two which, when multiplier is multiplied by it, // results in an integer value. pwr will be <= 52 since multiplier // is at least 1. int pwr = 0; double intgrl; while (modf(scalbn(multiplier, pwr), &intgrl) != 0.0) pwr++; int64_t i2 = (int64_t)intgrl; // scale pwr and i2 up to a reasonably large value so the next loop doesn't take forever while (llabs(i2) < (1LL << 50)) { i2 *= 2; pwr++; } int64_t cnt = 0; while ((1LL << 53) <= llabs(tmp)) { // subtract (multiplier * 2^pwr) each time tmp -= i2; // move tmp toward zero cnt += (1LL << pwr); // remember how many 2^pwr we subtracted } // If the integer is less than 2^53, there is no loss // in converting it to double, so we can just do the // direct operation now. double rem = fmod((double)tmp, multiplier); if (rem != 0.0) passedMultiplier = false; if (passedMultiplier) { // The original tmp, which we need to divide by multiplier, is at this point: // tmp + k * 2^n * multiplier, where k is the number of loop iterations // That original value needs to be divided by multiplier and put back in the // buffer. Noting that k * 2^n == cnt, and after some algebra, we have: tmp = (int64_t)((double)tmp / multiplier) + cnt; *(int64_t *)buffer = tmp; } } } if (passedMultiplier && ((r.length == CFStringGetLength(string)) || (options & kCFNumberFormatterParseIntegersOnly))) { if (rangep) *rangep = r; return CFNumberCreate(allocator, kCFNumberSInt64Type, buffer); } } if (options & kCFNumberFormatterParseIntegersOnly) return NULL; if (CFNumberFormatterGetValueFromString(formatter, string, rangep, kCFNumberFloat64Type, buffer)) { return CFNumberCreate(allocator, kCFNumberFloat64Type, buffer); } return NULL; } Boolean CFNumberFormatterGetValueFromString(CFNumberFormatterRef formatter, CFStringRef string, CFRange *rangep, CFNumberType numberType, void *valuePtr) { __CFGenericValidateType(formatter, CFNumberFormatterGetTypeID()); __CFGenericValidateType(string, CFStringGetTypeID()); CFStringRef stringToParse = formatter->_isLenient ? __CFNumberFormatterCreateCompressedString(string, false, rangep) : (CFStringRef)CFRetain(string); CFRange range = {0, 0}; if(formatter->_isLenient) { range.length = CFStringGetLength(stringToParse); } else { if (rangep) { range = *rangep; } else { range.length = CFStringGetLength(stringToParse); } // __cficu_unum_parse chokes on leading whitespace CFCharacterSetRef whitespace = CFCharacterSetGetPredefined(kCFCharacterSetWhitespace); while(range.length > 0 && CFCharacterSetIsCharacterMember(whitespace, CFStringGetCharacterAtIndex(stringToParse, range.location))) { range.location++; range.length--; } } Boolean isZero = false; if (formatter->_zeroSym) { CFStringRef zeroSym = formatter->_isLenient ? __CFNumberFormatterCreateCompressedString(formatter->_zeroSym, false, NULL) : (CFStringRef)CFRetain(formatter->_zeroSym); if (kCFCompareEqualTo == CFStringCompare(stringToParse, zeroSym, 0)) { isZero = true; } CFRelease(zeroSym); } if (1024 < range.length) range.length = 1024; const UChar *ustr = (const UChar *)CFStringGetCharactersPtr(stringToParse); STACK_BUFFER_DECL(UChar, ubuffer, (NULL == ustr) ? range.length : 1); if (NULL == ustr) { CFStringGetCharacters(stringToParse, range, (UniChar *)ubuffer); ustr = ubuffer; } else if (!formatter->_isLenient) { ustr += range.location; } CFNumberRef multiplierRef = formatter->_multiplier; formatter->_multiplier = NULL; if (formatter->_isLenient) { __CFNumberFormatterApplyPattern(formatter, formatter->_compformat); if (formatter->_multiplier) CFRelease(formatter->_multiplier); formatter->_multiplier = NULL; } Boolean integerOnly = 1; switch (numberType) { case kCFNumberSInt8Type: case kCFNumberCharType: case kCFNumberSInt16Type: case kCFNumberShortType: case kCFNumberSInt32Type: case kCFNumberIntType: case kCFNumberLongType: case kCFNumberCFIndexType: case kCFNumberSInt64Type: case kCFNumberLongLongType: __cficu_unum_setAttribute(formatter->_nf, UNUM_PARSE_INT_ONLY, 1); // ignored by ICU for rule-based formatters break; default: __cficu_unum_setAttribute(formatter->_nf, UNUM_PARSE_INT_ONLY, 0); // ignored by ICU for rule-based formatters integerOnly = 0; break; } int32_t dpos = 0; UErrorCode status = U_ZERO_ERROR; int64_t dreti = 0; double dretd = 0.0; if (isZero) { dpos = rangep ? rangep->length : 0; } else { char buffer[1024]; memset(buffer, 0, sizeof(buffer)); int32_t len = __cficu_unum_parseDecimal(formatter->_nf, ustr, range.length, &dpos, buffer, sizeof(buffer), &status); if (!U_FAILURE(status) && 0 < len && integerOnly) { char *endptr = NULL; errno = 0; dreti = strtoll_l(buffer, &endptr, 10, NULL); if (!(errno == 0 && *endptr == '\0')) status = U_INVALID_FORMAT_ERROR; } if (!U_FAILURE(status) && 0 < len) { char *endptr = NULL; errno = 0; dretd = strtod_l(buffer, &endptr, NULL); if (!(errno == 0 && *endptr == '\0')) status = U_INVALID_FORMAT_ERROR; } } if (formatter->_isLenient) { if (rangep) { CFIndex uncompEnd = rangep->location + rangep->length; CFIndex uncompIdx = rangep->location; for (CFIndex compIdx = 0; compIdx < dpos && uncompIdx < uncompEnd; compIdx++, uncompIdx++) { while (uncompIdx < uncompEnd && ustr[compIdx] != __CFNumberFormatterNormalizeCharacter(CFStringGetCharacterAtIndex(string, uncompIdx))) uncompIdx++; } rangep->length = uncompIdx - rangep->location; } __CFNumberFormatterApplyPattern(formatter, formatter->_format); if (formatter->_multiplier) CFRelease(formatter->_multiplier); formatter->_multiplier = NULL; } else if (rangep) { rangep->length = dpos + (range.location - rangep->location); } formatter->_multiplier = multiplierRef; CFRelease(stringToParse); if (U_FAILURE(status)) { return false; } if (formatter->_multiplier) { double multiplier = 1.0; if (!CFNumberGetValue(formatter->_multiplier, kCFNumberFloat64Type, &multiplier)) { multiplier = 1.0; } dreti = (int64_t)((double)dreti / multiplier); // integer truncation, plus double cast can be lossy for dreti > 2^53 dretd = dretd / multiplier; } switch (numberType) { case kCFNumberSInt8Type: case kCFNumberCharType: if (INT8_MIN <= dreti && dreti <= INT8_MAX) { *(int8_t *)valuePtr = (int8_t)dreti; return true; } break; case kCFNumberSInt16Type: case kCFNumberShortType: if (INT16_MIN <= dreti && dreti <= INT16_MAX) { *(int16_t *)valuePtr = (int16_t)dreti; return true; } break; case kCFNumberSInt32Type: case kCFNumberIntType: #if !__LP64__ case kCFNumberLongType: case kCFNumberCFIndexType: #endif if (INT32_MIN <= dreti && dreti <= INT32_MAX) { *(int32_t *)valuePtr = (int32_t)dreti; return true; } break; case kCFNumberSInt64Type: case kCFNumberLongLongType: #if __LP64__ case kCFNumberLongType: case kCFNumberCFIndexType: #endif if (INT64_MIN <= dreti && dreti <= INT64_MAX) { *(int64_t *)valuePtr = (int64_t)dreti; return true; } break; case kCFNumberFloat32Type: case kCFNumberFloatType: if (-FLT_MAX <= dretd && dretd <= FLT_MAX) { *(float *)valuePtr = (float)dretd; return true; } break; case kCFNumberFloat64Type: case kCFNumberDoubleType: if (-DBL_MAX <= dretd && dretd <= DBL_MAX) { *(double *)valuePtr = (double)dretd; return true; } break; } return false; } void CFNumberFormatterSetProperty(CFNumberFormatterRef formatter, CFStringRef key, CFTypeRef value) { int32_t n; double d; UErrorCode status = U_ZERO_ERROR; UChar ubuffer[BUFFER_SIZE]; CFIndex cnt; __CFGenericValidateType(formatter, CFNumberFormatterGetTypeID()); __CFGenericValidateType(key, CFStringGetTypeID()); // rule-based formatters don't do attributes and symbols, except for one if (CFEqual(kCFNumberFormatterFormattingContextKey, key)) { #if U_ICU_VERSION_MAJOR_NUM >= 55 __CFGenericValidateType(value, CFNumberGetTypeID()); CFNumberGetValue((CFNumberRef)value, kCFNumberSInt32Type, &n); __cficu_unum_setContext(formatter->_nf, n, &status); #endif } if (kCFNumberFormatterSpellOutStyle == formatter->_style && kCFNumberFormatterIsLenientKey != key) return; if (kCFNumberFormatterOrdinalStyle == formatter->_style && kCFNumberFormatterIsLenientKey != key) return; if (kCFNumberFormatterDurationStyle == formatter->_style && kCFNumberFormatterIsLenientKey != key) return; if (kCFNumberFormatterCurrencyPluralStyle == formatter->_style && kCFNumberFormatterIsLenientKey != key) return; if (kCFNumberFormatterCurrencyCodeKey == key) { __CFGenericValidateType(value, CFStringGetTypeID()); cnt = CFStringGetLength((CFStringRef)value); if (BUFFER_SIZE < cnt) cnt = BUFFER_SIZE; CFStringGetCharacters((CFStringRef)value, CFRangeMake(0, cnt), (UniChar *)ubuffer); __cficu_unum_setTextAttribute(formatter->_nf, UNUM_CURRENCY_CODE, ubuffer, cnt, &status); } else if (kCFNumberFormatterDecimalSeparatorKey == key) { __CFGenericValidateType(value, CFStringGetTypeID()); cnt = CFStringGetLength((CFStringRef)value); if (BUFFER_SIZE < cnt) cnt = BUFFER_SIZE; CFStringGetCharacters((CFStringRef)value, CFRangeMake(0, cnt), (UniChar *)ubuffer); __cficu_unum_setSymbol(formatter->_nf, UNUM_DECIMAL_SEPARATOR_SYMBOL, ubuffer, cnt, &status); } else if (kCFNumberFormatterCurrencyDecimalSeparatorKey == key) { __CFGenericValidateType(value, CFStringGetTypeID()); cnt = CFStringGetLength((CFStringRef)value); if (BUFFER_SIZE < cnt) cnt = BUFFER_SIZE; CFStringGetCharacters((CFStringRef)value, CFRangeMake(0, cnt), (UniChar *)ubuffer); __cficu_unum_setSymbol(formatter->_nf, UNUM_MONETARY_SEPARATOR_SYMBOL, ubuffer, cnt, &status); } else if (kCFNumberFormatterAlwaysShowDecimalSeparatorKey == key) { __CFGenericValidateType(value, CFBooleanGetTypeID()); __cficu_unum_setAttribute(formatter->_nf, UNUM_DECIMAL_ALWAYS_SHOWN, (kCFBooleanTrue == value)); } else if (kCFNumberFormatterGroupingSeparatorKey == key) { __CFGenericValidateType(value, CFStringGetTypeID()); cnt = CFStringGetLength((CFStringRef)value); if (BUFFER_SIZE < cnt) cnt = BUFFER_SIZE; CFStringGetCharacters((CFStringRef)value, CFRangeMake(0, cnt), (UniChar *)ubuffer); __cficu_unum_setSymbol(formatter->_nf, UNUM_GROUPING_SEPARATOR_SYMBOL, (const UChar *)ubuffer, cnt, &status); } else if (kCFNumberFormatterUseGroupingSeparatorKey == key) { __CFGenericValidateType(value, CFBooleanGetTypeID()); __cficu_unum_setAttribute(formatter->_nf, UNUM_GROUPING_USED, (kCFBooleanTrue == value)); } else if (kCFNumberFormatterPercentSymbolKey == key) { __CFGenericValidateType(value, CFStringGetTypeID()); cnt = CFStringGetLength((CFStringRef)value); if (BUFFER_SIZE < cnt) cnt = BUFFER_SIZE; CFStringGetCharacters((CFStringRef)value, CFRangeMake(0, cnt), (UniChar *)ubuffer); __cficu_unum_setSymbol(formatter->_nf, UNUM_PERCENT_SYMBOL, ubuffer, cnt, &status); } else if (kCFNumberFormatterZeroSymbolKey == key) { __CFGenericValidateType(value, CFStringGetTypeID()); CFStringRef old = formatter->_zeroSym; formatter->_zeroSym = value ? (CFStringRef)CFRetain(value) : NULL; if (old) CFRelease(old); } else if (kCFNumberFormatterNaNSymbolKey == key) { __CFGenericValidateType(value, CFStringGetTypeID()); cnt = CFStringGetLength((CFStringRef)value); if (BUFFER_SIZE < cnt) cnt = BUFFER_SIZE; CFStringGetCharacters((CFStringRef)value, CFRangeMake(0, cnt), (UniChar *)ubuffer); __cficu_unum_setSymbol(formatter->_nf, UNUM_NAN_SYMBOL, ubuffer, cnt, &status); } else if (kCFNumberFormatterInfinitySymbolKey == key) { __CFGenericValidateType(value, CFStringGetTypeID()); cnt = CFStringGetLength((CFStringRef)value); if (BUFFER_SIZE < cnt) cnt = BUFFER_SIZE; CFStringGetCharacters((CFStringRef)value, CFRangeMake(0, cnt), (UniChar *)ubuffer); __cficu_unum_setSymbol(formatter->_nf, UNUM_INFINITY_SYMBOL, ubuffer, cnt, &status); } else if (kCFNumberFormatterMinusSignKey == key) { __CFGenericValidateType(value, CFStringGetTypeID()); cnt = CFStringGetLength((CFStringRef)value); if (BUFFER_SIZE < cnt) cnt = BUFFER_SIZE; CFStringGetCharacters((CFStringRef)value, CFRangeMake(0, cnt), (UniChar *)ubuffer); __cficu_unum_setSymbol(formatter->_nf, UNUM_MINUS_SIGN_SYMBOL, ubuffer, cnt, &status); } else if (kCFNumberFormatterPlusSignKey == key) { __CFGenericValidateType(value, CFStringGetTypeID()); cnt = CFStringGetLength((CFStringRef)value); if (BUFFER_SIZE < cnt) cnt = BUFFER_SIZE; CFStringGetCharacters((CFStringRef)value, CFRangeMake(0, cnt), (UniChar *)ubuffer); __cficu_unum_setSymbol(formatter->_nf, UNUM_PLUS_SIGN_SYMBOL, ubuffer, cnt, &status); } else if (kCFNumberFormatterCurrencySymbolKey == key) { __CFGenericValidateType(value, CFStringGetTypeID()); cnt = CFStringGetLength((CFStringRef)value); if (BUFFER_SIZE < cnt) cnt = BUFFER_SIZE; CFStringGetCharacters((CFStringRef)value, CFRangeMake(0, cnt), (UniChar *)ubuffer); __cficu_unum_setSymbol(formatter->_nf, UNUM_CURRENCY_SYMBOL, (const UChar *)ubuffer, cnt, &status); } else if (kCFNumberFormatterExponentSymbolKey == key) { __CFGenericValidateType(value, CFStringGetTypeID()); cnt = CFStringGetLength((CFStringRef)value); if (BUFFER_SIZE < cnt) cnt = BUFFER_SIZE; CFStringGetCharacters((CFStringRef)value, CFRangeMake(0, cnt), (UniChar *)ubuffer); __cficu_unum_setSymbol(formatter->_nf, UNUM_EXPONENTIAL_SYMBOL, ubuffer, cnt, &status); } else if (kCFNumberFormatterMinIntegerDigitsKey == key) { __CFGenericValidateType(value, CFNumberGetTypeID()); CFNumberGetValue((CFNumberRef)value, kCFNumberSInt32Type, &n); __cficu_unum_setAttribute(formatter->_nf, UNUM_MIN_INTEGER_DIGITS, n); } else if (kCFNumberFormatterMaxIntegerDigitsKey == key) { __CFGenericValidateType(value, CFNumberGetTypeID()); CFNumberGetValue((CFNumberRef)value, kCFNumberSInt32Type, &n); __cficu_unum_setAttribute(formatter->_nf, UNUM_MAX_INTEGER_DIGITS, n); } else if (kCFNumberFormatterMinFractionDigitsKey == key) { __CFGenericValidateType(value, CFNumberGetTypeID()); CFNumberGetValue((CFNumberRef)value, kCFNumberSInt32Type, &n); __cficu_unum_setAttribute(formatter->_nf, UNUM_MIN_FRACTION_DIGITS, n); } else if (kCFNumberFormatterMaxFractionDigitsKey == key) { __CFGenericValidateType(value, CFNumberGetTypeID()); CFNumberGetValue((CFNumberRef)value, kCFNumberSInt32Type, &n); __cficu_unum_setAttribute(formatter->_nf, UNUM_MAX_FRACTION_DIGITS, n); } else if (kCFNumberFormatterGroupingSizeKey == key) { __CFGenericValidateType(value, CFNumberGetTypeID()); CFNumberGetValue((CFNumberRef)value, kCFNumberSInt32Type, &n); __cficu_unum_setAttribute(formatter->_nf, UNUM_GROUPING_SIZE, n); } else if (kCFNumberFormatterSecondaryGroupingSizeKey == key) { __CFGenericValidateType(value, CFNumberGetTypeID()); CFNumberGetValue((CFNumberRef)value, kCFNumberSInt32Type, &n); __cficu_unum_setAttribute(formatter->_nf, UNUM_SECONDARY_GROUPING_SIZE, n); } else if (kCFNumberFormatterRoundingModeKey == key) { __CFGenericValidateType(value, CFNumberGetTypeID()); CFNumberGetValue((CFNumberRef)value, kCFNumberSInt32Type, &n); __cficu_unum_setAttribute(formatter->_nf, UNUM_ROUNDING_MODE, n); } else if (kCFNumberFormatterRoundingIncrementKey == key) { __CFGenericValidateType(value, CFNumberGetTypeID()); CFNumberGetValue((CFNumberRef)value, kCFNumberDoubleType, &d); __cficu_unum_setDoubleAttribute(formatter->_nf, UNUM_ROUNDING_INCREMENT, d); } else if (kCFNumberFormatterFormatWidthKey == key) { __CFGenericValidateType(value, CFNumberGetTypeID()); CFNumberGetValue((CFNumberRef)value, kCFNumberSInt32Type, &n); __cficu_unum_setAttribute(formatter->_nf, UNUM_FORMAT_WIDTH, n); } else if (kCFNumberFormatterPaddingPositionKey == key) { __CFGenericValidateType(value, CFNumberGetTypeID()); CFNumberGetValue((CFNumberRef)value, kCFNumberSInt32Type, &n); __cficu_unum_setAttribute(formatter->_nf, UNUM_PADDING_POSITION, n); } else if (kCFNumberFormatterPaddingCharacterKey == key) { __CFGenericValidateType(value, CFStringGetTypeID()); cnt = CFStringGetLength((CFStringRef)value); if (BUFFER_SIZE < cnt) cnt = BUFFER_SIZE; CFStringGetCharacters((CFStringRef)value, CFRangeMake(0, cnt), (UniChar *)ubuffer); __cficu_unum_setTextAttribute(formatter->_nf, UNUM_PADDING_CHARACTER, ubuffer, cnt, &status); } else if (kCFNumberFormatterDefaultFormatKey == key) { // read-only attribute } else if (kCFNumberFormatterMultiplierKey == key) { __CFGenericValidateType(value, CFNumberGetTypeID()); CFNumberRef old = formatter->_multiplier; formatter->_multiplier = value ? (CFNumberRef)CFRetain(value) : NULL; formatter->_userSetMultiplier = value ? true : false; if (old) CFRelease(old); } else if (kCFNumberFormatterPositivePrefixKey == key) { __CFGenericValidateType(value, CFStringGetTypeID()); cnt = CFStringGetLength((CFStringRef)value); if (BUFFER_SIZE < cnt) cnt = BUFFER_SIZE; CFStringGetCharacters((CFStringRef)value, CFRangeMake(0, cnt), (UniChar *)ubuffer); __cficu_unum_setTextAttribute(formatter->_nf, UNUM_POSITIVE_PREFIX, ubuffer, cnt, &status); } else if (kCFNumberFormatterPositiveSuffixKey == key) { __CFGenericValidateType(value, CFStringGetTypeID()); cnt = CFStringGetLength((CFStringRef)value); if (BUFFER_SIZE < cnt) cnt = BUFFER_SIZE; CFStringGetCharacters((CFStringRef)value, CFRangeMake(0, cnt), (UniChar *)ubuffer); __cficu_unum_setTextAttribute(formatter->_nf, UNUM_POSITIVE_SUFFIX, (const UChar *)ubuffer, cnt, &status); } else if (kCFNumberFormatterNegativePrefixKey == key) { __CFGenericValidateType(value, CFStringGetTypeID()); cnt = CFStringGetLength((CFStringRef)value); if (BUFFER_SIZE < cnt) cnt = BUFFER_SIZE; CFStringGetCharacters((CFStringRef)value, CFRangeMake(0, cnt), (UniChar *)ubuffer); __cficu_unum_setTextAttribute(formatter->_nf, UNUM_NEGATIVE_PREFIX, ubuffer, cnt, &status); } else if (kCFNumberFormatterNegativeSuffixKey == key) { __CFGenericValidateType(value, CFStringGetTypeID()); cnt = CFStringGetLength((CFStringRef)value); if (BUFFER_SIZE < cnt) cnt = BUFFER_SIZE; CFStringGetCharacters((CFStringRef)value, CFRangeMake(0, cnt), (UniChar *)ubuffer); __cficu_unum_setTextAttribute(formatter->_nf, UNUM_NEGATIVE_SUFFIX, (const UChar *)ubuffer, cnt, &status); } else if (kCFNumberFormatterPerMillSymbolKey == key) { __CFGenericValidateType(value, CFStringGetTypeID()); cnt = CFStringGetLength((CFStringRef)value); if (BUFFER_SIZE < cnt) cnt = BUFFER_SIZE; CFStringGetCharacters((CFStringRef)value, CFRangeMake(0, cnt), (UniChar *)ubuffer); __cficu_unum_setSymbol(formatter->_nf, UNUM_PERMILL_SYMBOL, ubuffer, cnt, &status); } else if (kCFNumberFormatterInternationalCurrencySymbolKey == key) { __CFGenericValidateType(value, CFStringGetTypeID()); cnt = CFStringGetLength((CFStringRef)value); if (BUFFER_SIZE < cnt) cnt = BUFFER_SIZE; CFStringGetCharacters((CFStringRef)value, CFRangeMake(0, cnt), (UniChar *)ubuffer); __cficu_unum_setSymbol(formatter->_nf, UNUM_INTL_CURRENCY_SYMBOL, ubuffer, cnt, &status); } else if (kCFNumberFormatterCurrencyGroupingSeparatorKey == key) { __CFGenericValidateType(value, CFStringGetTypeID()); cnt = CFStringGetLength((CFStringRef)value); if (BUFFER_SIZE < cnt) cnt = BUFFER_SIZE; CFStringGetCharacters((CFStringRef)value, CFRangeMake(0, cnt), (UniChar *)ubuffer); __cficu_unum_setSymbol(formatter->_nf, UNUM_MONETARY_GROUPING_SEPARATOR_SYMBOL, ubuffer, cnt, &status); } else if (kCFNumberFormatterIsLenientKey == key) { __CFGenericValidateType(value, CFBooleanGetTypeID()); formatter->_isLenient = (kCFBooleanTrue == value); __cficu_unum_setAttribute(formatter->_nf, UNUM_LENIENT_PARSE, (kCFBooleanTrue == value)); } else if (kCFNumberFormatterUseSignificantDigitsKey == key) { __CFGenericValidateType(value, CFBooleanGetTypeID()); __cficu_unum_setAttribute(formatter->_nf, UNUM_SIGNIFICANT_DIGITS_USED, (kCFBooleanTrue == value)); } else if (kCFNumberFormatterMinSignificantDigitsKey == key) { __CFGenericValidateType(value, CFNumberGetTypeID()); CFNumberGetValue((CFNumberRef)value, kCFNumberSInt32Type, &n); __cficu_unum_setAttribute(formatter->_nf, UNUM_MIN_SIGNIFICANT_DIGITS, n); } else if (kCFNumberFormatterMaxSignificantDigitsKey == key) { __CFGenericValidateType(value, CFNumberGetTypeID()); CFNumberGetValue((CFNumberRef)value, kCFNumberSInt32Type, &n); __cficu_unum_setAttribute(formatter->_nf, UNUM_MAX_SIGNIFICANT_DIGITS, n); } else if (kCFNumberFormatterUsesCharacterDirectionKey == key) { __CFGenericValidateType(value, CFBooleanGetTypeID()); formatter->_usesCharacterDirection = value == kCFBooleanTrue; } else { CFAssert(0, __kCFLogAssertion, "%s(): unknown key %p (%@)", __PRETTY_FUNCTION__, key, key); } if (_CFExecutableLinkedOnOrAfter(CFSystemVersionSnowLeopard)) { // do a dummy call to CFNumberFormatterGetFormat() after changing an attribute because // ICU sometimes changes the pattern due to a property change, and we need to poke // __cficu_unum_toPattern() and also update our own variables CFNumberFormatterGetFormat(formatter); } } CFTypeRef CFNumberFormatterCopyProperty(CFNumberFormatterRef formatter, CFStringRef key) { int32_t n; double d; UErrorCode status = U_ZERO_ERROR; UChar ubuffer[BUFFER_SIZE]; CFIndex cnt; __CFGenericValidateType(formatter, CFNumberFormatterGetTypeID()); __CFGenericValidateType(key, CFStringGetTypeID()); // rule-based formatters don't do attributes and symbols, except for one if (CFEqual(kCFNumberFormatterFormattingContextKey, key)) { #if U_ICU_VERSION_MAJOR_NUM >= 55 n = __cficu_unum_getContext(formatter->_nf, UDISPCTX_TYPE_CAPITALIZATION, &status); if (1) { return CFNumberCreate(CFGetAllocator(formatter), kCFNumberSInt32Type, &n); } #endif } if (kCFNumberFormatterSpellOutStyle == formatter->_style && kCFNumberFormatterIsLenientKey != key) return NULL; if (kCFNumberFormatterOrdinalStyle == formatter->_style && kCFNumberFormatterIsLenientKey != key) return NULL; if (kCFNumberFormatterDurationStyle == formatter->_style && kCFNumberFormatterIsLenientKey != key) return NULL; if (kCFNumberFormatterCurrencyPluralStyle == formatter->_style && kCFNumberFormatterIsLenientKey != key) return NULL; if (kCFNumberFormatterCurrencyCodeKey == key) { cnt = __cficu_unum_getTextAttribute(formatter->_nf, UNUM_CURRENCY_CODE, ubuffer, BUFFER_SIZE, &status); if (U_SUCCESS(status) && cnt == 0) { CFStringRef localeName = CFLocaleGetIdentifier(formatter->_locale); char buffer[BUFFER_SIZE]; const char *cstr = CFStringGetCStringPtr(localeName, kCFStringEncodingASCII); if (NULL == cstr) { if (CFStringGetCString(localeName, buffer, BUFFER_SIZE, kCFStringEncodingASCII)) cstr = buffer; } if (NULL == cstr) { return NULL; } UErrorCode status = U_ZERO_ERROR; UNumberFormat *nf = __cficu_unum_open(UNUM_CURRENCY, NULL, 0, cstr, NULL, &status); if (NULL != nf) { cnt = __cficu_unum_getTextAttribute(nf, UNUM_CURRENCY_CODE, ubuffer, BUFFER_SIZE, &status); __cficu_unum_close(nf); } } if (U_SUCCESS(status) && 0 < cnt && cnt <= BUFFER_SIZE) { return CFStringCreateWithCharacters(CFGetAllocator(formatter), (const UniChar *)ubuffer, cnt); } } else if (kCFNumberFormatterDecimalSeparatorKey == key) { cnt = __cficu_unum_getSymbol(formatter->_nf, UNUM_DECIMAL_SEPARATOR_SYMBOL, ubuffer, BUFFER_SIZE, &status); if (U_SUCCESS(status) && cnt <= BUFFER_SIZE) { return CFStringCreateWithCharacters(CFGetAllocator(formatter), (const UniChar *)ubuffer, cnt); } } else if (kCFNumberFormatterCurrencyDecimalSeparatorKey == key) { cnt = __cficu_unum_getSymbol(formatter->_nf, UNUM_MONETARY_SEPARATOR_SYMBOL, (UChar *)ubuffer, BUFFER_SIZE, &status); if (U_SUCCESS(status) && cnt <= BUFFER_SIZE) { return CFStringCreateWithCharacters(CFGetAllocator(formatter), (const UniChar *)ubuffer, cnt); } } else if (kCFNumberFormatterAlwaysShowDecimalSeparatorKey == key) { n = __cficu_unum_getAttribute(formatter->_nf, UNUM_DECIMAL_ALWAYS_SHOWN); if (1) { return CFRetain(n ? kCFBooleanTrue : kCFBooleanFalse); } } else if (kCFNumberFormatterGroupingSeparatorKey == key) { cnt = __cficu_unum_getSymbol(formatter->_nf, UNUM_GROUPING_SEPARATOR_SYMBOL, ubuffer, BUFFER_SIZE, &status); if (U_SUCCESS(status) && cnt <= BUFFER_SIZE) { return CFStringCreateWithCharacters(CFGetAllocator(formatter), (const UniChar *)ubuffer, cnt); } } else if (kCFNumberFormatterUseGroupingSeparatorKey == key) { n = __cficu_unum_getAttribute(formatter->_nf, UNUM_GROUPING_USED); if (1) { return CFRetain(n ? kCFBooleanTrue : kCFBooleanFalse); } } else if (kCFNumberFormatterPercentSymbolKey == key) { cnt = __cficu_unum_getSymbol(formatter->_nf, UNUM_PERCENT_SYMBOL, ubuffer, BUFFER_SIZE, &status); if (U_SUCCESS(status) && cnt <= BUFFER_SIZE) { return CFStringCreateWithCharacters(CFGetAllocator(formatter), (const UniChar *)ubuffer, cnt); } } else if (kCFNumberFormatterZeroSymbolKey == key) { return formatter->_zeroSym ? CFRetain(formatter->_zeroSym) : NULL; } else if (kCFNumberFormatterNaNSymbolKey == key) { cnt = __cficu_unum_getSymbol(formatter->_nf, UNUM_NAN_SYMBOL, ubuffer, BUFFER_SIZE, &status); if (U_SUCCESS(status) && cnt <= BUFFER_SIZE) { return CFStringCreateWithCharacters(CFGetAllocator(formatter), (const UniChar *)ubuffer, cnt); } } else if (kCFNumberFormatterInfinitySymbolKey == key) { cnt = __cficu_unum_getSymbol(formatter->_nf, UNUM_INFINITY_SYMBOL, ubuffer, BUFFER_SIZE, &status); if (U_SUCCESS(status) && cnt <= BUFFER_SIZE) { return CFStringCreateWithCharacters(CFGetAllocator(formatter), (const UniChar *)ubuffer, cnt); } } else if (kCFNumberFormatterMinusSignKey == key) { cnt = __cficu_unum_getSymbol(formatter->_nf, UNUM_MINUS_SIGN_SYMBOL, ubuffer, BUFFER_SIZE, &status); if (U_SUCCESS(status) && cnt <= BUFFER_SIZE) { return CFStringCreateWithCharacters(CFGetAllocator(formatter), (const UniChar *)ubuffer, cnt); } } else if (kCFNumberFormatterPlusSignKey == key) { cnt = __cficu_unum_getSymbol(formatter->_nf, UNUM_PLUS_SIGN_SYMBOL, ubuffer, BUFFER_SIZE, &status); if (U_SUCCESS(status) && cnt <= BUFFER_SIZE) { return CFStringCreateWithCharacters(CFGetAllocator(formatter), (const UniChar *)ubuffer, cnt); } } else if (kCFNumberFormatterCurrencySymbolKey == key) { cnt = __cficu_unum_getSymbol(formatter->_nf, UNUM_CURRENCY_SYMBOL, ubuffer, BUFFER_SIZE, &status); if (U_SUCCESS(status) && cnt <= BUFFER_SIZE) { return CFStringCreateWithCharacters(CFGetAllocator(formatter), (const UniChar *)ubuffer, cnt); } } else if (kCFNumberFormatterExponentSymbolKey == key) { cnt = __cficu_unum_getSymbol(formatter->_nf, UNUM_EXPONENTIAL_SYMBOL, ubuffer, BUFFER_SIZE, &status); if (U_SUCCESS(status) && cnt <= BUFFER_SIZE) { return CFStringCreateWithCharacters(CFGetAllocator(formatter), (const UniChar *)ubuffer, cnt); } } else if (kCFNumberFormatterMinIntegerDigitsKey == key) { n = __cficu_unum_getAttribute(formatter->_nf, UNUM_MIN_INTEGER_DIGITS); if (1) { return CFNumberCreate(CFGetAllocator(formatter), kCFNumberSInt32Type, &n); } } else if (kCFNumberFormatterMaxIntegerDigitsKey == key) { n = __cficu_unum_getAttribute(formatter->_nf, UNUM_MAX_INTEGER_DIGITS); if (1) { return CFNumberCreate(CFGetAllocator(formatter), kCFNumberSInt32Type, &n); } } else if (kCFNumberFormatterMinFractionDigitsKey == key) { n = __cficu_unum_getAttribute(formatter->_nf, UNUM_MIN_FRACTION_DIGITS); if (1) { return CFNumberCreate(CFGetAllocator(formatter), kCFNumberSInt32Type, &n); } } else if (kCFNumberFormatterMaxFractionDigitsKey == key) { n = __cficu_unum_getAttribute(formatter->_nf, UNUM_MAX_FRACTION_DIGITS); if (1) { return CFNumberCreate(CFGetAllocator(formatter), kCFNumberSInt32Type, &n); } } else if (kCFNumberFormatterGroupingSizeKey == key) { n = __cficu_unum_getAttribute(formatter->_nf, UNUM_GROUPING_SIZE); if (1) { return CFNumberCreate(CFGetAllocator(formatter), kCFNumberSInt32Type, &n); } } else if (kCFNumberFormatterSecondaryGroupingSizeKey == key) { n = __cficu_unum_getAttribute(formatter->_nf, UNUM_SECONDARY_GROUPING_SIZE); if (1) { return CFNumberCreate(CFGetAllocator(formatter), kCFNumberSInt32Type, &n); } } else if (kCFNumberFormatterRoundingModeKey == key) { n = __cficu_unum_getAttribute(formatter->_nf, UNUM_ROUNDING_MODE); if (1) { return CFNumberCreate(CFGetAllocator(formatter), kCFNumberSInt32Type, &n); } } else if (kCFNumberFormatterRoundingIncrementKey == key) { d = __cficu_unum_getDoubleAttribute(formatter->_nf, UNUM_ROUNDING_INCREMENT); if (1) { return CFNumberCreate(CFGetAllocator(formatter), kCFNumberDoubleType, &d); } } else if (kCFNumberFormatterFormatWidthKey == key) { n = __cficu_unum_getAttribute(formatter->_nf, UNUM_FORMAT_WIDTH); if (1) { return CFNumberCreate(CFGetAllocator(formatter), kCFNumberSInt32Type, &n); } } else if (kCFNumberFormatterPaddingPositionKey == key) { n = __cficu_unum_getAttribute(formatter->_nf, UNUM_PADDING_POSITION); if (1) { return CFNumberCreate(CFGetAllocator(formatter), kCFNumberSInt32Type, &n); } } else if (kCFNumberFormatterPaddingCharacterKey == key) { cnt = __cficu_unum_getTextAttribute(formatter->_nf, UNUM_PADDING_CHARACTER, ubuffer, BUFFER_SIZE, &status); if (U_SUCCESS(status) && cnt <= BUFFER_SIZE) { return CFStringCreateWithCharacters(CFGetAllocator(formatter), (const UniChar *)ubuffer, cnt); } } else if (kCFNumberFormatterDefaultFormatKey == key) { return formatter->_defformat ? CFRetain(formatter->_defformat) : NULL; } else if (kCFNumberFormatterMultiplierKey == key) { return formatter->_multiplier ? CFRetain(formatter->_multiplier) : NULL; } else if (kCFNumberFormatterPositivePrefixKey == key) { cnt = __cficu_unum_getTextAttribute(formatter->_nf, UNUM_POSITIVE_PREFIX, ubuffer, BUFFER_SIZE, &status); if (U_SUCCESS(status) && cnt <= BUFFER_SIZE) { return CFStringCreateWithCharacters(CFGetAllocator(formatter), (const UniChar *)ubuffer, cnt); } } else if (kCFNumberFormatterPositiveSuffixKey == key) { cnt = __cficu_unum_getTextAttribute(formatter->_nf, UNUM_POSITIVE_SUFFIX, ubuffer, BUFFER_SIZE, &status); if (U_SUCCESS(status) && cnt <= BUFFER_SIZE) { return CFStringCreateWithCharacters(CFGetAllocator(formatter), (const UniChar *)ubuffer, cnt); } } else if (kCFNumberFormatterNegativePrefixKey == key) { cnt = __cficu_unum_getTextAttribute(formatter->_nf, UNUM_NEGATIVE_PREFIX, ubuffer, BUFFER_SIZE, &status); if (U_SUCCESS(status) && cnt <= BUFFER_SIZE) { return CFStringCreateWithCharacters(CFGetAllocator(formatter), (const UniChar *)ubuffer, cnt); } } else if (kCFNumberFormatterNegativeSuffixKey == key) { cnt = __cficu_unum_getTextAttribute(formatter->_nf, UNUM_NEGATIVE_SUFFIX, ubuffer, BUFFER_SIZE, &status); if (U_SUCCESS(status) && cnt <= BUFFER_SIZE) { return CFStringCreateWithCharacters(CFGetAllocator(formatter), (const UniChar *)ubuffer, cnt); } } else if (kCFNumberFormatterPerMillSymbolKey == key) { cnt = __cficu_unum_getSymbol(formatter->_nf, UNUM_PERMILL_SYMBOL, ubuffer, BUFFER_SIZE, &status); if (U_SUCCESS(status) && cnt <= BUFFER_SIZE) { return CFStringCreateWithCharacters(CFGetAllocator(formatter), (const UniChar *)ubuffer, cnt); } } else if (kCFNumberFormatterInternationalCurrencySymbolKey == key) { cnt = __cficu_unum_getSymbol(formatter->_nf, UNUM_INTL_CURRENCY_SYMBOL, ubuffer, BUFFER_SIZE, &status); if (U_SUCCESS(status) && cnt <= BUFFER_SIZE) { return CFStringCreateWithCharacters(CFGetAllocator(formatter), (const UniChar *)ubuffer, cnt); } } else if (kCFNumberFormatterCurrencyGroupingSeparatorKey == key) { cnt = __cficu_unum_getSymbol(formatter->_nf, UNUM_MONETARY_GROUPING_SEPARATOR_SYMBOL, ubuffer, BUFFER_SIZE, &status); if (U_SUCCESS(status) && cnt <= BUFFER_SIZE) { return CFStringCreateWithCharacters(CFGetAllocator(formatter), (const UniChar *)ubuffer, cnt); } } else if (kCFNumberFormatterIsLenientKey == key) { // __cficu_unum_getAttribute(, UNUM_LENIENT_PARSE) is undefined. return CFRetain(formatter->_isLenient ? kCFBooleanTrue : kCFBooleanFalse); } else if (kCFNumberFormatterUseSignificantDigitsKey == key) { n = __cficu_unum_getAttribute(formatter->_nf, UNUM_SIGNIFICANT_DIGITS_USED); if (1) { return CFRetain(n ? kCFBooleanTrue : kCFBooleanFalse); } } else if (kCFNumberFormatterMinSignificantDigitsKey == key) { n = __cficu_unum_getAttribute(formatter->_nf, UNUM_MIN_SIGNIFICANT_DIGITS); if (1) { return CFNumberCreate(CFGetAllocator(formatter), kCFNumberSInt32Type, &n); } } else if (kCFNumberFormatterMaxSignificantDigitsKey == key) { n = __cficu_unum_getAttribute(formatter->_nf, UNUM_MAX_SIGNIFICANT_DIGITS); if (1) { return CFNumberCreate(CFGetAllocator(formatter), kCFNumberSInt32Type, &n); } } else { CFAssert(0, __kCFLogAssertion, "%s(): unknown key %p (%@)", __PRETTY_FUNCTION__, key, key); } return NULL; } Boolean CFNumberFormatterGetDecimalInfoForCurrencyCode(CFStringRef currencyCode, int32_t *defaultFractionDigits, double *roundingIncrement) { UChar ubuffer[4]; __CFGenericValidateType(currencyCode, CFStringGetTypeID()); CFAssert(3 == CFStringGetLength(currencyCode), __kCFLogAssertion, "%s(): currencyCode is not 3 characters", __PRETTY_FUNCTION__); CFStringGetCharacters(currencyCode, CFRangeMake(0, 3), (UniChar *)ubuffer); ubuffer[3] = 0; UErrorCode icuStatus = U_ZERO_ERROR; if (defaultFractionDigits) *defaultFractionDigits = __cficu_ucurr_getDefaultFractionDigits(ubuffer, &icuStatus); if (roundingIncrement) *roundingIncrement = __cficu_ucurr_getRoundingIncrement(ubuffer, &icuStatus); if (U_FAILURE(icuStatus)) return false; return (!defaultFractionDigits || 0 <= *defaultFractionDigits) && (!roundingIncrement || 0.0 <= *roundingIncrement); } // This is for NSNumberFormatter use only! void *_CFNumberFormatterGetFormatter(CFNumberFormatterRef formatter) { return (void *)formatter->_nf; } #undef BUFFER_SIZE
bdice/pymbar
pymbar/_pymbar.c
/* C helper module for time-critical MBAR routines. #============================================================================================= # VERSION CONTROL INFORMATION #============================================================================================= __version__ = "$Revision: $ $Date: $" # $Date: $ # $Revision: $ # $LastChangedBy: $ # $HeadURL: $ # $Id: $ #============================================================================================= #============================================================================================= # COPYRIGHT NOTICE # # Written by <NAME> <<EMAIL>> and <NAME> <<EMAIL>>. # # Copyright (c) 2006-2007 The Regents of the University of California. All Rights Reserved. # Portions of this software are Copyright (c) 2007-2008 Stanford University and Columbia University. # Portions of this software are Copyright (c) 2014 University of Virginia # Portions of this software are Copyright (c) 2017 University of Colorado Boulder, Memorial Sloan Kettering Cancer Center # # This program is free software; you can redistribute it and/or modify it under the terms of # the MIT License. # # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the MIT License for more details. # # You should have received a copy of the MIT License along with this program; #============================================================================================= #============================================================================================= # INSTALLATION INSTRUCTIONS #============================================================================================= To compile on Mac OS X: gcc -O3 -lm -bundle -I(directory with Python.h) -I(directory with numpy/arrayobject.h) _pymbar.c -o _pymbar.so -undefined dynamic_lookup For Python 2.6 and numpy installed via MacPorts: gcc -O3 -lm -bundle -I/opt/local/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 -I/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/numpy/core/include _pymbar.c -o _pymbar.so -undefined dynamic_lookup For Mac OS X system Python 2.5 with system numpy: gcc -O3 -lm -bundle -I/System/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5 -I/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/numpy/core/include/ _pymbar.c -o _pymbar.so -undefined dynamic_lookup For example, for Python 2.4 installed via fink: gcc -O3 -lm -bundle -I/sw/include/python2.4 -I/sw/lib/python2.4/site-packages/numpy/core/include/ _pymbar.c -o _pymbar.so -undefined dynamic_lookup For Python 2.4 and numpy installed by MacPorts: gcc -O3 -lm -bundle -I/opt/local/Library/Frameworks/Python.framework/Versions/2.4/include/python2.4/ -I/opt/local/var/macports/software/py-numpy/1.0.3_0/opt/local/lib/python2.4/site-packages/numpy/core/include/ _pymbar.c -o _pymbar.so -undefined dynamic_lookup For Python 2.7 installed in anaconda gcc -O3 -lm -bundle -I${HOME}/anaconda/include/python2.7/ -I${HOME}/anaconda/lib/python2.7/site-packages/numpy/core/include/ _pymbar.c -o _pymbar.so -undefined dynamic_lookup * * * To compile on Linux: gcc -O3 -lm -fPIC -shared -I(directory with Python.h) -I(directory with numpy/arrayobject.h) -o _pymbar.so _pymbar.c For example, for a default installation of python 2.5: gcc -O3 -lm -fPIC -shared -I/usr/local/include/python2.5 -I/usr/local/lib/python2.5/site-packages/numpy/core/include -o _pymbar.so _pymbar.c On NCSA Lincoln: gcc -O3 -lm -fPIC -shared -I/usr/local/Python-2.5.2/include/python2.5/ -I/usr/local/Python-2.5.2/lib/python2.5/site-packages//numpy/core/include/ -o _pymbar.so _pymbar.c On NCSA Forge: gcc -O3 -lm -fPIC -shared -I$HOME/epd-7.1-2-rh5-x86_64/include/python2.7/ -I$HOME/epd-7.1-2-rh5-x86_64/lib/python2.7/site-packages/numpy/core/include/ -o _pymbar.so _pymbar.c */ #include "Python.h" #include "numpy/arrayobject.h" PyObject *_pymbar_computeUnnormalizedLogWeightsCpp(PyObject *self, PyObject *args) { int i,k,n,K,N,nonzero_N; int s0,s1; npy_intp dim1[1]; int *nonzero_N_k,*N_k; double *FlogN,*f_k,*log_term,*u_n,*log_w_n; double u_k, max_log_term, term_sum, log_sum; PyArrayObject *array_nonzero_N_k, *array_N_k, *array_f_k, *array_u_kn, *array_u_n, *array_log_w_n; if (!PyArg_ParseTuple(args, "iiiOOOOO", &K, &N, &nonzero_N, &array_nonzero_N_k, &array_N_k, &array_f_k, &array_u_kn, &array_u_n)) { return NULL; } //------------------------------------------- //Set the dimensions Python array of log_w_n //------------------------------------------- dim1[0] = N; //------------------------------------------- //Create Python array of log_w_n //------------------------------------------- array_log_w_n = (PyArrayObject *) PyArray_SimpleNew(1, dim1, PyArray_DOUBLE); //------------------------------------------- //Make C arrays from python single-dimension numeric arrays //------------------------------------------- nonzero_N_k = (int *) array_nonzero_N_k->data; N_k = (int *) array_N_k->data; f_k = (double *) array_f_k->data; u_n = (double *) array_u_n->data; log_w_n = (double *) array_log_w_n->data; //------------------------------------------- // Allocate space for helper arrays //------------------------------------------- FlogN = malloc(nonzero_N*sizeof(double)); log_term = malloc(nonzero_N*sizeof(double)); //------------------------------------------- // Precalculate some constant terms //------------------------------------------- for (i=0;i<nonzero_N;i++) { k = nonzero_N_k[i]; FlogN[i] = log((double)N_k[k])+f_k[k]; } s0 = array_u_kn->strides[0]; s1 = array_u_kn->strides[1]; //------------------------------------------- // The workhorse double loop //------------------------------------------- for (n=0;n<N;n++) { term_sum = 0; max_log_term = -1e300; // very low number //------------------------------------------- // Sum over only nonzero terms //------------------------------------------- for (i=0;i<nonzero_N;i++) { k = nonzero_N_k[i]; u_k = *((double *)(array_u_kn->data + k*s0 + n*s1)); //------------------------------------------------------------------------ // Heart of the calculation -- sum_k over log(N_k) + f_k - (u_kn + u_n) //------------------------------------------------------------------------ log_term[i] = FlogN[i] - (u_k - u_n[n]); if (log_term[i] > max_log_term) {max_log_term = log_term[i];} } //---------------------------------------------- // subtract off the maximum, to prevent overflow //---------------------------------------------- for (i=0;i<nonzero_N;i++) { term_sum += exp(log_term[i]-max_log_term); } log_sum = log(term_sum) + max_log_term; log_w_n[n] = -log_sum; } //------------------------------------------- // Free the temporary helper arrays //------------------------------------------- free(FlogN); free(log_term); return PyArray_Return(array_log_w_n); } static PyMethodDef _pymbar_methods[] = { {"computeUnnormalizedLogWeightsCpp", (PyCFunction)_pymbar_computeUnnormalizedLogWeightsCpp, METH_VARARGS, "Computes unnormalized log weights via compiled C++, computeUnnormalizedLogWeightsCpp(K,N,nonzero_N,f_k,u_kn)"}, {NULL, NULL, 0, NULL} }; DL_EXPORT(void) init_pymbar(void) { Py_InitModule3("_pymbar", _pymbar_methods, "Computes unnormalized log weights via compiled C++.\n"); import_array(); }
ashwinma/shoc-experiments
src/opencl/common/shoc_compat_cas.h
<filename>src/opencl/common/shoc_compat_cas.h<gh_stars>1-10 #ifndef SHOC_COMPAT_CAS_H #define SHOC_COMPAT_CAS_H #if defined( __PGI ) #if defined( __x86_64 ) inline int __sync_val_compare_and_swap( volatile int* destptr, int testval, int newval ) { int retval; __asm__ __volatile__ ("lock; cmpxchg %2, %1" : "=a" (retval), "+m" (*destptr) : "r" (newval), "0" (testval) : "memory"); return retval; } #else /* defined(__x86_64) */ # error "atomic compare-and-swap on this processor architecture not yet supported" #endif /* defined(__x86_64) */ #endif // defined( PGI ) #endif // SHOC_COMPAT_CAS_H
ashwinma/shoc-experiments
src/cuda/level1/scan/scan_kernel.h
<gh_stars>1-10 #ifndef SCAN_KERNEL_H_ #define SCAN_KERNEL_H_ #include <cuda.h> // NB: The following class is a workaround for using dynamically sized // shared memory in templated code. Without this workaround, the // compiler would generate two shared memory arrays (one for SP // and one for DP) of the same name and would generate an error. template <class T> class SharedMem { public: __device__ inline T* getPointer() { extern __shared__ T s[]; return s; }; }; // Specialization for double template <> class SharedMem <double> { public: __device__ inline double* getPointer() { extern __shared__ double s_double[]; return s_double; } }; // Specialization for float template <> class SharedMem <float> { public: __device__ inline float* getPointer() { extern __shared__ float s_float[]; return s_float; } }; // Reduction Kernel // Note: This kernel is slightly different than the kernel in the // reduction benchmark, in which blocks read in a coalesced, but // non-contiguous pattern (i.e. the accesses are coalesced, but // strided by the grid size). This kernel essentially assigns // each block a contiguous region of the input array. template <class T, int blockSize> __global__ void reduce(const T* __restrict__ g_idata, T* __restrict__ g_odata, int n) { // First, calculate the bounds of the region of the array // that this block will sum. We need these regions to match // perfectly with those in the bottom-level scan, so we index // as if vector types of length 4 were in use. This prevents // errors due to slightly misaligned regions. int region_size = ((n / 4) / gridDim.x) * 4; int block_start = blockIdx.x * region_size; // Give the last block any extra elements int block_stop = (blockIdx.x == gridDim.x - 1) ? n : block_start + region_size; // Calculate starting index for this thread int tid = threadIdx.x; int i = block_start + tid; // Shared memory will be used for intrablock summation // NB: CC's < 1.3 seem incompatible with the templated dynamic // shared memory workaround. // Inspection with cuda-gdb shows sdata as a pointer to *global* // memory and incorrect results are obtained. This explicit macro // works around this issue. Further, it is acceptable to specify // float, since CC's < 1.3 do not support double precision. #if __CUDA_ARCH__ <= 130 extern volatile __shared__ float sdata[]; #else SharedMem<T> shared; volatile T* sdata = shared.getPointer(); #endif // This thread's sum T sum = 0.0f; // Reduce multiple elements per thread while (i < block_stop) { sum += g_idata[i]; i += blockSize; } // Load this thread's sum into shared memory sdata[tid] = sum; __syncthreads(); // Reduce the contents of shared memory // NB: This is an unrolled loop, and assumes warp-syncrhonous // execution. if (blockSize >= 512) { if (tid < 256) { sdata[tid] += sdata[tid + 256]; } __syncthreads(); } if (blockSize >= 256) { if (tid < 128) { sdata[tid] += sdata[tid + 128]; } __syncthreads(); } if (blockSize >= 128) { if (tid < 64) { sdata[tid] += sdata[tid + 64]; } __syncthreads(); } if (tid < warpSize) { // NB2: This section would also need __sync calls if warp // synchronous execution were not assumed if (blockSize >= 64) sdata[tid] += sdata[tid + 32]; if (blockSize >= 32) sdata[tid] += sdata[tid + 16]; if (blockSize >= 16) sdata[tid] += sdata[tid + 8]; if (blockSize >= 8) sdata[tid] += sdata[tid + 4]; if (blockSize >= 4) sdata[tid] += sdata[tid + 2]; if (blockSize >= 2) sdata[tid] += sdata[tid + 1]; } // Write result for this block to global memory if (tid == 0) { g_odata[blockIdx.x] = sdata[0]; } } template <class T, int blockSize> __device__ T scanLocalMem(const T val, volatile T* s_data) { // Set first half of local memory to zero to make room for scanning int idx = threadIdx.x; s_data[idx] = 0.0f; // Set second half to block sums from global memory, but don't go out // of bounds idx += blockSize; s_data[idx] = val; __syncthreads(); // Now, perform Kogge-Stone scan T t; t = s_data[idx - 1]; __syncthreads(); s_data[idx] += t; __syncthreads(); t = s_data[idx - 2]; __syncthreads(); s_data[idx] += t; __syncthreads(); t = s_data[idx - 4]; __syncthreads(); s_data[idx] += t; __syncthreads(); t = s_data[idx - 8]; __syncthreads(); s_data[idx] += t; __syncthreads(); t = s_data[idx - 16]; __syncthreads(); s_data[idx] += t; __syncthreads(); if (blockSize > 32) { t = s_data[idx - 32]; __syncthreads(); s_data[idx] += t; __syncthreads(); } if (blockSize > 64) { t = s_data[idx - 64]; __syncthreads(); s_data[idx] += t; __syncthreads(); } if (blockSize > 128) { t = s_data[idx - 128]; __syncthreads(); s_data[idx] += t; __syncthreads(); } if (blockSize > 256) { t = s_data[idx - 256]; __syncthreads(); s_data[idx] += t; __syncthreads(); } if (blockSize > 512) { t = s_data[idx - 512]; __syncthreads(); s_data[idx] += t; __syncthreads(); } return s_data[idx-1]; // exclusive } template <class T, int blockSize> __global__ void scan_single_block(T* __restrict__ g_block_sums, const int n) { // Shared memory will be used for intrablock scanning // NB: CC's < 1.3 seem incompatible with the templated dynamic // shared memory workaround. // Inspection with cuda-gdb shows sdata as a pointer to *global* // memory and incorrect results are obtained. This explicit macro // works around this issue. Further, it is acceptable to specify // float, since CC's < 1.3 do not support double precision. #if __CUDA_ARCH__ <= 130 extern volatile __shared__ float s_data[]; #else SharedMem<T> shared; volatile T* s_data = shared.getPointer(); #endif T val = (threadIdx.x < n) ? g_block_sums[threadIdx.x] : 0.0f; val = scanLocalMem<T, blockSize>(val, (volatile T*) s_data); // Write out to global memory if (threadIdx.x < n) { g_block_sums[threadIdx.x] = val; } } template <class T, class vecT, int blockSize> __global__ void bottom_scan(const T* __restrict__ g_idata, T* __restrict__ g_odata, const T* __restrict__ g_block_sums, int n) { // Shared memory will be used for intrablock summation // NB: CC's < 1.3 seem incompatible with the templated dynamic // shared memory workaround. // Inspection with cuda-gdb shows sdata as a pointer to *global* // memory and incorrect results are obtained. This explicit macro // works around this issue. Further, it is acceptable to specify // float, since CC's < 1.3 do not support double precision. #if __CUDA_ARCH__ <= 130 extern volatile __shared__ float sdata[]; #else SharedMem<T> shared; volatile T* sdata = shared.getPointer(); #endif __shared__ T s_seed; // Prepare for reading 4-element vectors // Assume n is divisible by 4 vecT *g_idata4 = (vecT*)g_idata; vecT *g_odata4 = (vecT*)g_odata; n /= 4; //vecT is four wide // Calculate the bounds of the region of the array // that this block will scan int region_size = n / gridDim.x; int block_start = blockIdx.x * region_size; int block_stop = (blockIdx.x == gridDim.x - 1) ? n : block_start + region_size; // Calculate initial starting point for this thread int i = block_start + threadIdx.x; int window = block_start; // Seed the bottom scan with the results from the top scan (i.e. load the per // block sums from the previous kernel) if (threadIdx.x == 0) s_seed = g_block_sums[blockIdx.x]; // Scan multiple elements per thread while (window < block_stop) { vecT val_4; if (i < block_stop) // Make sure we don't read out of bounds { val_4 = g_idata4[i]; } else { val_4.x = 0.0f; val_4.y = 0.0f; val_4.z = 0.0f; val_4.w = 0.0f; } // Serial scan in registers val_4.y += val_4.x; val_4.z += val_4.y; val_4.w += val_4.z; // ExScan sums in shared memory T res = scanLocalMem<T, blockSize>(val_4.w, (volatile T*) sdata); // Update and write out to global memory val_4.x += res + s_seed; val_4.y += res + s_seed; val_4.z += res + s_seed; val_4.w += res + s_seed; // Make sure we don't write out of bounds if (i < block_stop) { g_odata4[i] = val_4; } // Next seed will be the last value if (threadIdx.x == blockSize-1) s_seed = val_4.w; // Advance window window += blockSize; i += blockSize; } } #endif // SCAN_KERNEL_H_
wesklei/OCEV
mersenne.c
<reponame>wesklei/OCEV<filename>mersenne.c /*=============================================================================================================== G E R A D O R M E R S E N N E T W I S T E R ===============================================================================================================*/ /*------------------------------------------------------------------------------------------------------------- Nome: MT_randInt Descricao: gerador Mersenne Twister entrada: inteiro que limita o intervalo de numeros saida: numero inteiro Data de criacao: 08/08/08 -------------------------------------------------------------------------------------------------------------*/ #include "mersenne.h" unsigned long MT_randInt(unsigned long n) // inteiro entre [0,n] para n < 2^32 { unsigned long used = n; used |= used >> 1; used |= used >> 2; used |= used >> 4; used |= used >> 8; used |= used >> 16; unsigned long i; do{ i = randInt() & used; }while( i > n ); return i; } unsigned long randInt() { register unsigned long s1; if( left == 0 ) reload(); --left; s1 = *pNext++; s1 ^= (s1 >> 11); s1 ^= (s1 << 7) & 0x9d2c5680UL; s1 ^= (s1 << 15) & 0xefc60000UL; return ( s1 ^ (s1 >> 18) ); } void reload() { register unsigned long *p = state; register int i; for( i = N - M; i--; ++p ) *p = twist( p[M], p[0], p[1] ); for( i = M; --i; ++p ) *p = twist( p[M-N], p[0], p[1] ); *p = twist( p[M-N], p[0], state[0] ); left = N, pNext = state; } unsigned long twist(unsigned long m, unsigned long s0, unsigned long s1 ) { return m ^ (mixBits(s0,s1)>>1) ^ (-loBit(s1) & 0x9908b0dfUL); } void MT_seed() { /* FILE* urandom = fopen( "/dev/urandom", "rb" ); */ /*if( urandom ) { unsigned long bigSeed[N]; register unsigned long *s = bigSeed; register int i=N; register bool success = true; while( success && i-- ) success = fread( s++, sizeof(unsigned long), 1, urandom ); fclose(urandom); if( success ) { seed( bigSeed, N ); return; } }*/ MT_seedfinal( MT_hash( time(NULL), clock() ) ); } unsigned long MT_hash(time_t t, clock_t c) { size_t i, j; static unsigned long differ = 0; unsigned long h1 = 0; unsigned char *p = (unsigned char *) &t; for(i = 0; i < sizeof(t); ++i) { h1 *= UCHAR_MAX + 2U; h1 += p[i]; } unsigned long h2 = 0; p = (unsigned char *) &c; for(j = 0; j < sizeof(c); ++j) { h2 *= UCHAR_MAX + 2U; h2 += p[j]; } return ( h1 + differ++ ) ^ h2; } void MT_seedfinal(unsigned long oneSeed) { MT_initialize(oneSeed); reload(); } void MT_initialize(unsigned long seed) { register unsigned long *s = state; register unsigned long *r = state; register int i = 1; *s++ = seed & 0xffffffffUL; for( ; i < N; ++i ) { *s++ = ( 1812433253UL * ( *r ^ (*r >> 30) ) + i ) & 0xffffffffUL; r++; } } float MT_randfloat() { return (float)(randInt()) * (1.0/4294967295.0); } double MT_rand() { return (double) (randInt()) * (1.0/4294967296.0); } double MT_randExc(const double *n ) { return MT_rand() * *n; } unsigned long hiBit(unsigned long u) { return u & 0x80000000UL; } unsigned long loBit(unsigned long u) { return u & 0x00000001UL; } unsigned long loBits(unsigned long u){ return u & 0x7fffffffUL; } unsigned long mixBits(unsigned long u, unsigned long v ) { return hiBit(u) | loBits(v); }
wesklei/OCEV
functions.c
<filename>functions.c /* Description: The ANSI C code of the PRVNS approach Programmer: <NAME> E-mail: <EMAIL> Date: 04/11/2014 Lisence: Free Note: The system was developed using Linux. To compile: Type: make To run: ./algorithm input.in */ #include "functions.h" void prepararObjFunc(int* FUNCTION, double* lb, double* ub)/*{{{*/ { switch (*FUNCTION) { case 0: //Rastrigin *lb = -5.12; *ub = 5.12; break; case 1: //Schaffer *lb = -100.00; *ub = 100.00; break; case 2: //Griewank *lb = -600.00; *ub = 600.00; break; case 3: //Ackley *lb = -32.00; *ub = 32.00; break; case 4: //Rosenbrock *lb = -30.00; *ub = 30.00; break; case 5: //Sphere *lb = -100.00; *ub = 100.00; break; case 6: //MPE *lb = 0; *ub = 5; break; case 7: //SCHAFFER_F6 *lb = -100.00; *ub = 100.00; break; case 8: //Generalized Schwefel's function 2.26 *lb = -500.00; *ub = 500.00; break; case 9: // Step function *lb = -100.00; *ub = 100.00; break; case 11: // Generalized Penalized function #1 *lb = -500.00; *ub = 500.00; break; case 12: // Levy Function *lb = -10.00; *ub = 10.00; break; case 13: // Zakharov *lb = -5.00; *ub = 10.00; break; case 14: // EggHolder *lb = -512.00; *ub = 512.00; break; case 15: // Holzman *lb = -10.00; *ub = 10.00; break; case 16: // Michalewitz *lb = 0.00; *ub = PI; break; case 17: // Generalized penalized function #2 *lb = -50.00; *ub = 50.00; break; case 18: // Powell *lb = -4.00; *ub = 5.00; break; case 19: // Rana *lb = -512.00; *ub = 512.00; break; case 20: // Shubert *lb = -10.00; *ub = 10.00; break; case 21: //StretchedV *lb = -10.00; *ub = 10.00; break; case 22: // Multimod *lb = -10.00; *ub = 10.00; break; case 23: // Schwefels 222 *lb = -10.00; *ub = 10.00; break; //Shifted functions case 25: //Shifted Sphere *lb = -100.00; *ub = 100.00; break; case 26: //Shifted Schwefel's Problem 2.21 *lb = -100.00; *ub = 100.00; break; case 27: //Shifted Rosenbrock *lb = -100.00; *ub = 100.00; break; case 28: //Shifted Rastrigin *lb = -5.12; *ub = 5.12; break; case 29: //Shifted Griewank *lb = -600.00; *ub = 600.00; break; case 30: //Shifted Ackley *lb = -32.00; *ub = 32.00; break; case 31: //Shifted Schwefel 2.22 *lb = -10.00; *ub = 10.00; break; case 32: //Shifted Schwefel 1.2 *lb = -65.536; *ub = 65.536; break; case 33: //Shifted Extended_f10 *lb = -100.00; *ub = 100.00; break; case 34: //Shifted Bohachevsky *lb = -15.00; *ub = 15.00; break; case 35: //Shifted schaffer *lb = -100.00; *ub = 100.00; break; //Hybrid functions case 36: //Hybrid 1 *lb = -100.00; *ub = 100.00; break; case 37: //Hybrid 2 *lb = -5.00; *ub = 5.00; break; case 38: //Hybrid 3 *lb = -10.00; *ub = 10.00; break; case 39: //Hybrid 4 *lb = -100.00; *ub = 100.00; break; case 40: //Hybrid 5 *lb = -100.00; *ub = 100.00; break; case 41: //Hybrid 6 *lb = -100.00; *ub = 100.00; break; case 42: //Hybrid 7 *lb = -5.00; *ub = 5.00; break; case 43: //Hybrid 8 *lb = -10.00; *ub = 10.00; break; default: printf("Info: Invalid function.\n") ; exit(0); } }/*}}}*/ double objfunc(double sol[],const int* FUNCTION, const int* DIM, int *cont)/*{{{*/ { *cont+=1; switch (*FUNCTION) { case 0: //Rastrigin return rastrigin(sol,*DIM); case 1: //Schaffer return schaffer(sol,*DIM); case 2: //Griewank return griewank(sol,*DIM); case 3: //Ackley return ackley(sol,*DIM); case 4: //Rosenbrock return rosenbrock(sol,*DIM); case 5: //Sphere return sphere(sol,*DIM); case 6: //MPE return mpe(sol,*DIM); case 7: //SCHAFFER_F6 return schaffer_f6(sol,*DIM); break; case 8: //Generalized Schwefel's function 2.26 return g_schwefels(sol,*DIM); break; case 9: // Step Function return step(sol,*DIM); break; case 11: // Generalized Penalized function #1 return penalized1(sol,*DIM); break; case 12: // Levy Function return levy(sol,*DIM); break; case 13: // Zakharov return zakharov(sol,*DIM); break; case 14: // EggHolder return egg_holder(sol,*DIM); break; case 15: // Holzman return holzman(sol,*DIM); break; case 16: // Michalewitz return michalewitz(sol,*DIM); break; case 17: // Generalized Penalized function #2 return penalized2(sol,*DIM); break; case 18: // Powell return powell(sol,*DIM); break; case 19: // Rana return rana(sol,*DIM); break; case 20: // Shubert return shubert(sol,*DIM); break; case 21: // StretchedV return stretchedV(sol,*DIM); break; case 22: // Multimod return multimod(sol,*DIM); break; case 23: // Schwefel's function 2.22 return schwefels222(sol,*DIM); break; //Shifted functions case 25: //Shifted_Sphere return shifted_sphere(sol,*DIM); break; case 26: //Shifted Schwefel Problem 2.21 return shifted_schwefel_221(sol,*DIM); break; case 27: //Shifted_Rosenbrock return shifted_rosenbrock(sol,*DIM); break; case 28: //Shifted Rastrigin return shifted_rastrigin(sol,*DIM); break; case 29: //Shifted Griewank return shifted_griewank(sol,*DIM); break; case 30://Shifted Ackley return shifted_ackley(sol,*DIM); break; case 31: //Shifted Schwefel 2.22 return shifted_schwefel_222(sol,*DIM); break; case 32: //Shifted Schwefel 1.2 return shifted_schwefel_12(sol,*DIM); break; case 33: //Shifted Extended_f10 return shifted_extended_f10(sol,*DIM); break; case 34: //Shifted Bohachevsky return shifted_bohachevsky(sol,*DIM); break; case 35: //Shifted schaffer return shifted_schaffer(sol,*DIM); break; //Hybrid functions case 36: //Hybrid 1 return hybrid_1(sol,*DIM); break; case 37: //Hybrid 2 return hybrid_2(sol,*DIM); break; case 38: //Hybrid 3 return hybrid_3(sol,*DIM); break; case 39: //Hybrid 4 return hybrid_4(sol,*DIM); break; case 40: //Hybrid 5 return hybrid_5(sol,*DIM); break; case 41: //Hybrid 6 return hybrid_6(sol,*DIM); break; case 42: //Hybrid 7 return hybrid_7(sol,*DIM); break; case 43: //Hybrid 8 return hybrid_8(sol,*DIM); break; default: printf("Info: Invalid function.\n") ; exit(0); } }/*}}}*/ char *getFunctionName(int FUNCTION){/*{{{*/ switch (FUNCTION) { case 0: //Rastrigin return "Rastrigin"; case 1: //Schaffer return "Schaffer F7"; case 2: //Griewank return "Griewank"; case 3: //Ackley return "Ackley"; case 4: //Rosenbrock return "Rosenbrock"; case 5: //Sphere return "Sphere"; case 6: //MPE return "Molecular Potential Energy"; case 7: //SCHAFFER_F6 return "Schaffer F6"; break; case 8: //G_SCHWEFELS return "Generalized Schwefels 2.26"; break; case 9: // Step function return "Step"; break; case 11: // Generalized Penalized function #1 return "Generalized Penalized function #1"; break; case 12: // Levy return "Levy"; break; case 13: // Zakharov return "Zakharov"; break; case 14: // Egg holder return "Egg holder"; break; case 15: // Generalized Holzman return "Generalized Holzman"; break; case 16: // Michalewitz return "Michalewitz"; break; case 17: // Generalized penalized function #2 return "Generalized penalized function #2"; break; case 18: // Powell return "Powell"; break; case 19: // Rana return "Rana"; break; case 20: // Shubert return "Shubert"; break; case 21: //StretchedV return "StretchedV"; break; case 22: //Multimod return "Multimod"; break; case 23: // Schwefel's function 2.22 return "Schwefel's function 2.22"; break; //Shifted functions case 25: //Shifted Sphere return "Shifted Sphere"; break; case 26: //Shifted Schwefel's Problem 2.21 return "Shifted Schwefel's Problem 2.21"; break; case 27: //Shifted Rosenbrock return "Shifted Rosenbrock"; break; case 28: //Shifted Rastrigin return "Shifted Rastrigin"; break; case 29: //Shifted Griewank return "Shifted Griewank"; break; case 30: //Shifted Ackley return "Shifted Ackley"; break; case 31: //Shifted Schwefel 2.22 return "Shifted Schwefel 2.22"; break; case 32: //Shifted Schwefel 1.2 return "Shifted Schwefel 1.2"; break; case 33: //Shifted Extended_f10 return "Shifted Extended_f10"; break; case 34: //Shifted Bohachevsky return "Shifted Bohachevsky"; break; case 35: //Shifted schaffer return "Shifted Schaffer"; break; //Hybrid functions case 36: //Hybrid 1 return "Hybrid 1"; break; case 37: //Hybrid 2 return "Hybrid 2"; break; case 38: //Hybrid 3 return "Hybrid 3"; break; case 39: //Hybrid 4 return "Hybrid 4"; break; case 40: //Hybrid 5 return "Hybrid 5"; break; case 41: //Hybrid 6 return "Hybrid 6"; break; case 42: //Hybrid 7 return "Hybrid 7"; break; case 43: //Hybrid 8 return "Hybrid 8"; break; default: printf("Info: Invalid function.\n") ; exit(0); } }/*}}}*/ double rastrigin( double sol[], int DIM){/*{{{*/ //sol[] -> the population set //DIM the dimension of sol[] int j; double top = 0.00; for(j=0;j<DIM;j++) { top=top+(pow(sol[j],(double)2)-10*cos(2*M_PI*sol[j])+10); } return top; }/*}}}*/ double schaffer( double sol[], int DIM){/*{{{*/ //sol[] -> the population set //DIM the dimension of sol[] int j; double top = 0.00 , top1 = 0.00; for(j=0;j<DIM;j++) { top=top+(pow(sol[j],(double)2)); } top = pow(top,(double)0.25); for(j=0;j<DIM;j++) { top1=top1+(pow(sol[j],(double)2)); } top1=pow(top1,(double)0.1); top1 = pow(sin(50*top1),(double)2) +1.0; return top*top1; }/*}}}*/ double griewank( double sol[], int DIM){/*{{{*/ //sol[] -> the population set //DIM the dimension of sol[] int j; double top = 0.00 , top1 = 0.00, top2 = 0.00; for(j=0;j<DIM;j++) { top1=top1+pow((sol[j]),(double)2); top2=top2*cos((((sol[j])/sqrt((double)(j+1)))*M_PI)/180); } top=(1/(double)4000)*top1-top2+1; return top; }/*}}}*/ double ackley( double sol[], int DIM){/*{{{*/ //sol[] -> the population set //DIM the dimension of sol[] int i; double aux = 0.0; double aux1 = 0.0; for (i = 0; i < DIM; i++) { aux += sol[i]*sol[i]; } for (i = 0; i < DIM; i++) { aux1 += cos(2.0*M_PI*sol[i]); } return (-20.0*(exp(-0.2*sqrt(1.0/(float)DIM*aux)))-exp(1.0/(float)DIM*aux1)+20.0+exp(1)); }/*}}}*/ double rosenbrock( double sol[], int DIM){/*{{{*/ //sol[] -> the population set //DIM the dimension of sol[] int i; double top = 0.00; for (i = 0; i < DIM-1; i++) { top=top+100.*pow((sol[i+1] - pow(sol[i],2.)),2) + pow((1. - sol[i]),2); } return top; }/*}}}*/ double sphere( double sol[], int DIM){/*{{{*/ //sol[] -> the population set //DIM the dimension of sol[] int j; double top = 0.00; for(j=0;j<DIM;j++) { top=top+sol[j]*sol[j]; } return top; }/*}}}*/ double shubert(double sol[], int DIM){/*{{{*/ //sol[] -> the population set //DIM the dimension of sol[] //Shubert /* - Domain |x| <= 10.0 - Number of local minimum = 400 - Global minimum fmin = -24.062499 at the ff. points - (-6.774576, -6.774576), ..., (5.791794, 5.791794) */ double sum = 0.0; int i; for (i = 0; i < DIM; i++) { sum += -sin(2.0*sol[i]+1.0) -2.0*sin(3.0*sol[i]+2.0) -3.0*sin(4.0*sol[i]+3.0) -4.0*sin(5.0*sol[i]+4.0) -5.0*sin(6.0*sol[i]+5.0); } return sum/(DIM/2.0); }/*}}}*/ double schaffer_f6( double sol[], int DIM){/*{{{*/ double top=0; double top1=0; double top2=0; int j; for(j=0;j<DIM-1;j++) { top1 = pow( sin( sqrt( pow(sol[j],(double)2) + pow(sol[j+1],(double)2) ) ), (double)2) - 0.5; top2 = pow( 1.0 + 0.001* ( pow(sol[j],(double)2) + pow(sol[j+1],(double)2) ), (double)2); top = top + (0.5 + top1/top2); } return top; }/*}}}*/ double g_schwefels( double sol[], int DIM){/*{{{*/ //known_optimal = -418.982887272433 at sol(i)=420.9687 int i; double aux = 0.0; for (i=0;i<DIM;i++) { aux += (-1 * sol[i]) * sin(sqrt(fabs(sol[i]))); } return(aux); }/*}}}*/ double mpe( double sol[], int DIM){/*{{{*/ //[0,5] fmin=-0.411183034 * n int i; double aux1=0.0,aux2=0.0; for (i=0;i<DIM;i++) { aux1 += 1 + cos(3*sol[i]); aux2 += (pow(-1,i) / (sqrt(fabs(10.60099896-4.141720682 * cos(sol[i]))))); } return aux1 + aux2; }/*}}}*/ double michalewitz( double sol[], int DIM){/*{{{*/ int i; double aux; //Michalewitz /* Dimension: n Domain: 0< | x[i] | <= PI Global minimum: x[] = -0.966*n */ aux=0; for (i=0;i<DIM;i++) { aux = aux + sin(sol[i]) * pow(sin((i+1)*sol[i]*sol[i]/(float)PI), 2.0 * 10.0); } return(-1*aux); }/*}}}*/ double powell( double sol[], int DIM){/*{{{*/ int j; double aux; //Powell /* Dimension: n > 4 Domain: -4<= x[i] <= 5 Global minimum: at (3, -1, 0, 1, ..., 3, -1, 0, 1) with fmin = 0 */ aux = 0.0; for (j = 1; j <= (int)DIM/4; j++) { aux += pow(sol[4*j-4] + 10 * sol[4*j-3],2.0) + 5 * pow(sol[4*j-2] - sol[4*j-1],2.0) + pow(sol[4*j-3] - 2 * sol[4*j-2], 4.0) + 10 * pow(sol[4*j - 4] - sol[4*j-1], 4.0); } return aux; }/*}}}*/ double levy( double sol[], int DIM)/*{{{*/ { //Levy Function double aux,*y; int i; //x[i] = 1 f(x[i])=0 y = (double*) malloc (DIM * sizeof(double)); for (i = 0; i< DIM; i++) y[i] = 1+(sol[i]-1)/4.0; aux = pow(sin(PI*y[0]),2.0); for (i = 0; i<DIM-1;i++) aux = aux + pow(y[i]-1,2.0)*(1+10*pow(sin(PI*y[i]+1),2.0)); aux = aux+pow(y[DIM-1]-1,2.0)*(1+pow(sin(2*PI*y[DIM-1]),2.0) ); free (y); return ( aux ); }/*}}}*/ double zakharov( double sol[], int DIM)/*{{{*/ { // Zakharov function //x[i] = 0 f(x[i])=0 // double aux,aux1; int j; aux = aux1 = 0.0; for (j = 0; j< DIM; j++) { aux = aux + pow(sol[j],2.0); aux1 = aux1+0.5*j*sol[j]; } return ( aux+pow(aux1,2.0)+pow(aux1,4.0) ); }/*}}}*/ double egg_holder( double sol[], int DIM)/*{{{*/ { //Egg holder /* - Dimension: n - Domain: -512 < | x_i | < 512 - Minimum for n=2 fmin(512, 404.2319) = -959.641 */ double aux; int i; aux = 0.0; for (i = 0; i < DIM-1; i++) { aux += -(sol[i+1] + 47.0) * sin(sqrt(fabs(sol[i+1] + sol[i] * 0.5 + 47.0))) + sin(sqrt(fabs(sol[i] - (sol[i+1] + 47.0)))) * (-sol[i]); } return (aux); }/*}}}*/ double rana( double sol[], int DIM)/*{{{*/ { //Rana /* Dimension: n Domain: -520<= x[i] <= 520 Global minimum: ??? */ double sum,t1,t2; int i; sum = 0.0; for (i = 0; i < DIM-1; i++) { /* if(sol[i] < -520.00f || sol[i] > 520.00f) */ /* printf("rana %f\n",sol[i]); */ t1 = sqrt(fabsf(sol[i+1] + sol[i] + 1.0)); t2 = sqrt(fabsf(sol[i+1] - sol[i] + 1.0)); sum += (sol[i+1] + 1.0) * cos(t2) * sin(t1) + cos(t1) * sin(t2) * sol[i]; } return sum/(double)(DIM-1); }/*}}}*/ double holzman( double sol[], int DIM){/*{{{*/ //Generalized Holzman /* Dimension: n Domain: | x[i] | <= 10 Global minimum: 0 at x[i] = 0 */ int i; double aux = 0.0; for (i = 0; i < DIM; i++) { aux += i * pow(sol[i] , 4); } return aux; }/*}}}*/ double schwefels222( double sol[], int DIM){/*{{{*/ // Schwefel's function 2.22 /* - Domain: | x_i | <= 10.0 Global minimum is 0.0 at x_i = 0.00 */ int i; double aux = 0.0,aux1=0.0; for (i=0;i<DIM;i++) { aux += fabs(sol[i]); aux1 *= fabs(sol[i]); } return (aux+aux1); }/*}}}*/ double stretchedV( double sol[], int DIM){/*{{{*/ //StretchedV /* - Domain: | x_i | <= 10.0 Global minimum is 0.0 at x_i = 0.00 */ double sum = 0.0; double aux; int i; for (i = 0; i < DIM-1; i++) { aux = sol[i+1]*sol[i+1] + sol[i]*sol[i]; sum += pow(aux, 0.25) * (pow(sin(50.0 * pow(aux, 0.1)), 2.0)+1.0); } return sum; }/*}}}*/ double step(double sol[], int DIM){/*{{{*/ // Step function /* - Domain: | x_i | < 100.0 - Global minimum is 0.0 at x_i = 0.5 */ double aux,aux1=0.0; int i; for (i=0;i<DIM;i++) { aux = (sol[i]+0.5); aux1 += aux*aux; } return (aux1); }/*}}}*/ double tempValue(double x,int a,int k,int m)/*{{{*/ { double temp = 0.0; if( x > a) { temp = k*pow(x-a,m); } else if( x <= a && x >= -a) { temp = 0.0; } else { temp = k*pow(-x-a,m); } return temp; }/*}}}*/ double penalized1(double sol[], int DIM){/*{{{*/ //Generalized Penalized function #1 // -500 <= xi <= 500 //known_optimal = 1.57044103551786e-032; double aux=0.0; double aux1=0.0; int i; double *y = (double*) malloc (DIM * sizeof(double)); for (i=0;i<DIM;i++) { y[i]=0.0; } for (i=0;i<DIM;i++) { y[i]=1+(sol[i]+1)/4.0; } for (i=0;i<DIM-1;i++) { aux += pow(y[i]-1,2.0)*(1.0+10.0*pow(sin(PI*y[i+1]),2.0)); } for (i=0;i<DIM;i++) { aux1 += tempValue(sol[i],10,100,4); } aux = (10.0*pow(sin(PI*y[0]),2.0)+aux+pow(y[DIM-1]-1,2))*PI/DIM+aux1; free(y); return ( aux ); }/*}}}*/ double penalized2(double sol[], int DIM){/*{{{*/ //Generalized Penalized function #2 //known_optimal = 1.34969464963992e-032; double aux= 0.0; double aux1=0.0; int i; for (i=0;i<DIM-1;i++) { aux += pow(sol[i]-1,2.0)*(1.0+10.0*pow(sin(3*PI*sol[i+1]),2.0)); } for (i=0;i<DIM;i++) { aux1 += tempValue(sol[i],5,100,4); } return ( (pow(sin(3.0*PI*sol[0]),2.0)+aux+pow(sol[DIM-1]-1,2.0) *(1.0+pow(sin(2.0*PI*sol[DIM-1]),2.0)))/10.0+aux1 ); }/*}}}*/ double multimod(double sol[], int DIM){/*{{{*/ //Multimod /* Dimension: n Domain: -10<= x[i] <= 10 Global minimum: x[0] = 0 */ double s,p,t; int i; s = p = fabs(sol[0]); for (i = 1; i < DIM; i++) { t = fabs(sol[i]); s += t; p *= t; } return s + p; }/*}}}*/ //=== Shifted Functions double shifted_sphere( double sol[], int DIM){/*{{{*/ // x* = o , F(x*) = f_bias1 = - 450 int i; double Fx = 0.0; double z = 0.0; for(i=0;i<DIM;i++){ z = sol[i] - sphere_data[i]; Fx += z*z; } return Fx + f_bias[0]; }/*}}}*/ double shifted_schwefel_221( double sol[], int DIM){/*{{{*/ //Shifted Schwefel Problem 2.21 // x* = o , F(x*) = f_bias1 = - 450 int i; double Fx = 0.0; double z = 0.0; Fx = abss(sol[0]); for(i=1;i<DIM;i++){ z = sol[i] - schwefel_data[i]; Fx = max(Fx , abss(z)); } return Fx + f_bias[1]; }/*}}}*/ double shifted_rosenbrock( double sol[], int DIM){/*{{{*/ int i; double Fx = 0.0; double zx[DIM]; //Shifted_Rosenbrock // x* = o , F(x* ) = f_bias3 = 390 for(i=0;i<DIM;i++) zx[i] = sol[i] - rosenbrock_data[i] + 1; for(i=0;i<DIM-1;i++){ Fx = Fx + 100*( pow((pow(zx[i],2)-zx[i+1]) , 2) ) + pow((zx[i]-1) , 2); } return Fx + f_bias[2]; }/*}}}*/ double shifted_rastrigin( double sol[], int DIM){/*{{{*/ int i; double Fx = 0.0; double z = 0.0; double pi = acos(-1.0); //Shifted Rastrigin //x* = o , F( x * ) = f_bias4 = - 330 for(i=0;i<DIM;i++){ z = sol[i] - rastrigin_data[i]; Fx = Fx + ( pow(z,2) - 10*cos(2*pi*z) + 10); } return Fx + f_bias[3]; }/*}}}*/ double shifted_griewank( double sol[], int DIM){/*{{{*/ int i; double z = 0.0; double top1 = 0.00, top2 = 0.00; //Shifted Griewank //x* = o , F(x* ) = f_bias5 = -180 top1 = 0; top2 = 1; for(i=0;i<DIM;i++){ z = sol[i] - griewank_data[i]; top1 = top1 + ( pow(z,2) / 4000 ); top2 = top2 * ( cos(z/sqrt(i+1))); } return (top1 - top2 + 1 + f_bias[4]); }/*}}}*/ double shifted_ackley( double sol[], int DIM){/*{{{*/ int i; double Fx = 0.0; double z = 0.0; double top1 = 0.00, top2 = 0.00; double pi = acos(-1.0); double e = exp(1.0); //Shifted Ackley // x* = o , F(x* ) = f_bias6 = - 140 top1 = 0; top2 = 0; Fx = 0; for(i=0;i<DIM;i++){ z = sol[i] - ackley_data[i]; top1 = top1 + pow(z , 2 ); top2 = top2 + cos(2*pi*z); } Fx = -20*exp(-0.2*sqrt(top1/DIM)) -exp(top2/DIM) + 20 + e + f_bias[5]; return Fx; }/*}}}*/ double shifted_schwefel_222(double sol[], int DIM) /*{{{*/ { double sum, currentGen, prod; int i; sum = 0.0; prod = 1.0; for (i = 0; i < DIM; i++) { currentGen = fabs(sol[i]-data_shif_schwefels_222[i]); sum += currentGen; prod *= currentGen; } return sum + prod; }/*}}}*/ double shifted_schwefel_12(double sol[], int DIM)/*{{{*/ { double Sum=0.0, Val=0.0; int i; for (i = 0; i < DIM; i++) { Val += sol[i]-data_shif_schwefels_12[i]; Sum += Val * Val; } return Sum; }/*}}}*/ double f_10(double x, double y)/*{{{*/ { double p, z, t; p=(x*x+y*y); z=pow(p, 0.25); t=sin(50.0*pow(p, 0.1)); t=t*t+1.0; return z*t; }/*}}}*/ double shifted_extended_f10(double sol[], int DIM)/*{{{*/ { double suma=0.0; int i; for(i=0; i<DIM-1; i++) suma+=f_10(sol[i]-data_shif_extendedf10[i], sol[i+1]-data_shif_extendedf10[i+1]); suma+=f_10(sol[DIM-1]-data_shif_extendedf10[DIM-1], sol[0]-data_shif_extendedf10[0]); return suma; }/*}}}*/ double shifted_bohachevsky(double sol[], int DIM) /*{{{*/ { double sum = 0.0; int i; double currentGen; double nextGen; currentGen = sol[0]-data_shif_bohachevsky[0]; for (i = 1; i < DIM; i++) { nextGen = sol[i]-data_shif_bohachevsky[i]; sum += currentGen * currentGen + 2.0 * nextGen * nextGen; sum += -0.3 * cos(3.0 * PI * currentGen) -0.4 * cos(4.0 * PI * nextGen) + 0.7; currentGen = nextGen; } return sum; }/*}}}*/ double shifted_schaffer(double sol[], int DIM) /*{{{*/ { int i=0; double sum; double aux, aux2; double currentGen, nextGen; sum = 0.0; currentGen = sol[0]-data_shif_schaffer[i]; currentGen = currentGen * currentGen; for (i = 1; i < DIM; i++) { nextGen = sol[i]-data_shif_schaffer[i]; nextGen = nextGen * nextGen; aux = currentGen + nextGen; currentGen = nextGen; aux2 = sin(50. * pow(aux, 0.1)); sum += pow(aux, 0.25) * (aux2 * aux2 + 1.0); } return sum; }/*}}}*/ //=== Hybrid Functions static void divideFunctions(double sol[], int DIM, double *part1, double *part2, double m, int *psize1, int *psize2) {/*{{{*/ int shared; int rest, i, total; double *partrest; if (m <= 0.5) { partrest = part2; } else { partrest = part1; m = 1-m; } shared = (int) floor(DIM*m); rest = 2*shared; for (i = 0; i < shared; i++) { part1[i] = sol[i*2]; part2[i] = sol[i*2+1]; } total = DIM-shared; for (i = 0; i < total-shared; i++) { partrest[i+shared] = sol[i+rest]; } *psize1 = shared; *psize2 = DIM-shared; if (partrest == part1) { int temp = *psize1; *psize1 = *psize2; *psize2 = temp; } }/*}}}*/ double Extended_f_10NoDesplazamiento(double sol[], int DIM)/*{{{*/ { double suma=0.0; int i; for(i=0; i<DIM-1; i++) suma+=f_10(sol[i], sol[i+1]); suma+=f_10(sol[DIM-1], sol[0]); return suma; }/*}}}*/ double f_BohachevskyNoDesplazamiento(double sol[], int DIM) /*{{{*/ { double sum = 0.0; int i; double currentGen; double nextGen; currentGen = sol[0]; for (i = 1; i < DIM; i++) { nextGen = sol[i]; sum += currentGen * currentGen + 2.0 * nextGen * nextGen; double c1=cos(3.0 * PI * currentGen); double c2=cos(4.0 * PI * nextGen); sum += 0.7 -(0.3*c1+0.4*c2); currentGen = nextGen; } return sum; }/*}}}*/ double f_Schwefel2_22NoDesplazamiento(double sol[], int DIM) /*{{{*/ { double sum, currentGen, prod; sum = 0.0; prod = 1.0; int i; for (i = 0; i < DIM; i++) { currentGen = fabs(sol[i]); sum += currentGen; prod *= currentGen; } return sum + prod; }/*}}}*/ double hybrid_1(double sol[], int DIM) /*{{{*/ //12 { double part1[DIM], part2[DIM]; int size1, size2; double f1, f2; divideFunctions(sol, DIM, part1, part2, 0.25, &size1, &size2); f1=Extended_f_10NoDesplazamiento(part1,size1); f2=shifted_sphere(part2,size2)-f_bias[0]; assert(f1 >= 0); assert(f2 >= 0); return f1+f2; }/*}}}*/ double hybrid_2(double sol[], int DIM) /*{{{*/ //13 { double part1[DIM], part2[DIM]; int size1, size2; double f1, f2; divideFunctions(sol, DIM, part1, part2, 0.25, &size1, &size2); f1=Extended_f_10NoDesplazamiento(part1,size1); f2=shifted_rosenbrock(part2,size2)-f_bias[2]; return f1+f2; }/*}}}*/ double hybrid_3(double sol[], int DIM) /*{{{*/ //14 { double part1[DIM], part2[DIM]; int size1, size2; double f1, f2; divideFunctions(sol, DIM, part1, part2, 0.25, &size1, &size2); f1=Extended_f_10NoDesplazamiento(part1,size1); f2=shifted_rastrigin(part2,size2)-f_bias[3]; return f1+f2; }/*}}}*/ double hybrid_4(double sol[], int DIM) /*{{{*/ //15 { double part1[DIM], part2[DIM]; double desp[DIM]; int size1, size2; double f1, f2; int i; for (i = 0; i < DIM; ++i) { desp[i] = sol[i] - f15[i]; } divideFunctions(desp, DIM, part1, part2, 0.25, &size1, &size2); f1=f_BohachevskyNoDesplazamiento(part1, size1); f2=f_Schwefel2_22NoDesplazamiento(part2, size2); return f1+f2; }/*}}}*/ double hybrid_5(double sol[], int DIM) /*{{{*/ //16new { double part1[DIM], part2[DIM]; int size1, size2; double f1, f2; divideFunctions(sol, DIM, part1, part2, 0.5, &size1, &size2); f1=Extended_f_10NoDesplazamiento(part1,size1); assert(f1 >= 0); f2=shifted_sphere(part2, size2)-f_bias[0]; assert(f2 >= 0); return f1+f2; }/*}}}*/ double hybrid_6(double sol[], int DIM) /*{{{*/ //17new { double part1[DIM], part2[DIM]; int size1, size2; double f1, f2; divideFunctions(sol, DIM, part1, part2, 0.75, &size1, &size2); f1=Extended_f_10NoDesplazamiento(part1, size1); f2=shifted_rosenbrock(part2, size2)-f_bias[2]; return f1+f2; }/*}}}*/ double hybrid_7(double sol[], int DIM) /*{{{*/ //18new { double part1[DIM], part2[DIM]; int size1, size2; double f1=0; double f2=0; divideFunctions(sol, DIM, part1, part2, 0.75, &size1, &size2); f1=Extended_f_10NoDesplazamiento(part1, size1); f2=shifted_rastrigin(part2, size2)-f_bias[3]; assert(isfinite(f1)); assert(isfinite(f2)); return f1+f2; }/*}}}*/ double hybrid_8(double sol[], int DIM) /*{{{*/ //19new { double part1[DIM], part2[DIM]; int size1, size2; double desp[DIM]; double f1, f2; int i; for (i = 0; i < DIM; ++i) { desp[i] = sol[i] - f19[i]; } divideFunctions(desp, DIM, part1, part2, 0.75, &size1, &size2); f1=f_BohachevskyNoDesplazamiento(part1, size1); f2=f_Schwefel2_22NoDesplazamiento(part2, size2); return f1+f2; }/*}}}*/
wesklei/OCEV
main.c
/* Description: The ANSI C code of the PRVNS approach Programmer: <NAME> E-mail: <EMAIL> Date: 04/11/2014 Lisence: Free Note: The system was developed using Linux. To compile: Type: make To run: ./algorithm input.in */ #ifndef max #define max(x, y) ((x) > (y) ? (x) : (y)) #endif #ifndef abss #define abss(a) (a<0 ? (-a) : a) #endif typedef int bool; #define true 1 #define false 0 #define FAIL 0 #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include "mersenne.h" #include "functions.c" #include <fcntl.h> #include <unistd.h> #include <pthread.h> #include <unistd.h> /* sleep() */ #include <string.h> typedef struct _AG { int P; /*The metric used, l1,l2,l_inf */ int FUNCTION; //Problem definitions int DIM; //number of problem variables int RUN; /*Algorithm can run many times in order to see its robustness*/ double *best; //[DIM]; //best solution found double bestfo; //best fo value double LB; //lower bound of the variables double UB; //upper bound of the variables int KMAX,TMAX,AVAL_MAX; int RADII_T_FLAG; int know; double Q,RADII,RHO,EPSILON; double *r; int METHOD; int ECO_STEP; int EVO_STEP; int VNS_POP; int POP_INDEX; double DELTA_MUTATION; int G_MAX; double PC; //probabilidade de crossover }pAG; int getParametersAG(FILE *file, pAG *ag) { int *P,*ECO_STEP,*EVO_STEP,*VNS_POP,*G_MAX,*FUNCTION,*DIM,*RUN; int *KMAX,*TMAX,*AVAL_MAX,*METHOD; int *RADII_T_FLAG; double *Q,*RADII,*RHO,*EPSILON,*PC; FUNCTION = (int*) malloc(sizeof(int)); DIM = (int*) malloc(sizeof(int)); RUN = (int*) malloc(sizeof(int)); ECO_STEP = (int*) malloc(sizeof(int)); EVO_STEP = (int*) malloc(sizeof(int)); VNS_POP = (int*) malloc(sizeof(int)); KMAX = (int*) malloc(sizeof(int)); TMAX = (int*) malloc(sizeof(int)); METHOD = (int*) malloc(sizeof(int)); AVAL_MAX = (int*) malloc(sizeof(int)); RADII_T_FLAG = (int*) malloc(sizeof(int)); Q = (double*) malloc(sizeof(double)); RADII = (double*) malloc(sizeof(double)); RHO = (double*) malloc(sizeof(double)); EPSILON = (double*) malloc(sizeof(double)); P = (int*) malloc(sizeof(int)); G_MAX = (int*) malloc(sizeof(int)); PC = (double*) malloc(sizeof(double)); if (file == 0) { printf( "Could not open ini file! Usage ./<exec> <file.in>\n" ); return -1; } else { ffscanf("RUN", file, "%d", &RUN); ffscanf("DIM", file, "%d", &DIM); ffscanf("FUNCTION",file, "%d", &FUNCTION); ffscanf("KMAX", file, "%d", &KMAX); ffscanf("TMAX", file, "%d", &TMAX); ffscanf("Q", file, "%lf", &Q); ffscanf("RADII", file, "%lf", &RADII); ffscanf("RADII_T_FLAG", file, "%d", &RADII_T_FLAG); ffscanf("AVAL_MAX", file, "%d", &AVAL_MAX); ffscanf("RHO", file, "%lf", &RHO); ffscanf("EPSILON", file, "%lf", &EPSILON); ffscanf("METHOD", file, "%d", &METHOD); ffscanf("P", file, "%d", &P); ffscanf("VNS_POP", file, "%d", &VNS_POP); ffscanf("ECO_STEP", file, "%d", &ECO_STEP); ffscanf("EVO_STEP", file, "%d", &EVO_STEP); ffscanf("G_MAX", file, "%d", &G_MAX); ffscanf("PC", file, "%lf", &PC); vns->RUN = *RUN; vns->DIM = *DIM; vns->FUNCTION = *FUNCTION; vns->KMAX = *KMAX; vns->TMAX = *TMAX; vns->Q = *Q; vns->RADII = *RADII; vns->RADII_T_FLAG = *RADII_T_FLAG; vns->AVAL_MAX = *AVAL_MAX; vns->RHO = *RHO; vns->EPSILON = *EPSILON; vns->METHOD = *METHOD; vns->P = *P; vns->VNS_POP = *VNS_POP; vns->ECO_STEP = *ECO_STEP; vns->EVO_STEP = *EVO_STEP; vns->G_MAX = *G_MAX; vns->PC = *PC; return 1; } } /*Main program of the search algorithm*/ int main(int argc, char **argv) { srand(time(NULL)); MT_seed(); }
wesklei/OCEV
functions.h
<reponame>wesklei/OCEV /* Description: The ANSI C code of the PRVNS approach Programmer: <NAME> E-mail: <EMAIL> Date: 04/11/2014 Lisence: Free Note: The system was developed using Linux. To compile: Type: make To run: ./algorithm input.in */ #ifndef functions_h #define functions_h #include <assert.h> #include "data.h" #define PI 3.14159265 //aux methods void prepararObjFunc(int* FUNCTION, double* lb, double* ub); double objfunc(double sol[], const int* FUNCTION, const int* DIM, int *cont); char *getFunctionName(int FUNCTION); //functions double rastrigin( double SOL[], int DIM); double schaffer( double SOL[], int DIM); double griewank( double SOL[], int DIM); double ackley( double SOL[], int DIM); double rosenbrock( double SOL[], int DIM); double sphere( double SOL[], int DIM); double schaffer_f6( double sol[], int DIM); double g_schwefels( double sol[], int DIM); double mpe( double sol[], int DIM); double shubert(double SOL[], int DIM); double powell( double sol[], int DIM); double michalewitz( double sol[], int DIM); double levy( double sol[], int DIM); double zakharov( double sol[], int DIM); double egg_holder( double sol[], int DIM); double generalized_holzman( double sol[], int DIM); double rana( double sol[], int DIM); double holzman( double sol[], int DIM); double schwefels222( double sol[], int DIM); double stretchedV( double sol[], int DIM); double step(double sol[], int DIM); double penalized1(double sol[], int DIM); double penalized2(double sol[], int DIM); double TempValue(double x,int a,int k,int m); double multimod(double sol[], int DIM); //shifted functions double shifted_sphere( double sol[], int DIM); double shifted_schwefel_221( double sol[], int DIM); double shifted_rosenbrock( double sol[], int DIM); double shifted_rastrigin( double sol[], int DIM); double shifted_griewank( double sol[], int DIM); double shifted_ackley( double sol[], int DIM); double shifted_schwefel_222(double sol[], int dim); double shifted_schwefel_12(double sol[], int dim); double f_10(double x, double y);// auxiliar double shifted_extended_f10(double sol[], int dim); double shifted_bohachevsky(double sol[], int dim); double shifted_schaffer(double sol[], int dim); //hybrid functions static void divideFunctions(double sol[], int DIM, double *part1, double *part2, double m, int *psize1, int *psize2); double Extended_f_10NoDesplazamiento(double sol[], int DIM); double f_BohachevskyNoDesplazamiento(double sol[], int DIM); double f_Schwefel2_22NoDesplazamiento(double sol[], int DIM); double hybrid_1(double sol[], int DIM); double hybrid_2(double sol[], int DIM); double hybrid_3(double sol[], int DIM); double hybrid_4(double sol[], int DIM); double hybrid_5(double sol[], int DIM); double hybrid_6(double sol[], int DIM); double hybrid_7(double sol[], int DIM); double hybrid_8(double sol[], int DIM); #endif
wesklei/OCEV
mersenne.h
<reponame>wesklei/OCEV #include <math.h> #include <time.h> #include <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> //<NAME> enum { N = 624 }; // length of state vector enum { M = 397 }; // period parameter unsigned long state[N]; // internal state unsigned long *pNext; // next value to get from state int left; // number of values left before reload needed unsigned long MT_randInt(unsigned long n); unsigned long randInt(); void reload(); unsigned long twist(unsigned long m, unsigned long s0, unsigned long s1); unsigned long hiBit(unsigned long u); unsigned long loBit(unsigned long u); unsigned long loBits(unsigned long u); unsigned long mixBits(unsigned long u, unsigned long v ); void MT_seed(); unsigned long MT_hash(time_t t, clock_t c); void MT_seedfinal(unsigned long oneSeed); void MT_initialize(unsigned long seed); float MT_randfloat(); double MT_randExc(const double *n );
SGBotic/SGBotic_FN_MP3
SGBotic_FN_MP3.h
/*************************************************** This is a library for our Mini MP3 Module (DEV-02247) http://www.sgbotic.com/index.php?dispatch=products.view&product_id=2247 Written by KC for SGBotic.com BSD license, all text above must be included in any redistribution ****************************************************/ #include "Arduino.h" #ifdef __AVR__ #include <SoftwareSerial.h> #endif //#define FN_MP3_DEBUG //control commands #define FN_MP3_NEXT 0x01 #define FN_MP3_PREV 0x02 #define FN_MP3_PLAYTRACK 0x03 #define FN_MP3_INCVOLUME 0x04 #define FN_MP3_DECVOLUME 0x05 #define FN_MP3_SETVOLUME 0x06 #define FN_MP3_SETEQ 0x07 #define FN_MP3_REPEATTRACK 0x08 #define FN_MP3_SETDEVICE 0x09 #define FN_MP3_SLEEP 0x0A #define FN_MP3_RESET 0x0C #define FN_MP3_PLAY 0x0D #define FN_MP3_PAUSE 0x0E #define FN_MP3_PLAYTRACKFOLDER 0x0F #define FN_MP3_SETGAIN 0x10 #define FN_MP3_SETALLREPEATPLAYBACK 0x11 #define FN_MP3_SETPLAYBACKMP3 0x12 #define FN_MP3_INTERCUTADVERTISEMENT OX13 #define FN_MP3_PLAYFOLDER3K 0x14 #define FN_MP3_STOPADV 0x15 #define FN_MP3_STOP 0x16 #define FN_MP3_REPEATFOLDER 0x17 #define FN_MP3_RANDOMP 0x18 #define FN_MP3_REPEATCURRENT 0x19 #define FN_MP3_SETDAC 0x1A //Query commands #define FN_MP3_GETDEVICE 0x3F #define FN_MP3_ACKERROR 0x40 #define FN_MP3_ACKFEEDBACK 0x41 #define FN_MP3_GETSTATUS 0x42 #define FN_MP3_GETVOLUME 0x43 #define FN_MP3_GETEQ 0x44 #define FN_MP3_GETTOTALTRACKUSBROOT 0x47 #define FN_MP3_GETTOTALTRACKSDROOT 0x48 #define FN_MP3_GETTRACKUSB 0x4B #define FN_MP3_GETTRACKSD 0x4C #define FN_MP3_GETTOTALTRACKFOLDER 0x4E #define FN_MP3_GETTOTALFOLDER 0x4F #define FN_MP3_STARTCODE 0x7E #define FN_MP3_ENDCODE 0xEF #define FN_MP3_VERSION 0xFF #define FN_MP3_PACKETSIZE 0x06 #define NORMAL 0x00 #define POP 0x01 #define ROCK 0xO2 #define JAZZ 0x03 #define CLASSIC 0x04 #define BASS 0x05 class SGBotic_FN_MP3 { public: #ifdef __AVR__ SGBotic_FN_MP3(SoftwareSerial *); #endif SGBotic_FN_MP3(HardwareSerial *); void begin(uint16_t baud); void writePacket(uint8_t cmd, uint8_t feedback, uint16_t packet); void setVolume(uint16_t volume); void play(); void play(uint16_t track); void play(uint8_t track, uint8_t folder); void repeat(uint16_t track); void repeatFolder(uint16_t track); void reset(); void pause(); void next(); void prev(); void stop(); void sleep(); void setEq(uint16_t eq); void setGain(uint16_t gain); private: Stream *mySerial; #ifdef __AVR__ SoftwareSerial *swSerial; #endif HardwareSerial *hwSerial; };
Tamookk/Basil
Basil/include/Math/Math.h
<reponame>Tamookk/Basil /* * This header file declares a wrapper for glm, and some functions to suit the project's needs. */ #pragma once #include <glm/glm.hpp> namespace Basil::Math { bool decomposeTransform(const glm::mat4& transform, glm::vec3& outTranslation, glm::vec3& outRotation, glm::vec3& outScale); }
Tamookk/Basil
Basil/include/Core/Input.h
/* * This file defines the Input base class that all other input classes * inherit from. It is a singleton and involves multiple static functions * for polling input. */ #pragma once #include <utility> #include "Core/Core.h" #include "Core/KeyCodes.h" #include "Core/MouseCodes.h" namespace Basil { class Input { public: static bool isKeyPressed(KeyCode keyCode); static bool isMouseButtonPressed(MouseCode mouseCode); static std::pair<float, float> getMousePosition(); static float getMouseX(); static float getMouseY(); }; }
Tamookk/Basil
Basil/include/Scene/ScriptableEntity.h
/* * This header declares a class for an entity that can be scripted. */ #pragma once #include "Scene/Entity.h" namespace Basil { class ScriptableEntity { public: virtual ~ScriptableEntity() {} template <typename T> T& getComponent() { return entity.getComponent<T>(); } protected: virtual void onCreate() {} virtual void onDestroy() {} virtual void onUpdate(Timestep timeStep) {} private: Entity entity; friend class Scene; }; }
Tamookk/Basil
Basil/include/Renderer/OrthographicCameraController.h
/* * This header declares a class that is a wrapper around OrthographicCamera. */ #pragma once #include "Core/Timestep.h" #include "Events/ApplicationEvent.h" #include "Events/MouseEvent.h" #include "Renderer/OrthographicCamera.h" namespace Basil { class OrthographicCameraController { public: OrthographicCameraController(float aspectRatio, bool rotation = false); void onUpdate(Timestep timeStep); void onEvent(Event& e); void resize(float width, float height); OrthographicCamera& getCamera(); const OrthographicCamera& getCamera() const; float getZoomLevel() const; void setZoomLevel(float zoomLevel); private: bool onMouseScrolled(MouseScrolledEvent& e); bool onWindowResize(WindowResizeEvent& e); float aspectRatio; float zoomLevel = 1.0f; OrthographicCamera camera; bool rotation; glm::vec3 cameraPosition = { 0.0f, 0.0f, 0.0f }; float cameraRotation; float cameraXSpeed; float cameraYSpeed; float cameraRotateSpeed; }; }
Tamookk/Basil
Basil/include/Scene/SceneSerializer.h
/* * This header declares a class for serializing scenes. */ #pragma once #include "Scene/Scene.h" namespace Basil { class SceneSerializer { public: SceneSerializer(const Shared<Scene>& scene); void serialize(const std::string& filePath); void serializeRuntime(const std::string& filePath); bool deserialize(const std::string& filePath); bool deserializeRuntime(const std::string& filePath); private: Shared<Scene> scene; }; }
Tamookk/Basil
Basil/include/ImGui/ImGuiLayer.h
<filename>Basil/include/ImGui/ImGuiLayer.h /* * This header file defines the ImGui layer of Basil. */ #pragma once #include "Core/Layer.h" #include "Events/KeyEvent.h" #include "Events/MouseEvent.h" namespace Basil { class ImGuiLayer : public Layer { public: ImGuiLayer(); ~ImGuiLayer() {} void onAttach() override; void onDetach() override; void onEvent(Event& e) override; void onImGuiRender() override; void begin(); void end(); void setBlockEvents(bool block); void setDarkThemeColors(); private: bool blockEvents; }; }
Tamookk/Basil
Basil/include/Core/Core.h
<reponame>Tamookk/Basil /* * This header file is used by the engine, and games * created using it, to make various definitions and * declare various macros. */ #pragma once #include <memory> #ifdef DEBUG #ifdef PLATFORM_WINDOWS #define DEBUG_BREAK() __debugbreak() #else #error "Platform doesn't support debugbreak yet." #endif #define ENABLE_ASSERTS #else #define DEBUG_BREAK() #endif #ifdef ENABLE_ASSERTS #define ASSERT(x, ...) { if(!(x)) { LOG_ERROR("Assertion Failed: {0}", __VA_ARGS__); DEBUG_BREAK(); } } #define ASSERT_CLIENT(x, ...) { if(!(x)) { LOG_ERROR("Assertion Failed: {0}", __VA_ARGS__); DEBUG_BREAK(); } } #else #define ASSERT(x, ...) #define ASSERT_CLIENT(x, ...) #endif #define BIND_EVENT(fn) [this](auto&&... args) -> decltype(auto) {return this->fn(std::forward<decltype(args)>(args)...);} namespace Basil { template <typename T> using Unique = std::unique_ptr<T>; template <typename T, typename ... Args> constexpr Unique<T> makeUnique(Args&& ... args) { return std::make_unique<T>(std::forward<Args>(args)...); } template <typename T> using Shared = std::shared_ptr<T>; template <typename T, typename ... Args> constexpr Shared<T> makeShared(Args&& ... args) { return std::make_shared<T>(std::forward<Args>(args)...); } }
Tamookk/Basil
Basil/include/Renderer/GraphicsContext.h
<filename>Basil/include/Renderer/GraphicsContext.h<gh_stars>0 /* * This header defines the rendering context, which is a parent class for API-specific graphics contexts. */ #pragma once namespace Basil { class GraphicsContext { public: virtual void init() = 0; virtual void swapBuffers() = 0; static Unique<GraphicsContext> create(void* window); }; }
Tamookk/Basil
Basil/include/Renderer/Shader.h
/* * This header file declares a class for creating an OpenGL shader. */ #pragma once #include <string> #include "Core/Core.h" #include <glm/glm.hpp> namespace Basil { class Shader { public: virtual ~Shader() {} virtual void bind() const = 0; virtual void unbind() const = 0; virtual const std::string& getName() const = 0; virtual void setInt(const std::string& name, int value) = 0; virtual void setIntArray(const std::string& name, int* values, uint32_t count) = 0; virtual void setFloat(const std::string& name, float value) = 0; virtual void setFloat3(const std::string& name, const glm::vec3& value) = 0; virtual void setFloat4(const std::string& name, const glm::vec4& value) = 0; virtual void setMat4(const std::string& name, const glm::mat4& matrix) = 0; static Shared<Shader> create(const std::string& filePath); static Shared<Shader> create(const std::string& name, const std::string& vertexSource, const std::string& fragmentSource); }; }
Tamookk/Basil
Sandbox/include/ExampleLayer.h
<reponame>Tamookk/Basil /* * Declares a class with examples of features of Basil. */ #pragma once #include "Core/Basil.h" #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <imgui.h> class ExampleLayer : public Basil::Layer { public: ExampleLayer(); void onUpdate(Basil::Timestep timeStep) override; void onEvent(Basil::Event& e) override; void onImGuiRender() override; bool onKeyPressedEvent(Basil::KeyPressedEvent& event); private: Basil::ShaderLibrary shaderLibrary; Basil::Shared<Basil::Shader> shader; Basil::Shared<Basil::VertexArray> vao; Basil::Shared<Basil::Shader> squareShader; Basil::Shared<Basil::VertexArray> squareVao; Basil::Shared<Basil::VertexArray> imageVao; Basil::Shared<Basil::Texture2D> texture; Basil::OrthographicCameraController cameraController; glm::vec3 squareColor = { 0.0f, 0.0f, 0.0f }; };
Tamookk/Basil
Basil/include/Platform/OpenGL/OpenGLRendererAPI.h
<gh_stars>0 /* * This header file declares the OpenGL-specific implementation of RendererAPI. */ #pragma once #include "Renderer/RendererAPI.h" namespace Basil { class OpenGLRendererAPI : public RendererAPI { public: void init() override; void setViewport(unsigned int x, unsigned int y, unsigned int width, unsigned int height) override; void setClearColor(const glm::vec4& color) override; void clear() override; void drawIndexed(const Shared<VertexArray>& vao, uint32_t indexCount = 0) override; void drawLines(const Shared<VertexArray>& vao, uint32_t vertexCount) override; void setLineWidth(float width) override; }; }
Tamookk/Basil
Basil/include/Renderer/UniformBuffer.h
<reponame>Tamookk/Basil /* * This header file declares the base class for sending uniforms to shader uniform buffers. */ #pragma once #include "Core/Core.h" namespace Basil { class UniformBuffer { public: virtual ~UniformBuffer() {} virtual void setData(const void* data, uint32_t size, uint32_t offset = 0) = 0; static Shared<UniformBuffer> create(uint32_t size, uint32_t binding); }; }
Tamookk/Basil
Basil/include/Renderer/OrthographicCamera.h
/* * This header file declares an orthographic camera class. */ #pragma once #include <glm/glm.hpp> namespace Basil { class OrthographicCamera { public: OrthographicCamera(float left, float right, float bottom, float top); const glm::vec3& getPosition() const; void setPosition(const glm::vec3& position); float getRotation() const; void setRotation(float rotation); const glm::mat4& getProjectionMatrix() const; void setProjectionMatrix(float left, float right, float bottom, float top); const glm::mat4& getViewMatrix() const; const glm::mat4& getViewProjectionMatrix() const; private: void recalculateViewMatrix(); glm::mat4 projMatrix; glm::mat4 viewMatrix; glm::mat4 viewProjectionMatrix; glm::vec3 position; float rotation; }; }
Tamookk/Basil
Basil/include/Platform/OpenGL/OpenGLUniformBuffer.h
/* * This header declares the OpenGL implementation of UniformBuffer. */ #pragma once #include "Renderer/UniformBuffer.h" namespace Basil { class OpenGLUniformBuffer : public UniformBuffer { public: OpenGLUniformBuffer(uint32_t size, uint32_t binding); ~OpenGLUniformBuffer(); void setData(const void* data, uint32_t size, uint32_t offset = 0) override; private: uint32_t rendererID; }; }
Tamookk/Basil
Pesto/include/Panels/SceneHierarchyPanel.h
<filename>Pesto/include/Panels/SceneHierarchyPanel.h<gh_stars>0 /* * This header file declares a panel for displaying the hierarchy of objects within a scene. */ #pragma once #include "Core/Core.h" #include "Core/Log.h" #include "Scene/Entity.h" #include "Scene/Scene.h" namespace Basil { class SceneHierarchyPanel { public: SceneHierarchyPanel() = default; SceneHierarchyPanel(const Shared<Scene>& context); void setContext(const Shared<Scene>& context); Entity& getSelectedEntity(); void setSelectedEntity(Entity entity); void onImGuiRender(); private: void drawEntityNode(Entity entity); Shared<Scene> context; Entity selectionContext; }; }
Tamookk/Basil
Sandbox/include/Sandbox2D.h
/* * Declares a class for testing 2D rendering. */ #pragma once #include "Core/Basil.h" class Sandbox2D : public Basil::Layer { public: Sandbox2D(); virtual ~Sandbox2D() {} void onAttach() override; void onDetach() override; void onUpdate(Basil::Timestep timeStep) override; void onEvent(Basil::Event& e) override; void onImGuiRender() override; private: Basil::OrthographicCameraController cameraController; Basil::Shared<Basil::VertexArray> vao; Basil::Shared<Basil::Shader> shader; Basil::Shared<Basil::Texture2D> texture; glm::vec4 squareColor = { 0.2f, 0.3f, 0.8f, 1.0f }; std::vector<Basil::ProfileResult> profileResults; };
Tamookk/Basil
Basil/include/Events/MouseEvent.h
/* * This header defines mouse event classes. */ #pragma once #include "Events/Event.h" namespace Basil { class MouseButtonPressedEvent : public Event { public: MouseButtonPressedEvent(int button); int getMouseButton() const; virtual EventType getEventType() const override; static EventType getStaticType(); virtual const char* getName() const override; virtual std::string toString() const override; virtual int getCategory() const override; private: int button; }; class MouseButtonReleasedEvent : public Event { public: MouseButtonReleasedEvent(int button); int getMouseButton() const; virtual EventType getEventType() const override; static EventType getStaticType(); virtual const char* getName() const override; virtual std::string toString() const override; virtual int getCategory() const override; private: int button; }; class MouseMovedEvent : public Event { public: MouseMovedEvent(float x, float y); float getX() const; float getY() const; virtual EventType getEventType() const override; static EventType getStaticType(); virtual const char* getName() const override; virtual std::string toString() const override; virtual int getCategory() const override; private: float mouseX; float mouseY; }; class MouseScrolledEvent : public Event { public: MouseScrolledEvent(float xOffset, float yOffset); float getXOffset() const; float getYOffset() const; virtual EventType getEventType() const override; static EventType getStaticType(); virtual const char* getName() const override; virtual std::string toString() const override; virtual int getCategory() const override; private: float xOffset; float yOffset; }; }
Tamookk/Basil
Basil/include/Core/EntryPoint.h
/* * This class manages the entry point for an application created * using Basil. */ #pragma once #include "Core/Application.h" #include "Core/Log.h" #ifdef PLATFORM_WINDOWS extern Basil::Application* Basil::createApplication(ApplicationCommandLineArgs args); int main(int argc, char* argv[]) { // Initialise loggers Basil::Log::init(); PROFILE_BEGIN_SESSION("Startup", "Profile-Startup.json"); auto app = Basil::createApplication({ argc, argv }); PROFILE_END_SESSION(); PROFILE_BEGIN_SESSION("Runtime", "Profile-Runtime.json"); app->run(); PROFILE_END_SESSION(); PROFILE_BEGIN_SESSION("Shutdown", "Profile-Shutdown.json"); delete app; PROFILE_END_SESSION(); return 0; } #else #error Basil only supports Windows #endif
Tamookk/Basil
Basil/include/Core/UUID.h
/* * This class manages UUIDs. For now they are randomly-generated uint64_t variables, * as the likelihood of two UUIDs being the same using this generation method * is 1 in 2^64 - 1. That's a big number. */ #pragma once #include <xhash> namespace Basil { class UUID { public: UUID(); UUID(uint64_t uuid); UUID(const UUID&) = default; operator uint64_t() const; private: uint64_t uuid; }; } // Hashing operator for UUIDs namespace std { template<> struct hash<Basil::UUID> { std::size_t operator()(const Basil::UUID& uuid) const { return hash<uint64_t>()((uint64_t)uuid); } }; }
Tamookk/Basil
Basil/include/Core/Window.h
/* * This header file declares a generic Window class. */ #pragma once #include "pch.h" #include "Core/Core.h" #include "Events/Event.h" namespace Basil { struct WindowProps { std::string title; unsigned int width; unsigned int height; WindowProps(const std::string& title = "Basil Game Engine", unsigned int width = 1600, unsigned int height = 900) { this->title = title; this->width = width; this->height = height; } }; class Window { public: using EventCallbackFunction = std::function<void(Event&)>; static Unique<Window> create(const WindowProps& props = WindowProps()); virtual void onUpdate() = 0; virtual unsigned int getWidth() const = 0; virtual unsigned int getHeight() const = 0; virtual void setEventCallback(const EventCallbackFunction& callback) = 0; virtual void setVsync(bool enabled) = 0; virtual bool isVsync() const = 0; virtual void* getNativeWindow() const = 0; }; }
Tamookk/Basil
Basil/include/Renderer/Texture2D.h
/* * This header file contains the base class for 2D textures. */ #pragma once #include <string> #include "Core/Core.h" #include "Renderer/Texture.h" namespace Basil { class Texture2D : public Texture { public: static Shared<Texture2D> create(const std::string& path); static Shared<Texture2D> create(uint32_t width, uint32_t height); }; }
Tamookk/Basil
Basil/include/Utils/PlatfomUtils.h
<gh_stars>0 /* * This header file declares utilities implemented for each platform. */ #pragma once #include <string> namespace Basil { class FileDialogs { public: static std::string openFile(const char* filter); static std::string saveFile(const char* filter); }; }
Tamookk/Basil
Basil/include/pch.h
/* * Pre-compiled header for the Basil Game Engine. */ #pragma once #include <array> #include <filesystem> #include <functional> #include <iostream> #include <memory> #include <ostream> #include <sstream> #include <string> #include <vector> #include "Core/Log.h" #include "Debug/Instrumentor.h" #ifdef PLATFORM_WINDOWS #include <Windows.h> #endif
Tamookk/Basil
Basil/include/Events/ApplicationEvent.h
/* * This header defines classes for events relating to the application. */ #pragma once #include "Events/Event.h" namespace Basil { class WindowCloseEvent : public Event { public: WindowCloseEvent() = default; EventType getEventType() const override; static EventType getStaticType(); const char* getName() const override; int getCategory() const override; }; class WindowResizeEvent : public Event { public: WindowResizeEvent(unsigned int width, unsigned int height); unsigned int getWidth() const; unsigned int getHeight() const; EventType getEventType() const override; static EventType getStaticType(); const char* getName() const override; std::string toString() const override; int getCategory() const override; private: unsigned int width; unsigned int height; }; class WindowFocusEvent : public Event { public: WindowFocusEvent() = default; EventType getEventType() const override; static EventType getStaticType(); const char* getName() const override; int getCategory() const override; }; class WindowLostFocusEvent : public Event { public: WindowLostFocusEvent() = default; EventType getEventType() const override; static EventType getStaticType(); const char* getName() const override; int getCategory() const override; }; class WindowMovedEvent : public Event { public: WindowMovedEvent() = default; EventType getEventType() const override; static EventType getStaticType(); const char* getName() const override; int getCategory() const override; }; class AppTickEvent : public Event { public: AppTickEvent() = default; EventType getEventType() const override; static EventType getStaticType(); const char* getName() const override; int getCategory() const override; }; class AppUpdateEvent : public Event { AppUpdateEvent() = default; EventType getEventType() const override; static EventType getStaticType(); const char* getName() const override; int getCategory() const override; }; class AppRenderEvent : public Event { AppRenderEvent() = default; EventType getEventType() const override; static EventType getStaticType(); const char* getName() const override; int getCategory() const override; }; }
Tamookk/Basil
Basil/include/Platform/OpenGL/OpenGLIndexBuffer.h
<reponame>Tamookk/Basil<filename>Basil/include/Platform/OpenGL/OpenGLIndexBuffer.h /* * This header file contains a class for the OpenGL-specific implementation of * IndexBuffer.h. */ #pragma once #include "Renderer/IndexBuffer.h" #include <glad/glad.h> #include <GLFW/glfw3.h> namespace Basil { class OpenGLIndexBuffer : public IndexBuffer { public: OpenGLIndexBuffer(std::vector<uint32_t>& indices); ~OpenGLIndexBuffer() override; void bind() const override; void unbind() const override; uint32_t getSize() const override; private: unsigned int ibo; uint32_t size; }; }
Tamookk/Basil
Pesto/include/Panels/PropertiesPanel.h
<reponame>Tamookk/Basil /* * This header file declares a panel for displaying the properties of entities within a scene. */ #pragma once #include "Core/Core.h" #include "Core/Log.h" #include "Scene/Entity.h" #include "Scene/Scene.h" namespace Basil { class PropertiesPanel { public: PropertiesPanel() = default; PropertiesPanel(const Shared<Scene>& context); void setContext(const Shared<Scene>& context); void onImGuiRender(Entity& selectionContext); private: void drawComponents(Entity entity); Shared<Scene> context; Entity selectionContext; }; }
Tamookk/Basil
Basil/include/Renderer/Renderer2D.h
<reponame>Tamookk/Basil /* * This header file declares the 2D renderer class. */ #pragma once #include "Renderer/Camera.h" #include "Renderer/EditorCamera.h" #include "Renderer/OrthographicCamera.h" #include "Renderer/Texture2D.h" #include "Scene/Component.h" namespace Basil { class Renderer2D { public: struct Statistics { uint32_t drawCalls = 0; uint32_t quadCount = 0; uint32_t getTotalVertexCount(); uint32_t getTotalIndexCount(); }; static void init(); static void shutdown(); static void beginScene(const Camera& camera, const glm::mat4& transform); static void beginScene(const OrthographicCamera& camera); static void beginScene(const EditorCamera& camera); static void endScene(); static void startBatch(); static void flush(); static void nextBatch(); static void drawQuad(const glm::mat4& transform, const glm::vec4& color, int entityID = -1); static void drawQuad(const glm::mat4& transform, const Shared<Texture2D>& texture, float textureScale = 1.0f, const glm::vec4& tintColor = glm::vec4(1.0f), int entityID = -1); static void drawSprite(const glm::mat4& transform, SpriteRendererComponent& src, int entityID); static void drawCircle(const glm::mat4& transform, const glm::vec4& color, float thickness = 1.0f, float fade = 0.005f, int entityID = -1); static void drawLine(const glm::vec3& p0, const glm::vec3& p1, const glm::vec4& color, int entityID = -1); static void drawRect(const glm::vec3& position, const glm::vec2& size, const glm::vec4& color, int entityID = -1); static void drawRect(const glm::mat4& transform, const glm::vec4& color, int entityID = -1); static float getLineWidth(); static void setLineWidth(float width); static void resetStats(); static Statistics getStats(); }; }
Tamookk/Basil
Basil/include/Core/Layer.h
/* * This header is for defining an API layer class. */ #pragma once #include "Core/Core.h" #include "Core/Timestep.h" #include "Events/Event.h" namespace Basil { class Layer { public: Layer(const std::string& name = "Layer"); virtual ~Layer() {} virtual void onAttach() {} virtual void onDetach() {} virtual void onUpdate(Timestep timestep) {} virtual void onEvent(Event& e) {} virtual void onImGuiRender() {} inline const std::string& getName() const { return debugName; } protected: std::string debugName; }; }
Tamookk/Basil
Basil/include/Renderer/BufferLayout.h
/* * This header file declares a class used for specifying the layout of buffers. */ #pragma once #include <vector> #include "Core/Core.h" #include "Renderer/BufferElement.h" namespace Basil { class BufferLayout { public: BufferLayout(); BufferLayout(const std::initializer_list<BufferElement>& elements); uint32_t getStride() const; const std::vector<BufferElement>& getElements() const; std::vector<BufferElement>::iterator begin(); std::vector<BufferElement>::const_iterator begin() const; std::vector<BufferElement>::iterator end(); std::vector<BufferElement>::const_iterator end() const; private: void calculateOffsetAndStride(); std::vector<BufferElement> elements; uint32_t stride; }; }
Tamookk/Basil
Basil/include/Renderer/Renderer.h
<reponame>Tamookk/Basil /* * This header decleares the base renderer class. */ #pragma once #include "Renderer/OrthographicCamera.h" #include "Renderer/RendererAPI.h" #include "Renderer/Shader.h" namespace Basil { class Renderer { public: static void init(); static void shutdown(); static void onWindowResize(unsigned int width, unsigned int height); static void beginScene(OrthographicCamera& camera); static void endScene(); static void submit(const Shared<Shader>& shader, const Shared<VertexArray>& vao, const glm::mat4& transform = glm::mat4(1.0f)); static void setClearColor(const glm::vec4& color); static void clear(); static void drawIndexed(const Shared<VertexArray>& vao, uint32_t indexCount = 0); static void drawLines(const Shared<VertexArray>& vertexArray, uint32_t vertexCount); static void setLineWidth(float width); static RendererAPI::API getAPI(); private: struct SceneData { glm::mat4 viewProjectionMatrix; }; static Unique<RendererAPI> rendererAPI; static Unique<SceneData> sceneData; }; }
Tamookk/Basil
Basil/include/Platform/OpenGL/OpenGLContext.h
/* * This class defines the OpenGL-specific graphics context. */ #pragma once #include "Renderer/GraphicsContext.h" #include <glad/glad.h> #include <GLFW/glfw3.h> struct GLFWwindow; namespace Basil { class OpenGLContext : public GraphicsContext { public: OpenGLContext(GLFWwindow* window); void init() override; void swapBuffers() override; private: GLFWwindow* window; }; }
Tamookk/Basil
Basil/include/Platform/OpenGL/OpenGLVertexBuffer.h
<gh_stars>0 /* * This header file contains a class for the OpenGL-specific implementation of * VertexBuffer.h. */ #pragma once #include "Renderer/VertexBuffer.h" #include <glad/glad.h> #include <GLFW/glfw3.h> namespace Basil { class OpenGLVertexBuffer : public VertexBuffer { public: OpenGLVertexBuffer(std::vector<float>& vertices); OpenGLVertexBuffer(uint32_t size); ~OpenGLVertexBuffer() override; void setData(const void* data, uint32_t size); void bind() const override; void unbind() const override; const BufferLayout& getLayout() const override; void setLayout(const BufferLayout& layout) override; private: unsigned int vbo; BufferLayout layout; }; }
Tamookk/Basil
Basil/include/Core/Application.h
/* * This class manages application run-time. */ #pragma once #include "Core/Core.h" #include "Core/Input.h" #include "Core/LayerStack.h" #include "Core/Timestep.h" #include "Core/Window.h" #include "Events/Event.h" #include "Events/ApplicationEvent.h" #include "ImGui/ImGuiLayer.h" #include "Renderer/Renderer.h" #include "Renderer/Shader.h" int main(int argc, char** argv); namespace Basil { struct ApplicationCommandLineArgs { int count = 0; char** args = nullptr; const char* operator[](int index) { ASSERT(index < count, ""); return args[index]; } }; class Application { public: Application(const std::string& name = "Basil Application", ApplicationCommandLineArgs args = ApplicationCommandLineArgs()); virtual ~Application(); void close(); ImGuiLayer* getImGuiLayer(); void onEvent(Event& e); void pushLayer(Layer* layer); void pushOverlay(Layer* layer); static Application& get(); ApplicationCommandLineArgs getCommandLineArgs() const; Window& getWindow(); private: void run(); bool onWindowClose(WindowCloseEvent& e); bool onWindowResize(WindowResizeEvent& e); ApplicationCommandLineArgs commandLineArgs; Unique<Window> window; ImGuiLayer* imGuiLayer; bool running; bool minimised; LayerStack layerStack; static Application* instance; float lastFrameTime; friend int ::main(int argc, char** argv); }; // To be defined in the client Application* createApplication(ApplicationCommandLineArgs args); }
Tamookk/Basil
Basil/include/Renderer/Framebuffer.h
<gh_stars>0 /* * This header file declares a class for a basic frame buffer. */ #pragma once #include "Core/Core.h" namespace Basil { // Framebuffer texture formats enum class FramebufferTextureFormat { None = 0, // Color RGBA8, RED_INTEGER, // Depth/stencil DEPTH24STENCIL8, // Defaults Depth = DEPTH24STENCIL8 }; // Framebuffer texture specification struct FramebufferTextureSpecification { FramebufferTextureSpecification() = default; FramebufferTextureSpecification(FramebufferTextureFormat format) : textureFormat(format) {} FramebufferTextureFormat textureFormat; }; // Framebuffer attachment specification struct FramebufferAttachmentSpecification { FramebufferAttachmentSpecification() = default; FramebufferAttachmentSpecification(std::initializer_list<FramebufferTextureSpecification> attachments) : attachments(attachments) {} std::vector<FramebufferTextureSpecification> attachments; }; // Framebuffer specification struct FramebufferSpecification { uint32_t width; uint32_t height; FramebufferAttachmentSpecification attachments; uint32_t samples = 1; bool swapChainTarget = false; }; class Framebuffer { public: virtual ~Framebuffer() {} virtual void bind() = 0; virtual void unbind() = 0; virtual void resize(uint32_t width, uint32_t height) = 0; virtual int readPixel(uint32_t attachmentIndex, int x, int y) = 0; virtual void clearAttachment(uint32_t attachmentIndex, int value) = 0; virtual uint32_t getColorAttachmentRendererID(uint32_t index = 0) const = 0; virtual const FramebufferSpecification& getSpecification() const = 0; static Shared<Framebuffer> create(const FramebufferSpecification& spec); }; }
Tamookk/Basil
Basil/include/Platform/OpenGL/OpenGLShader.h
/* * OpenGL-specific implementation of Shader.h. */ #pragma once #include <unordered_map> #include "Renderer/Shader.h" #include <glm/glm.hpp> namespace Basil { typedef unsigned int GLenum; // Bad, remove eventually class OpenGLShader : public Shader { public: OpenGLShader(const std::string& filePath); OpenGLShader(const std::string& name, const std::string& vertexShaderSource, const std::string& fragmentShaderSource); ~OpenGLShader(); void bind() const override; void unbind() const override; const std::string& getName() const override; void setInt(const std::string& name, int value) override; void setIntArray(const std::string& name, int* values, uint32_t count) override; void setFloat(const std::string& name, float value) override; void setFloat3(const std::string& name, const glm::vec3& value) override; void setFloat4(const std::string& name, const glm::vec4& value) override; void setMat4(const std::string& name, const glm::mat4& matrix) override; void uploadUniformInt(const std::string& name, int value); void uploadUniformIntArray(const std::string& name, int* values, uint32_t count); void uploadUniformFloat(const std::string& name, float value); void uploadUniformFloat2(const std::string& name, const glm::vec2& value); void uploadUniformFloat3(const std::string& name, const glm::vec3& value); void uploadUniformFloat4(const std::string& name, const glm::vec4& value); void uploadUniformMat3(const std::string& name, const glm::mat3& value); void uploadUniformMat4(const std::string& name, const glm::mat4& matrix); private: std::string readFile(const std::string& filePath); std::unordered_map<GLenum, std::string> preProcess(const std::string& source); void compileOrGetVulkanBinaries(std::unordered_map<GLenum, std::string>& shaderSources); void compileOrGetOpenGLBinaries(); void createProgram(); void reflect(GLenum stage, const std::vector<uint32_t>& shaderData); uint32_t rendererID; std::string filePath; std::string name; std::unordered_map<GLenum, std::vector<uint32_t>> VulkanSPIRV; std::unordered_map<GLenum, std::vector<uint32_t>> OpenGLSPIRV; std::unordered_map<GLenum, std::string> OpenGLSourceCode; }; }
Tamookk/Basil
Basil/include/Scene/Component.h
/* * This header file defines various components. */ #pragma once #include "Core/UUID.h" #include "Renderer/Texture2D.h" #include "Scene/SceneCamera.h" #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #define GLM_ENABLE_EXPERIMENTAL #include <glm/gtx/quaternion.hpp> namespace Basil { struct CameraComponent { CameraComponent() = default; CameraComponent(const CameraComponent&) = default; SceneCamera camera; bool primary = true; bool fixedAspectRatio = false; }; struct IDComponent { UUID id; IDComponent() = default; IDComponent(const IDComponent&) = default; }; class ScriptableEntity; // Forward declaration struct NativeScriptComponent { ScriptableEntity* instance = nullptr; ScriptableEntity*(*instantiateScript)(); void (*destroyScript)(NativeScriptComponent*); template <typename T> void bind() { instantiateScript = []() { return static_cast<ScriptableEntity*>(new T()); }; destroyScript = [](NativeScriptComponent* nsc) { delete nsc->instance; nsc->instance = nullptr; }; } }; struct TagComponent { TagComponent() = default; TagComponent(const TagComponent&) = default; TagComponent(const std::string& tag) : tag(tag) {} std::string tag; }; struct TransformComponent { TransformComponent() = default; TransformComponent(const TransformComponent&) = default; TransformComponent(const glm::vec3& translation) : translation(translation) {} glm::mat4 getTransform() const { glm::mat4 localRotation = glm::toMat4(glm::quat(rotation)); return glm::translate(glm::mat4(1.0f), translation) * localRotation * glm::scale(glm::mat4(1.0f), scale); } glm::vec3 translation{ 0.0f, 0.0f, 0.0f }; glm::vec3 rotation = { 0.0f, 0.0f, 0.0f }; glm::vec3 scale{ 1.0f, 1.0f, 1.0f }; }; // == 2D Rendering == struct SpriteRendererComponent { SpriteRendererComponent() = default; SpriteRendererComponent(const SpriteRendererComponent&) = default; SpriteRendererComponent(const glm::vec4& color) : color(color) {} float tilingFactor = 1.0f; glm::vec4 color{ 1.0f, 1.0f, 1.0f, 1.0f }; Shared<Texture2D> texture; }; struct CircleRendererComponent { glm::vec4 color{ 1.0f, 1.0f, 1.0f, 1.0f }; float thickness = 1.0f; float fade = 0.005f; CircleRendererComponent() = default; CircleRendererComponent(const CircleRendererComponent&) = default; }; // == Physics == struct Rigidbody2DComponent { enum class BodyType { Static = 0, Dynamic, Kinematic }; Rigidbody2DComponent() = default; Rigidbody2DComponent(const Rigidbody2DComponent& other) = default; BodyType type = BodyType::Static; bool fixedRotation = false; void* runtimeBody = nullptr; }; struct BoxCollider2DComponent { BoxCollider2DComponent() = default; BoxCollider2DComponent(const BoxCollider2DComponent& other) = default; glm::vec2 offset = { 0.0f, 0.0f }; glm::vec2 size = { 0.5f, 0.5f }; float density = 1.0f; float friction = 0.5f; float restitution = 0.0f; float restitutionThreshold = 0.5f; void* runtimeBody = nullptr; }; struct CircleCollider2DComponent { CircleCollider2DComponent() = default; CircleCollider2DComponent(const CircleCollider2DComponent& other) = default; glm::vec2 offset = { 0.0f, 0.0f }; float radius = 0.5f; float density = 1.0f; float friction = 0.5f; float restitution = 0.0f; float restitutionThreshold = 0.5f; void* runtimeBody = nullptr; }; }
Tamookk/Basil
Basil/include/Renderer/VertexBuffer.h
/* * This header file contains a class for creating vertex buffers. */ #pragma once #include <cstdint> #include "Renderer/BufferLayout.h" namespace Basil { class VertexBuffer { public: virtual ~VertexBuffer() {}; virtual void bind() const = 0; virtual void unbind() const = 0; virtual void setData(const void* data, uint32_t size) = 0; virtual const BufferLayout& getLayout() const = 0; virtual void setLayout(const BufferLayout& layout) = 0; static Shared<VertexBuffer> create(std::vector<float>& vertices); static Shared<VertexBuffer> create(uint32_t size); }; }
Tamookk/Basil
Basil/include/Core/Basil.h
<filename>Basil/include/Core/Basil.h /* * This header file is for use by applications created using Basil, and not by Basil itself. * This header will include all necessary headers needed by applications created using Basil. */ #pragma once // For use by applications created using Basil, not by Basil itself #include "Core/Application.h" #include "Core/Input.h" #include "Core/KeyCodes.h" #include "Core/Layer.h" #include "Core/Log.h" #include "Core/MouseCodes.h" #include "Core/Timestep.h" #include "Debug/Timer.h" #include "ImGui/ImGuiLayer.h" #include "Renderer/Framebuffer.h" #include "Renderer/IndexBuffer.h" #include "Renderer/OrthographicCamera.h" #include "Renderer/OrthographicCameraController.h" #include "Renderer/Renderer.h" #include "Renderer/Renderer2D.h" #include "Renderer/Shader.h" #include "Renderer/ShaderLibrary.h" #include "Renderer/Texture2D.h" #include "Renderer/VertexArray.h" #include "Renderer/VertexBuffer.h" #include "Scene/Component.h" #include "Scene/Entity.h" #include "Scene/Scene.h" #include "Scene/ScriptableEntity.h"